接第三章:输出。
第三章的“输出”一节描述了:
1、response_format: 在创建Agent时指定输出格式;
2、Schema:定义输出格式
本章对未完事项继续描述。
4.1response_format 与 Schema 搭配
4.1.1 Pydantic models 自动选择策略
这是官方推荐的方式,定义Pydantic models格式,直接将schema类型赋值给response_format即可。无需显式指定策略,LangChain会自动判断。
返回类型:Pydantic 对象,不是字典、不是字符串、不是json
from pydantic import BaseModel, Field from langchain.agents import create_agent class ContactInfo(BaseModel): """Contact information for a person.""" name: str = Field(description="The name of the person") email: str = Field(description="The email address of the person") phone: str = Field(description="The phone number of the person") agent = create_agent( model="gpt-5.5", response_format=ContactInfo # 自动选择 ProviderStrategy ) result = agent.invoke({ "messages": [{"role": "user", "content": "Extract contact info from: John Doe, john@example.com, (555) 123-4567"}] }) print(result["structured_response"]) # ContactInfo(name='John Doe', email='john@example.com', phone='(555) 123-4567')LangChain的内部选择逻辑:
如果模型支持原生结构化输出(如OpenAI、Anthropic、xAI等),它会自动采用
ProviderStrategy。否则,它会回退到
ToolStrategy。返回的数据可以直接用点号(
.)访问:print(result["structured_response"].name) print(result["structured_response"].email)
4.1.2 Dataclasses和TypedDict 也是自动选择策略
同Pydantic一样,Dataclasses和TypedDict也是可以直接传给response_format,由模型自动选择策略。
他们返回的都是dict字典。
如何选择:这更多是代码风格的选择。如果你在项目中倾向于用对象来传递数据,就用 Dataclass;如果倾向于用字典,就用 TypedDict。两者在 LangChain 结构化输出中的实际运行效果是等价的,都不会像 Pydantic 那样进行强力的运行时校验。
4.1.3 JSON +ProviderStrategy或ToolStrategy
如果schema是json格式,必须显式地将其包裹在ProviderStrategy或ToolStrategy中。
from langchain.agents import create_agent from langchain.agents.structured_output import ProviderStrategy contact_info_schema = { "title": "ContactInfo", "type": "object", "description": "Contact information for a person.", "properties": { "name": {"type": "string", "description": "The name of the person"}, "email": {"type": "string", "description": "The email address of the person"}, "phone": {"type": "string", "description": "The phone number of the person"} }, "required": ["name", "email", "phone"] } agent = create_agent( model="gpt-5.5", tools=[], response_format=ProviderStrategy(contact_info_schema) ) result = agent.invoke({ "messages": [{"role": "user", "content": "Extract contact info from: John Doe, john@example.com, (555) 123-4567"}] }) result["structured_response"] # {'name': 'John Doe', 'email': 'john@example.com', 'phone': '(555) 123-4567'}4.1.4 Union +ToolStrategy
Union 类型的 Schema,只能搭配ToolStrategy,而且必须显式指定。
这是由两种策略的工作机制决定的:
ProviderStrategy:依赖提供商原生的结构化输出 API。该 API 通常要求一个确定的 Schema,不支持“要么 A,要么 B”这种多选一的模糊定义。因此ProviderStrategy无法处理Union。ToolStrategy:通过“让模型调用一个结构化输出工具”来实现。Union可以被建模为多个候选工具,模型根据上下文自行选择调用哪一个,从而天然支持多 Schema 二选一甚至多选一。
所以,Union是ToolStrategy的独占能力,ProviderStrategy和直接传类型的方式都不支持。
使用示例见第三章。
4.2 structured_response
structured_response是 LangChain 在启用结构化输出后,智能体最终状态中一个独立的数据容器,它的类型和行为完全由你传入的 Schema 决定。
相当于Agent在原有的数据基础上做了加工,按照Schema的格式,把数据放入structured_response结构中。
这样最终的结果里会同时有两条信息线:
messages:保留完整的对话历史(包括模型思考、工具调用等过程)。structured_response:存放经过 Schema 校验的纯净、机器可读的结果。
返回类型:
| Schema类型 | 访问方式 |
| Pydantic | Pydantic 类的实例: result.structured_response.字段名 |
| Dataclass / TypedDict / JSON | 字典: result["structured_response"]["字段名"] |
一个重要的行为细节(流式场景)
在流式输出(streaming)时,structured_response可能不会实时出现。因为结构化工具调用的args(参数)是逐步流式传输的,在流结束或工具调用完成之前,这些参数可能是不完整的。因此,如果你在流式过程中检查structured_response,可能需要处理它暂时为空或为None的情况,等待流结束后再读取。