抽取类任务(发票信息、简历字段、工单分类)的价值全在「能不能直接入库」。而模型输出 JSON 的稳定性,取决于你用了哪一层约束。
| 层级 | 手段 | 稳定性 | 代价 |
|---|---|---|---|
| 靠提示 | system 里写「只返回 JSON,不要解释」 | 中,长输出时容易破功 | 零成本 |
| 格式模式 | response_format={"type":"json_object"} | 较高,但字段结构不保证 | 需 prompt 含 json 字样 |
| Schema 约束 | json_schema + strict | 高,字段与类型受约束 | 部分厂商不支持;schema 有子集限制 |
{
"model": "gpt-5-mini",
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "invoice",
"strict": true,
"schema": {
"type": "object",
"properties": {
"invoice_no": {"type": "string"},
"amount": {"type": "number"},
"date": {"type": "string"},
"items": {"type": "array", "items": {"type": "object",
"properties": {"name": {"type": "string"}, "price": {"type": "number"}},
"required": ["name", "price"], "additionalProperties": false}}
},
"required": ["invoice_no", "amount", "date", "items"],
"additionalProperties": false
}
}
}
}additionalProperties: false、不支持部分 JSON Schema 关键字(如 patternProperties)。schema 不合规时接口会直接 400,报错信息往往不直观。三个兜底手段,按顺序用:
prefix 或 assistant 预填(部分厂商支持),能显著降低「先来一段解释」的概率。def parse_json_loose(text):
t = text.strip()
if t.startswith('```'):
t = re.sub(r'^```[a-zA-Z]*\n|```$', '', t).strip()
i, j = t.find('{'), t.rfind('}')
if i < 0 or j <= i:
raise ValueError('no json object')
return json.loads(t[i:j+1])schema 约束保证「形状对」,不保证「内容对」。金额可能是 0,日期可能是 2099 年,枚举值可能在集合外。入库前必须有业务校验:
开了 stream 之后 JSON 是逐字到达的,不能边收边 json.loads。做法是累积完整内容后再解析;如果要在前端渐进展示,用一个容错的增量解析器,或干脆流式只用于展示、结构化结果从最后一次完整响应里取。