Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain Structured Output

LangChain Structured Output Structured Output

Most of the time, what we need is not a piece of free text, but data that a program can process directly, such as a JSON object, user information, product data, or course recommendation results.

LangChain provides the Structured Output feature, which lets the model return results according to a specified data structure, reducing the work of manually parsing text.

In LangChain 1.x, you can through create_agent(response_format=...) configure the Agent's structured output, or directly use the model's with_structured_output() method.

This section is based on LangChain 1.x and Pydantic 2, introducing Pydantic, TypedDict, ProviderStrategy, ToolStrategy, nested structures, and error handling.


1. Why Do We Need Structured Output?

Suppose a user provides a description:

张三今年 28 岁,是一名 Python 工程师。

A regular model might return:

张三今年 28 岁,职业是 Python 工程师。

If you need to write this information into a database, you also need to extract the name, age, and occupation from the natural language.

Structured output, on the other hand, can directly return:

{

    "name": "张三",

    "age": 28,

    "job": "Python 工程师"

}

Method Returns Subsequent processing
Plain text Natural language answer Requires parsing and field extraction
Structured output Pydantic object or dictionary Can be accessed and validated by field

The advantages of structured output are:

**Note:** Structured output can check the data format, but cannot guarantee the data content is truthful. For example, the model can generate an incorrect date or a non-existent course name that conforms to the Schema.


2. Installation and Environment Setup

Using Python 3.10 or later, install LangChain 1.x, the DeepSeek integration, and related dependencies:

python -m pip install -U "langchain>=1.2,<2" langchain-deepseek python-dotenv "pydantic>=2,<3" typing_extensions

Project directory creation .env File:

DEEPSEEK_API_KEY=your_deepseek_api_key

Load environment variables before calling the model:

from dotenv import load_dotenv

load_dotenv()

This tutorial uses ChatDeepSeek(model="deepseek-flash"). Among them, deepseek-flash is the DeepSeek API model name; when using init_chat_model() the corresponding full form is deepseek:deepseek-flash。

To facilitate the demonstration of information extraction, the examples uniformly disable thinking mode and explicitly use tool calling. DeepSeek's current thinking mode also supports tool calls, but multi-round tool calls require correctly preserving reasoning_contentand you cannot simply assume that "thinking models do not support structured output."

The complete code examples in each section all load .env and initialize the model; snippets marked "reuse" require you to first retain the corresponding Schema definition. Section 12 provides a complete program that can be saved and run on its own.


3. The Simplest Usage: Pydantic Model

Use Pydantic to define the desired output structure, then through response_format to create_agent()。

For example, extract the course name, difficulty, study duration, and whether it is free from a user description.

Example: Extracting Course Information

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

typing

import

Literal

from

pydantic

import

BaseModel

,

Field

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

structured_output

import

ToolStrategy

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

class

CourseInfo

(

BaseModel

)

:

   

"""Extract course information from text."""

    course_name:

str

=

Field

(

description

=

"Course name"

)

    difficulty: Literal

[

"Beginner"

,

"Intermediate"

,

"Advanced"

]

    estimated_hours:

int

=

Field

(

ge

=

1

,

description

=

"Estimated study hours"

)

    is_free:

bool

=

Field

(

description

=

"Whether it is free"

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

]

,

    response_format

=

ToolStrategy

(

CourseInfo

)

,

    system_prompt

=

"Only extract course information explicitly provided by the user; do not fabricate."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"I am studying the Python3 Basics Tutorial, which is an introductory course, estimated at 20 hours, and it is free."

}

]

}

)

course

=

result

[

"structured_response"

]

print

(

"Course name:"

,

course.

course_name

)

print

(

"Difficulty:"

,

course.

difficulty

)

print

(

"Duration:"

,

course.

estimated_hours

,

"hours"

)

print

(

"Free:"

,

course.

is_free

)

print

(

"Object type:"

,

type

(

course

)

.name

)

If the model extracts successfully, the output is similar to:

课程名: Python3 基础教程

难度: 入门

时长: 20 小时

免费: True

对象类型: CourseInfo

Where:

