LangChain Output Strategies — ToolStrategy, ProviderStrategy, and AutoStrategy
In the previous section we learned about LangChain's Structured Output。
Structured output allows the Agent to return results according to data structures defined by Pydantic, TypedDict, or JSON Schema, making it easy for programs to process them directly.
In LangChain 1.x, there are three main strategies for structured output: ToolStrategy, ProviderStrategy, and AutoStrategy.
This section introduces how they work, their parameter configuration, compatibility, error handling, and how to choose among them.
1. Three Structured Output Strategies
The main differences among the three strategies are: through which mechanism the structured data is generated, and who is responsible for ensuring the output conforms to the Schema.
| Strategy | How It Works | Usage conditions | Main Features |
|---|---|---|---|
ToolStrategy |
Use the model's Tool Calling to generate structured data | The model supports tool calling | Supports structured output error feedback and retry |
ProviderStrategy |
Use the model provider's native structured output mechanism | The model and provider support native structured output | Can leverage the provider's Schema constraint capabilities |
AutoStrategy |
Select a strategy based on model capability information | Model capability information can be correctly identified | Reduces the work of manually selecting a strategy |
Basic usage:
# 使用 ToolStrategy
response_format=ToolStrategy(CourseInfo)
# Using ProviderStrategy
response_format=ProviderStrategy(CourseInfo)
# Auto-select
response_format=CourseInfo
It is generally recommended to pass the Schema directly first. If you need explicit control over the structured output mechanism, then manually specify ToolStrategy or ProviderStrategy.
**Note:** The three strategies are not a fixed performance ranking. Actual request latency, Token consumption, and stability depend on the model, Schema, API, and whether retries occur.
2. Installation and Environment Setup
Install LangChain and related dependencies:
pip install -U langchain langchain-deepseek python-dotenv pydantic
Create in the project directory .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
to load environment variables:
from dotenv import load_dotenv
load_dotenv()
In this tutorial, ToolStrategy and the automatic strategy are mainly demonstrated using DeepSeek Flash.
Note that whether the DeepSeek model supports native Schema constraints should be determined by actual service capabilities; you cannot simply assume it supports ProviderStrategy.
3. ToolStrategy: Outputting Data via Tool Calls
ToolStrategy Use the model's Tool Calling capability to achieve structured output.
LangChain converts the Schema into a tool definition for structured responses, letting the model generate data that meets the tool's parameter requirements.
The tool here is mainly responsible for expressing the output structure; it does not mean an external API or Python business function is actually executed.
The execution process can be understood as follows:
用户输入
↓
模型接收结构化输出 Schema
↓
模型生成 Tool Call
↓
LangChain 解析并验证参数
↓
structured_response
Example: Extracting a Weather Description
Below we extract the city, temperature, weather condition, and humidity from a user-provided weather description.
All information comes from the input text; no real weather service is called.
Example
from
dotenv
import
load_dotenv
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
structured_output
import
ToolStrategy
load_dotenv
(
)
class
WeatherReport
(
BaseModel
)
:
"""Extract weather information from text."""
city:
str
=
Field
(
description
=
"City name"
)
temperature:
float
=
Field
(
description
=
"Temperature in Celsius"
)
condition:
str
=
Field
(
description
=
"Weather condition"
)
humidity:
int
=
Field
(
ge
=
0
,
le
=
100
,
description
=
"Humidity percentage"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
response_format
=
ToolStrategy
(
WeatherReport
)
,
system_prompt
=
"Only extract weather data explicitly provided in the user's description; do not query or fabricate real-time weather."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hangzhou is sunny, temperature 25 degrees, humidity 60%."
}
]
}
)
report
=
result
[
"structured_response"
]
(
report.
model_dump
(
)
)
On successful execution, the result may be:
{
'city': '杭州',
'temperature': 25.0,
'condition': '晴天',
'humidity': 60
}
Since a Pydantic model is passed in, after successful parsing you can access fields via attributes:
print(report.city)
print(report.temperature)
print(report.humidity)
Wherehumidity Use ge=0 and le=100 Constrain the humidity range.
4. Viewing ToolStrategy's Message Process
When using ToolStrategy, the model typically generates a structured output Tool Call.
You can inspect the actual execution through the message history.
Example
for
msg
in
result
[
"messages"
]
:
if
msg.
type
==
"ai"
and
msg.
tool_calls
:
(
"Structured call:"
,
[
(
c
[
"name"
]
,
c
[
"args"
]
)
for
c
in
msg.
tool_calls
]
)
elif
msg.
type
==
"tool"
:
(
"Tool message:"
,
msg.
content
)
else
:
(
"Message type:"
,
msg.
type
)
(
"Total messages:"
,
len
(
result
[
"messages"
]
)
)
If the model generates correct structured data on the first try, you may see:
消息类型: human
结构化调用: [('WeatherReport', {...})]
工具消息: Returning structured response: ...
消息总数: 3
**Note:** Do not hardcode the message count as 4.
For a successful ToolStrategy structured response, it may contain only the user message, an AIMessage with a Tool Call, and the corresponding ToolMessage.
If the model generates invalid data, LangChain may feed back an error and request the model again, increasing the message count.
Likewise, ToolStrategy does not necessarily mean an extra model API call every time. The tool call request itself can be generated by a single model response.
5. ToolStrategy's handle_errors Parameter
ToolStrategy Supports handling structured output errors such as missing fields, out-of-range values, Schema validation failures, and the model erroneously producing multiple structured outputs.
The default value of handle_errors is True.
That is, by default, LangChain tries to feed supported structured output errors back to the model so it can regenerate data that meets the requirements.
| Configure | Purpose |
|---|---|
True |
Use the default error prompt, allowing the model to attempt a correction |
False |
Do not perform this strategy's automatic error recovery; let the exception propagate |
| String | Use a specified fixed error prompt |
| Exception type | Handle only specified exception types |
| A tuple of exception types | Handle the specified multiple exception types |
| Callable | Call a custom function to generate the error prompt |
Example: Using Default Error Handling
Example
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
.
structured_output
import
ToolStrategy
class
ProductRating
(
BaseModel
)
:
"""Product rating."""
rating:
int
=
Field
(
ge
=
1
,
le
=
5
)
comment:
str
strategy
=
ToolStrategy
(
schema
=
ProductRating
,
handle_errors
=
True
)
If the model outputs rating=10validation will fail, and LangChain can feed the error back to the model so it can try to fix it.
But the model does not necessarily succeed in fixing it every time.
Example: Custom Error Prompt
Example
strategy
=
ToolStrategy
(
schema
=
ProductRating
,
handle_errors
=
"The rating must be between 1 and 5, and a review must be provided."
)
The string here is used as a fixed error prompt.
**Note:** Do not write it as:
handle_errors="格式有误:{error}"
and then assume LangChain will automatically {error} replace it with the specific exception.
If you need to generate a prompt based on the error content, you should pass a Callable.
Example: Custom Error Handling Function
Example
from
langchain.
agents
.
structured_output
import
(
ToolStrategy
,
StructuredOutputValidationError
,
MultipleStructuredOutputsError
)
def
handle_format_error
(
error:
Exception
)
str
:
if
isinstance
(
error
,
StructuredOutputValidationError
)
:
return
"The field format or value does not meet the requirements; please correct it and output again."
if
isinstance
(
error
,
MultipleStructuredOutputsError
)
:
return
"Only one structured result may be returned; please choose the one that best fits the task."
return
"Structured output failed; please check the format."
strategy
=
ToolStrategy
(
ProductRating
,
handle_errors
=
handle_format_error
)
In actual use, you can pass strategy to create_agent(response_format=strategy)。
Note that structured output retry is not the same as retry after a normal tool execution failure, nor is it the same as automatic API retry after a network request failure.
6. tool_message_content: Customizing Tool Messages
ToolStrategy also has a useful parameter:
tool_message_content
It can set the content of the ToolMessage added to the message history after successful structured output.
Example
Example
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
response_format
=
ToolStrategy
(
schema
=
WeatherReport
,
tool_message_content
=
"Weather description extracted successfully."
)
)
In this way, after successful structured output, the corresponding tool message can be displayed as:
天气描述已成功提取。
This parameter only changes the text of the tool message; it does not replace or modify the final structured_response data object.
7. ProviderStrategy: Using Native Structured Output
ProviderStrategy Use the native structured output interface provided by the model service provider.
For example, some OpenAI, Anthropic, Google, and xAI models support constraining the output structure through provider capabilities.
This approach can usually leverage the provider's own Schema constraint mechanism.
But you cannot simply assume all versions of a model family support it, nor can you guarantee that ProviderStrategy is faster than ToolStrategy in all cases.
Example: Using a Model That Supports Native Structured Output
The following uses an OpenAI-compatible example. Before running, you need to install langchain-openai and configure the corresponding API Key.
Example
from
typing
import
Literal
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
structured_output
import
ProviderStrategy
class
CourseInfo
(
BaseModel
)
:
"""Course information."""
name:
str
level: Literal
[
"Beginner"
,
"Intermediate"
,
"Advanced"
]
price:
str
=
Field
(
description
=
"The price or payment method explicitly described by the user"
)
agent
=
create_agent
(
model
=
"openai:gpt-4o"
,
tools
=
[
]
,
response_format
=
ProviderStrategy
(
CourseInfo
)
,
system_prompt
=
"Only extract course information explicitly provided by the user."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"The Python3 Basics Tutorial is an introductory free course."
}
]
}
)
course
=
result
[
"structured_response"
]
(
course.
model_dump
(
)
)
On successful execution, the result may be:
{
'name': 'Python3 基础教程',
'level': '入门',
'price': '免费'
}
This is the calling approach used when native structured output is explicitly supported.
**Note:** If you use another provider or model, you should first check its native structured output support.
The strict Parameter
ProviderStrategy supports an optional strict Parameters:
response_format=ProviderStrategy(
CourseInfo,
strict=True
)
but strict=True This requires the corresponding model provider to support strict Schema constraints; not all models support it.
If the server does not accept the corresponding setting, it may directly return an API error.
8. Is ProviderStrategy Necessarily Faster Than ToolStrategy?
Not necessarily.
ProviderStrategy does not need to represent structured output as a Tool Calling request, but this does not mean it necessarily reduces network requests or achieves lower latency.
In a single successful call, ToolStrategy can also generate complete structured data through one model response.
Actual performance depends on:
- Model generation speed and response latency.
- The complexity of the Schema.
- Whether multiple rounds of tool calls are needed.
- The number of retries after structured output failures.
- The model provider and network environment.
Therefore, you should measure with real requests rather than judging solely by the message count.
Which metrics should performance comparison look at?
| Pointer | Description |
|---|---|
| Request latency | The time from start to finish of one Agent call |
| Number of model calls | The actual number of requests to the model API |
| Token consumption | Number of input and output Tokens |
| Schema success rate | The proportion of outputs that pass data validation |
| Number of retries | The number of re-requests after structured output errors |
If your business is very sensitive to cost and latency, it is recommended to use the same model, Schema, and test data to compare different strategies multiple times.
9. AutoStrategy: Automatically Selecting a Structured Output Strategy
LangChain provides AutoStrategyfor automatically selecting a structured output approach based on model capabilities.
But in regular development, you do not need to explicitly create AutoStrategy.
You only need to pass the Pydantic model directly to response_format .
Example: Course Review Analysis
Example
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
class
Analysis
(
BaseModel
)
:
"""Course review analysis."""
summary:
str
=
Field
(
description
=
"Brief summary"
)
score:
int
=
Field
(
ge
=
1
,
le
=
10
,
description
=
"Rating from 1 to 10"
)
pros:
list
[
str
]
=
Field
(
description
=
"Pros"
)
cons:
list
[
str
]
=
Field
(
description
=
"Cons"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
response_format
=
Analysis
,
system_prompt
=
"Analyze only based on the review provided by the user; do not add facts that were not provided."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"This Python tutorial is systematic with many examples, but has relatively few advanced topics."
}
]
}
)
analysis
=
result
[
"structured_response"
]
(
"Summary:"
,
analysis.
summary
)
(
"Rating:"
,
analysis.
score
)
(
"Pros:"
,
analysis.
pros
)
(
"Cons:"
,
analysis.
cons
)
The model may return:
总结:内容系统、示例较多,但高级专题相对有限
评分:8
优点:['内容系统', '示例丰富']
不足:['高级专题相对较少']
Note that the rating is a subjective judgment made by the model based on the user's description, not a quality score obtained through objective testing.
How Does the Automatic Strategy Choose?
It generally follows these ideas:
response_format=Analysis
|
v
读取模型能力信息
|
+-- 支持原生结构化输出
| |
| v
| ProviderStrategy
|
+-- 不支持或未识别
|
v
ToolStrategy
LangChain can determine whether native structured output is supported based on the model's Profile information.
However, Profile information may be missing or not fully consistent with actual API capabilities, so automatic selection does not guarantee success or optimal performance.
10. Checking Model Capabilities via model.profile
In LangChain 1.x, a model object can provide Profile information describing the features supported by the current model.
For example:
Example
from
langchain.
chat_models
import
init_chat_model
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
profile
=
model.
profile
or
{
}
(
"Native structured output:"
,
profile
.
get
(
"structured_output"
)
)
(
"Tool calls:"
,
profile
.
get
(
"tool_calling"
)
)
If the Profile returns:
structured_output: True
it usually means LangChain's model metadata considers the model to have native structured output capability.
If False or Noneyou cannot directly assert that all structured output methods are unavailable, because ToolStrategy may still be usable.
**Note:** Profile is reference capability information and does not replace real request testing.
11. Choosing Between ToolStrategy and ProviderStrategy
You can choose a structured output strategy based on actual model capabilities and business needs.
| Scenario | Recommended approach | Reason |
|---|---|---|
| General structured output | Pass the Pydantic Schema directly | Let LangChain choose automatically |
| Explicitly need tool calling mode | ToolStrategy | Explicitly use Tool Calling |
| Need to handle Schema errors and retry | ToolStrategy | Provide handle_errors |
| The model explicitly supports native structured output | ProviderStrategy | Use the provider's native Schema mechanism |
| Emphasis on complex data validation | Pydantic Schema | Supports field ranges and custom validators |
| Pursuing low latency and cost | Actual benchmarking | Different models and tasks perform differently |
You can usually start with the automatic strategy; if output validation fails frequently, then consider explicitly using ToolStrategy for error recovery.
If the model provider explicitly supports strict native structured output, you can further test ProviderStrategy.
12. Notes on JSON Schema and Strategies
Besides Pydantic, LangChain also supports using JSON Schema dictionaries to define output structures.
However, JSON Schema dictionaries are handled differently from Pydantic classes.
When using a JSON Schema dictionary, you should explicitly wrap it in a strategy object:
Example
from
langchain.
agents
.
structured_output
import
ToolStrategy
course_schema
=
{
"title"
:
"CourseInfo"
,
"description"
:
"Course information"
,
"type"
:
"object"
,
"properties"
:
{
"name"
:
{
"type"
:
"string"
}
,
"hours"
:
{
"type"
:
"integer"
,
"minimum"
:
1
}
}
,
"required"
:
[
"name"
,
"hours"
]
}
strategy
=
ToolStrategy
(
course_schema
)
**Note:** When ToolStrategy uses a raw JSON Schema dictionary, LangChain does not perform full client-side Schema validation as it does with Pydantic models.
Therefore, you cannot rely solely on minimum and similar fields to conclude that the program has validated the actual result.
If you need strict Python-side field validation, cross-field validation, and error retry, it is recommended to prefer Pydantic.
13. Complete Example: Dynamically Selecting an Output Strategy
Below we implement a course review analysis tool that can choose between the automatic strategy and ToolStrategy based on configuration.
To ensure example model compatibility, we do not force DeepSeek to be configured as ProviderStrategy here.
Filename:output_strategy_demo.py
Complete example
from
typing
import
Literal
from
dotenv
import
load_dotenv
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
structured_output
import
ToolStrategy
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
class
ReviewResult
(
BaseModel
)
:
"""Tutorial review result."""
sentiment: Literal
[
"Positive"
,
"Negative"
,
"Neutral"
]
score:
int
=
Field
(
ge
=
1
,
le
=
10
)
advantages:
list
[
str
]
disadvantages:
list
[
str
]
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
profile
=
model.
profile
or
{
}
(
"Model native structured output support:"
,
profile
.
get
(
"structured_output"
)
)
def
build_agent
(
strategy:
str
=
"auto"
)
:
response_format
=
ReviewResult
if
strategy
==
"auto"
else
ToolStrategy
(
ReviewResult
,
handle_errors
=
True
)
return
create_agent
(
model
=
model
,
response_format
=
response_format
,
system_prompt
=
"Only extract information from the tutorial review provided by the user. The rating is a subjective judgment, not an objective assessment."
)
agent
=
build_agent
(
"tool"
)
Change to "auto" to test the automatic strategy
try
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"This Python tutorial is clear and rich in examples, but some advanced topics are less covered."
}
]
}
,
config
=
{
"recursion_limit"
:
15
}
)
review
=
result
[
"structured_response"
]
(
"Sentiment:"
,
review.
sentiment
)
(
"Rating:"
,
review.
score
)
(
"Pros:"
,
review.
advantages
)
(
"Drawbacks:"
,
review.
disadvantages
)
(
"Number of model messages:"
,
sum
(
m.
type
==
"ai"
for
m
in
result
[
"messages"
]
)
)
except
Exception
as
error:
(
"Structured output failed:"
,
type
(
error
)
.name
)
Here you can modify:
build_agent("auto")
build_agent("tool")
to compare the automatic strategy with explicit ToolStrategy.
But this is only a functional demonstration. If you need a rigorous performance comparison, you should use the same test set and record actual API latency, Token consumption, and structured output success rate.
14. Frequently Asked Questions
1. Does AutoStrategy need to be created manually?
Generally no. Pass Pydantic, TypedDict, or other supported Schema types directly to response_format .
2. Is ToolStrategy supported by all models?
No. It depends on the model and the corresponding integration supporting Tool Calling.
3. Does ToolStrategy necessarily make one extra model call?
Not necessarily. A single model response may already contain the structured output Tool Call.
Only if error retry is needed may the number of model calls increase.
4. What is the default value of handle_errors?
The current official ToolStrategy default is True。
5. Is ProviderStrategy necessarily faster than ToolStrategy?
Not necessarily. You need to test it in combination with the model, the request, and the actual network environment.
6. Does it automatically fall back when ProviderStrategy is not supported?
No such guarantee can be made for all models and integrations.
If you want LangChain to choose automatically based on model capabilities, pass the Schema type directly; before explicitly using ProviderStrategy, you should first verify model support.
7. Why does the ProviderStrategy call fail?
It may be that the current model does not support native structured output, or the provider does not support the current Schema, the strict parameter, or the relevant API configuration.
8. How to check whether a model supports native structured output?
You can check model.profile The structured_output information, combined with actual API testing.
9. Can ToolStrategy customize tool messages?
Yes, via tool_message_content to configure the tool message text after successful structured output.
10. Is JSON Schema equivalent to Pydantic validation?
No. For a raw JSON Schema dictionary with ToolStrategy, you cannot assume LangChain performs the same client-side validation as Pydantic.
11. Can structured output be used together with ordinary tools?
Yes, but the model must support using ordinary tools together with the chosen structured output mechanism.
12. Why doesn't structured_response exist?
It may be that response_formatwas not configured, or the model did not successfully complete the structured output process.
Summary
LangChain 1.x manages Agent structured output mainly through three strategies.
ToolStrategy: Use Tool Calling to generate structured data, supporting output validation error feedback and retry.ProviderStrategy: Use the model provider's native structured output capability.AutoStrategy: Select an appropriate strategy based on model capabilities, usually just by passing the Schema directly.
The most commonly used form is:
agent = create_agent(
model="deepseek:deepseek-flash",
response_format=CourseInfo
)
result = agent.invoke({
"messages": [{"role": "user", "content": "提取课程信息"}]
})
data = result["structured_response"]
If you need to explicitly use tool calling mode:
response_format=ToolStrategy(
CourseInfo,
handle_errors=True
)
If the current model explicitly supports native structured output:
response_format=ProviderStrategy(CourseInfo)
**Core principle:** Prefer the automatic strategy for ordinary scenarios; use ToolStrategy when you need explicit control over error handling; consider ProviderStrategy only after confirming the model has native structured output capability.
Do not judge performance solely by the message count, and do not equate Schema-conforming output directly with real, reliable business data.