> ## Documentation Index
> Fetch the complete documentation index at: https://nvd-54.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 结构化输出

结构化输出允许智能体以特定的、可预测的格式返回数据。你可以获得 JSON 对象、[Pydantic 模型](https://docs.pydantic.dev/latest/concepts/models/#basic-model-usage)或 dataclass 形式的结构化数据，而不是解析自然语言响应，你的应用程序可以直接使用这些数据。

<Tip>
  本页介绍使用 `create_agent` 的智能体的结构化输出。要直接在模型上使用结构化输出（智能体之外），请参阅[模型 - 结构化输出](/oss/python/langchain/models#structured-output)。
</Tip>

LangChain 的 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 自动处理结构化输出。用户设置所需的结构化输出模式，当模型生成结构化数据时，它会被捕获、验证并返回在智能体状态的 `'structured_response'` 键中。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
def create_agent(
    ...
    response_format: Union[
        ToolStrategy[StructuredResponseT],
        ProviderStrategy[StructuredResponseT],
        type[StructuredResponseT],
        None,
    ]
```

## 响应格式

使用 `response_format` 来控制智能体如何返回结构化数据：

* **`ToolStrategy[StructuredResponseT]`**：使用工具调用来实现结构化输出
* **`ProviderStrategy[StructuredResponseT]`**：使用提供商原生的结构化输出
* **`type[StructuredResponseT]`**：模式类型 - 根据模型能力自动选择最佳策略
* **`None`**：未显式请求结构化输出

当直接提供模式类型时，LangChain 会自动选择：

* 如果所选模型和提供商支持原生结构化输出（例如 [OpenAI](/oss/python/integrations/providers/openai)、[Anthropic (Claude)](/oss/python/integrations/providers/anthropic) 或 [xAI (Grok)](/oss/python/integrations/providers/xai)），则使用 `ProviderStrategy`。
* 对于所有其他模型，使用 `ToolStrategy`。

<Note>
  如果使用 `langchain>=1.1`，对原生结构化输出功能的支持会从模型的[配置文件数据](/oss/python/langchain/models#model-profiles)中动态读取。如果数据不可用，请使用其他条件或手动指定：

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  custom_profile = {
      "structured_output": True,
      # ...
  }
  model = init_chat_model("...", profile=custom_profile)
  ```

  如果指定了工具，模型必须支持同时使用工具和结构化输出。
</Note>

结构化响应在智能体最终状态的 `structured_response` 键中返回。

## 提供商策略

一些模型提供商通过其 API 原生支持结构化输出（例如 OpenAI、xAI (Grok)、Gemini、Anthropic (Claude)）。这是可用时最可靠的方法。

要使用此策略，配置一个 `ProviderStrategy`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
class ProviderStrategy(Generic[SchemaT]):
    schema: type[SchemaT]
    strict: bool | None = None
```

<Info>
  `strict` 参数需要 `langchain>=1.2`。
</Info>

<ParamField path="schema" required>
  定义结构化输出格式的模式。支持：

  * **Pydantic 模型**：带字段验证的 `BaseModel` 子类。返回已验证的 Pydantic 实例。
  * **Dataclass**：带类型注解的 Python dataclass。返回字典。
  * **TypedDict**：类型化字典类。返回字典。
  * **JSON Schema**：包含 JSON schema 规范的字典。返回字典。
</ParamField>

<ParamField path="strict">
  可选的布尔参数，启用严格模式遵守。部分提供商支持（例如 [OpenAI](/oss/python/integrations/chat/openai) 和 [xAI](/oss/python/integrations/chat/xai)）。默认为 `None`（禁用）。
</ParamField>

当你直接将模式类型传递给 [`create_agent.response_format`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 且模型支持原生结构化输出时，LangChain 会自动使用 `ProviderStrategy`。

提供商原生结构化输出提供高可靠性和严格验证，因为模型提供商强制执行模式。可用时请优先使用。

<Note>
  如果提供商原生支持你所选模型的结构化输出，写 `response_format=ProductReview` 和写 `response_format=ProviderStrategy(ProductReview)` 在功能上是等价的。

  在任一情况下，如果不支持结构化输出，智能体将回退到工具调用策略。
</Note>

## 工具调用策略

对于不支持原生结构化输出的模型，LangChain 使用工具调用来实现相同的结果。这适用于所有支持工具调用的模型（大多数现代模型）。

要使用此策略，配置一个 `ToolStrategy`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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],
    ]
```

<ParamField path="schema" required>
  定义结构化输出格式的模式。支持：

  * **Pydantic 模型**：带字段验证的 `BaseModel` 子类。返回已验证的 Pydantic 实例。
  * **Dataclass**：带类型注解的 Python dataclass。返回字典。
  * **TypedDict**：类型化字典类。返回字典。
  * **JSON Schema**：包含 JSON schema 规范的字典。返回字典。
  * **Union 类型**：多个模式选项。模型将根据上下文选择最合适的模式。
</ParamField>

<ParamField path="tool_message_content">
  生成结构化输出时返回的工具消息的自定义内容。
  如果未提供，默认为显示结构化响应数据的消息。
</ParamField>

<ParamField path="handle_errors">
  结构化输出验证失败的错误处理策略。默认为 `True`。

  * **`True`**：使用默认错误模板捕获所有错误
  * **`str`**：使用此自定义消息捕获所有错误
  * **`type[Exception]`**：仅捕获此异常类型并使用默认消息
  * **`tuple[type[Exception], ...]`**：仅捕获这些异常类型并使用默认消息
  * **`Callable[[Exception], str]`**：返回错误消息的自定义函数
  * **`False`**：不重试，让异常传播
</ParamField>

### 自定义工具消息内容

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

### 错误处理

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

#### 多个结构化输出错误

当模型错误地调用多个结构化输出工具时，智能体会在 [`ToolMessage`](https://reference.langchain.com/python/langchain-core/messages/tool/ToolMessage) 中提供错误反馈并提示模型重试。

#### 模式验证错误

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

#### 错误处理策略

你可以使用 `handle_errors` 参数自定义如何处理错误：

**自定义错误消息：**

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ToolStrategy(
    schema=ProductRating,
    handle_errors="Please provide a valid rating between 1-5 and include a comment."
)
```

**仅处理特定异常：**

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ToolStrategy(
    schema=ProductRating,
    handle_errors=ValueError  # 仅在 ValueError 时重试，其他异常抛出
)
```

**处理多种异常类型：**

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ToolStrategy(
    schema=ProductRating,
    handle_errors=(ValueError, TypeError)  # 在 ValueError 和 TypeError 时重试
)
```

**不处理错误：**

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
response_format = ToolStrategy(
    schema=ProductRating,
    handle_errors=False  # 所有错误都会抛出
)
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs)到 Claude、VSCode 等工具，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/structured-output.mdx)或[提交 issue](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