When using a Pydantic Schema and parsing succeeds,structured_response is a Pydantic model instance that can be accessed directly via attributes. Pydantic allows some type conversions by default, such as converting a numeric string to an integer; when you need to strictly reject such conversions, you can use Field(strict=True)。

Convert to JSON

If you need to send it to the frontend, you can use:

print(course.model_dump())

print(course.model_dump_json(indent=2))

model_dump() returns a Python dictionary,model_dump_json() returns a JSON string.

**Note:** If a field is not provided in the original text, you should not let the model guess arbitrarily. You can use optional fields or request additional information.


4. ProviderStrategy and ToolStrategy

LangChain 1.x provides two main Agent structured output strategies:

Strategy Implementation Applicable scenarios
ProviderStrategy Use the model provider's native structured output capability The provider supports native Schema constraints
ToolStrategy Generate structured data via Tool Calling Models that support tool calling
Pass the Schema directly Let LangChain choose the strategy based on model capabilities Regular scenarios where automatic selection is desired

1. Automatic Strategy Selection

Below we reuse the previous section's model and CourseInfo:

agent = create_agent(

    model=model,

    response_format=CourseInfo

)

LangChain selects a supported structured output approach based on the current model's capability information.

When a Schema type is passed directly, LangChain uses after recognizing native structured output capability ProviderStrategyotherwise it uses ToolStrategy. Since LangChain 1.1, this decision reads the model's profile capability information.

Automatic selection depends on model capability information and does not guarantee that all models can complete structured output.

2. Explicitly Using ToolStrategy

For models that use Tool Calling to complete structured output, you can configure it explicitly. Below we continue to reuse the third section's CourseInfo:

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

structured_output

import

ToolStrategy

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

]

,

    response_format

=

ToolStrategy

(

CourseInfo

)

,

    system_prompt

=

"Extract course information from the user description."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"The Python3 Basics Tutorial is a free introductory course, estimated at 20 hours."

}

]

}

)

print

(

result

[

"structured_response"

]

.

model_dump

(

)

)

ToolStrategy passes structured data through the model's tool calling mechanism, and then LangChain parses and validates it.

The structured output tool here is mainly used to convey the data Schema; it does not mean a real course-query Python function was executed.

3. Explicitly Using ProviderStrategy

Only when the model, API endpoint, and LangChain integration all support native structured output should you explicitly use ProviderStrategy. The following uses an OpenAI model that supports this capability for demonstration, without reusing the previous DeepSeek model:

python -m pip install -U langchain-openai

in .env configure separately in OPENAI_API_KEYand then run:

from dotenv import load_dotenv

from pydantic import BaseModel

from langchain_openai import ChatOpenAI

from langchain.agents import create_agent

from langchain.agents.structured_output import ProviderStrategy



load_dotenv()



class ContactInfo(BaseModel):

    """联系人信息。"""

    name: str

    email: str



native_model = ChatOpenAI(model="gpt-5.5")

agent = create_agent(

    model=native_model,

    response_format=ProviderStrategy(ContactInfo, strict=True),

)



result = agent.invoke({

    "messages": [{"role": "user", "content": "张三的邮箱是 zhangsan@example.com。"}]

})

print(result["structured_response"].model_dump())

ProviderStrategy(strict=True) Requires LangChain 1.2 or later, and only applies to providers that support this parameter. It controls server-side Schema constraints and is not the same setting as Pydantic's Field(strict=True) type validation.

JSON mode mainly constrains the output to valid JSON; it does not mean generating according to a specified JSON Schema. This tutorial's ChatDeepSeek.with_structured_output(..., method="function_calling") takes the tool calling path; you cannot infer from the parameter name alone that the request uses the provider's native Schema interface.

4. JSON Schema Dictionary

If the Schema comes from a configuration file, you can also use a JSON Schema dictionary. When passing it to the Agent, you should explicitly wrap it in a strategy, rather than relying directly on response_format=schema_dict automatic selection:

person_schema = {

    "title": "PersonInfo",

    "description": "从文本中提取姓名与年龄。",

    "type": "object",

    "properties": {

        "name": {"type": "string"},

        "age": {"type": "integer", "minimum": 0}

    },

    "required": ["name", "age"],

    "additionalProperties": False

}



