结构化输出
Grok 可以通过 Responses API 的 text.format、JSON Schema、清晰提示词和服务端校验生成稳定结构化结果。使用 Chat Completions 或 xAI SDK 时,也可能看到 response_format 写法。生产环境不要只依赖模型自觉输出正确 JSON,应配合解析和校验。
如何让 Grok 输出 JSON
简单场景可以设置 text.format,并在提示词中说明字段。
json
{
"model": "grok-4.3-latest",
"text": {
"format": {
"type": "json_object"
}
},
"input": [
{
"role": "user",
"content": "Extract the name and email from this text: Jane Doe, email jane.doe@example.com. Output JSON only."
}
]
}使用 JSON Schema 约束字段
对关键业务字段,建议使用 json_schema 约束结构。
json
{
"model": "grok-4.3-latest",
"text": {
"format": {
"type": "json_schema",
"name": "contact_info",
"schema": {
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" },
"intent": {
"type": "string",
"enum": ["complaint", "question", "praise", "other"]
}
},
"required": ["name", "email", "intent"],
"additionalProperties": false
},
"strict": true
}
},
"input": [
{
"role": "user",
"content": "Jane Doe says she paid but the order has not arrived. Her email is jane.doe@example.com"
}
]
}如何避免无效 JSON
- 使用低
temperature - 设置
text.format - 能用 schema 时使用
json_schema - 不要要求同时输出解释文本
- 服务端用 JSON parse 校验
- 失败时自动重试或进入人工复核
JSON 提示词模板
text
You are a structured information extraction assistant.
Requirements:
1. Output valid JSON only
2. Do not output Markdown
3. Do not add fields that are not in the schema
4. Use null for fields that cannot be determined
JSON structure:
{
"summary": "string",
"risk_level": "low | medium | high",
"reasons": ["string"],
"need_manual_review": true
}结合工具调用获得稳定结构
如果结构化结果非常关键,可以把目标结构定义为工具参数,让 Grok 通过工具调用返回参数。
json
{
"type": "function",
"name": "submit_contact_info",
"description": "Submit structured contact information",
"parameters": {
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" },
"intent": {
"type": "string",
"enum": ["complaint", "question", "praise", "other"]
}
},
"required": ["name", "email", "intent"],
"additionalProperties": false
}
}服务端 JSON 校验建议
- 使用 JSON Schema 或业务校验器检查字段
- 对枚举值、金额、日期、手机号等做二次校验
- 记录原始输入、模型输出和解析错误
- 对解析失败任务设置重试次数上限
- 高风险业务不要直接执行模型输出结果