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
建構/上下文管理

上下文編輯

隨著對話成長自動管理對話上下文,使用上下文編輯。

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 看到的內容:上下文是一種有限資源,具有遞減的回報,無關內容會降低模型的專注力。上下文編輯為您提供對該策劃的細粒度運行時控制。有關上下文管理背後的更廣泛原則,請參閱有效的上下文工程。本頁面涵蓋:

  • 工具結果清除 - 最適合使用大量工具的代理工作流,其中不再需要舊的工具結果
  • 思考塊清除 - 用於在使用擴展思考時管理思考塊,可選擇保留最近的思考以保持上下文連續性
  • 客戶端 SDK 壓縮 - 用於基於摘要的上下文管理的 SDK 替代方案(通常首選伺服器端壓縮)
方法運行位置策略工作原理
伺服器端API工具結果清除 (clear_tool_uses_20250919)
思考塊清除 (clear_thinking_20251015)
在提示到達 Claude 之前應用。清除對話歷史中的特定內容。每個策略可以獨立配置。
客戶端SDK壓縮在使用 tool_runner 時在 Python、TypeScript 和 Ruby SDK 中可用。生成摘要並替換完整的對話歷史。請參閱下面的客戶端壓縮。

伺服器端策略

上下文編輯處於測試版,支持工具結果清除和思考塊清除。要啟用它,請在您的 API 請求中使用測試版標頭 context-management-2025-06-27。

通過反饋表單分享對此功能的反饋。

工具結果清除

clear_tool_uses_20250919 策略在對話上下文超過您配置的閾值時清除工具結果。這對於使用大量工具的代理工作流特別有用。一旦 Claude 處理了舊的工具結果(如文件內容或搜索結果),就不再需要它們。

激活後,API 會按時間順序自動清除最舊的工具結果。API 用佔位符文本替換每個清除的結果,以便 Claude 知道它已被移除。默認情況下,只清除工具結果。您可以通過將 clear_tool_inputs 設置為 true 來選擇性地清除工具結果和工具調用(工具使用參數)。

思考塊清除

clear_thinking_20251015 策略在啟用擴展思考時管理對話中的 thinking 塊。此策略讓您可以控制思考保留:您可以選擇保留更多思考塊以保持推理連續性,或更積極地清除它們以節省上下文空間。

默認行為: 啟用擴展思考而不配置 clear_thinking_20251015 策略時,API 會自動僅保留最後一個助手轉向的思考塊(等同於 keep: {type: "thinking_turns", value: 1})。

要最大化緩存命中,通過設置 keep: "all" 保留所有思考塊。

助手對話轉向可能包括多個內容塊(例如使用工具時)和多個思考塊(例如使用交錯思考時)。

上下文編輯在伺服器端進行

上下文編輯在提示到達 Claude 之前在伺服器端應用。您的客戶端應用程序維護完整的、未修改的對話歷史。您無需將客戶端狀態與編輯版本同步。像往常一樣繼續在本地管理您的完整對話歷史。

上下文編輯和提示緩存

上下文編輯與提示緩存的交互因策略而異:

  • 工具結果清除:清除內容時使緩存的提示前綴失效。為了解決這個問題,清除足夠的令牌以使緩存失效值得。使用 clear_at_least 參數確保每次清除內容時至少清除最少數量的令牌。每次清除內容時您都會產生緩存寫入成本,但後續請求可以重用新緩存的前綴。

  • 思考塊清除:當思考塊保留在上下文中(未清除)時,提示緩存被保留,啟用緩存命中並減少輸入令牌成本。當思考塊被清除時,緩存在清除發生的位置失效。根據您是否想優先考慮緩存性能或上下文窗口可用性來配置 keep 參數。

支持的模型

上下文編輯在所有支持的 Claude 模型上可用。

工具結果清除使用

啟用工具結果清除的最簡單方法是僅指定策略類型。所有其他配置選項使用其默認值:

response = client.beta.messages.create(
    model="claude-opus-4-7",
    max_tokens=4096,
    messages=[{"role": "user", "content": "Search for recent developments in AI"}],
    tools=[{"type": "web_search_20250305", "name": "web_search"}],
    betas=["context-management-2025-06-27"],
    context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
)

進階配置

您可以使用其他參數自訂工具結果清除行為:

