Skip to main content

Documentation Index

Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

结构化输出允许智能体以特定的、可预测的格式返回数据。你可以获得 JSON 对象、Pydantic 模型或 dataclass 形式的结构化数据,而不是解析自然语言响应,你的应用程序可以直接使用这些数据。
本页介绍使用 create_agent 的智能体的结构化输出。要直接在模型上使用结构化输出(智能体之外),请参阅模型 - 结构化输出
LangChain 的 create_agent 自动处理结构化输出。用户设置所需的结构化输出模式,当模型生成结构化数据时,它会被捕获、验证并返回在智能体状态的 'structured_response' 键中。
def create_agent(
    ...
    response_format: Union[
        ToolStrategy[StructuredResponseT],
        ProviderStrategy[StructuredResponseT],
        type[StructuredResponseT],
        None,
    ]

响应格式

使用 response_format 来控制智能体如何返回结构化数据:
  • ToolStrategy[StructuredResponseT]:使用工具调用来实现结构化输出
  • ProviderStrategy[StructuredResponseT]:使用提供商原生的结构化输出
  • type[StructuredResponseT]:模式类型 - 根据模型能力自动选择最佳策略
  • None:未显式请求结构化输出
当直接提供模式类型时,LangChain 会自动选择:
  • 如果所选模型和提供商支持原生结构化输出(例如 OpenAIAnthropic (Claude)xAI (Grok)),则使用 ProviderStrategy
  • 对于所有其他模型,使用 ToolStrategy
如果使用 langchain>=1.1,对原生结构化输出功能的支持会从模型的配置文件数据中动态读取。如果数据不可用,请使用其他条件或手动指定:
custom_profile = {
    "structured_output": True,
    # ...
}
model = init_chat_model("...", profile=custom_profile)
如果指定了工具,模型必须支持同时使用工具和结构化输出。
结构化响应在智能体最终状态的 structured_response 键中返回。

提供商策略

一些模型提供商通过其 API 原生支持结构化输出(例如 OpenAI、xAI (Grok)、Gemini、Anthropic (Claude))。这是可用时最可靠的方法。 要使用此策略,配置一个 ProviderStrategy
class ProviderStrategy(Generic[SchemaT]):
    schema: type[SchemaT]
    strict: bool | None = None
strict 参数需要 langchain>=1.2
schema
required
定义结构化输出格式的模式。支持:
  • Pydantic 模型:带字段验证的 BaseModel 子类。返回已验证的 Pydantic 实例。
  • Dataclass:带类型注解的 Python dataclass。返回字典。
  • TypedDict:类型化字典类。返回字典。
  • JSON Schema:包含 JSON schema 规范的字典。返回字典。
strict
可选的布尔参数,启用严格模式遵守。部分提供商支持(例如 OpenAIxAI)。默认为 None(禁用)。
当你直接将模式类型传递给 create_agent.response_format 且模型支持原生结构化输出时,LangChain 会自动使用 ProviderStrategy 提供商原生结构化输出提供高可靠性和严格验证,因为模型提供商强制执行模式。可用时请优先使用。
如果提供商原生支持你所选模型的结构化输出,写 response_format=ProductReview 和写 response_format=ProviderStrategy(ProductReview) 在功能上是等价的。在任一情况下,如果不支持结构化输出,智能体将回退到工具调用策略。

工具调用策略

对于不支持原生结构化输出的模型,LangChain 使用工具调用来实现相同的结果。这适用于所有支持工具调用的模型(大多数现代模型)。 要使用此策略,配置一个 ToolStrategy
class ToolStrategy(Generic[SchemaT]):
    schema: type[SchemaT]
    tool_message_content: str | None
    handle_errors: Union[
        bool,
        str,
        type[Exception],
        tuple[type[Exception], ...],
        Callable[[Exception], str],
    ]
schema
required
定义结构化输出格式的模式。支持:
  • Pydantic 模型:带字段验证的 BaseModel 子类。返回已验证的 Pydantic 实例。
  • Dataclass:带类型注解的 Python dataclass。返回字典。
  • TypedDict:类型化字典类。返回字典。
  • JSON Schema:包含 JSON schema 规范的字典。返回字典。
  • Union 类型:多个模式选项。模型将根据上下文选择最合适的模式。
tool_message_content
生成结构化输出时返回的工具消息的自定义内容。 如果未提供,默认为显示结构化响应数据的消息。
handle_errors
结构化输出验证失败的错误处理策略。默认为 True
  • True:使用默认错误模板捕获所有错误
  • str:使用此自定义消息捕获所有错误
  • type[Exception]:仅捕获此异常类型并使用默认消息
  • tuple[type[Exception], ...]:仅捕获这些异常类型并使用默认消息
  • Callable[[Exception], str]:返回错误消息的自定义函数
  • False:不重试,让异常传播

自定义工具消息内容

tool_message_content 参数允许你自定义生成结构化输出时出现在对话历史中的消息。

错误处理

模型在通过工具调用生成结构化输出时可能会出错。LangChain 提供了智能重试机制来自动处理这些错误。

多个结构化输出错误

当模型错误地调用多个结构化输出工具时,智能体会在 ToolMessage 中提供错误反馈并提示模型重试。

模式验证错误

当结构化输出不匹配预期模式时,智能体提供特定的错误反馈。

错误处理策略

你可以使用 handle_errors 参数自定义如何处理错误: 自定义错误消息:
ToolStrategy(
    schema=ProductRating,
    handle_errors="Please provide a valid rating between 1-5 and include a comment."
)
仅处理特定异常:
ToolStrategy(
    schema=ProductRating,
    handle_errors=ValueError  # 仅在 ValueError 时重试,其他异常抛出
)
处理多种异常类型:
ToolStrategy(
    schema=ProductRating,
    handle_errors=(ValueError, TypeError)  # 在 ValueError 和 TypeError 时重试
)
不处理错误:
response_format = ToolStrategy(
    schema=ProductRating,
    handle_errors=False  # 所有错误都会抛出
)