第 61 章:输出的精确控制

卷五协议验证日期:2026-05-17,基于 Anthropic Output Configuration 和 Structured Output 规范
前面六章都在讲输入。这一章讲输出——如何控制 Claude 回答的深度、格式和确定性。
路线图
1 | graph LR |
三大输出控制维度
| 维度 | 参数 | 效果 |
|---|---|---|
| 努力程度 | output_config.effort | 控制思考深度和 token 消耗 |
| 输出结构 | output_config.format | 强制 JSON Schema 格式 |
| 随机性 | temperature, top_p, top_k | 控制创造性和确定性 |
effort — 控制思考深度
1 | // → src/my-agent/output-config.ts |
各 effort 级别的行为和适用场景
| effort | 行为 | 典型场景 |
|---|---|---|
low | 精简回答,减少工具调用 | 分类、简单问答、高吞吐 |
medium | 平衡速度和质量 | 常规编程、Agent 任务 |
high | 全面分析(默认) | 复杂推理、代码审查 |
xhigh | 扩展探索(Opus 4.7) | 长时 Agent 任务(30分钟+) |
max | 最强能力,不限 token | 前沿问题、需要极致质量 |
各模型推荐设置
1 | // → src/my-agent/output-config.ts |
effort 与 thinking 的关系
1 | Opus 4.7: effort + adaptive thinking |
Structured Output — 强制 JSON
1 | // → src/my-agent/structured-output.ts |
Schema 约束
- 支持 JSON Schema Draft 2020-12
- 必须是
{ "type": "object", ... }顶层 - 不支持
oneOf、anyOf等复杂组合(子 schema 可用) - 模型保证输出符合 schema
错误处理
1 | // → src/my-agent/structured-output.ts |
采样参数 — 控制随机性
1 | // → src/my-agent/sampling.ts |
实现 OutputController
1 | // → src/my-agent/output-controller.ts |
试试看
任务 1:同一段代码审查,分别用 effort: "low"、effort: "medium"、effort: "high" 发送。比较回答的详细程度和 token 消耗。
任务 2:从一段自由文本中提取结构化数据(人名、年龄、技能),实现自动重试。
任务 3:对比 temperature: 0、temperature: 0.5、temperature: 1.0 下同一个创意写作任务(如”写一首关于编程的俳句”)的输出多样性。
常见错误
| 现象 | 原因 | 解法 |
|---|---|---|
| Schema 格式错误 | 不是合法的 JSON Schema | 用 JSON Schema validator 预检 |
| effort 不生效 | 模型不支持该 effort 级别 | 检查模型 capability |
| structured output 不精确 | Schema 过于宽松 | 加 additionalProperties: false |
| Opus 4.7 用 high 觉得不够 | 该用 xhigh | 编码/Agent 推荐起步 xhigh |
检查点
- 理解了 effort 五个级别及其与 thinking 的关系
- 能用
output_config.format强制结构化输出 - 理解了 temperature/top_p/top_k 的采样语义
- 实现了 OutputController(预设模式切换)
- 能根据任务类型选择合适的输出控制策略