agent = create_agent(

    model=model,

    response_format=ToolStrategy(person_schema),

)

Here we reuse the previous DeepSeek model and ToolStrategy import. The return result is a dictionary; a raw JSON Schema dictionary in the ToolStrategy path does not automatically perform full local Schema validation, nor can you rely on handle_errors to fix all field violations. When you need local validation and automatic error correction, prefer Pydantic.


5. Structured Output Coexisting with Tools

Structured output and ordinary tools can be used together.

For example, a course recommendation Agent can first search for courses, then organize the final result into the specified structure.

Note that the model must support the combination of the current structured output strategy and ordinary tool calling.

Example: Searching for Courses and Generating Recommendations

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

pydantic

import

BaseModel

,

Field

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

structured_output

import

ToolStrategy

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

COURSES

=

{

   

"python"

:

"Python3 Basics Tutorial, introductory, simulated study duration 20 hours"

,

   

"java"

:

"Java Basics Tutorial, introductory, simulated study duration 25 hours"

}

@

tool

def

search_course

(

keyword

:

str

)

str

:

   

"""Query simulated courses by programming language."""

   

return

COURSES.

get

(

keyword

.

lower

(

)

,

"No relevant mock courses found"

)

class

CourseRecommendation

(

BaseModel

)

:

   

"""Course recommendation result."""

    course_name:

str

=

Field

(

description

=

"Recommended courses"

)

    reason:

str

=

Field

(

description

=

"Reason for recommendation"

)

    difficulty:

str

=

Field

(

description

=

"Course difficulty"

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

search_course

]

,

    response_format

=

ToolStrategy

(

CourseRecommendation

)

,

    system_prompt

=

"You are a programming learning advisor. Use the tool when querying courses, and only recommend courses actually returned by the tool."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"I have no prior experience and want to learn Python. Please query courses and make recommendations."

}

]

}

)

rec

=

result

[

"structured_response"

]

print

(

"Course:"

,

rec.

course_name

)

print

(

"Reason:"

,

rec.

reason

)

print

(

"Difficulty:"

,

rec.

difficulty

)

for

msg

in

result

[

"messages"

]

:

   

if

msg.

type

==

"tool"

and

msg.

name

==

"search_course"

:

       

print

(

"Course query results:"

,

msg.

content

)

If the model correctly calls the query tool, you may get:

课程: Python3 基础教程

理由: 适合没有编程基础的学习者

难度: 入门

The code filters by tool name search_course messages to display course query results separately.

result["messages"] may also contain ToolMessages generated by the structured output strategy, so you cannot treat every tool message as a business query.

**Note:** The model does not necessarily call ordinary tools exactly as expected. If you must query a real database and guarantee data provenance, you should enforce the query in the business workflow.


6. Complex Nested Structures

Pydantic supports lists, nested models, enums, and field constraints, making it suitable for complex data structures such as study plans and order information.

Example: Generating a Python Study Plan

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

typing

import

Literal

from

pydantic

import

BaseModel

,

Field

,

model_validator

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

structured_output

import

ToolStrategy

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

class

Topic

(

BaseModel

)

:

   

"""A single study topic."""

    name:

str

    order:

int

=

Field

(

ge

=

1

)

    minutes:

int

=

Field

(

gt

=

0

)

class

LearningPlan

(

BaseModel

)

:

   

"""Study plan."""

    goal:

str

    level: Literal

[

"Beginner"

,

"Intermediate"

,

"Advanced"

]

    total_hours:

float

=

Field

(

gt

=

0

,

le

=

10

)

    topics:

list

[

Topic

]

=

Field

(

min_length

=

1

)

   

@

model_validator

(

mode

=

"after"

)

   

def

check_duration

(

self

)

:

        total

=

sum

(

topic.

minutes

for

topic

in

self

.

topics

)

       

if

abs

(

total /

60

self

.

total_hours

)

0.01

:

           

raise

ValueError

(

"total_hours must equal the sum of all topic minutes divided by 60"

)

       

return

self

agent

=

create_agent

(

    model

=

model

,

    response_format

=

ToolStrategy

(

LearningPlan

)

,

    system_prompt

=

"Create a reasonable study plan. The sum of all topic minutes must equal total_hours × 60."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Create a Python introductory study plan with a total duration of no more than 10 hours."

}

]

}

)

