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

# 结构化输出

> 用 JSON 模式 / JSON Schema 让模型严格按结构返回

结构化输出可以让模型严格按 JSON 结构返回,适合在程序中直接解析。

## JSON 模式(基础)

```json theme={null}
{
  "model": "gpt-5.5",
  "response_format": { "type": "json_object" },
  "messages": [
    {"role": "system", "content": "你必须仅返回合法 JSON"},
    {"role": "user", "content": "返回一个 user 对象,包含 name 与 age"}
  ]
}
```

注意:

* 仅保证 **返回合法 JSON**,但字段名 / 类型可能与你期望不一致。
* 必须在 prompt 中提示 "返回 JSON",否则模型可能因为安全策略拒绝。

## JSON Schema(强约束)

```json theme={null}
{
  "model": "gpt-5.5",
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "user",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "age": {"type": "integer"},
          "hobbies": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["name", "age", "hobbies"],
        "additionalProperties": false
      }
    }
  },
  "messages": [{"role": "user", "content": "随机生成一个用户"}]
}
```

`strict: true` 让模型在生成时进行 token 级约束,**输出 100% 符合 schema**。

### 支持的模型

* OpenAI:`gpt-5.5` / `gpt-5.4-mini` / `o3` 系列。
* Claude:间接支持(通过 prompt 引导 + tool 强约束)。
* Gemini:通过 `responseSchema` 实现等效约束。

## Python(Pydantic)

OpenAI Python SDK 提供 `parse` 方法直接接 Pydantic 模型:

```python theme={null}
from pydantic import BaseModel
from openai import OpenAI

client = OpenAI(api_key="sk-...", base_url="https://openp.ai/v1")

class User(BaseModel):
    name: str
    age: int
    hobbies: list[str]

resp = client.beta.chat.completions.parse(
    model="gpt-5.5",
    messages=[{"role": "user", "content": "随机生成一个用户"}],
    response_format=User,
)

user: User = resp.choices[0].message.parsed
print(user.name, user.age)
```

## Gemini

```json theme={null}
{
  "contents": [{"role": "user", "parts": [{"text": "随机生成一个用户"}]}],
  "generationConfig": {
    "responseMimeType": "application/json",
    "responseSchema": {
      "type": "object",
      "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"}
      },
      "required": ["name", "age"]
    }
  }
}
```

## Claude

Claude 没有专门的 `response_format`,但可用 **tool 强约束** 实现等价效果:

```python theme={null}
resp = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    tools=[{
        "name": "save_user",
        "input_schema": {
            "type": "object",
            "properties": {"name":{"type":"string"},"age":{"type":"integer"}},
            "required": ["name","age"]
        }
    }],
    tool_choice={"type": "tool", "name": "save_user"},
    messages=[{"role": "user", "content": "随机生成一个用户"}]
)
user = resp.content[0].input  # dict
```

## 注意

* JSON Schema 约束会 **略微增加** 延迟与成本(模型在生成时反复检验)。
* 即使开了 `strict`,Schema 还是要尽量明确(用 `enum`、`pattern`、`min/max` 等)。
* 嵌套深度 ≤ 5,字段数 ≤ 100,数组 ≤ 5000 元素,具体限制以上游为准。
