LangChain 输出策略
核对 LangChain 1.4.9 三大结构化输出策略(ToolStrategy、ProviderStrategy、AutoStrategy)的底层路由、model.profile 判定、消息条数真相、handle_errors 六种配置与 {error} 非插值陷阱、tool_message_content 及 JSON Schema 客户端校验局限。
学完这一章,你能够
- 核对 LangChain 1.4.9 三大结构化输出策略(ToolStrategy、ProviderStrategy、AutoStrategy)的底层路由、model.profile 判定、消息条数真相、handle_errors 六种配置与 {error} 非插值陷阱、tool_message_content 及 JSON Schema 客户端校验局限。
三大结构化输出策略总览与运行前提
在 LangChain 1.x 中,Agent 结构化输出由 ToolStrategy、ProviderStrategy 与 AutoStrategy 三种策略协同承担(机制与特点见下表)。常规开发优先直接向 response_format 传入 Schema 交由自动策略选择;需精细控制纠错重试或明确锁定原生约束时再显式指定策略。切记三者并无固定速度榜单,真实延迟、Token 与稳定性取决于模型、Schema 复杂度及是否触发重试。
在线调用 DeepSeek 等模型前须安装对应集成包并经 .env 加载密钥;同时不要默认任意模型支持服务端原生 Schema 约束,使用 ProviderStrategy 前务必核实服务商实际端点能力。
ToolStrategy 机制、消息数真相、handle_errors 与 tool_message_content
ToolStrategy 把输出 Schema 转为结构化响应工具协议供模型生成 Tool Call(仅承载数据结构,非业务 API 调用)。本站实测 WeatherReport(含 humidity: Field(ge=0, le=100)):单轮一次成功时,仅调用模型 1 次,消息历史精确为 **3 条** ['human', 'ai', 'tool'](并非固定 4 条,也不必然多发一次模型请求);只有触发校验失败并进入自动纠错重试时,模型调用次数与消息数才会增加(如 1 次重试后增至 5 条消息、2 次模型调用)。
ToolStrategy.handle_errors 默认值为 True,涵盖六种配置(详见下表)。本站在 langchain 1.4.9 逐一实测:(1)默认 True 在 rating=10 越界后反馈纠错,2 次调用成功收敛为 rating=4;(2)False 直接抛出 StructuredOutputValidationError;(3)传入字符串 '格式有误:{error}' 时,发回模型的工具消息原样保留字面量 '格式有误:{error}'——证实框架**不会**自动插值 {error},需按异常详情定制提示必须传 Callable;(4)仅传异常类 StructuredOutputValidationError 时,遇双结构化调用仍让 MultipleStructuredOutputsError 向外抛出;(5)传入 Callable 回调准确识别 MultipleStructuredOutputsError 并返回“只能返回一种结构化结果。”促成第 2 轮成功。注意结构化重试独立于普通工具异常和网络 API 重试。
通过 tool_message_content 可定制结构化输出成功后写入消息历史的 ToolMessage 文本。本站实测设置 tool_message_content='天气描述已成功提取。' 后,末条 ToolMessage.content 变为该自定义文案,而 result['structured_response'] 数据对象保持完全一致不受影响。
ProviderStrategy、性能基准指标与 AutoStrategy 路由
ProviderStrategy 直接依托支持原生结构化输出的服务商(如部分 OpenAI、Anthropic、Google、xAI 模型)在服务端约束格式,支持可选 strict=True 参数(服务端不支持时可能直接报 API 错误)。本站实测 ProviderStrategy(CourseInfo) 默认 schema_spec.strict 为 None,传入 strict=True 后为 True;在声明支持原生结构化输出的离线模型上运行时绑定工具数为 0,仅需 ['human', 'ai'] 两消息即完成解析。
ProviderStrategy 并不一定比 ToolStrategy 更快:ToolStrategy 单次成功同样只需 1 次模型请求,真正决定时延与成本的是模型推理速度、Schema 复杂度、工具轮次、重试率与网络状况。严谨选型应以相同测试集测量请求耗时、模型调用次数、Token 消耗、Schema 成功率与重试次数五项指标(见指标表)。
日常直接写 response_format=Analysis 即可触发自动选择(等价于 AutoStrategy(Analysis)),框架通过读取 model.profile.get('structured_output') 决定路由。本站实测三组对照完美还原 LangChain 1.4.9 路由逻辑:(1)profile={'structured_output': True} 时走原生 ProviderStrategy(bound_tools=0,消息 ['human', 'ai']);(2)profile={'structured_output': False} 时走 ToolStrategy(bound_tools=1,消息 ['human', 'ai', 'tool']);(3)profile={} 缺失元数据时安全回退至 ToolStrategy(bound_tools=1)。须注意 profile 仅为能力元数据参考,返回 False/None 不代表 ToolStrategy 不可用,也不能替代真实请求验证。
策略选型、JSON Schema 局限、动态构建与常见问题
实际选型可对照场景建议表:常规先用自动策略,需精细错误恢复显式选 ToolStrategy,确认服务端支持原生严格约束再测 ProviderStrategy。当 Schema 以原始 JSON Schema 字典形式传给 ToolStrategy 时,本站再次实测证实:尽管声明了 'minimum': 1,传入 hours=-5 仍原样通过未抛错,因此需要本地字段校验与跨字段验证器时应优先采用 Pydantic。
在动态策略构建示例(output_strategy_demo.py)中,build_agent('auto') 与 build_agent('tool') 可按配置切换自动策略或显式 ToolStrategy。本站离线实测两种路径在单次成功提取 ReviewResult 时 AI 消息数均为 1,结构化评价字段完全一致(需提醒模型生成的评价分数属主观判断,非客观基准)。
常见问题梳理:一般无需手动实例化 AutoStrategy;ToolStrategy 依赖模型支持 Tool Calling 且不保证多调一次模型;handle_errors 默认 True;显式指定 ProviderStrategy 在不支持的端点不会保证自动降级,需先核对 model.profile 与实测端点;tool_message_content 仅改工具消息文案;原始 JSON Schema 字典不等同 Pydantic 客户端校验;结构化输出可与普通工具共存但须模型兼容。归根结底:不凭消息数臆断性能,也不把合法 Schema 输出直接等同真实业务事实。
LangChain 三大结构化输出策略对比
| 策略 | 工作原理 | 使用条件 | 主要特点 |
| ToolStrategy | 把 Schema 转为工具定义,借 Tool Calling 输出并校验。 | 模型及集成支持工具调用。 | 支持 handle_errors 自动纠错重试与自定义 tool_message_content。 |
| ProviderStrategy | 调用模型服务商原生结构化输出接口。 | 模型、端点与集成明确支持原生 Schema 约束。 | 可传递 strict=True 利用服务端约束,不占用工具绑定。 |
| AutoStrategy | 读取 model.profile['structured_output'] 自动在两者间路由。 | 模型 Profile 元数据准确(缺失时回退 ToolStrategy)。 | 直接传 Schema 类型即可触发,免去手动判断。 |
ToolStrategy.handle_errors 六种配置行为
| 配置 | 作用 |
| True | 默认启用:使用内置错误提示反馈模型尝试修正。 |
| False | 禁用自动恢复,直接抛出 StructuredOutputValidationError 等异常。 |
| 字符串 | 向模型返回固定字面量提示(实测不会自动替换 {error} 占位符)。 |
| 异常类型 | 仅捕获并反馈该指定异常类,其余异常继续向外抛出。 |
| 异常类型元组 | 捕获并反馈元组中列出的多个结构化输出异常类。 |
| Callable | 将异常实例传入回调函数,按类型动态生成精准纠错提示。 |
结构化输出策略性能对比核心指标
| 指标 | 说明 |
| 请求耗时 | 单次 Agent 调用从发起至拿到 structured_response 的端到端时延。 |
| 模型调用次数 | 一次任务中实际请求语言模型 API 的总轮数(实测单次成功均为 1)。 |
| Token 消耗 | 包含 Schema 定义、重试上下文在内的总输入与输出 Token。 |
| Schema 成功率 | 测试集上最终通过数据校验并产出有效结构化对象的比例。 |
| 重试次数 | 因校验失败或多输出错误触发 ToolStrategy 二次请求的次数。 |
业务场景与结构化输出策略选型建议
| 场景 | 建议方案 | 原因 |
| 一般结构化输出 | 直接传入 Pydantic Schema。 | 由 LangChain 依据 model.profile 自动择优,代码最简。 |
| 明确需要工具调用模式 | 显式使用 ToolStrategy。 | 锁定 Tool Calling 路径,跨厂商行为可预期。 |
| 需要处理 Schema 错误并重试 | 显式使用 ToolStrategy。 | 提供六种 handle_errors 精细纠错恢复配置。 |
| 模型明确支持原生结构化输出 | 显式测试 ProviderStrategy。 | 可结合 strict=True 发挥服务商原生约束能力。 |
| 强调复杂数据验证 | 使用 Pydantic BaseModel。 | 支持范围约束、自定义验证器,弥补原始 JSON Schema 字典无本地校验的短板。 |
| 追求低延迟与成本 | 执行同集基准实测。 | 耗时与 Token 受模型、Schema 与重试率共同影响,不可凭策略名猜测。 |
离线实测 ToolStrategy 3 消息机制、handle_errors 六模式与非插值验证、ProviderStrategy strict 及 AutoStrategy profile 路由
展开查看收起
"""Offline deterministic runtime lab for LangChain Chapter 20 (structured-output-strategies)."""
import json
import platform
from typing import Any, Literal
from langchain.agents import create_agent
from langchain.agents.structured_output import (
AutoStrategy,
MultipleStructuredOutputsError,
ProviderStrategy,
StructuredOutputValidationError,
ToolStrategy,
)
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, BaseMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from pydantic import BaseModel, Field
class ScriptedChatModel(BaseChatModel):
responses: list[AIMessage] = Field(default_factory=list)
call_index: int = 0
bound_tool_count: int = 0
@property
def _llm_type(self) -> str:
return "scripted-offline-strategies"
def bind_tools(self, tools, **kwargs):
self.bound_tool_count = len(list(tools))
return self
def _generate(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: Any = None,
**kwargs: Any,
) -> ChatResult:
idx = min(self.call_index, len(self.responses) - 1)
self.call_index += 1
return ChatResult(generations=[ChatGeneration(message=self.responses[idx])])
def case_tool_strategy_messages_and_custom_tool_message() -> dict:
class WeatherReport(BaseModel):
"""从文本中提取天气信息。"""
city: str = Field(description="城市名称")
temperature: float = Field(description="摄氏温度")
condition: str = Field(description="天气状况")
humidity: int = Field(ge=0, le=100, description="湿度百分比")
m_default = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "WeatherReport",
"args": {"city": "杭州", "temperature": 25.0, "condition": "晴天", "humidity": 60},
"id": "w1",
"type": "tool_call",
}
],
)
]
)
r_def = create_agent(
model=m_default,
tools=[],
response_format=ToolStrategy(WeatherReport),
).invoke({"messages": [{"role": "user", "content": "杭州晴天,温度25度,湿度60%。"}]})
m_custom = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "WeatherReport",
"args": {"city": "杭州", "temperature": 25.0, "condition": "晴天", "humidity": 60},
"id": "w2",
"type": "tool_call",
}
],
)
]
)
r_cust = create_agent(
model=m_custom,
tools=[],
response_format=ToolStrategy(WeatherReport, tool_message_content="天气描述已成功提取。"),
).invoke({"messages": [{"role": "user", "content": "杭州晴天,温度25度,湿度60%。"}]})
actual = {
"default_model_calls": m_default.call_index,
"default_msg_count": len(r_def["messages"]),
"default_msg_types": [x.type for x in r_def["messages"]],
"default_structured": r_def["structured_response"].model_dump(),
"custom_tool_msg_content": r_cust["messages"][-1].content,
"custom_structured_unchanged": r_cust["structured_response"].model_dump()
== r_def["structured_response"].model_dump(),
}
expected = {
"default_model_calls": 1,
"default_msg_count": 3,
"default_msg_types": ["human", "ai", "tool"],
"default_structured": {"city": "杭州", "temperature": 25.0, "condition": "晴天", "humidity": 60},
"custom_tool_msg_content": "天气描述已成功提取。",
"custom_structured_unchanged": True,
}
return {
"name": "tool_strategy_messages_and_custom_tool_message",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_handle_errors_variants() -> dict:
class ProductRating(BaseModel):
rating: int = Field(ge=1, le=5)
comment: str
bad_call = AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 10, "comment": "越界"}, "id": "b1", "type": "tool_call"}
],
)
good_call = AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 4, "comment": "好评"}, "id": "g1", "type": "tool_call"}
],
)
dup_call = AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 4, "comment": "A"}, "id": "d1", "type": "tool_call"},
{"name": "ProductRating", "args": {"rating": 5, "comment": "B"}, "id": "d2", "type": "tool_call"},
],
)
# 1) default True -> retries and succeeds
m_true = ScriptedChatModel(responses=[bad_call, good_call])
r_true = create_agent(model=m_true, tools=[], response_format=ToolStrategy(ProductRating)).invoke(
{"messages": [{"role": "user", "content": "评分"}]}
)
# 2) False -> raises StructuredOutputValidationError
m_false = ScriptedChatModel(responses=[bad_call])
false_err = None
try:
create_agent(
model=m_false, tools=[], response_format=ToolStrategy(ProductRating, handle_errors=False)
).invoke({"messages": [{"role": "user", "content": "评分"}]})
except StructuredOutputValidationError as exc:
false_err = type(exc).__name__
# 3) literal str -> does NOT interpolate {error}
m_str = ScriptedChatModel(responses=[bad_call, good_call])
r_str = create_agent(
model=m_str,
tools=[],
response_format=ToolStrategy(ProductRating, handle_errors="格式有误:{error}"),
).invoke({"messages": [{"role": "user", "content": "评分"}]})
str_feedback = next(x.content for x in r_str["messages"] if isinstance(x, ToolMessage))
# 4) exception type -> catches ValidationError, lets MultipleStructuredOutputsError propagate
m_exc = ScriptedChatModel(responses=[dup_call])
unhandled_dup = None
try:
create_agent(
model=m_exc,
tools=[],
response_format=ToolStrategy(ProductRating, handle_errors=StructuredOutputValidationError),
).invoke({"messages": [{"role": "user", "content": "评分"}]})
except MultipleStructuredOutputsError as exc:
unhandled_dup = type(exc).__name__
# 5) Callable -> distinguishes error types
def handle_format_error(error: Exception) -> str:
if isinstance(error, StructuredOutputValidationError):
return "字段格式或取值不符合要求,请修正。"
if isinstance(error, MultipleStructuredOutputsError):
return "只能返回一种结构化结果。"
return "未知结构化错误。"
m_cb = ScriptedChatModel(responses=[dup_call, good_call])
r_cb = create_agent(
model=m_cb,
tools=[],
response_format=ToolStrategy(ProductRating, handle_errors=handle_format_error),
).invoke({"messages": [{"role": "user", "content": "评分"}]})
cb_feedback = next(x.content for x in r_cb["messages"] if isinstance(x, ToolMessage))
actual = {
"default_retry_calls": m_true.call_index,
"default_retry_msg_count": len(r_true["messages"]),
"default_retry_rating": r_true["structured_response"].rating,
"false_raises": false_err,
"str_not_interpolated": str_feedback,
"typed_handler_propagates_dup": unhandled_dup,
"callable_dup_feedback": cb_feedback,
"callable_final_rating": r_cb["structured_response"].rating,
}
expected = {
"default_retry_calls": 2,
"default_retry_msg_count": 5,
"default_retry_rating": 4,
"false_raises": "StructuredOutputValidationError",
"str_not_interpolated": "格式有误:{error}",
"typed_handler_propagates_dup": "MultipleStructuredOutputsError",
"callable_dup_feedback": "只能返回一种结构化结果。",
"callable_final_rating": 4,
}
return {
"name": "handle_errors_variants",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_provider_strategy_and_strict_flag() -> dict:
class CourseInfo(BaseModel):
name: str
level: Literal["入门", "进阶", "高级"]
price: str
s_default = ProviderStrategy(CourseInfo)
s_strict = ProviderStrategy(CourseInfo, strict=True)
m_native = ScriptedChatModel(
profile={"structured_output": True, "tool_calling": True},
responses=[AIMessage(content='{"name": "Python3 基础教程", "level": "入门", "price": "免费"}')],
)
res = create_agent(model=m_native, tools=[], response_format=s_strict).invoke(
{"messages": [{"role": "user", "content": "提取课程资料"}]}
)
actual = {
"default_strict": s_default.schema_spec.strict,
"explicit_strict": s_strict.schema_spec.strict,
"bound_tool_count": m_native.bound_tool_count,
"msg_types": [x.type for x in res["messages"]],
"structured": res["structured_response"].model_dump(),
}
expected = {
"default_strict": None,
"explicit_strict": True,
"bound_tool_count": 0,
"msg_types": ["human", "ai"],
"structured": {"name": "Python3 基础教程", "level": "入门", "price": "免费"},
}
return {
"name": "provider_strategy_and_strict_flag",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_auto_strategy_and_model_profile_routing() -> dict:
class Analysis(BaseModel):
summary: str
score: int = Field(ge=1, le=10)
pros: list[str]
cons: list[str]
payload = {
"summary": "内容系统、示例较多,但高级专题有限",
"score": 8,
"pros": ["内容系统", "示例丰富"],
"cons": ["高级专题相对较少"],
}
m_nat = ScriptedChatModel(
profile={"structured_output": True, "tool_calling": True},
responses=[AIMessage(content=json.dumps(payload, ensure_ascii=False))],
)
r_nat = create_agent(model=m_nat, tools=[], response_format=Analysis).invoke(
{"messages": [{"role": "user", "content": "分析评价"}]}
)
m_tool = ScriptedChatModel(
profile={"structured_output": False, "tool_calling": True},
responses=[
AIMessage(
content="",
tool_calls=[{"name": "Analysis", "args": payload, "id": "a1", "type": "tool_call"}],
)
],
)
r_tool = create_agent(model=m_tool, tools=[], response_format=AutoStrategy(Analysis)).invoke(
{"messages": [{"role": "user", "content": "分析评价"}]}
)
m_empty = ScriptedChatModel(
profile={},
responses=[
AIMessage(
content="",
tool_calls=[{"name": "Analysis", "args": payload, "id": "a2", "type": "tool_call"}],
)
],
)
r_empty = create_agent(model=m_empty, tools=[], response_format=Analysis).invoke(
{"messages": [{"role": "user", "content": "分析评价"}]}
)
actual = {
"native_profile_flag": (m_nat.profile or {}).get("structured_output"),
"native_bound_tools": m_nat.bound_tool_count,
"native_msg_types": [x.type for x in r_nat["messages"]],
"tool_profile_flag": (m_tool.profile or {}).get("structured_output"),
"tool_bound_tools": m_tool.bound_tool_count,
"tool_msg_types": [x.type for x in r_tool["messages"]],
"empty_profile_bound_tools": m_empty.bound_tool_count,
"empty_profile_msg_types": [x.type for x in r_empty["messages"]],
"all_scores_equal": (
r_nat["structured_response"].score
== r_tool["structured_response"].score
== r_empty["structured_response"].score
== 8
),
}
expected = {
"native_profile_flag": True,
"native_bound_tools": 0,
"native_msg_types": ["human", "ai"],
"tool_profile_flag": False,
"tool_bound_tools": 1,
"tool_msg_types": ["human", "ai", "tool"],
"empty_profile_bound_tools": 1,
"empty_profile_msg_types": ["human", "ai", "tool"],
"all_scores_equal": True,
}
return {
"name": "auto_strategy_and_model_profile_routing",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_json_schema_caveat_and_dynamic_builder() -> dict:
course_schema = {
"title": "CourseInfo",
"description": "课程信息",
"type": "object",
"properties": {
"name": {"type": "string"},
"hours": {"type": "integer", "minimum": 1},
},
"required": ["name", "hours"],
}
m_js = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{"name": "CourseInfo", "args": {"name": "Python", "hours": -5}, "id": "j1", "type": "tool_call"}
],
)
]
)
r_js = create_agent(model=m_js, tools=[], response_format=ToolStrategy(course_schema)).invoke(
{"messages": [{"role": "user", "content": "提取"}]}
)
class ReviewResult(BaseModel):
sentiment: Literal["积极", "消极", "中性"]
score: int = Field(ge=1, le=10)
advantages: list[str]
disadvantages: list[str]
def build_agent(model: BaseChatModel, strategy: str = "auto"):
rf = ReviewResult if strategy == "auto" else ToolStrategy(ReviewResult, handle_errors=True)
return create_agent(model=model, tools=[], response_format=rf)
sample = {
"sentiment": "积极",
"score": 8,
"advantages": ["内容清晰", "实例丰富"],
"disadvantages": ["高级主题覆盖较少"],
}
m_auto = ScriptedChatModel(
profile={"structured_output": True, "tool_calling": True},
responses=[AIMessage(content=json.dumps(sample, ensure_ascii=False))],
)
m_tool = ScriptedChatModel(
profile={"structured_output": False, "tool_calling": True},
responses=[
AIMessage(
content="",
tool_calls=[{"name": "ReviewResult", "args": sample, "id": "rv1", "type": "tool_call"}],
)
],
)
r_auto = build_agent(m_auto, "auto").invoke({"messages": [{"role": "user", "content": "分析评价"}]})
r_tool = build_agent(m_tool, "tool").invoke({"messages": [{"role": "user", "content": "分析评价"}]})
actual = {
"raw_json_schema_hours_not_validated": r_js["structured_response"]["hours"],
"auto_ai_msg_count": sum(x.type == "ai" for x in r_auto["messages"]),
"tool_ai_msg_count": sum(x.type == "ai" for x in r_tool["messages"]),
"auto_review": r_auto["structured_response"].model_dump(),
"tool_review": r_tool["structured_response"].model_dump(),
}
expected = {
"raw_json_schema_hours_not_validated": -5,
"auto_ai_msg_count": 1,
"tool_ai_msg_count": 1,
"auto_review": sample,
"tool_review": sample,
}
return {
"name": "json_schema_caveat_and_dynamic_builder",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def main() -> None:
cases = [
case_tool_strategy_messages_and_custom_tool_message(),
case_handle_errors_variants(),
case_provider_strategy_and_strict_flag(),
case_auto_strategy_and_model_profile_routing(),
case_json_schema_caveat_and_dynamic_builder(),
]
print(
json.dumps(
{
"version": platform.python_version(),
"system": platform.system(),
"cases": cases,
},
ensure_ascii=False,
indent=2,
)
)
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
在 LangChain 1.x 实现中,传入字符串型 `handle_errors` 会作为固定错误提示原样发给模型,框架不对其进行 `.format()` 字符串插值;只有传入接收 `Exception` 参数的 `Callable` 回调函数,才能依据异常类型和详情动态构造纠错提示。