结构化输出
结构化输出(JSON Mode)让大模型直接返回可解析的标准 JSON 字符串,无需处理 json 等多余文本,避免下游解析失败和额外的格式校验。
使用方式
在请求体中设置 response_format 参数即可开启结构化输出,需满足以下两个条件:
- 设置 response_format 参数:将
response_format参数设置为{"type": "json_object"}。 - 提示词中包含 JSON 关键词:System Message 或 User Message 中必须包含 "JSON" 关键词(不区分大小写),否则 API 会返回错误:
'messages' must contain the word 'json' in some form, to use 'response_format' of type 'json_object'.
支持的模型
- GLM 系列:
glm-5.2,glm-5.1 - Qwen(通义千问)系列:
qwen3.7-plus,qwen3.6-plus,qwen3.6-flash,qwen3.6-35b-a3b
调用示例
如果你的项目已经接入 OpenAI SDK,把 base_url 和 model 换成下方的值即可直接复用,无需迁移到新 SDK。
python
# 首次使用前请先安装 OpenAI SDK:`pip install openai`
from openai import OpenAI
client = OpenAI(
base_url="https://maas-api.unisound.com/v1",
api_key="<API_KEY>",
)
completion = client.chat.completions.create(
model="qwen3.6-flash",
messages=[
{
"role": "system",
"content": "请抽取用户的姓名与年龄信息,以JSON格式返回"
},
{
"role": "user",
"content": "大家好,我叫刘五,今年34岁,邮箱是liuwu@example.com,平时喜欢打篮球和旅游",
},
],
response_format={"type": "json_object"}
)
json_string = completion.choices[0].message.content
print(json_string)
返回结果
{
"姓名": "刘五",
"年龄": 34
}
