文档 · 模型能力
JSON 输出
让模型输出可以直接解析的 JSON,用于信息抽取、分类、表单填充等场景。
JSON 模式
response_format: {"type": "json_object"} 保证输出是合法 JSON,但不约束字段。
resp = client.chat.completions.create(
model="gpt-4.1-mini",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply in JSON with keys: title, tags (array of strings)."},
{"role": "user", "content": "Summarize: MAX routes one API to many model vendors."},
],
)
data = json.loads(resp.choices[0].message.content)使用 JSON 模式时,提示词中必须明确要求输出 JSON 并说明字段,否则部分模型会报错或输出不稳定。
JSON Schema(结构化输出)
response_format: {"type": "json_schema", ...} 并设置 strict: true 时,输出严格符合你给的 schema。严格模式要求所有字段都在 required 中,且 additionalProperties: false。
resp = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": "Extract: Alice, 31, lives in Berlin."}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"},
},
"required": ["name", "age", "city"],
"additionalProperties": False,
},
},
},
)
print(resp.choices[0].message.content) # {"name":"Alice","age":31,"city":"Berlin"}支持情况
目录中带「JSON 模式」能力的模型支持 json_object;json_schema 主要由 OpenAI、Gemini 等较新的模型支持。不支持的模型可以改用工具调用:定义一个函数,让模型按 schema 填写参数。
健壮性
- 始终解析并校验结果,失败时重试或降级处理。
finish_reason为length时 JSON 可能被截断,请调大输出上限。