深度

Claude Extended Thinking 深度思考模式:复杂推理场景实战指南

Claude Extended Thinking(扩展思考)完整指南:工作原理、支持模型、API 用法、thinking budget 配置、流式输出处理、适用场景(数学/架构/安全审计)、成本控制与常见误区。

2026/3/154分钟 阅读ClaudeEagle

普通模式下,Claude 直接生成答案。Extended Thinking 开启后,Claude 会先进行内部推理——探索多个思路、自我验证、逐步推导——再给出最终答案。对于复杂问题,质量提升显著。

什么时候用 Extended Thinking

适合

  • 需要多步推理的数学/算法问题
  • 复杂系统架构设计(需要权衡多个方案)
  • 安全审计(需要穷举攻击面)
  • 代码 Bug 根因分析(需要追踪执行链路)
  • 需要高置信度答案的关键决策

不适合

  • 简单问答、格式转换
  • 对延迟敏感的实时应用
  • 预算有限的高频调用

支持的模型

  • claude-opus-4-5(效果最好)
  • claude-sonnet-4-5(性价比高)

基础用法

python
import anthropic
client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 10000  # 给思考过程分配的最大 Token 数
    },
    messages=[{
        "role": "user",
        "content": "Analyze the time complexity of this algorithm and suggest optimizations: [code]"
    }]
)

# 解析响应
for block in response.content:
    if block.type == "thinking":
        print("Thinking process:")
        print(block.thinking[:500])  # 推理过程
    elif block.type == "text":
        print("Answer:")
        print(block.text)  # 最终答案

thinking_budget 如何设置

budget_tokens 控制 Claude 内部思考过程的最大 Token 数。

场景建议 budget_tokens
简单推理1000-3000
中等复杂度5000-8000
复杂架构/算法10000-16000
极复杂问题32000+

注意:max_tokens 必须大于 budget_tokens(需要为答案留空间)。

流式输出(推荐生产使用)

python
with client.messages.stream(
    model="claude-sonnet-4-5",
    max_tokens=8000,
    thinking={"type": "enabled", "budget_tokens": 5000},
    messages=[{"role": "user", "content": user_question}]
) as stream:
    thinking_shown = False
    for event in stream:
        if hasattr(event, 'type'):
            if event.type == "content_block_start":
                if hasattr(event.content_block, "type"):
                    if event.content_block.type == "thinking" and not thinking_shown:
                        print("[Thinking...]", end="", flush=True)
                        thinking_shown = True
                    elif event.content_block.type == "text":
                        print("\n[Answer]")
            elif event.type == "content_block_delta":
                if hasattr(event.delta, 'text'):
                    print(event.delta.text, end='', flush=True)

三个实战场景

场景 1:复杂 Bug 根因分析

python
bug_prompt = """
This distributed system occasionally produces duplicate records.
Reproduce rate: ~0.1% under high load.
Stack: Redis distributed lock + PostgreSQL + async Python workers.

Analyze the root cause systematically. Consider:
1. Race conditions in the locking mechanism
2. Network partition scenarios
3. Worker crash/restart during transaction
4. Clock skew between services

Code: [paste relevant code]
"""

response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=12000,
    thinking={"type": "enabled", "budget_tokens": 8000},
    messages=[{"role": "user", "content": bug_prompt}]
)

场景 2:架构方案选型

python
arch_prompt = """
We need to design a real-time notification system for 10M users.
Requirements: <100ms delivery, 99.9% reliability, support push/email/SMS.
Current stack: Python/FastAPI, PostgreSQL, Redis.

Evaluate these approaches:
1. WebSocket + Redis Pub/Sub
2. Server-Sent Events + message queue
3. Third-party service (Firebase/Pusher)

Give detailed tradeoff analysis and a final recommendation.
"""

response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=16000,
    thinking={"type": "enabled", "budget_tokens": 12000},
    messages=[{"role": "user", "content": arch_prompt}]
)

