结构化输出
了解如何使用结构化输出功能,确保模型返回符合预定义 Schema 的 JSON 数据。
什么是结构化输出
结构化输出允许你定义期望的 JSON Schema,模型将根据预定义的格式返回数据。 这对于需要程序化处理模型输出的场景非常有用,例如:
- 从非结构化文本中提取结构化数据
- 生成符合特定格式的报告
- 创建可预测的 API 响应格式
- 自动化数据入库流程
response_format 参数
使用 response_format 参数指定输出格式:
JSON 对象模式
适用于需要返回 JSON 对象的场景:
type: 'json_object'JSON Schema 模式
使用 tools/function 参数定义完整的 JSON Schema,获得更精确的结构控制。
JSON Schema 定义
通过 function parameters 定义输出结构:
Schema 定义示例
# 定义函数参数 schema
tools = [{
"type": "function",
"function": {
"name": "extract_user_info",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "用户姓名"
},
"email": {
"type": "string",
"description": "用户邮箱"
},
"phone": {
"type": "string",
"description": "用户手机号"
}
},
"required": ["name", "email"]
}
}
}]完整示例
以下示例演示如何从文本中提取结构化信息:
提取用户信息
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[{
"role": "user",
"content": """从以下文本中提取用户信息:
姓名:张三
邮箱:zhangsan@example.com
手机:13800138000
地址:北京市朝阳区"""
}],
response_format={"type": "json_object"},
tools=[{
"type": "function",
"function": {
"name": "extract_user_info",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"phone": {"type": "string"}
}
}
}
}]
)
# 获取结构化输出
result = response.choices[0].message
print(result.content)使用 Function Calling
Function Calling 提供了一种更可靠的结构化输出方式:
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[{
"role": "user",
"content": "提取用户信息:张三,邮箱 zhangsan@example.com"
}],
tools=[{
"type": "function",
"function": {
"name": "extract_user_info",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"phone": {"type": "string"}
},
"required": ["name", "email"]
}
}
}],
tool_choice={"type": "function", "function": {"name": "extract_user_info"}}
)
# 模型会自动使用 function 调用格式返回
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.function.arguments)限制说明
模型兼容性
并非所有模型都完全支持结构化输出。建议使用 GPT-4o、Claude 3.5 等最新模型 以获得更好的效果。
Schema 遵循度
某些情况下,模型可能不会完全遵循定义的 Schema。建议在应用中添加 JSON 验证逻辑,确保输出的数据符合预期格式。
字段缺失
如果模型无法从输入中提取某些字段,返回的 JSON 中可能不包含这些字段, 或值为 null。请做好相应的处理。
内容限制
避免在 Schema 中定义过于复杂的嵌套结构,这会增加模型遵循的难度。 建议尽量保持结构扁平化。