Loading...
  • 建構
  • 管理
  • 模型與定價
  • 客戶端 SDK
  • API 參考
Search...
⌘K
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 的擴展思考功能來增強推理能力

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 中使用擴展思考的示例:

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}")

要打開擴展思考,添加一個 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.

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 進行串流的文件,請參閱串流訊息。

以下是如何處理思考串流的方法:

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.")

串流輸出範例:

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:交錯思考會自動發生。每個工具間推理步驟都會進入思考區塊而不是純文字,思考區塊預設會在回應中保留。不需要或不支援測試版標頭。
  • Claude Opus 4.7:使用自適應思考時會自動啟用交錯思考(Opus 4.7 上唯一支援的思考模式)。不需要測試版標頭。
  • Claude Opus 4.6:使用自適應思考時會自動啟用交錯思考。不需要測試版標頭。interleaved-thinking-2025-05-14 測試版標頭在 Opus 4.6 上已棄用,如果包含則會被安全地忽略。
  • Claude Sonnet 4.6:使用自適應思考時會自動啟用交錯思考(建議)。interleaved-thinking-2025-05-14 測試版標頭與手動擴展思考(thinking: {type: "enabled"})仍然可用但已棄用。
  • 其他 Claude 4 模型(Opus 4.5、Opus 4.1、Opus 4(已棄用)、Sonnet 4.5、Sonnet 4(已棄用)):將測試版標頭 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. If you pass them back, whether the API keeps or strips them depends on the model: Opus 4.5+ and Sonnet 4.6+ keep them in context by default; earlier Opus/Sonnet models and all Haiku models strip them. See context editing to configure this.

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 標頭或使用自適應思考自動支持使用自適應思考自動支持(不支持 beta 標頭)使用自適應思考自動支持(不支持 beta 標頭)。在此模型上,工具間推理移入思考塊。
思考塊保留不跨輪保留不跨輪保留默認保留默認保留默認保留默認保留。 在繼續不支持 Mythos 思考格式的模型上的對話時,塊被剝離。

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 prior assistant turns kept in context: only the last turn on earlier Opus/Sonnet models and all Haiku models; all turns by default on Opus 4.5+ and Sonnet 4.6+ (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 的思考能力,請查看擴展思考提示提示。

後續步驟

試試擴展思考 cookbook

在 cookbook 中探索思考的實際示例。

擴展思考提示提示

了解擴展思考的提示工程最佳實踐。

Was this page helpful?

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