05Structured Output
L1P1
让模型稳定输出指定结构有三种主流方式,稳定度从低到高:
1. JSON mode(Anthropic 没专门 flag,靠 prompt 约束 + 后处理)。失败率 5~10%,需要 retry。
2. XML tags。Claude 训练数据里大量 XML,模型对 <answer>...</answer> 边界非常稳定。失败率 <1%,parse 用正则即可。
3. Tool use 作为结构化输出。把"返回结果"伪装成一个 tool 调用,模型按 schema 生成,SDK 自动校验类型。失败率接近 0。
// Tool-use-as-structured-output
tools = [{
name: "submit_answer",
description: "Submit the final structured answer",
input_schema: { type: "object", properties: {
summary: {type: "string"},
score: {type: "number"}
}, required: ["summary", "score"] }
}]
tool_choice = { type: "tool", name: "submit_answer" } // 强制调
失败 retry 策略:把 parse 错误塞回 messages 让模型修,最多 3 次,超过就降级或报错。
速查
"为什么 Anthropic 推荐 XML 标签?"——训练数据 XML 形式多,token 边界稳;且 XML 允许嵌套和注释,适合复杂结构。JSON 在长字符串里容易因为逗号/引号出错。