response = client.beta.messages.create(
    model="claude-opus-4-7",
    max_tokens=4096,
    messages=[
        {
            "role": "user",
            "content": "Create a simple command line calculator app using Python",
        }
    ],
    tools=[
        {
            "type": "text_editor_20250728",
            "name": "str_replace_based_edit_tool",
            "max_characters": 10000,
        },
        {"type": "web_search_20250305", "name": "web_search", "max_uses": 3},
    ],
    betas=["context-management-2025-06-27"],
    context_management={
        "edits": [
            {
                "type": "clear_tool_uses_20250919",
                # Trigger clearing when threshold is exceeded
                "trigger": {"type": "input_tokens", "value": 30000},
                # Number of tool uses to keep after clearing
                "keep": {"type": "tool_uses", "value": 3},
                # Optional: Clear at least this many tokens
                "clear_at_least": {"type": "input_tokens", "value": 5000},
                # Exclude these tools from being cleared
                "exclude_tools": ["web_search"],
            }
        ]
    },
)

思考區塊清除使用方法

啟用思考區塊清除功能,以在啟用延伸思考時有效管理上下文和提示快取:

response = client.beta.messages.create(
    model="claude-opus-4-6",
    max_tokens=16000,
    messages=[...],
    thinking={"type": "enabled", "budget_tokens": 10000},
    betas=["context-management-2025-06-27"],
    context_management={
        "edits": [
            {
                "type": "clear_thinking_20251015",
                "keep": {"type": "thinking_turns", "value": 2},
            }
        ]
    },
)

思考區塊清除的配置選項

clear_thinking_20251015 策略支援以下配置:

配置選項預設值說明
keep{type: "thinking_turns", value: 1}定義要保留多少個最近的助手回合(包含思考區塊)。使用 {type: "thinking_turns", value: N},其中 N 必須 > 0 以保留最後 N 個回合,或使用 "all" 保留所有思考區塊。

配置範例:

保留最後 3 個助手回合的思考區塊:

{
  "type": "clear_thinking_20251015",
  "keep": {
    "type": "thinking_turns",
    "value": 3
  }
}

保留所有思考區塊(最大化快取命中率):

{
  "type": "clear_thinking_20251015",
  "keep": "all"
}

結合策略

您可以同時使用思考區塊清除和工具結果清除:

使用多個策略時,clear_thinking_20251015 策略必須在 edits 陣列中首先列出。

response = client.beta.messages.create(
    model="claude-opus-4-6",
    max_tokens=16000,
    messages=[...],
    thinking={"type": "enabled", "budget_tokens": 10000},
    tools=[...],
    betas=["context-management-2025-06-27"],
    context_management={
        "edits": [
            {
                "type": "clear_thinking_20251015",
                "keep": {"type": "thinking_turns", "value": 2},
            },
            {
                "type": "clear_tool_uses_20250919",
                "trigger": {"type": "input_tokens", "value": 50000},
                "keep": {"type": "tool_uses", "value": 5},
            },
        ]
    },
)

工具結果清除的配置選項

配置選項預設值說明
trigger100,000 個輸入令牌定義上下文編輯策略何時啟動。一旦提示超過此閾值,清除就會開始。您可以在 input_tokens 或 tool_uses 中指定此值。
keep3 個工具使用定義清除發生後要保留多少個最近的工具使用/結果對。API 會首先移除最舊的工具互動,保留最新的互動。
clear_at_least無確保每次策略啟動時至少清除一定數量的令牌。如果 API 無法清除至少指定的數量,該策略將不會被應用。這有助於判斷上下文清除是否值得破壞您的提示快取。
exclude_tools無工具名稱列表,其工具使用和結果永遠不應被清除。適用於保留重要上下文。
clear_tool_inputsfalse控制工具呼叫參數是否與工具結果一起被清除。預設情況下,只清除工具結果,同時保持 Claude 的原始工具呼叫可見。

上下文編輯回應

您可以使用 context_management 回應欄位查看哪些上下文編輯已應用於您的請求,以及有關已清除內容和輸入令牌的有用統計資訊。

Output
{
  "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message",
  "role": "assistant",
  "content": [
    // ...
  ],
  "usage": {
    // ...
  },
  "context_management": {
    "applied_edits": [
      // 使用 `clear_thinking_20251015` 時
      {
        "type": "clear_thinking_20251015",
        "cleared_thinking_turns": 3,
        "cleared_input_tokens": 15000
      },
      // 使用 `clear_tool_uses_20250919` 時
      {
        "type": "clear_tool_uses_20250919",
        "cleared_tool_uses": 8,
        "cleared_input_tokens": 50000
      }
    ]
  }
}

對於串流回應,上下文編輯將包含在最終的 message_delta 事件中:

Streaming Response
{
  "type": "message_delta",
  "delta": {
    "stop_reason": "end_turn",
    "stop_sequence": null
  },
  "usage": {
    "output_tokens": 1024
  },
  "context_management": {
    "applied_edits": [
      // ...
    ]
  }
}

令牌計數