plan

=

result

[

"structured_response"

]

print

(

"Goal:"

,

plan.

goal

)

print

(

"Difficulty:"

,

plan.

level

)

print

(

"Total duration:"

,

plan.

total_hours

,

"hours"

)

for

topic

in

plan.

topics

:

   

print

(

f

"{topic.order}. {topic.name} ({topic.minutes} minutes)"

)

On successful execution, you may get:

目标:掌握 Python 基础语法

难度:入门

总时长:6.0 小时



1. Python 环境与变量(60分钟)

2. 数据类型(60分钟)

3. 条件判断(60分钟)

4. 循环(60分钟)

5. 函数(60分钟)

6. 综合练习(60分钟)

Here, not only is total_hours verified not to exceed 10 hours, but also model_validator used to verify that the total duration is consistent with the minutes of each topic. Custom validators execute locally in Python, and their logic does not automatically become JSON Schema rules that the provider can execute; this example allows a tolerance of no more than 0.01 hours in the total duration.

If the model returns data that does not meet the constraints, Pydantic produces a validation error. When using ToolStrategy, LangChain can ask the model to regenerate according to the error handling strategy.


7. Using TypedDict to Return a Dictionary

Besides Pydantic, LangChain also supports using TypedDict Define structured output.

Unlike Pydantic models, the TypedDict approach usually returns a plain Python dictionary.

Example: Extracting Person Information

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

typing_extensions

import

TypedDict

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

structured_output

import

ToolStrategy

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

class

PersonInfo

(

TypedDict

)

:

   

"""Person information."""

    name:

str

    age:

int

    job:

str

agent

=

create_agent

(

    model

=

model

,

    response_format

=

ToolStrategy

(

PersonInfo

)

,

    system_prompt

=

"Extract person information explicitly provided by the user; do not guess."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Zhang San is 28 years old and is a Python engineer."

}

]

}

)

person

=

result

[

"structured_response"

]

print

(

person

[

"name"

]

)

print

(

person

[

"age"

]

)

print

(

person

[

"job"

]

)

print

(

type

(

person

)

.name

)

Possible output:

张三

28

Python工程师

dict

The difference between the two approaches:

Method Return Type Main Features
Pydantic BaseModel instance Supports rich field constraints and custom validation
TypedDict dict Simple declaration, suitable for ordinary structured data

TypedDict itself mainly provides type declarations; the current Agent structured output path uses Pydantic TypeAdapter for parsing and type validation. But when directly calling the model's with_structured_output(TypedDict) you should not assume the same local validation behavior. When custom business rules are involved, prefer Pydantic.


8. Optional Fields and Missing Data

Real-world text often has incomplete information.

For example:

我正在学习 Python 基础教程,属于入门级别。

The user did not provide the estimated study duration, nor did they state whether there is a fee.

In this case, you should not let the model fabricate these two fields.

You can define the fields as optional:

Example

from

typing

import

Literal

from

pydantic

import

BaseModel

,

Field

class

OptionalCourseInfo

(

BaseModel

)

:

   

"""Course information with allowed missing fields."""

    course_name:

str

|

None

=

Field

(

default

=

None

,

min_length

=

1

)

    difficulty: Literal

[

"Beginner"

,

"Intermediate"

,

"Advanced"

]

|

None

=

None

    estimated_hours:

int

|

None

=

Field

(

default

=

None

,

ge

=

1

)

    is_free:

bool

|

None

=

None

Replace this section's OptionalCourseInfo to ToolStrategy to use this structure.str | None indicates that null values are allowed,= None indicates that the field may be omitted; in Pydantic 2, writing only name: str | None still makes the field required.

In Python, None indicates an unknown value, which after serialization to JSON corresponds to null。

For example:

{

    "course_name": "Python 基础教程",

    "difficulty": "入门",

    "estimated_hours": null,

    "is_free": null

}

**Note:** Declaring optional fields only allows missing values and does not completely prevent the model from guessing. Therefore, you still need to state in the System Prompt to extract only explicitly provided information.


9. Directly Using with_structured_output()

