JSON Output
用于需要结构化输出、由后续代码直接解析的场景。调用时需明确要求模型输出 JSON,并提供输出样例。
开启方式
在Chat Completions API 的请求体里加一个参数:
{
"model": "<模型名>",
"messages": [
{ "role": "system", "content": "按要求把结果以 json 输出,样例:{\"question\": \"...\", \"answer\": \"...\"}" },
{ "role": "user", "content": "把这段内容解析成 question 和 answer" }
],
"response_format": { "type": "json_object" }
}
注意事项
| 检查项 | 说明 |
|---|---|
prompt 中需出现 json 字样 |
不出现时,模型可能不按 JSON 输出,甚至直接报错 |
| 提供输出样例 | 把期望的结构写进 system 或 user 消息,模型按该结构输出。只写“输出 JSON”是不够的 |
max_tokens 不宜过小 |
JSON 被截断就不是合法 JSON,解析必然失败(此时 finish_reason 是 length) |
请求示例
curl https://open.feiyutoken.com/v1/chat/completions \
-H "Authorization: Bearer <你的飞鱼Token API Key>" \
-H "Content-Type: application/json" \
-d '{
"model": "<模型名>",
"messages": [
{
"role": "system",
"content": "把用户给的题目解析成 json,样例:{\"question\": \"...\", \"answer\": \"...\"}"
},
{ "role": "user", "content": "世界上最高的山是哪座?珠穆朗玛峰。" }
],
"response_format": { "type": "json_object" }
}'
响应
content 是一段字符串,内容是合法 JSON:
{
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\n \"question\": \"世界上最高的山是哪座?\",\n \"answer\": \"珠穆朗玛峰\"\n}"
},
"finish_reason": "stop"
}
],
"usage": { "prompt_tokens": 48, "completion_tokens": 24, "total_tokens": 72 }
}
需将 content 作为字符串做一次 JSON 解析后再使用 —— 它不会自动变成对象。
哪些模型支持这个参数,以控制台模型列表里的说明为准。