结构化输出
Gemini 可以通过 responseMimeType、responseJsonSchema、清晰提示词和服务端校验生成稳定结构化结果。生产环境不要只依赖模型自觉输出正确 JSON,应配合解析和校验。
如何让 Gemini 输出 JSON
简单场景可以在 generationConfig 中设置响应格式,并在提示词中说明字段。
json
{
"generationConfig": {
"responseMimeType": "application/json",
"temperature": 0
},
"contents": [
{
"parts": [
{
"text": "Extract the name and email from this text: Jane Doe, email jane.doe@example.com. Output JSON only."
}
]
}
]
}使用 responseJsonSchema 约束字段
对关键业务字段,建议使用 schema 约束结构。
json
{
"generationConfig": {
"responseMimeType": "application/json",
"responseJsonSchema": {
"type": "OBJECT",
"properties": {
"name": { "type": "STRING" },
"email": { "type": "STRING" },
"intent": {
"type": "STRING",
"enum": ["complaint", "question", "praise", "other"]
}
},
"required": ["name", "email", "intent"]
}
},
"contents": [
{
"parts": [
{ "text": "Jane Doe says she paid but the order has not arrived. Her email is jane.doe@example.com" }
]
}
]
}如何避免无效 JSON
- 使用低
temperature - 设置
responseMimeType - 能用 schema 时使用
responseJsonSchema - 不要要求同时输出解释文本
- 服务端用 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
}结合函数调用获得稳定结构
如果结构化结果非常关键,可以把目标结构定义为函数参数,让 Gemini 通过函数调用返回参数。
json
{
"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"]
}
}服务端 JSON 校验建议
- 使用 JSON Schema 或业务校验器检查字段
- 对枚举值、金额、日期、手机号等做二次校验
- 记录原始输入、模型输出和解析错误
- 对解析失败任务设置重试次数上限
- 高风险业务不要直接执行模型输出结果