令牌計數端點支援上下文管理,允許您預覽應用上下文編輯後提示將使用多少令牌。

response = client.beta.messages.count_tokens(
    model="claude-opus-4-7",
    messages=[{"role": "user", "content": "Continue our conversation..."}],
    tools=[...],  # Your tool definitions
    betas=["context-management-2025-06-27"],
    context_management={
        "edits": [
            {
                "type": "clear_tool_uses_20250919",
                "trigger": {"type": "input_tokens", "value": 30000},
                "keep": {"type": "tool_uses", "value": 5},
            }
        ]
    },
)

print(f"Original tokens: {response.context_management['original_input_tokens']}")
print(f"After clearing: {response.input_tokens}")
print(
    f"Savings: {response.context_management['original_input_tokens'] - response.input_tokens} tokens"
)
Output
{
  "input_tokens": 25000,
  "context_management": {
    "original_input_tokens": 70000
  }
}

回應顯示應用上下文管理後的最終令牌計數(input_tokens)和任何清除發生前的原始令牌計數(original_input_tokens)。

與記憶工具搭配使用

上下文編輯可以與記憶工具結合使用。當您的對話上下文接近配置的清除閾值時,Claude 會收到自動警告以保留重要資訊。這使 Claude 能夠在工具結果從對話歷史中清除之前,將工具結果或上下文保存到其記憶檔案中。

這種組合允許您:

  • 保留重要上下文:Claude 可以在工具結果被清除之前,將工具結果中的必要資訊寫入記憶檔案
  • 維持長期運行的工作流程:通過將資訊卸載到持久儲存,啟用否則會超過上下文限制的代理工作流程
  • 按需存取資訊:Claude 可以在需要時從記憶檔案中查找之前清除的資訊,而不是將所有內容保留在活動上下文視窗中

例如,在 Claude 執行許多操作的檔案編輯工作流程中,Claude 可以在上下文增長時將已完成的變更摘要保存到記憶檔案。當工具結果被清除時,Claude 通過其記憶系統保留對該資訊的存取權限,並可以繼續有效地工作。

要同時使用這兩個功能,請在您的 API 請求中啟用它們:

response = client.beta.messages.create(
    model="claude-opus-4-7",
    max_tokens=4096,
    messages=[...],
    tools=[
        {"type": "memory_20250818", "name": "memory"},
        # Your other tools
    ],
    betas=["context-management-2025-06-27"],
    context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
)

如需完整的記憶工具參考(包括命令和範例),請參閱記憶工具。

用戶端壓縮 (SDK)

Anthropic 建議使用伺服器端壓縮而非 SDK 壓縮。伺服器端壓縮自動處理上下文管理,具有更低的整合複雜性、更好的代幣使用計算,以及沒有用戶端限制。只有在您特別需要對摘要過程進行用戶端控制時,才使用 SDK 壓縮。

當使用tool_runner 方法時,壓縮在 Python、TypeScript 和 Ruby SDK 中可用。

壓縮是一個 SDK 功能,通過在代幣使用量增長過大時生成摘要來自動管理對話上下文。與清除內容的伺服器端上下文編輯策略不同,壓縮指示 Claude 摘要對話歷史,然後用該摘要替換完整歷史。這允許 Claude 繼續處理長期運行的任務,否則會超過上下文視窗。

壓縮如何工作

啟用壓縮後,SDK 在每個模型回應後監控代幣使用情況:

  1. 閾值檢查: SDK 將總代幣計算為 input_tokens + cache_creation_input_tokens + cache_read_input_tokens + output_tokens。
  2. 摘要生成: 當超過閾值時,摘要提示被注入為使用者回合,Claude 生成包裝在 <summary></summary> 標籤中的結構化摘要。
  3. 上下文替換: SDK 提取摘要並用它替換整個訊息歷史。
  4. 繼續: 對話從摘要恢復,Claude 從中斷的地方繼續。

使用壓縮

將 compaction_control 添加到您的 tool_runner 呼叫中,以在代幣使用量超過閾值時啟用自動摘要。

壓縮期間發生的情況

隨著對話增長,訊息歷史累積:

壓縮前(接近 100k 代幣):

[
  { "role": "user", "content": "Analyze all files and write a report..." },
  { "role": "assistant", "content": "I'll help. Let me start by reading..." },
  {
    "role": "user",
    "content": [{ "type": "tool_result", "tool_use_id": "...", "content": "..." }]
  },
  { "role": "assistant", "content": "Based on file1.txt, I see..." },
  {
    "role": "user",
    "content": [{ "type": "tool_result", "tool_use_id": "...", "content": "..." }]
  },
  { "role": "assistant", "content": "After analyzing file2.txt..." }
  // ... 50 more exchanges like this ...
]

