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

# 结构化输出

## 结构化输出与 JSON 模式

在处理语言模型时，生成符合特定结构的回应对于构建可靠的应用程序至关重要。Agno Agents 支持两种实现此目标的方法：**结构化输出**和**JSON 模式**。

***

### 结构化输出 (如果支持，则为默认选项)

“结构化输出”是从模型中提取格式正确、符合模式的回应的**首选**且最**可靠**的方式。如果模型类支持它，Agno Agents 默认使用结构化输出。

通过结构化输出，我们向模型提供一个模式（使用 Pydantic 或 JSON Schema），模型的响应**严格遵循**该模式。这消除了许多常见问题，如缺少字段、无效的枚举值或格式不一致。结构化输出非常适合需要高置信度的结构化回应，例如实体提取、用于 UI 渲染的内容生成等。

在这种情况下，响应模型作为关键字参数传递给模型。

## 示例

```python theme={null}
from pydantic import BaseModel
from agno.agent import Agent
from agno.models.openai import OpenAIChat

class User(BaseModel):
    name: str
    age: int
    email: str

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    description="You are a helpful assistant that can extract information from a user's profile.",
    response_model=User,
)
```

在上面的示例中，模型将使用 OpenAI 的 `gpt-4o` 模型通过结构化输出来生成符合 `User` 模式的回应。然后，代理将按原样返回 `User` 对象。

***

### JSON 模式

某些模型类**不支持结构化输出**，或者当模型同时支持这两种选项时，您可能希望回退到 JSON 模式。在这种情况下，您可以通过设置 `use_json_mode=True` 来启用**JSON 模式**。

JSON 模式通过将期望的 JSON 结构的详细描述注入系统提示来工作。然后指示模型返回符合此结构的有效 JSON 对象。与结构化输出不同，响应**不会在 API 层面自动验证**是否符合模式。

## 示例

```python theme={null}
from pydantic import BaseModel
from agno.agent import Agent
from agno.models.openai import OpenAIChat

class User(BaseModel):
    name: str
    age: int
    email: str

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    description="You are a helpful assistant that can extract information from a user's profile.",
    response_model=User,
    use_json_mode=True,
)

```

### 何时使用

如果模型支持，请使用**结构化输出**——它更可靠、更简洁，并且会自动进行验证。

使用**JSON 模式**：

* 当模型不支持结构化输出时。Agno 代理会代表您自动执行此操作。
* 当您需要更广泛的兼容性，但可以接受手动验证时。
* 当模型不支持带有结构化输出的工具时。
