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

# 结构化输出（Structured Output）

> 了解如何在算秩 Model Inference 中使用 response_format、JSON 模式和 JSON Schema 让模型返回可解析的结构化输出。

结构化输出（Structured Output）用于让模型返回可被程序解析的 JSON 内容，便于后续进行校验、解析和自动化处理。

## 使用场景

* 从新闻文章中抽取结构化字段，例如标题、时间和链接。
* 对商品评论进行情感分析，包括极性、强度和关键词。
* 根据交易或浏览历史生成推荐列表，例如商品、理由、价格和促销信息。

## 支持的模型

* 大多数在线语言模型支持 Structured Output；VL 模型目前不支持
* 模型能力会持续更新，请通过 [模型广场](https://console.siflow.cn/model-inference/models) 的模型详情页获取最新支持情况。

## 输出格式

平台支持通过 `response_format` 控制模型输出格式。包括：

* JSON 模式（`json_object`）：如果只需要模型返回合法 JSON，可以使用 `json_object`
* 严格 Schema（`json_schema`）：如果需要输出结构固定，可以使用 `json_schema`。

### JSON 模式

JSON 模式可以让模型返回 JSON 字符串，而不是自由格式文本。

```python theme={null}
response_format = {"type": "json_object"}
```

使用 JSON 模式时，仍建议在 prompt 中说明需要返回的字段和格式。

### 严格 Schema

如果您需要模型按照指定结构输出，可以传入 JSON Schema。模型会尽量遵循您定义的字段名、类型和必填项，从而减少后处理成本。

```python theme={null}
response_format = {
    "type": "json_schema",
    "json_schema": {
        "name": "city",
        "schema": {
            "type": "object",
            "properties": {
                "capital": {"type": "string"},
            },
            "required": ["capital"],
        },
    },
}
```

## 最佳实践

* **明确输出约束**：在 prompt 中说明只输出 JSON，不要输出解释性文字。
* **强化 Schema 约束**：使用 `json_schema` 时，明确字段名、类型、必填字段和可选字段。
* **减少随机性**：建议使用较低的 `temperature`，例如 0.2～0.5，以减少随机性和偏移。
* **优先非流式**：优先使用 `stream=False`。如果使用流式响应，请等到收齐所有分块后再调用 `json.loads`。
* **控制输出长度**：设置合理的 `max_completion_tokens`，避免 JSON 对象被截断。
* **处理解析失败**：解析失败时，可以使用更严格的约束重试，并记录原始输出以便排查。
* **校验外部 JSON**：建议在应用侧处理模型返回不完整 JSON 或无效 JSON 的边界情况。在使用模型返回的 JSON 前先进行校验，避免将不受信任的内容直接拼接到 SQL 查询或代码路径中。

## 调用示例

示例使用环境变量读取 API Key，避免将密钥写入代码。

```bash theme={null}
export API_KEY="YOUR_API_KEY"
```

### JSON 模式

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

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url="https://api.siflow.cn/model-api",
)

resp = client.chat.completions.create(
    model="MiniMaxAI/MiniMax-M2.7",
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant designed to output JSON.",
        },
        {
            "role": "user",
            "content": "What is the capital of France? Please respond as {\"capital\": ...}",
        },
    ],
    response_format={"type": "json_object"},
    temperature=0.3,
    max_completion_tokens=256,
    stream=False,
)

raw = resp.choices[0].message.content
print("RAW:", raw)

try:
    data = json.loads(raw)
    print("PARSED:", data)
except json.JSONDecodeError:
    print("JSON parsing failed; retry with lower temperature or higher max_completion_tokens")
```

示例输出：

```json theme={null}
{"capital": "Paris"}
```

### 严格 Schema

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

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url="https://api.siflow.cn/model-api",
)

response_format = {
    "type": "json_schema",
    "json_schema": {
        "name": "city",
        "schema": {
            "type": "object",
            "properties": {
                "capital": {"type": "string"},
            },
            "required": ["capital"],
        },
    },
}

resp = client.chat.completions.create(
    model="Qwen/Qwen3-32B",
    messages=[{"role": "user", "content": "Capital of France?"}],
    response_format=response_format,
)

print(resp.choices[0].message.content)
```
