模型能力
结构化输出
请求 JSON Schema 输出,并在应用中处理拒答、截断和校验失败。
选择输出方式
需要程序读取字段时,选择支持结构化输出的模型与线路。JSON 模式侧重合法 JSON;JSON Schema 还描述字段与类型。仅在提示词中写“返回 JSON”不能替代程序校验。
请求并校验
按 OpenAI SDK准备 Python 环境和模型变量。下面使用 Chat Completions 的 response_format,仅适用于支持该结构的线路。
import json
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["IROUTER_API_KEY"], base_url="https://gateway.irouter.io/v1")
reply = client.chat.completions.create(
model=os.environ["IROUTER_MODEL"],
messages=[{"role": "user", "content": "Return the product name iRouter as label."}],
response_format={"type": "json_schema", "json_schema": {
"name": "product_label", "strict": True,
"schema": {"type": "object", "properties": {"label": {"type": "string"}},
"required": ["label"], "additionalProperties": False}
}},
)
choice = reply.choices[0]
if choice.finish_reason != "stop" or getattr(choice.message, "refusal", None):
raise ValueError("Response did not complete normally")
result = json.loads(choice.message.content or "")
if not isinstance(result, dict) or set(result) != {"label"} or not isinstance(result["label"], str):
raise ValueError("Invalid result shape")
print(result["label"])异常与协议差异
遇到参数不支持时核对模型能力,不要在生产代码中静默退回无约束文本。拒答、截断、空内容、JSON 解析失败和 Schema 不匹配都应进入错误处理,不应当作有效业务结果。
Responses 的结构化配置使用 text.format,不能直接把 Chat Completions 的顶层 response_format 原样复制过去。复杂 Schema 的支持范围也随模型变化。
字段参考 OpenAI 结构化输出。