JSON 模式只回答一个问题:json.loads() 会不会成功?它不回答第二个问题:这是不是我的代码期望的那个对象?
工作原理
在 Chat Completions API 中,一个字段就能打开它:
{"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": "Return JSON with keys name and email."},
{"role": "user", "content": "Reach me at Sara, sara@example.com"}]}
OpenAI 的 API 参考称之为 “the older JSON mode, which ensures the message the model generates is valid JSON.”(译文:较早的 JSON 模式,确保模型生成的消息是合法 JSON。)它附带两条规则。第一,你必须在消息里要求输出 JSON:OpenAI 的指南说,API “will throw an error if the string ‘JSON’ does not appear somewhere in the context.”(译文:如果上下文中没有出现字符串 ‘JSON’,就会抛出错误。)第二,结构由模型决定。指南明确指出,JSON 模式 “will not guarantee the output matches any specific schema.”(译文:不保证输出符合任何特定 schema。)
结构化输出是更严格的选项。它用 {"type": "json_schema", ...} 传入一个 JSON Schema,模型的输出受其约束。
JSON 模式(json_object) |
结构化输出(json_schema) |
|
|---|---|---|
| 合法 JSON | 是 | 是 |
| 必填键与类型 | 否 | 是 |
| 需要你提供 schema | 否 | 是 |
| 提示词中必须提到 “JSON” | 是(OpenAI) | 否 |
OpenAI 建议 “always using Structured Outputs instead of JSON mode when possible.”(译文:只要可能,始终用 Structured Outputs 代替 JSON 模式。)
为什么重要
- 校验仍然要你来做。 用 JSON 模式时,缺一个键、或者把数字当字符串发回来,都能正常解析,却会在后面出错。请在代码里按 schema 校验。
- 截断。 如果回复触到
max_tokens,JSON 就是不完整的。推理模型更容易遇到这种情况,因为思考也消耗同一份预算。 - 后备方案。 OpenAI 的指南把 JSON 模式列为不支持
json_schema的旧模型上的选项。各服务商和模型的支持情况不一,所以当 schema 不被接受时,JSON 模式加上你自己的校验就是后备方案。
在 BroadNet Inference 上
BroadNet 的 API 参考文档为 GLM 5.3 和 Qwen3.8 27B 列出了结构化输出,但没有说明支持的 response_format 是 json_object 还是 json_schema,也没有说明 DeepSeek V4.1 Flash 和 BroadNet Gemma 4 VL 26B 是否接受其中任何一种。请在你的模型上把两种都测一遍。编写 schema 可以用 JSON Schema 生成器。JSON mode 与 json_schema 一文介绍了修复与监控,发票指南演示了如何从图片中提取 JSON。