Loading...
    • 构建
    • 管理
    • 模型和定价
    • 客户端 SDK
    • API 参考
    Search...
    ⌘K
    第一步
    Claude 简介快速开始
    使用 Claude 构建
    功能概览使用 Messages APIClaude API 技能处理停止原因
    模型能力
    扩展思考自适应思考工作量任务预算(测试版)快速模式(测试版:研究预览)结构化输出引用流式消息批量处理搜索结果流式拒绝多语言支持嵌入
    工具
    概览工具使用原理网络搜索工具网络获取工具代码执行工具顾问工具内存工具Bash 工具计算机使用工具文本编辑器工具
    工具基础设施
    工具参考工具搜索程序化工具调用细粒度工具流式传输
    上下文管理
    上下文窗口压缩上下文编辑提示缓存Token 计数
    处理文件
    Files APIPDF 支持图像和视觉
    技能
    概览快速开始最佳实践企业技能API 中的技能
    MCP
    远程 MCP 服务器MCP 连接器
    提示工程
    概览提示最佳实践Console 提示工具
    测试和评估
    定义成功并构建评估在 Console 中使用评估工具降低延迟
    加强防护栏
    减少幻觉提高输出一致性缓解越狱减少提示泄露
    资源
    术语表
    发布说明
    Claude Platform
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    模型能力

    使用扩展思考进行构建

    了解如何使用扩展思考来增强 Claude 的推理能力,用于复杂任务。

    Was this page helpful?

    • Claude Opus 4.5 及更高版本中的思考块保留

    This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.

    扩展思考为 Claude 提供了增强的推理能力,用于处理复杂任务,同时在提供最终答案之前提供不同级别的透明度来了解其逐步思考过程。

    对于 Claude Opus 4.7 及更高版本的模型,请使用自适应思考(thinking: {type: "adaptive"})与努力参数。手动扩展思考(thinking: {type: "enabled", budget_tokens: N})在 Claude Opus 4.7 及更高版本的模型上不再支持,会返回 400 错误。对于 Claude Opus 4.6 和 Claude Sonnet 4.6,也建议使用自适应思考;手动配置在这些模型上仍然可用,但已弃用,将在未来的模型版本中移除。

    支持的模型

    手动扩展思考(thinking: {type: "enabled", budget_tokens: N})在所有当前 Claude 模型上都支持,除了 Claude Opus 4.7 及更高版本的模型,其中不再接受此配置并会返回 400 错误。少数模型具有特定于模式的行为:

    • Claude Opus 4.7(claude-opus-4-7)及更高版本的模型: 不再支持手动扩展思考。改为使用自适应思考(thinking: {type: "adaptive"})与努力参数。
    • Claude Mythos Preview: 自适应思考是默认设置;也接受 thinking: {type: "enabled", budget_tokens: N}。不支持 thinking: {type: "disabled"},display 默认为 "omitted" 而不是返回思考内容。传递 display: "summarized" 以接收摘要。
    • Claude Opus 4.6(claude-opus-4-6): 建议使用自适应思考;手动模式(type: "enabled")已弃用但仍然可用。
    • Claude Sonnet 4.6(claude-sonnet-4-6): 建议使用自适应思考;手动模式(type: "enabled")与交错模式已弃用但仍然可用。

    API 行为在 Claude Sonnet 3.7 和 Claude 4 模型之间有所不同,但 API 形状保持完全相同。

    有关更多信息,请参阅不同模型版本中思考的差异。

    扩展思考的工作原理

    当扩展思考打开时,Claude 创建 thinking 内容块,其中输出其内部推理。Claude 在制作最终响应之前,从这个推理中获取见解。

    API 响应包括 thinking 内容块,后跟 text 内容块。

    以下是默认响应格式的示例:

    {
      "content": [
        {
          "type": "thinking",
          "thinking": "Let me analyze this step by step...",
          "signature": "WaUjzkypQ2mUEVM36O2TxuC06KN8xyfbJwyem2dw3URve/op91XWHOEBLLqIOMfFG/UvLEczmEsUjavL...."
        },
        {
          "type": "text",
          "text": "Based on my analysis..."
        }
      ]
    }

    有关扩展思考响应格式的更多信息,请参阅消息 API 参考。

    如何使用扩展思考

    以下是在消息 API 中使用扩展思考的示例:

    要打开扩展思考,添加一个 thinking 对象,将 type 参数设置为 enabled,并将 budget_tokens 设置为扩展思考的指定令牌预算。对于 Claude Opus 4.6 和 Claude Sonnet 4.6,改为使用 type: "adaptive"。有关详细信息,请参阅自适应思考。虽然 type: "enabled" 与 budget_tokens 在这些模型上仍然可用,但已弃用,将在未来版本中移除。

    budget_tokens 参数确定 Claude 允许用于其内部推理过程的最大令牌数。在 Claude 4 及更高版本的模型中,此限制适用于完整思考令牌,而不是摘要输出。更大的预算可以通过为复杂问题启用更彻底的分析来改进响应质量,尽管 Claude 可能不会使用整个分配的预算,特别是在 32k 以上的范围内。

    budget_tokens 在 Claude Opus 4.6 和 Claude Sonnet 4.6 上已弃用,将在未来的模型版本中移除。改为使用自适应思考与努力参数来控制思考深度。

    Claude Mythos Preview、Claude Opus 4.7 和 Claude Opus 4.6 支持最多 128k 输出令牌。Claude Sonnet 4.6 和 Claude Haiku 4.5 支持最多 64k。有关旧版模型的限制,请参阅模型概览。在消息批处理 API 上,output-300k-2026-03-24 测试版标头将 Opus 4.7、Opus 4.6 和 Sonnet 4.6 的输出限制提高到 300k。

    budget_tokens 必须设置为小于 max_tokens 的值。但是,当使用与工具交错的思考时,您可以超过此限制,因为令牌限制变成您的整个上下文窗口。

    摘要思考

    With extended thinking enabled, the Messages API for Claude 4 models returns a summary of Claude's full thinking process. Summarized thinking provides the full intelligence benefits of extended thinking, while preventing misuse. This is the default behavior on Claude 4 models when the display field on the thinking configuration is unset or set to "summarized". On Claude Opus 4.7 and Claude Mythos Preview, display defaults to "omitted" instead, so you must set display: "summarized" explicitly to receive summarized thinking.

    Here are some important considerations for summarized thinking:

    • You're charged for the full thinking tokens generated by the original request, not the summary tokens.
    • The billed output token count will not match the count of tokens you see in the response.
    • On Claude 4 models, the first few lines of thinking output are more verbose, providing detailed reasoning that's particularly helpful for prompt engineering purposes. Claude Mythos Preview summarizes from the first token, so its thinking blocks do not show this verbose preamble.
    • As Anthropic seeks to improve the extended thinking feature, summarization behavior is subject to change.
    • Summarization preserves the key ideas of Claude's thinking process with minimal added latency, enabling a streamable user experience and easy migration from Claude Sonnet 3.7 to Claude 4 and later models.
    • Summarization is processed by a different model than the one you target in your requests. The thinking model does not see the summarized output.

    Claude Sonnet 3.7 continues to return full thinking output.

    In rare cases where you need access to full thinking output for Claude 4 models, contact our sales team.

    控制思考显示

    The display field on the thinking configuration controls how thinking content is returned in API responses. It accepts two values:

    • "summarized": Thinking blocks contain summarized thinking text. See Summarized thinking for details. This is the default on Claude Opus 4.6, Claude Sonnet 4.6, and earlier Claude 4 models.
    • "omitted": Thinking blocks are returned with an empty thinking field. The signature field still carries the encrypted full thinking for multi-turn continuity (see Thinking encryption). This is the default on Claude Opus 4.7 and Claude Mythos Preview.

    Setting display: "omitted" is useful when your application doesn't surface thinking content to users. The primary benefit is faster time-to-first-text-token when streaming: The server skips streaming thinking tokens entirely and delivers only the signature, so the final text response begins streaming sooner.

    No SDK currently includes display in its type definitions. The Python SDK forwards unrecognized dict keys to the API at runtime; passing display in the thinking dict works transparently. The TypeScript SDK requires a type assertion. The C#, Go, Java, PHP, and Ruby SDKs require a direct HTTP request until native support lands.

    Here are some important considerations for omitted thinking:

    • You're still charged for the full thinking tokens. Omitting reduces latency, not cost.
    • If you pass thinking blocks back in multi-turn conversations, pass them unchanged. The server decrypts the signature to reconstruct the original thinking for prompt construction (see Preserving thinking blocks). Any text you place in the thinking field of a round-tripped omitted block is ignored.
    • display is invalid with thinking.type: "disabled" (there is nothing to display).
    • When using thinking.type: "adaptive" and the model skips thinking for a simple request, no thinking block is produced regardless of display.

    The signature field is identical whether display is "summarized" or "omitted". Switching display values between turns in a conversation is supported.

    在Claude Mythos Preview 上,display 默认为 "omitted"。本部分中的示例明确传递 display,以便它们适用于所有模型,但在 Mythos Preview 上,您可以不设置它并接收相同的行为。要在 Mythos Preview 上接收摘要思考,请明确设置 display: "summarized"。

    永远不会向最终用户显示思考内容的自动化管道可以跳过通过网络接收思考令牌的开销。对延迟敏感的应用程序获得相同的推理质量,而无需等待思考文本流开始最终响应。

    当设置 display: "omitted" 时,响应包含具有空 thinking 字段的 thinking 块:

    Output
    {
      "content": [
        {
          "type": "thinking",
          "thinking": "",
          "signature": "EosnCkYICxIMMb3LzNrMu..."
        },
        {
          "type": "text",
          "text": "The answer is 12,231."
        }
      ]
    }

    当使用 display: "omitted" 进行流式传输时,不会发出 thinking_delta 事件;有关事件序列,请参阅下面的流式思考。

    流式传输思考

    您可以使用服务器发送事件 (SSE)流式传输扩展思考响应。

    启用扩展思考的流式传输时,您会通过 thinking_delta 事件接收思考内容。

    当设置 display: "omitted" 时,不会发出 thinking_delta 事件。请参阅控制思考显示。

    有关通过 Messages API 进行流式传输的更多文档,请参阅流式传输消息。

    以下是如何处理思考流式传输的方法:

    流式传输输出示例:

    Output
    event: message_start
    data: {"type": "message_start", "message": {"id": "msg_01...", "type": "message", "role": "assistant", "content": [], "model": "claude-sonnet-4-6", "stop_reason": null, "stop_sequence": null}}
    
    event: content_block_start
    data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I need to find the GCD of 1071 and 462 using the Euclidean algorithm.\n\n1071 = 2 × 462 + 147"}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\n462 = 3 × 147 + 21\n147 = 7 × 21 + 0\n\nSo GCD(1071, 462) = 21"}}
    
    // Additional thinking deltas...
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."}}
    
    event: content_block_stop
    data: {"type": "content_block_stop", "index": 0}
    
    event: content_block_start
    data: {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "The greatest common divisor of 1071 and 462 is **21**."}}
    
    // Additional text deltas...
    
    event: content_block_stop
    data: {"type": "content_block_stop", "index": 1}
    
    event: message_delta
    data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}}
    
    event: message_stop
    data: {"type": "message_stop"}

    当设置 display: "omitted" 时,思考块打开,单个 signature_delta 到达,块关闭而不发出任何 thinking_delta 事件。文本流式传输在之后立即开始:

    Output
    event: content_block_start
    data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"EosnCkYICxIMMb3LzNrMu..."}}
    
    event: content_block_stop
    data: {"type":"content_block_stop","index":0}
    
    event: content_block_start
    data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}

    使用启用思考的流式传输时,您可能会注意到文本有时以较大的块到达,交替出现较小的逐令牌传输。这是预期的行为,特别是对于思考内容。

    流式传输系统需要分批处理内容以获得最佳性能,这可能导致这种"分块"传输模式,流式传输事件之间可能会出现延迟。Anthropic 正在不断努力改进这种体验,未来的更新将专注于使思考内容流式传输更加平滑。

    扩展思考与工具使用

    扩展思考可以与工具使用一起使用,允许 Claude 通过工具选择和结果处理进行推理。

    使用扩展思考和工具使用时,请注意以下限制:

    1. 工具选择限制:带有思考的工具使用仅支持 tool_choice: {"type": "auto"}(默认值)或 tool_choice: {"type": "none"}。使用 tool_choice: {"type": "any"} 或 tool_choice: {"type": "tool", "name": "..."} 会导致错误,因为这些选项强制工具使用,这与扩展思考不兼容。

    2. 保留思考块:在工具使用期间,您必须将 thinking 块传回 API 以用于最后的助手消息。将完整的未修改块传回 API 以保持推理连续性。

    在对话中切换思考模式

    您无法在助手回合中途切换思考,包括在工具使用循环期间。整个助手回合应该在单一思考模式下运行:

    • 如果启用了思考,最终的助手回合应该以思考块开始。
    • 如果禁用了思考,最终的助手回合不应该包含任何思考块

    从模型的角度来看,工具使用循环是助手回合的一部分。助手回合直到 Claude 完成其完整响应(可能包括多个工具调用和结果)才完成。

    例如,这个序列都是单个助手回合的一部分:

    User: "What's the weather in Paris?"
    Assistant: [thinking] + [tool_use: get_weather]
    User: [tool_result: "20°C, sunny"]
    Assistant: [text: "The weather in Paris is 20°C and sunny"]

    尽管有多个 API 消息,工具使用循环在概念上是一个连续的助手响应的一部分。

    优雅的思考降级

    当发生中途思考冲突时(例如在工具使用循环期间切换思考开启或关闭),API 会自动为该请求禁用思考。为了保持模型质量并保持在分布内,API 可能会:

    • 当思考块会创建无效的回合结构时,从对话中删除思考块
    • 当对话历史与启用思考不兼容时,为当前请求禁用思考

    这意味着尝试在中途切换思考不会导致错误,但该请求的思考将被静默禁用。要确认思考是否处于活动状态,请检查响应中是否存在 thinking 块。

    实践指导

    最佳实践:在每个回合开始时规划您的思考策略,而不是尝试在中途切换。

    示例:在完成回合后切换思考

    User: "What's the weather?"
    Assistant: [tool_use] (thinking disabled)
    User: [tool_result]
    Assistant: [text: "It's sunny"]
    User: "What about tomorrow?"
    Assistant: [thinking] + [text: "..."] (thinking enabled - new turn)

    通过在切换思考之前完成助手回合,您可以确保思考对新请求实际启用。

    切换思考模式也会使消息历史的提示缓存失效。有关更多详细信息,请参阅 扩展思考与提示缓存 部分。

    保留思考块

    在工具使用期间,您必须将 thinking 块传递回 API,并且必须将完整的未修改块传递回 API。这对于维持模型的推理流和对话完整性至关重要。

    虽然您可以从之前的 assistant 角色回合中省略 thinking 块,但对于任何多回合对话,始终将所有思考块传递回 API。API 会:

    • 自动过滤提供的思考块
    • 使用必要的相关思考块来保留模型的推理
    • 仅对显示给 Claude 的块的输入令牌进行计费

    在对话期间切换思考模式时,请记住整个助手回合(包括工具使用循环)必须在单一思考模式下运行。有关更多详细信息,请参阅 在对话中切换思考模式。

    当 Claude 调用工具时,它暂停了响应的构建以等待外部信息。当工具结果返回时,Claude 继续构建该现有响应。这需要在工具使用期间保留思考块,原因有几个:

    1. 推理连续性:思考块捕获了导致工具请求的 Claude 的逐步推理。当您发布工具结果时,包括原始思考可以确保 Claude 可以从中断的地方继续推理。

    2. 上下文维护:虽然工具结果在 API 结构中显示为用户消息,但它们是连续推理流的一部分。保留思考块在多个 API 调用中维持这个概念流。有关上下文管理的更多信息,请参阅 上下文窗口指南。

    重要:提供 thinking 块时,连续 thinking 块的整个序列必须与模型在原始请求期间生成的输出相匹配;您不能重新排列或修改这些块的序列。

    交错思考

    Claude 4 模型中的扩展思考与工具使用支持交错思考,这使 Claude 能够在工具调用之间进行思考,并在接收工具结果后进行更复杂的推理。

    通过交错思考,Claude 可以:

    • 在决定接下来做什么之前对工具调用的结果进行推理
    • 在推理步骤之间链接多个工具调用
    • 基于中间结果做出更细致的决定

    模型支持:

    • Claude Mythos Preview:交错思考自动发生。每个工具间推理步骤都进入思考块而不是纯文本,思考块默认在回合之间保留。不需要或支持 beta 标头。
    • Claude Opus 4.7:使用 自适应思考 时自动启用交错思考(Opus 4.7 上唯一支持的思考模式)。不需要 beta 标头。
    • Claude Opus 4.6:使用 自适应思考 时自动启用交错思考。不需要 beta 标头。interleaved-thinking-2025-05-14 beta 标头在 Opus 4.6 上已弃用,如果包含则被安全忽略。
    • Claude Sonnet 4.6:使用 自适应思考 时自动启用交错思考(推荐)。interleaved-thinking-2025-05-14 beta 标头与手动扩展思考(thinking: {type: "enabled"})仍然可用但已弃用。
    • 其他 Claude 4 模型(Opus 4.5、Opus 4.1、Opus 4(已弃用)、Sonnet 4.5、Sonnet 4(已弃用)):将 beta 标头 interleaved-thinking-2025-05-14 添加到您的 API 请求以启用交错思考。

    以下是交错思考的一些重要注意事项:

    • 使用交错思考时,budget_tokens 可以超过 max_tokens 参数,因为它代表一个助手回合内所有思考块的总预算。
    • 交错思考仅支持 通过 Messages API 使用的工具。
    • 对 Claude API 的直接调用允许您在请求中向任何模型传递 interleaved-thinking-2025-05-14,无任何效果(除了 Opus 4.7 和 Opus 4.6,其中已弃用并被安全忽略)。
    • 在第三方平台上(例如,Amazon Bedrock 和 Vertex AI),如果您将 interleaved-thinking-2025-05-14 传递给除 Claude Opus 4.7、Claude Opus 4.6、Claude Sonnet 4.6、Claude Opus 4.5、Claude Opus 4.1、Opus 4(已弃用)、Sonnet 4.5 或 Sonnet 4(已弃用)之外的任何模型,您的请求将失败。

    扩展思考与提示缓存

    提示缓存与思考有几个重要的考虑事项:

    扩展思考任务通常需要超过5分钟才能完成。考虑使用1小时缓存持续时间来在较长的思考会话和多步骤工作流中保持缓存命中。

    思考块上下文移除

    • 来自前面轮次的思考块会从上下文中移除,这可能会影响缓存断点
    • 当继续使用工具的对话时,思考块被缓存并在从缓存读取时计为输入令牌
    • 这造成了一个权衡:虽然思考块在视觉上不消耗上下文窗口空间,但在缓存时仍然计入您的输入令牌使用量
    • 如果思考被禁用,并且您在当前工具使用轮次中传递思考内容,思考内容将被剥离,该请求的思考将保持禁用状态

    缓存失效模式

    • 对思考参数(启用/禁用或预算分配)的更改会使消息缓存断点失效
    • 交错思考会放大缓存失效,因为思考块可能出现在多个工具调用之间
    • 系统提示和工具尽管思考参数更改或块移除,仍保持缓存状态

    虽然思考块为了缓存和上下文计算而被移除,但在继续使用工具的对话时必须保留,特别是使用交错思考时。

    理解思考块缓存行为

    在使用扩展思考和工具使用时,思考块表现出特定的缓存行为,这会影响令牌计数:

    工作原理:

    1. 仅当您发出包含工具结果的后续请求时,缓存才会发生
    2. 当发出后续请求时,之前的对话历史(包括思考块)可以被缓存
    3. 这些缓存的思考块在从缓存读取时计为使用指标中的输入令牌
    4. 当包含非工具结果用户块时,所有之前的思考块都会被忽略并从上下文中删除

    详细示例流程:

    请求 1:

    User: "What's the weather in Paris?"

    响应 1:

    [thinking_block_1] + [tool_use block 1]

    请求 2:

    User: ["What's the weather in Paris?"],
    Assistant: [thinking_block_1] + [tool_use block 1],
    User: [tool_result_1, cache=True]

    响应 2:

    [thinking_block_2] + [text block 2]

    请求 2 写入请求内容的缓存(不是响应)。缓存包括原始用户消息、第一个思考块、工具使用块和工具结果。

    请求 3:

    User: ["What's the weather in Paris?"],
    Assistant: [thinking_block_1] + [tool_use block 1],
    User: [tool_result_1, cache=True],
    Assistant: [thinking_block_2] + [text block 2],
    User: [Text response, cache=True]

    对于 Claude Opus 4.5 及更高版本(包括 Claude Opus 4.6),默认情况下保留所有之前的思考块。对于较旧的模型,因为包含了非工具结果用户块,所有之前的思考块都会被忽略。此请求的处理方式与以下相同:

    User: ["What's the weather in Paris?"],
    Assistant: [tool_use block 1],
    User: [tool_result_1, cache=True],
    Assistant: [text block 2],
    User: [Text response, cache=True]

    关键点:

    • 此缓存行为自动发生,即使没有显式的 cache_control 标记
    • 此行为在使用常规思考或交错思考时是一致的

    最大令牌数和扩展思考的上下文窗口大小

    在较早的 Claude 模型(Claude Sonnet 3.7 之前)中,如果提示令牌和 max_tokens 的总和超过了模型的上下文窗口,系统会自动调整 max_tokens 以适应上下文限制。这意味着您可以设置一个较大的 max_tokens 值,系统会根据需要静默地减少它。

    使用 Claude 3.7 和 4 模型,max_tokens(启用思考时包括您的思考预算)被强制执行为严格限制。如果提示令牌 + max_tokens 超过上下文窗口大小,系统现在将返回验证错误。

    您可以阅读关于上下文窗口的指南以获得更深入的了解。

    扩展思考的上下文窗口

    在启用思考的情况下计算上下文窗口使用时,需要注意一些事项:

    • 来自先前轮次的思考块被剥离,不计入您的上下文窗口
    • 当前轮次的思考计入该轮次的 max_tokens 限制

    下图演示了启用扩展思考时的专门令牌管理:

    扩展思考的上下文窗口图

    有效的上下文窗口计算如下:

    context window =
      (current input tokens - previous thinking tokens) +
      (thinking tokens + encrypted thinking tokens + text output tokens)

    使用令牌计数 API为您的特定用例获取准确的令牌计数,特别是在处理包含思考的多轮对话时。

    扩展思考和工具使用的上下文窗口

    使用扩展思考和工具使用时,思考块必须被明确保留并与工具结果一起返回。

    扩展思考和工具使用的有效上下文窗口计算变为:

    context window =
      (current input tokens + previous thinking tokens + tool use tokens) +
      (thinking tokens + encrypted thinking tokens + text output tokens)

    下图说明了扩展思考和工具使用的令牌管理:

    扩展思考和工具使用的上下文窗口图

    使用扩展思考管理令牌

    鉴于 Claude 3.7 和 4 模型的上下文窗口和 max_tokens 行为与扩展思考,您可能需要:

    • 更积极地监控和管理您的令牌使用
    • 随着提示长度的变化调整 max_tokens 值
    • 可能更频繁地使用令牌计数端点
    • 意识到先前的思考块不会在您的上下文窗口中累积

    进行此更改是为了提供更可预测和透明的行为,特别是因为最大令牌限制已显著增加。

    思考加密

    Full thinking content is encrypted and returned in the signature field. This field is used to verify that thinking blocks were generated by Claude when passed back to the API.

    It is only strictly necessary to send back thinking blocks when using tools with extended thinking. Otherwise you can omit thinking blocks from previous turns, or let the API strip them for you if you pass them back.

    If sending back thinking blocks, we recommend passing everything back as you received it for consistency and to avoid potential issues.

    Here are some important considerations on thinking encryption:

    • When streaming responses, the signature is added via a signature_delta inside a content_block_delta event just before the content_block_stop event.
    • signature values are significantly longer in Claude 4 models than in previous models.
    • The signature field is an opaque field and should not be interpreted or parsed.
    • signature values are compatible across platforms (Claude APIs, Amazon Bedrock, and Vertex AI). Values generated on one platform will be compatible with another.

    编辑的思考块

    除了常规的 thinking 块外,API 还可能返回 redacted_thinking 块。redacted_thinking 块在 data 字段中包含加密的思考内容,没有可读的摘要:

    {
      "type": "redacted_thinking",
      "data": "..."
    }

    data 字段是不透明的和加密的。与常规思考块上的 signature 字段一样,在使用工具继续多轮对话时,您应该将 redacted_thinking 块原封不动地传回 API。

    如果您的代码按类型过滤内容块(例如,block.type == "thinking")以在工具使用时往返响应,也要包括 redacted_thinking 块。仅按 block.type == "thinking" 过滤会静默地丢弃 redacted_thinking 块并破坏上述多轮协议。

    redacted_thinking 块是 API 在思考的某些部分被安全编辑时返回的不同内容块类型。这与display: "omitted"选项不同,后者返回带有空 thinking 字段的常规 thinking 块。

    不同模型版本中的思考差异

    Messages API 在 Claude Sonnet 3.7 和 Claude 4 模型中处理思考的方式不同,主要是在摘要行为方面。

    请参阅下表以获得简明比较:

    功能Claude Sonnet 3.7Claude 4 模型(Opus 4.5 之前)Claude Opus 4.5Claude Sonnet 4.6Claude Opus 4.6(自适应思考)Claude Mythos 预览版(自适应思考)
    思考输出返回完整思考输出返回摘要思考返回摘要思考返回摘要思考返回摘要思考默认情况下省略;设置 display: "summarized" 以接收摘要思考。原始思考令牌永远不会返回。
    交错思考不支持支持 interleaved-thinking-2025-05-14 beta 标头支持 interleaved-thinking-2025-05-14 beta 标头支持 interleaved-thinking-2025-05-14 beta 标头或使用自适应思考自动支持

    Claude Opus 4.5 及更高版本中的思考块保留

    从 Claude Opus 4.5 开始(并在 Claude Opus 4.6 中继续),来自先前助手轮次的思考块默认在模型上下文中被保留。这与较早的模型不同,较早的模型会删除先前轮次的思考块。

    思考块保留的好处:

    • 缓存优化:使用工具使用时,保留的思考块可以实现缓存命中,因为它们与工具结果一起传回并在助手轮次中增量缓存,导致多步工作流中的令牌节省
    • 无智能影响:保留思考块对模型性能没有负面影响

    重要考虑事项:

    • 上下文使用:长对话将消耗更多上下文空间,因为思考块保留在上下文中
    • 自动行为:这是 Claude Opus 4.5 及更高版本模型(包括 Claude Mythos 预览版和 Claude Opus 4.6)的默认行为。不需要代码更改或 beta 标头
    • 向后兼容性:要利用此功能,继续将完整的、未修改的思考块传回 API,就像您对工具使用所做的那样

    对于较早的模型(Claude Sonnet 4.5、Opus 4.1 等),来自先前轮次的思考块继续从上下文中被删除。扩展思考与提示缓存部分中描述的现有行为适用于这些模型。

    定价

    For complete pricing information including base rates, cache writes, cache hits, and output tokens, see the pricing page.

    The thinking process incurs charges for:

    • Tokens used during thinking (output tokens)
    • Thinking blocks from the last assistant turn included in subsequent requests (input tokens)
    • Standard text output tokens

    When extended thinking is enabled, a specialized system prompt is automatically included to support this feature.

    When using summarized thinking:

    • Input tokens: Tokens in your original request (excludes thinking tokens from previous turns)
    • Output tokens (billed): The original thinking tokens that Claude generated internally
    • Output tokens (visible): The summarized thinking tokens you see in the response
    • No charge: Tokens used to generate the summary

    When using display: "omitted":

    • Input tokens: Tokens in your original request (same as summarized)
    • Output tokens (billed): The original thinking tokens that Claude generated internally (same as summarized)
    • Output tokens (visible): Zero thinking tokens (the thinking field is empty)

    The billed output token count will not match the visible token count in the response. You are billed for the full thinking process, not the thinking content visible in the response.

    扩展思考的最佳实践和考虑事项

    使用思考预算

    • 预算优化: 最小预算为 1,024 个令牌。从最小值开始,逐步增加思考预算以找到适合您用例的最优范围。更高的令牌计数可以实现更全面的推理,但根据任务的不同会有递减的回报。增加预算可以改善响应质量,但代价是增加延迟。对于关键任务,测试不同的设置以找到最优平衡。请注意,思考预算是一个目标而不是严格限制。实际令牌使用可能因任务而异。
    • 起点: 对于复杂任务,从较大的思考预算(16k+ 个令牌)开始,并根据您的需求进行调整。
    • 大预算: 对于思考预算超过 32k 的情况,使用批处理以避免网络问题。推动模型思考超过 32k 个令牌的请求会导致长时间运行的请求,可能会遇到系统超时和开放连接限制。
    • 令牌使用跟踪: 监控思考令牌使用以优化成本和性能。

    性能考虑

    • 响应时间: 准备好因额外处理而导致的更长响应时间。生成思考块会增加总体响应时间。
    • 流式传输要求: 当 max_tokens 大于 21,333 时,SDK 需要流式传输以避免长时间运行请求的 HTTP 超时。这是客户端验证,而不是 API 限制。如果您不需要增量处理事件,使用 .stream() 与 .get_final_message()(Python)或 .finalMessage()(TypeScript)来获取完整的 Message 对象,而无需处理单个事件。有关详细信息,请参阅流式消息。流式传输时,准备好在思考和文本内容块到达时处理它们。
    • 为了降低延迟而省略思考: 如果您的应用程序不显示思考内容,在思考配置上设置 display: "omitted" 以减少首个文本令牌的时间。请参阅控制思考显示。

    功能兼容性

    • 思考与 temperature 或 top_k 修改以及强制工具使用不兼容。
    • 启用思考时,您可以将 top_p 设置为 1 到 0.95 之间的值。
    • 启用思考时,您无法预填充响应。
    • 对思考预算的更改会使包含消息的缓存提示前缀失效。但是,当思考参数更改时,缓存的系统提示和工具定义将继续工作。

    使用指南

    • 任务选择: 对于特别复杂的任务,使用扩展思考,这些任务受益于逐步推理,如数学、编码和分析。
    • 上下文处理: 您不需要自己删除先前的思考块。Claude API 会自动忽略先前轮次的思考块,在计算上下文使用时不包括它们。
    • 提示工程: 如果您想最大化 Claude 的思考能力,请查看扩展思考提示提示。

    后续步骤

    尝试扩展思考食谱

    在食谱中探索思考的实际示例。

    client = anthropic.Anthropic()
    
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=16000,
        thinking={"type": "enabled", "budget_tokens": 10000},
        messages=[
            {
                "role": "user",
                "content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
            }
        ],
    )
    
    # The response contains summarized thinking blocks and text blocks
    for block in response.content:
        if block.type == "thinking":
            print(f"\nThinking summary: {block.thinking}")
        elif block.type == "text":
            print(f"\nResponse: {block.text}")
    Try in Console
    client = anthropic.Anthropic()
    
    with client.messages.stream(
        model="claude-sonnet-4-6",
        max_tokens=16000,
        thinking={"type": "enabled", "budget_tokens": 10000},
        messages=[
            {
                "role": "user",
                "content": "What is the greatest common divisor of 1071 and 462?",
            }
        ],
    ) as stream:
        thinking_started = False
        response_started = False
    
        for event in stream:
            if event.type == "content_block_start":
                print(f"\nStarting {event.content_block.type} block...")
                # Reset flags for each new block
                thinking_started = False
                response_started = False
            elif event.type == "content_block_delta":
                if event.delta.type == "thinking_delta":
                    if not thinking_started:
                        print("Thinking: ", end="", flush=True)
                        thinking_started = True
                    print(event.delta.thinking, end="", flush=True)
                elif event.delta.type == "text_delta":
                    if not response_started:
                        print("Response: ", end="", flush=True)
                        response_started = True
                    print(event.delta.text, end="", flush=True)
            elif event.type == "content_block_stop":
                print("\nBlock complete.")

    使用自适应思考自动支持(不支持 beta 标头)
    使用自适应思考自动支持(不支持 beta 标头)。工具间推理在此模型上移入思考块。
    思考块保留不跨轮保留不跨轮保留默认保留默认保留默认保留默认保留。 在继续与不支持 Mythos 思考格式的模型的对话时,块被剥离。
    扩展思考提示提示

    了解扩展思考的提示工程最佳实践。