让大模型乖乖输出 JSON:结构化输出实战指南
大模型默认输出自然语言文本,但在实际开发中,我们经常需要结构化的 JSON 数据——比如从文本中提取信息、做分类、填表单。
结构化输出(Structured Output)就是让模型严格按照你定义的 JSON 格式返回数据。
JSON Mode:最简单的方式
设置 response_format: {"type": "json_object"} 即可强制模型返回合法 JSON:
from openai import OpenAI
client = OpenAI(
base_url="https://api.ofox.ai/v1",
api_key="your-api-key"
)
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": "你是一个数据提取助手,请以 JSON 格式返回结果。"},
{"role": "user", "content": "张三在2026年1月15日下单了3件商品,收货地址是北京市朝阳区"}
],
response_format={"type": "json_object"}
)
print(response.choices[0].message.content)
# {"customer": "张三", "date": "2026-01-15", "items": 3, "address": "北京市朝阳区"}
注意:必须在 system prompt 中包含 “JSON” 关键字,否则某些模型可能忽略格式要求。
JSON Schema:精确约束
JSON Mode 只保证返回合法 JSON,但不保证字段结构。JSON Schema 可以精确定义每个字段的名称、类型和必填项:
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": "从文本中提取订单信息。"},
{"role": "user", "content": "张三在2026年1月15日下单了3件商品"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "order_info",
"schema": {
"type": "object",
"properties": {
"customer_name": {"type": "string"},
"order_date": {"type": "string"},
"item_count": {"type": "integer"},
"shipping_address": {"type": "string"}
},
"required": ["customer_name", "order_date", "item_count"],
"additionalProperties": False
}
}
}
)
实战:文本分类
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": "对用户反馈进行分类,返回 JSON。"},
{"role": "user", "content": "你们的App太卡了,经常闪退,希望尽快修复"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "feedback_classification",
"schema": {
"type": "object",
"properties": {
"primary_category": {"type": "string"},
"secondary_category": {"type": "string"},
"sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
"priority": {"type": "string", "enum": ["low", "medium", "high"]}
},
"required": ["primary_category", "sentiment", "priority"]
}
}
}
)
模型支持情况
| 模型 | JSON Mode | JSON Schema |
|---|---|---|
| openai/gpt-4o | ✅ | ✅ |
| openai/gpt-4o-mini | ✅ | ✅ |
| anthropic/claude-sonnet-4.5 | ✅ | — |
| google/gemini-2.5-flash | ✅ | ✅ |
不支持 JSON Schema 的模型(如 Claude),可以在 system prompt 中详细描述期望的 JSON 格式来实现类似效果。
结构化输出是 AI 应用开发的基础设施。有了它,大模型的输出就能直接作为数据源接入你的业务流程,不再需要人工解析文本。