If the task is only to extract information from text and does not require the Agent to call tools, you can directly use the chat model's with_structured_output()。

This is usually simpler than creating an Agent. Specify explicitly below method="function_calling", returning structured data through DeepSeek's tool-calling mechanism.

Example: Sentiment Analysis

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

typing

import

Literal

from

pydantic

import

BaseModel

,

Field

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

class

SentimentResult

(

BaseModel

)

:

   

"""Sentiment analysis result."""

    sentiment: Literal

[

"Positive"

,

"Negative"

,

"Neutral"

]

    score:

float

=

Field

(

ge

=

0

,

le

=

1

,

description

=

"Sentiment judgment strength"

)

    keywords:

list

[

str

]

structured_model

=

model.

with_structured_output

(

SentimentResult

,

method

=

"function_calling"

)

texts

=

[

   

"Runoob Tutorial is really great, highly recommended!"

,

   

"This tutorial has rather little content, a bit disappointing."

,

   

"I learned about Python variables today."

]

for

text

in

texts:

    result

=

structured_model.

invoke

(

text

)

   

print

(

text

)

   

print

(

result.

model_dump

(

)

)

You might get:

Runoob Tutorial真的很好用,强烈推荐!

{'sentiment': '积极', 'score': 0.95, 'keywords': ['好用', '推荐']}

这个教程内容比较少,有些失望。

{'sentiment': '消极', 'score': 0.7, 'keywords': ['内容少', '失望']}

我今天学习了 Python 变量。

{'sentiment': '中性', 'score': 0.2, 'keywords': ['Python', '变量']}

The sentiment classification and scoring are judged by the model and are not absolutely objective.

In particular, note thatscore does not automatically represent a statistically calibrated probability or confidence level.

If needed for real business decisions, evaluate model performance with test data.

Difference from Agent

Method Return Value Applicable scenarios
create_agent(response_format=...) Agent state, containing structured_response Requires tool calls and multi-step processing
model.with_structured_output(...) Parsed structured data Text extraction, classification, simple parsing

with_structured_output() The internal implementation is determined by the model integration and method parameters. Direct calls do not automatically start Agent-style conversational error correction just because field validation fails; parsing exceptions need to be handled by the caller.

Difference between JSON mode and tool calling

Method Main purpose Local validation
method="function_calling" Convert Schema into tool parameter structure Validate fields when passed to Pydantic
method="json_mode" Requires valid JSON to be returned; the JSON format and fields must be explained in the prompt Validate the parsed result when passed to Pydantic, which does not mean the server enforces Schema compliance
ProviderStrategy Structure constrained by providers that support native structured output Business validations that cannot be expressed with Schema still need to be performed

10. include_raw: Viewing the raw model response

Use with_structured_output() , sometimes you need to view both the raw model message and the parsing result.

You can set:

include_raw=True

Example

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

pydantic

import

BaseModel

,

Field

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

class

Person

(

BaseModel

)

:

    name:

str

    age:

int

=

Field

(

ge

=

0

)

structured_model

=

model.

with_structured_output

(

    Person

,

method

=

"function_calling"

,

include_raw

=

True

)

result

=

structured_model.

invoke

(

"Zhang San is 28 years old this year."

)

print

(

"Parsing result:"

,

result

[

"parsed"

]

)

print

(

"Raw message:"

,

result

[

"raw"

]

)

print

(

"Parsing error:"

,

result

[

"parsing_error"

]

)

This call returns a dictionary containing the following three keys:

Field Description
raw The raw AIMessage generated by the model
parsed The successfully parsed structured object; None if parsing fails. May also be None when the expected tool call is not obtained
parsing_error The captured parsing exception object; None if there is no parsing exception

include_raw=True Suitable for debugging model output format. Before using the result, check both parsing_error, and also check parsed whether it is None; you cannot assume a structured object has been obtained just because there is no exception.

**Note:** It does not mean all errors will be converted into parsing_error. For example, network connection failures, API authentication errors, and request timeouts may still throw exceptions directly.


11. Error handling for structured output

When a model generates structured data, the following problems may occur:

For ToolStrategy, LangChain provides handle_errors parameter, which can control how Schema validation failures are handled.

