> ## 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.

# 响应格式

## JSON 模式（结构化输出）

JSON 模式可以让大语言模型直接返回可被机器解析的 JSON 字符串，便于后续做校验、解析和自动化处理。平台上的大多数语言模型都支持 JSON 模式（目前不包括 VL 模型）。

### 1. 使用场景

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

### 2. 使用方法

* 在请求中添加 `response_format={"type": "json_object"}`，让模型返回 JSON 字符串，而不是自由格式文本。
* 建议：
  * 使用较低的 temperature（例如 `temperature=0.2–0.5`）以减少随机性和偏移。
  * 将 `max_completion_tokens` 设置为合理的值，以避免 JSON 被截断。
  * 优先使用非流式响应；如果必须使用流式，请在客户端重新组装并校验 JSON。

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

### 3. 支持的模型

* 大多数在线语言模型支持 JSON 模式；VL 模型目前不支持。
* 模型能力会持续更新，请参阅 [模型广场](https://console.siflow.cn/maas-api/model_plaza) → 模型详情，获取最新支持情况。
* 建议在应用侧处理模型返回不完整 JSON 或无效 JSON 的边界情况。

### 4. 示例（OpenAI Python SDK）

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

client = OpenAI(
    api_key=os.getenv("API_KEY") or "<YOUR 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  # JSON mode: prefer non-streaming to avoid truncation
)

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

try:
    data = json.loads(raw)
    print("PARSED:", data)
except json.JSONDecodeError:
    # Fallback: log + retry with lower temperature / higher max_completion_tokens / stricter prompt
    print("JSON parsing failed; retry with lower temperature or higher max_completion_tokens")

```

示例输出（仅作说明）：

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

### 5. 严格 Schema（`json_schema`）

如果您需要模型严格按照指定结构输出，请传入 JSON Schema，而不是普通的 `json_object`。这样模型会尽量遵循您定义的字段名、类型和必填项，从而减少后处理成本。

```python theme={null}
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)  # {"capital": "Paris"}
```

如果您只需要“返回一个合法 JSON”，使用 `json_object` 即可；如果必须保证输出结构固定，则应使用 `json_schema`。

### 6. 最佳实践与注意事项

* **强化 Schema 约束**：明确指定字段名、类型、必填与可选字段、示例，以及“不允许额外字段”。
* **优先非流式**：优先使用 `stream=False`；如果使用流式，请等到收齐所有分块后再调用 `json.loads`。
* **健壮性**：解析失败时，建议使用更严格的约束重试，并记录原始输出以便排查。
* **长度控制**：设置 `max_completion_tokens` 以防止 JSON 对象在中途被截断，并指示模型仅输出 JSON（不要有解释性文字）。
* **安全性**：在使用外部 JSON 之前先进行校验，并避免将不受信任的内容直接拼接到 SQL 查询或代码路径中。
