请求 JSON Object
明确要求模型返回 JSON,并设置response_format。部分模型要求指令中显式出现 “JSON”。
curl https://api.yelu.ai/v1/chat/completions \
-H "Authorization: Bearer $YELU_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"gpt-4o-mini","messages":[{"role":"system","content":"返回包含 summary 和 priority 的有效 JSON。"},{"role":"user","content":"结账 API 有 5% 的请求返回 503。"}],"response_format":{"type":"json_object"},"temperature":0}'
const response = await fetch('https://api.yelu.ai/v1/chat/completions', {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.YELU_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: '返回包含 summary 和 priority 的有效 JSON。' },
{ role: 'user', content: '结账 API 有 5% 的请求返回 503。' },
],
response_format: { type: 'json_object' },
temperature: 0,
}),
});
if (!response.ok) throw new Error(await response.text());
console.log(JSON.parse((await response.json()).choices[0].message.content));
import json
import os
import requests
response = requests.post(
"https://api.yelu.ai/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['YELU_API_KEY']}"},
json={
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "返回包含 summary 和 priority 的有效 JSON。"},
{"role": "user", "content": "结账 API 有 5% 的请求返回 503。"},
],
"response_format": {"type": "json_object"},
"temperature": 0,
},
timeout=60,
)
response.raise_for_status()
print(json.loads(response.json()["choices"][0]["message"]["content"]))
使用 JSON Schema
支持严格结构化输出的模型可以使用:{
"type": "json_schema",
"json_schema": {
"name": "incident_triage",
"strict": true,
"schema": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"priority": {"type": "string", "enum": ["low", "medium", "high", "critical"]}
},
"required": ["summary", "priority"],
"additionalProperties": false
}
}
}
应用边界校验
应用必须检查 HTTP 与 Finish Status、限制 JSON 大小与深度、使用同一 Schema 校验、拒绝不安全的未知字段、执行领域规则,并分别处理拒绝、截断和 Schema 失败。| 能力 | JSON Object | JSON Schema |
|---|---|---|
| 有效 JSON 语法 | 目标能力 | 目标能力 |
| 必填字段与类型 | 依赖 Prompt | 严格支持时由 Schema 约束 |
| 模型覆盖 | 更广 | 更窄 |
| 适用场景 | 灵活抽取、原型 | 生产数据契约 |
不要把模型生成的 JSON 未经上下文校验和转义就拼接到 SQL、Shell、HTML 或授权规则中。