Configure Behavior
True Automatically handle supported structured output errors and try to have the model correct them
False Do not perform this strategy's automatic error recovery; exceptions continue to be thrown
String Feed the specified error prompt back to the model
Exception type or tuple of exception types Only handle specified structured output exceptions; others continue to be thrown
Callable Generate error prompts through a custom function

Example: Custom Error Prompt

Example

from

dotenv

import

load_dotenv

from

langchain_deepseek

import

ChatDeepSeek

from

pydantic

import

BaseModel

,

Field

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

structured_output

import

ToolStrategy

load_dotenv

(

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

class

ProductRating

(

BaseModel

)

:

   

"""Product rating."""

    rating:

int

=

Field

(

ge

=

1

,

le

=

5

)

    comment:

str

agent

=

create_agent

(

    model

=

model

,

    response_format

=

ToolStrategy

(

        ProductRating

,

        handle_errors

=

"The rating must be an integer from 1 to 5, and a comment must be provided."

   

)

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"This product is good, I give it 4 points."

}

]

}

)

print

(

result

[

"structured_response"

]

)

If the model returns an illegal rating, LangChain can pass the error prompt to the model and have it try to regenerate.

handle_errors default to True, handles parsing or validation errors of Agent structured output, does not handle all network or authentication exceptions, and does not guarantee eventual success.

When you need to limit repeated corrections, you can set an upper limit on graph execution steps when calling the Agent:

result = agent.invoke(

    {"messages": [{"role": "user", "content": "这个商品不错,我给它4分。"}]},

    config={"recursion_limit": 12},

)

recursion_limit Limits the number of graph execution steps, including nodes such as model and tools; it does not mean 'retry at most 12 times'. The model initialization's max_retries mainly controls request-level retries; the two serve different purposes.

**Note:** The ToolStrategy(handle_errors=...) here and the ordinary tool's BaseTool.handle_tool_error are different mechanisms and should not be confused.


12. Complete example: Extracting course information from user descriptions

Below we integrate Pydantic, nullable fields, field constraints, ToolStrategy, execution step limits, and JSON output. All business fields allow unknown values to avoid conflicts between 'return null for missing information' and the required course name.

Filename:structured_output_demo.py

Complete example

from

typing

import

Literal

from

dotenv

import

load_dotenv

from

pydantic

import

BaseModel

,

ConfigDict

,

Field

from

langchain_deepseek

import

ChatDeepSeek

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

structured_output

import

ToolStrategy

,

StructuredOutputError

from

langgraph.

errors

import

GraphRecursionError

from

openai

import

APIError

load_dotenv

(

)

class

CourseInfo

(

BaseModel

)

:

   

"""Extract course materials from user text; return null for fields not explicitly stated."""

    model_config

=

ConfigDict

(

extra

=

"forbid"

)

    course_name:

str

|

None

=

Field

(

default

=

None

,

min_length

=

1

,

description

=

"Course name"

)

    difficulty: Literal

[

"Beginner"

,

"Intermediate"

,

"Advanced"

]

|

None

=

None

    estimated_hours:

int

|

None

=

Field

(

default

=

None

,

ge

=

1

,

le

=

1000

)

    is_free:

bool

|

None

=

Field

(

default

=

None

,

description

=

"Whether it is free"

)

model

=

ChatDeepSeek

(

    model

=

"deepseek-flash"

,

    extra_body

=

{

"thinking"

:

{

"type"

:

"disabled"

}

}

,

    timeout

=

60

,

    max_retries

=

2

,

)

agent

=

create_agent

(

    model

=

model

,

    response_format

=

ToolStrategy

(

CourseInfo

,

handle_errors

=

True

)

,

    system_prompt

=

(

       

"Extract course information from the user's description, using only data explicitly provided by the user."

       

"Return null for missing fields; do not guess course prices, membership privileges, or study duration."

       

"Do not infer difficulty just because the course name contains 'basics'."

       

"If the text does not specify a course name, return null for course_name as well."

   

)

,

)

texts

=

[

   

"The Python3 basic tutorial is an introductory course, estimated at 20 hours, free."

,

   

"The Java advanced course takes about 35 hours."

,

   

"I have recently been studying the HTML basic tutorial."

,

   

"I want to learn programming but haven't chosen a course yet."

,

]