场景 3:安全漏洞全面审计

python
security_prompt = """
Perform a comprehensive security audit of this authentication module.
Be exhaustive - think through every possible attack vector:
- Authentication bypass
- Session management flaws
- Injection vulnerabilities
- Cryptographic weaknesses
- Race conditions in auth flow

Code: [paste auth code]
"""

response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=10000,
    thinking={"type": "enabled", "budget_tokens": 8000},
    messages=[{"role": "user", "content": security_prompt}]
)

成本控制

thinking 内容按普通输出 Token 计费(thinking_tokens * output_price)。

模型思考 Token 价格(/百万)
Sonnet 4.5$15.00
Opus 4.5$75.00

策略

  • 先用较小的 budget(2000-5000)测试,质量够就不必加大
  • 只对真正复杂的问题开启,简单问题关闭节省成本
  • Sonnet + thinking 通常比 Opus 无 thinking 更划算

常见误区

误区 1:thinking 过程可以修改 thinking block 是只读的,不能预填充或在 few-shot 中使用。

误区 2:budget 越大越好 Claude 会自动决定用多少思考 Token,设置过大浪费成本。从 5000 开始调整。

误区 3:所有任务都应该开启 简单任务开启 thinking 反而可能降低效率(过度思考)。


来源:Extended Thinking - Anthropic 官方文档

相关文章推荐

深度Claude API 速率限制完全指南:限额说明、错误处理与优化策略Anthropic Claude API 速率限制完整说明:请求频率限制(RPM)、Token 用量限制(TPM/TPD)、不同使用层级的限额对比(免费层/Build/Scale/Enterprise)、429 错误的标准处理方式(指数退避重试)、提升限额的申请方法、Prompt Caching 和 Batch API 绕过限制的技巧,以及高并发场景的队列设计方案。2026/3/18深度Claude API Prompt Caching 详解:让重复内容成本降低 90%Claude API Prompt Caching 完整指南:工作原理、缓存命中条件、supported models、代码示例(系统提示缓存/文档缓存/对话历史缓存)、成本对比计算、TTL 机制与最佳实践。2026/3/14深度高级提示词工程完全指南 2026:CoT、Few-Shot 与 XML 结构化技巧面向 Claude API 开发者的高级提示词工程完整指南:Chain-of-Thought(思维链)的原理与触发方式、Few-Shot 示例选取策略、Zero-Shot CoT 触发词、XML 标签结构化输出控制(强制 JSON)、角色扮演提示的正确姿势、多步骤任务分解、Claude 专属优化技巧(正向指令 vs 禁止指令)以及提示词 A/B 测试框架。2026/3/21深度Anthropic Batch API 完全指南:大批量处理 Claude 请求节省 50% 成本Anthropic Messages Batches API 完整教程:批量 API 是什么(异步批处理/24小时内完成)、与普通 API 的成本对比(50% 折扣)、Python/Node.js 创建批次请求、轮询批次状态、下载并处理结果、错误处理(部分失败的处理方式)、适合与不适合批量处理的场景、批次取消与数据保留策略,以及批量处理 1000 篇文章摘要的完整实战示例。2026/3/20深度Claude API 错误码完全手册:所有错误类型、原因与解决方案Anthropic Claude API 错误码完整参考:authentication_error(401/403)、rate_limit_error(429)、invalid_request_error(400)、api_error(500)、overloaded_error(529)的详细说明,每种错误的常见触发原因、标准解决方案和代码示例(Python/Node.js),以及生产环境的错误处理最佳实践(区分可重试/不可重试错误)。2026/3/18深度Claude API 批量处理完全指南:Message Batches API 大规模数据处理实战Claude API Message Batches 完整教程:批量 API 原理、与普通 API 的区别(50% 成本折扣)、Python/Node.js 提交批次代码示例、进度追踪与结果获取、错误处理策略、并发批次管理,以及文档摘要/数据分类/批量翻译等典型大规模处理场景实战。2026/3/16