开发文档
结构化输出
需要程序解析模型输出时,可以要求模型严格按照 JSON Schema 返回,不再需要在提示词里反复强调格式,也不用担心多出的解释文字。
OpenAI 兼容格式
使用 response_format,类型为 json_schema:
structured_openai.py
import json
from openai import OpenAI
client = OpenAI(api_key="sk-...", base_url="https://api.flyrouter.ai/v1")
resp = client.chat.completions.create(
model="gpt-6.1-sol",
messages=[{"role": "user", "content": "从这段话提取联系人:张三,电话 13800000000,在杭州工作。"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "contact",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"phone": {"type": "string"},
"city": {"type": "string"},
},
"required": ["name", "phone", "city"],
"additionalProperties": False,
},
},
},
)
print(json.loads(resp.choices[0].message.content))只需要合法 JSON、不限定字段时,可以用 "response_format": {"type": "json_object"},并在提示词里说明要返回 JSON。
Anthropic 原生格式
Claude 使用 output_config.format:
structured_claude.py
import json
from anthropic import Anthropic
client = Anthropic(api_key="sk-...", base_url="https://api.flyrouter.ai")
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"phone": {"type": "string"},
"city": {"type": "string"},
},
"required": ["name", "phone", "city"],
"additionalProperties": False,
}
msg = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "从这段话提取联系人:张三,电话 13800000000,在杭州工作。"}],
output_config={"format": {"type": "json_schema", "schema": schema}},
)
print(json.loads(msg.content[0].text))旧版的 output_format 参数已被 output_config.format 取代;新款 Claude 也不再支持在最后一条 assistant 消息里预填开头(prefill)来约束格式,请改用本页的方式。
编写 Schema 的建议
- 列出所有字段并放进
required,加上"additionalProperties": false,输出最稳定。 - 给字段写
description,模型更清楚每个字段该填什么。 - 枚举值用
enum限定,比如分类标签。 - 结构化输出约束的是格式,不保证内容正确,关键字段仍建议在代码里校验。