结构化输出(JSON Mode)
强制 AI 返回符合 JSON Schema 的结构化数据,确保输出格式完全可预期。
使用 response_format
Python
from openai import OpenAI
client = OpenAI(
api_key="am-your-api-key",
base_url="https://allmodel.top/v1"
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "user",
"content": """从以下文本提取信息,返回 JSON:
"张伟,男,1990年5月生,电话 13812345678,邮箱 [email protected]"
"""
}],
response_format={
"type": "json_object",
"json_schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"gender": {"type": "string"},
"birth_year": {"type": "integer"},
"phone": {"type": "string"},
"email": {"type": "string"}
},
"required": ["name", "gender", "phone"]
}
}
)
import json
data = json.loads(response.choices[0].message.content)
print(data)
# {'name': '张伟', 'gender': '男', 'birth_year': 1990, 'phone': '13812345678', 'email': '[email protected]'}
💡 注意:结构化输出需要模型支持 GPT-4o、Claude 3.5 等较新模型,不适用于 gpt-3.5-turbo 等旧模型。
allmodel.top