结构化输出
让模型返回合法 JSON 或符合指定 Schema 的结构。
需要模型输出可被程序直接消费的 JSON 时,使用结构化输出,无需靠提示词乞求「请只返回 JSON」。各模型支持情况见模型库能力标注。
JSON 模式
response_format: {"type": "json_object"} 保证输出是合法 JSON(不约束具体结构)。提示词中需明确说明期望的字段:
resp = client.chat.completions.create(
model="deepseek/deepseek-v4-pro",
messages=[
{"role": "system", "content": "从用户输入中提取城市与日期,返回 JSON,字段:city、date。"},
{"role": "user", "content": "帮我查下明天上海的天气"},
],
response_format={"type": "json_object"},
)JSON Schema 模式
response_format: {"type": "json_schema", ...} 进一步约束输出结构:
resp = client.chat.completions.create(
model="deepseek/deepseek-v4-pro",
messages=[{"role": "user", "content": "帮我查下明天上海的天气"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "extract_query",
"schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"date": {"type": "string"},
},
"required": ["city", "date"],
},
},
},
)Anthropic 协议下的替代方案
Messages 协议下可用「强制工具调用」达到同样效果:把期望结构定义为工具的 input_schema,并用 tool_choice: {"type": "tool", "name": "..."} 强制调用,从响应 tool_use 块的 input 中取结构化数据。
建议
- Schema 尽量扁平、字段配
description,成功率更高 - 推理模型 + 结构化输出组合时,思考过程仍在
reasoning_content/thinking块中,正文才是 JSON - 个别模型对复杂 Schema 支持有限,集成时先用真实 Schema 实测