當代幣超過閾值時,SDK 注入摘要請求,Claude 生成摘要。整個歷史隨後被替換:

壓縮後(回到約 2-3k 代幣):

[
  {
    "role": "assistant",
    "content": "# Task Overview\nThe user requested analysis of directory files to produce a summary report...\n\n# Current State\nAnalyzed 52 files across 3 subdirectories. Key findings documented in report.md...\n\n# Important Discoveries\n- Configuration files use YAML format\n- Found 3 deprecated dependencies\n- Test coverage at 67%\n\n# Next Steps\n1. Analyze remaining files in /src/legacy\n2. Complete final report sections...\n\n# Context to Preserve\nUser prefers markdown format with executive summary first..."
  }
]

Claude 從此摘要繼續工作,就像它是原始對話歷史一樣。

配置選項

參數類型必需預設值描述
enabledboolean是-是否啟用自動壓縮
context_token_thresholdnumber否100,000觸發壓縮的代幣計數
modelstring否與主模型相同用於生成摘要的模型
summary_promptstring否見下文摘要生成的自訂提示

選擇代幣閾值

閾值決定何時發生壓縮。較低的閾值意味著更頻繁的壓縮,上下文視窗較小。較高的閾值允許更多上下文,但有達到限制的風險。

# More frequent compaction for memory-constrained scenarios
compaction_control = {"enabled": True, "context_token_threshold": 50000}

# Less frequent compaction when you need more context
compaction_control = {"enabled": True, "context_token_threshold": 150000}

為摘要使用不同的模型

您可以使用更快或更便宜的模型來生成摘要:

compaction_control = {
    "enabled": True,
    "context_token_threshold": 100000,
    "model": "claude-haiku-4-5",
}

自訂摘要提示

您可以為特定領域的需求提供自訂提示。您的提示應指示 Claude 將其摘要包裝在 <summary></summary> 標籤中。

compaction_control = {
    "enabled": True,
    "context_token_threshold": 100000,
    "summary_prompt": """Summarize the research conducted so far, including:
- Sources consulted and key findings
- Questions answered and remaining unknowns
- Recommended next steps

Wrap your summary in <summary></summary> tags.""",
}

預設摘要提示

內建摘要提示指示 Claude 創建結構化的繼續摘要,包括:

  1. 任務概述: 使用者的核心請求、成功標準和約束。
  2. 目前狀態: 已完成的內容、修改的檔案和生成的成品。
  3. 重要發現: 技術約束、做出的決定、解決的錯誤和失敗的方法。
  4. 後續步驟: 所需的具體行動、阻礙因素和優先順序。
  5. 保留的上下文: 使用者偏好、特定領域的詳細資訊和做出的承諾。

此結構使 Claude 能夠有效地恢復工作,而不會失去重要上下文或重複錯誤。

限制

伺服器端工具

使用伺服器端工具(例如網路搜尋或網路擷取)時,壓縮需要特別考慮。

使用伺服器端工具時,SDK 可能會錯誤地計算代幣使用情況,導致壓縮在錯誤的時間觸發。

例如,在網路搜尋操作後,API 回應可能顯示:

Output
{
  "usage": {
    "input_tokens": 63000,
    "cache_read_input_tokens": 270000,
    "output_tokens": 1400
  }
}

SDK 將總使用量計算為 63,000 + 270,000 = 333,000 代幣。但是,cache_read_input_tokens 值包括伺服器端工具進行的多個內部 API 呼叫的累積讀取,而不是您的實際對話上下文。您的實際上下文長度可能只有 63,000 個 input_tokens,但 SDK 看到 333k 並過早觸發壓縮。

解決方案:

  • 使用代幣計數端點獲取準確的上下文長度
  • 在廣泛使用伺服器端工具時避免壓縮

工具使用邊界情況

當 SDK 在工具使用回應待處理時觸發壓縮時,它會在生成摘要之前從訊息歷史中移除工具使用區塊。如果仍然需要,Claude 將在從摘要恢復後重新發出工具呼叫。

監控壓縮

了解何時觸發壓縮有助於您調整閾值並驗證預期行為。

何時使用壓縮

良好的使用案例:

  • 處理許多檔案或資料來源的長期運行代理任務
  • 累積大量資訊的研究工作流程
  • 具有清晰、可測量進度的多步驟任務
  • 在對話外持久化的成品(檔案、報告)的任務

不太理想的使用案例:

  • 需要精確回憶早期對話詳細資訊的任務
  • 廣泛使用伺服器端工具的工作流程
  • 需要在許多變數中維持精確狀態的任務

Was this page helpful?

  • 用戶端壓縮 (SDK)