for

text

in

texts:

   

print

(

"\nOriginal text:"

,

text

)

   

try

:

        result

=

agent.

invoke

(

           

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

: text

}

]

}

,

            config

=

{

"recursion_limit"

:

12

}

,

       

)

        course

=

result.

get

(

"structured_response"

)

       

if

not

isinstance

(

course

,

CourseInfo

)

:

           

print

(

"Extraction failed: no valid structured course object returned"

)

           

continue

       

print

(

course.

model_dump_json

(

indent

=

2

)

)

   

except

GraphRecursionError:

       

print

(

"Extraction failed: execution step limit reached, please check the input or simplify the Schema"

)

   

except

StructuredOutputError

as

error:

       

print

(

"Structured output failed:"

,

type

(

error

)

.name

)

   

except

APIError

as

error:

       

print

(

"Model request failed:"

,

type

(

error

)

.name

)

Once configured .env , run in the terminal:

python structured_output_demo.py

If the first text is extracted successfully, the structured result should be close to:

{

  "course_name": "Python3 基础教程",

  "difficulty": "入门",

  "estimated_hours": 20,

  "is_free": true

}

The third text does not mention difficulty, duration, or pricing information, so the expected return is:

{

  "course_name": "HTML 基础教程",

  "difficulty": null,

  "estimated_hours": null,

  "is_free": null

}

The fourth text does not specify any course materials; all business fields are expected to be null。extra="forbid" used to reject extra fields outside the Schema cannot prevent the model from fabricating content for legitimate fields; important data still needs source verification.


XIII. Frequently Asked Questions

1. Is structured_response a string or an object?

The Pydantic examples in this chapter return corresponding model instances; the TypedDict and JSON Schema examples return dictionaries, not JSON strings. When a string is needed, call a serialization method.

2. Why does structured_response not exist?

First confirm that response_formatis configured, and that what you read is agent.invoke() returned final state, not a single event during streaming execution; then check whether the flow ended normally.with_structured_output() result is not placed in this key either.

3. Which should you choose, Pydantic or TypedDict?

If you need complex field validation, nested models, or custom validators, Pydantic is recommended; if you only need a simple dictionary structure, consider TypedDict.

4. What is the difference between ProviderStrategy and ToolStrategy?

ProviderStrategy uses the model provider's native structured output mechanism; ToolStrategy generates structured data through model tool calls.

5. Do all models support structured output?

No. Different models support different features, especially native JSON Schema, Tool Calling, and complex nested structures.

6. Can response_format be used together with tools?

Yes, but the model and the structured output method used must support the combination.

7. How to prevent the model from fabricating missing fields?

You can define fields as optional, require null to be returned for missing information in the system prompt, and validate at the application layer.

8. Can structured output guarantee data correctness?

No. Schema mainly constrains data format and some numeric relationships, and is not responsible for validating all business facts.

9. Why does the model keep retrying structured output?

Possibly because the model repeatedly generates content that does not conform to the Schema. You can simplify constraints, improve descriptions, use handle_errors=False to expose errors, or use recursion_limit to limit execution steps. When constraints contradict each other, fix the Schema first.

10. When is create_agent() not needed?

If the task is only text classification, information extraction, or simple structured transformation, you can directly use the model's with_structured_output()。


Summary

LangChain structured output allows the model to return data according to a specified Schema, making it easy for programs to use directly.

This chapter introduces:

Reuse the already initialized model、CourseInfo and ToolStrategy; the core pattern is:

agent = create_agent(

    model=model,

    response_format=ToolStrategy(CourseInfo)

)



result = agent.invoke({

    "messages": [{"role": "user", "content": "Python 入门课,20小时,免费。"}]

})



data = result["structured_response"]

If you don't need Agent tool calls, you can also directly use:

structured_model = model.with_structured_output(

    CourseInfo, method="function_calling"

)

data = structured_model.invoke("Python 入门课,20小时,免费。")

Core principles:Use Schema to constrain data format, Pydantic to check fields and business rules, and verify important facts through trusted data sources. Structured output solves the problem of data organization, not all problems of model content accuracy.


Reference Documentation