Skip to content

结构化输出

Claude 可以通过清晰提示词、示例、工具调用 schema 和服务端校验生成稳定结构化结果。生产环境不要只依赖模型自觉输出正确 JSON,应配合解析和校验。

如何让 Claude 输出 JSON

简单场景可以在 system 和用户提示中明确只输出 JSON。

json
{
  "model": "claude-sonnet-4-5",
  "max_tokens": 800,
  "temperature": 0,
  "system": "You are an information extraction assistant. Output valid JSON only, not Markdown.",
  "messages": [
    {
      "role": "user",
      "content": "Extract the name and email from this text: Jane Doe, email jane.doe@example.com"
    }
  ]
}

如何约束字段

在提示词中写清字段、类型、必填规则和无法判断时的默认值。

text
Output JSON only:
{
  "name": "string | null",
  "email": "string | null",
  "phone": "string | null",
  "intent": "complaint | question | praise | other"
}

Use null for unknown fields and do not add extra fields.

如何避免无效 JSON

  • 使用低 temperature
  • 明确“只输出 JSON”
  • 不要要求同时输出解释文本
  • 给出完整 JSON 示例
  • 服务端用 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
}

结合工具调用获得稳定结构

如果结构化结果非常关键,可以把目标结构定义为工具的 input_schema,让 Claude 通过工具调用返回参数。

json
{
  "name": "submit_contact_info",
  "description": "Submit structured contact information",
  "input_schema": {
    "type": "object",
    "properties": {
      "name": { "type": "string" },
      "email": { "type": "string" },
      "intent": {
        "type": "string",
        "enum": ["complaint", "question", "praise", "other"]
      }
    },
    "required": ["name", "email", "intent"]
  }
}

服务端 JSON 校验建议

  • 使用 JSON Schema 或业务校验器检查字段
  • 对枚举值、金额、日期、手机号等做二次校验
  • 记录原始输入、模型输出和解析错误
  • 对解析失败任务设置重试次数上限
  • 高风险业务不要直接执行模型输出结果