Agent 结构化输出的四种宏观策略(ProviderStrategy / ToolStrategy / AutoStrategy / None)及其适用场景与选择原则。
- 概念说明:两者针对不同层级——模型层使用
with_structured_output(),Agent 层使用 response_format 参数。 - 关键细节:
| 维度 | 模型结构化输出 | Agent 结构化输出 |
|---|
| 作用对象 | 大模型对象 | Agent 实例 |
| 解析时机 | 生成 AIMessage 时 | 任务结束时 |
| 绑定方式 | model.with_structured_output() | create_agent(response_format=...) |
| 结果位置 | 直接在 AIMessage 中 | response["structured_response"] |
- 概念说明:
response_format 参数支持四种策略,适配不同模型的能力。
| 策略 | 说明 | 适用场景 |
|---|
ProviderStrategy | 使用模型提供商原生结构化输出 API(如 OpenAI、Anthropic Claude、Grok) | 仅限原生支持的模型 |
ToolStrategy | 通过工具调用机制模拟结构化输出(发一个"伪工具"给模型) | 所有支持 function calling 的模型(推荐) |
AutoStrategy | 自动选择策略:原生支持则用 Provider,否则降级为 Tool | 不确定模型能力时使用 |
None | 不设置结构化输出,模型以自然语言响应 | 不需要结构化输出的场景 |
- 关键细节:
ToolStrategy 底层原理:将结构化输出 schema 包装为一个虚拟工具调用,模型 "调用" 该工具即完成结构化输出。- 由于当前几乎所有模型都支持工具调用,
ToolStrategy 具备普遍适用性。 AutoStrategy 在官方文档中未明确提及,但在源码中存在,传入类型时 LangChain 会自动包装为 AutoStrategy。- LangChain 1.0+ 版本不推荐直接传递类型(如直接写
response_format=ContactInfo),建议显式包裹为 Strategy 对象。
create_agent(model, response_format=ToolStrategy(ContactInfo))
│
▼ 模型决定调用"伪工具" ContactInfo
│ └─ tool_call: {name: "ContactInfo", args: {...}}
▼
结构化输出 → response["structured_response"]
│
└─ 包含 name, email, phone 等字段
ProviderStrategy:直接走原生 API,无伪工具痕迹。ToolStrategy:在 messages 中可看到 tool_calls → ToolMessage 的链路。
from langchain.agents import create_agent
from langchain.agents.structured_output import ProviderStrategy, ToolStrategy, AutoStrategy
from pydantic import BaseModel, Field
class ContactInfo(BaseModel):
"""用户联系方式"""
name: str = Field(description="用户姓名")
email: str = Field(description="用户邮箱")
phone: str = Field(description="用户电话")
agent = create_agent(
model=model,
response_format=ProviderStrategy(ContactInfo)
)
response = agent.invoke({
"messages": [{"role": "user", "content": "小明的邮箱是 13012341234@qq.com,请提取用户信息。"}]
})
print(response["structured_response"])
agent = create_agent(
model=model,
response_format=ToolStrategy(ContactInfo)
)
agent = create_agent(
model=model,
response_format=AutoStrategy(ContactInfo)
)
agent = create_agent(
model=model,
)
- LangChain 1.0+ 不推荐直接传类型:如
response_format=ContactInfo 这种写法虽在测试中仍可用,但官方已不推荐,应改为 ToolStrategy(ContactInfo)。 - ProviderStrategy 有模型限制:仅 OpenAI、Anthropic Claude、Grok 等原生支持结构化输出的模型可用,国产模型大多不支持。
- ToolStrategy 需要模型支持 function calling:几乎所有主流模型都支持,但需确认。
- ToolStrategy 会产生额外 token 消耗:伪工具的 schema 会包含在请求中。
- 生产环境强力推荐 ToolStrategy:具备最广泛的模型兼容性,不受模型提供商限制。
- 如果确定使用 OpenAI/Claude 等模型并追求极致性能,可选用 ProviderStrategy(减少伪工具带来的额外 token)。
- 结构化输出结果统一从
response["structured_response"] 中获取,与策略无关。