AI Agent / 系统课时
定义结构化输出
定义结构化输出
结构化输出的目标不是让模型“尽量返回 JSON”,而是先定义可验证的字段契约,再让生成结果进入解析与校验链路。掌握本节后,你可以用 JSON Schema 或数据模型收敛自由文本,并明确格式失败、字段越界和业务语义错误的处理方式。
学习目标
- 用 JSON Schema 明确字段、类型、枚举和必填约束
- 区分“提示模型输出 JSON”和“真正的结构化输出契约”
- 在应用侧增加解析、校验与有限重试,避免脏数据进入业务流程
先定义契约,再让模型填值
仅在提示词里写“请返回 JSON”只能影响模型倾向,不能形成可靠接口。真正的结构化输出应先定义字段集合和边界,例如对象只能包含哪些键、哪些字段必填、字符串允许哪些枚举值,以及某个字段能否为 null。
对于 Agent,输出契约最好只保留下游真正需要的字段。字段越多,模型越容易填入无意义值;字段含义越模糊,应用越难判断错误发生在生成阶段还是业务阶段。
用 JSON Schema 约束返回字段
下面是用于 Chat Completions 请求体的 response_format 值。前一章的文本客户端没有这个参数,本例单独展示协议。只有模型和供应商支持该能力时,才在 JSON 请求体中使用它。严格模式支持的是 JSON Schema 子集,对象应声明必填字段并设置 additionalProperties: false。允许缺省业务值时,本例仍要求该键出现,但把类型设为字符串或 null。
{
"type": "json_schema",
"json_schema": {
"name": "order_intent",
"strict": true,
"schema": {
"type": "object",
"additionalProperties": false,
"properties": {
"intent": {
"type": "string",
"enum": ["query_order", "cancel_order", "other"]
},
"orderId": {
"type": ["string", "null"],
"description": "从请求中提取的订单号,缺失时为 null"
}
},
"required": ["intent", "orderId"]
}
}
}模型只提取意图和候选订单号。订单状态由通过授权检查的业务系统查询后提供。cancel_order 只表示一种用户意图,执行前还需核对权限、当前订单状态和必要审批。JSON 模式 json_object 主要保证 JSON 语法,仍需单独检查字段契约。
让生成、解析和校验形成一条链
先读取模型是否拒绝及本次结束原因。完成文本候选再进入 JSON 解析、字段校验和业务语义检查。拒绝、长度截断或内容过滤分别交给相应的处理分支。

以下代码使用标准库解析一次非流式 Chat Completions 响应,预期请求设置单候选。固定响应来自测试数据,运行不需要 API 密钥。
import json
ALLOWED_INTENTS = {"query_order", "cancel_order", "other"}
def unique_object(pairs):
data = {}
for key, value in pairs:
if key in data:
raise ValueError("duplicate JSON key")
data[key] = value
return data
def parse_response(payload):
if not isinstance(payload, dict):
raise ValueError("expected response object")
choices = payload.get("choices")
if not isinstance(choices, list) or len(choices) != 1:
raise ValueError("expected exactly one choice")
choice = choices[0]
if not isinstance(choice, dict) or not isinstance(choice.get("message"), dict):
raise ValueError("expected response message")
message = choice["message"]
if message.get("refusal"):
raise ValueError("model refused")
if choice.get("finish_reason") != "stop":
raise ValueError("incomplete response")
content = message.get("content")
if not isinstance(content, str):
raise ValueError("missing response text")
data = json.loads(content, object_pairs_hook=unique_object)
if not isinstance(data, dict) or data.keys() != {"intent", "orderId"}:
raise ValueError("unexpected fields")
intent, order_id = data["intent"], data["orderId"]
if not isinstance(intent, str) or intent not in ALLOWED_INTENTS:
raise ValueError("invalid intent")
if order_id is not None and (not isinstance(order_id, str) or not order_id.strip()):
raise ValueError("invalid order ID")
if intent in {"query_order", "cancel_order"} and order_id is None:
raise ValueError("order ID required for this intent")
return data
if __name__ == "__main__":
response = {"choices": [{
"finish_reason": "stop",
"message": {"content": '{"intent":"query_order","orderId":"A1024"}'},
}]}
data = parse_response(response)
print(data["intent"], data["orderId"])预期输出
query_order A1024格式正确后再验业务含义
用户没有提供订单号时,Schema 允许 null,让模型可以表达缺失。应用在需要订单号的意图上应提示用户补充。已有订单号也要从可信系统查验归属和操作权限。记录错误分类和 Schema 版本,避免在日志中保存未脱敏的模型文本。下一课用可控的次数演示哪些错误适合交给模型修复。