開發文件
結構化輸出
需要程式解析模型輸出時,可以要求模型嚴格按照 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限定,比如分類標籤。 - 結構化輸出約束的是格式,不保證內容正確,關鍵欄位仍建議在程式碼裡驗證。