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

# 结构化输出

> 结构化输出（Structured Output）使模型返回严格符合指定格式的 JSON，而非自由发挥的文本。这在需要将模型输出直接用于程序处理时（如字段提取、配置生成、表单填充）尤为有用。

结构化输出（Structured Output）使模型返回严格符合指定格式的 JSON，而非自由发挥的文本。这在需要将模型输出直接用于程序处理时（如字段提取、配置生成、表单填充）尤为有用。

## 使用场景

普通对话中，模型可能以自由文本形式回答。程序难以稳定地从此类文本中提取结构化信息。结构化输出可强制模型返回规范 JSON，便于程序解析与使用。

## 方式一：JSON 模式（json\_object）

最简单的方式，通过 `response_format` 要求模型返回合法 JSON：

```json theme={null}
{
  "model": "gpt-4o",
  "messages": [
    {"role": "system", "content": "你是一个信息提取助手，只返回 JSON。"},
    {"role": "user", "content": "张三今年28岁，是一名工程师。请提取姓名、年龄、职业。"}
  ],
  "response_format": {
    "type": "json_object"
  }
}
```

模型将返回合法的 JSON 对象：

```json theme={null}
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "{\"name\": \"张三\", \"age\": 28, \"occupation\": \"工程师\"}"
      },
      "finish_reason": "stop"
    }
  ]
}
```

`json_object` 模式仅保证返回合法 JSON，但不保证字段名与结构完全符合预期。建议在 system 提示中明确要求字段。如需严格约束结构，应使用下文的 JSON Schema 模式。

## 方式二：JSON Schema 模式（推荐）

使用 `json_schema` 精确定义所需结构，模型将严格遵守：

```json theme={null}
{
  "model": "gpt-4o",
  "messages": [
    {"role": "user", "content": "张三今年28岁，是一名工程师。"}
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "person_info",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string", "description": "姓名"},
          "age": {"type": "integer", "description": "年龄"},
          "occupation": {"type": "string", "description": "职业"}
        },
        "required": ["name", "age", "occupation"],
        "additionalProperties": false
      }
    }
  }
}
```

* `strict: true`：启用严格模式，输出保证符合 schema。
* `required`：必填字段。
* `additionalProperties: false`：禁止出现 schema 之外的字段。

返回的 `content` 将严格符合该 schema 的 JSON 字符串。

## 完整 Python 示例

```python theme={null}
import json
from openai import OpenAI

client = OpenAI(api_key="sk-你的密钥", base_url="https://moxus.ai/v1")

resp = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "张三今年28岁，是一名工程师。"}
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person_info",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"},
                    "occupation": {"type": "string"},
                },
                "required": ["name", "age", "occupation"],
                "additionalProperties": False,
            },
        },
    },
)

data = json.loads(resp.choices[0].message.content)
print(data["name"], data["age"], data["occupation"])
```

## 复杂结构示例

Schema 支持嵌套对象、数组与枚举：

```json theme={null}
{
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "order",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "order_id": {"type": "string"},
          "status": {
            "type": "string",
            "enum": ["pending", "paid", "shipped", "done"]
          },
          "items": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "name": {"type": "string"},
                "quantity": {"type": "integer"},
                "price": {"type": "number"}
              },
              "required": ["name", "quantity", "price"],
              "additionalProperties": false
            }
          }
        },
        "required": ["order_id", "status", "items"],
        "additionalProperties": false
      }
    }
  }
}
```

## 建议

* 优先使用 JSON Schema 模式。需要程序稳定解析时，`strict` 模式最可靠。
* 为每个字段添加 `description`，帮助模型理解字段含义，提高准确率。
* 仍需进行容错。解析前应使用 try/except 包裹，防止极端情况下的格式异常。
* 并非所有模型均支持 `json_schema` 严格模式。若模型不支持，可退回 `json_object` 模式并结合 system 提示约束。

## 结构化输出与函数调用的区别

两者均可获得结构化数据，但目的不同：

|          | 结构化输出          | 函数调用            |
| -------- | -------------- | --------------- |
| 目的       | 使模型的响应为规范 JSON | 使模型决定调用哪个工具及参数  |
| 典型场景     | 信息提取、字段填充      | 触发外部操作（查询天气、下单） |
| 是否需要执行代码 | 否              | 是（执行函数后需回传）     |

## 后续步骤

* 深度推理：参阅 [推理模型](/zh/guide/reasoning)。
* 图像理解：参阅 [视觉与图像生成](/zh/guide/vision-and-image)。
