上下文編輯
透過上下文編輯,在對話上下文增長時自動進行管理。
概覽
「Context editing」(上下文編輯)讓您能夠在對話歷史增長時,選擇性地清除其中的特定內容。除了最佳化成本並維持在限制範圍內之外,這更關乎主動策劃 Claude 所看到的內容:上下文是一種報酬遞減的有限資源,而不相關的內容會降低模型的專注度。上下文編輯讓您在執行階段對這種策劃擁有細緻的控制權。關於上下文管理背後更廣泛的原則,請參閱有效的上下文工程。本頁涵蓋:
- 工具結果清除 - 最適合大量工具使用(tool use)的代理工作流程,其中舊的工具結果已不再需要
- 思考區塊清除 - 用於在使用擴展思考(extended thinking)時管理思考區塊,並提供保留近期思考以維持上下文連續性的選項
- 用戶端 SDK 壓縮 - 一種基於 SDK 的替代方案,用於基於摘要的上下文管理(通常建議優先使用伺服器端壓縮)
| 方法 | 執行位置 | 策略 | 運作方式 |
|---|---|---|---|
| 伺服器端 | API | 工具結果清除(clear_tool_uses_20250919)思考區塊清除( clear_thinking_20251015) | 在提示送達 Claude 之前套用。從對話歷史中清除特定內容。每種策略皆可獨立設定。 |
| 用戶端 | SDK | 壓縮 | 在使用 tool_runner 時,可於 TypeScript 和 Ruby SDK 中使用。產生摘要並取代完整的對話歷史。請參閱用戶端壓縮。 |
伺服器端策略
工具結果清除
clear_tool_uses_20250919 策略會在對話上下文增長超過您設定的閾值時清除工具結果。這對於大量工具使用的代理工作流程特別有用。較舊的工具結果(例如檔案內容或搜尋結果)在 Claude 處理完畢後便不再需要。
啟動後,API 會依時間順序自動清除最舊的工具結果。API 會以佔位文字取代每個被清除的結果,向 Claude 表明該結果已被移除。預設情況下,僅會清除工具結果。您可以選擇將 clear_tool_inputs 設為 true,以同時清除工具結果與工具呼叫(工具使用參數)。
思考區塊清除
clear_thinking_20251015 策略會在啟用擴展思考時管理對話中的 thinking 區塊。此策略讓您能控制思考內容的保留方式:您可以選擇保留更多思考區塊以維持推理連續性,或更積極地清除它們以節省上下文空間。
一個助理對話輪次可能包含多個內容區塊(例如使用工具時)以及多個思考區塊(例如使用交錯思考時)。
上下文編輯在伺服器端進行
上下文編輯會在提示送達 Claude 之前於伺服器端套用。您的用戶端應用程式會保有完整、未經修改的對話歷史。您不需要將用戶端狀態與編輯後的版本同步。請如往常一樣在本機繼續管理您的完整對話歷史。
在 Claude Fable 5.1 和 Claude Opus 5.5 上,伺服器端上下文管理永遠不會使思考區塊失效。在用戶端對較早輪次所做的編輯,可能會使之後每個助理輪次中的思考區塊失效。對於在 2026 年 8 月 31 日或之後建立的新帳戶,重播已失效區塊的請求將會被拒絕,除非您選擇捨棄該區塊。請參閱保持前綴不變。
上下文編輯與提示快取
上下文編輯與提示快取(prompt caching)的互動方式依策略而異:
-
工具結果清除: 清除內容時會使已快取的提示前綴失效。為此,請清除足夠多的 token,使快取失效變得值得。使用
clear_at_least參數可確保每次至少清除一定數量的 token。每次清除內容時您都會產生快取寫入成本,但後續請求可以重複使用新快取的前綴。 -
思考區塊清除: 當思考區塊被保留在上下文中(未清除)時,提示快取會被保留,從而實現快取命中並降低輸入 token 成本。當思考區塊被清除時,快取會在清除發生的位置失效。請根據您想優先考量快取效能還是上下文視窗(context window)可用空間來設定
keep參數。
支援的模型
上下文編輯可在所有支援的 Claude 模型上使用。
工具結果清除的用法
啟用工具結果清除最簡單的方式是僅指定策略類型。所有其他設定選項皆使用其預設值:
response = client.beta.messages.create(
model="claude-opus-5-5",
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-5-5",
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": {"type": "input_tokens", "value": 30000},
# 清除後要保留的工具使用次數
"keep": {"type": "tool_uses", "value": 3},
# 選用:至少清除此數量的 token
"clear_at_least": {"type": "input_tokens", "value": 5000},
# 將這些工具排除在清除範圍之外
"exclude_tools": ["web_search"],
}
]
},
)思考區塊清除的用法
啟用思考區塊清除,以便在啟用擴展思考時有效管理上下文與提示快取:
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Hello"}],
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: N}(其中 N 必須 > 0)以保留最後 N 個輪次,或使用 "all" 以保留所有思考區塊。Opus 4.5+ 與 Sonnet 4.6+:所有輪次。Fable 與 Mythos 模型:所有輪次。較早的 Opus/Sonnet 與所有 Haiku:僅最後一輪。 |
設定範例:
保留最後 3 個助理輪次的思考區塊:
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Hello"}],
betas=["context-management-2025-06-27"],
context_management={
"edits": [
{
"type": "clear_thinking_20251015",
"keep": {"type": "thinking_turns", "value": 3},
}
]
},
)保留所有思考區塊(最大化快取命中):
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Hello"}],
betas=["context-management-2025-06-27"],
context_management={
"edits": [
{
"type": "clear_thinking_20251015",
"keep": "all",
}
]
},
)組合策略
您可以同時使用思考區塊清除與工具結果清除:
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[
{
"role": "user",
"content": "Search for the latest developments in quantum error correction and summarize the key breakthroughs.",
}
],
tools=[
{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 5,
}
],
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},
},
]
},
)
print(response)工具結果清除的設定選項
| 設定選項 | 預設值 | 說明 |
|---|---|---|
trigger | 100,000 個輸入 token | 定義上下文編輯策略何時啟動。一旦提示超過此閾值,便會開始清除。您可以用 input_tokens 或 tool_uses 來指定此值。 |
keep | 3 次工具使用 | 定義清除發生後要保留多少個近期的工具使用/結果配對。API 會先移除最舊的工具互動,保留最近的互動。 |
clear_at_least | 無 | 確保每次策略啟動時至少清除一定數量的 token。如果 API 無法清除至少指定的數量,則不會套用該策略。這有助於判斷上下文清除是否值得破壞您的提示快取。 |
exclude_tools | 無 | 工具名稱清單,這些工具的工具使用與結果永遠不應被清除。適用於保留重要的上下文。 |
clear_tool_inputs | false | 控制是否連同工具結果一併清除工具呼叫參數。預設情況下,僅清除工具結果,同時保持 Claude 原始的工具呼叫可見。 |
上下文編輯回應
您可以透過 context_management 回應欄位查看哪些上下文編輯已套用至您的請求,以及關於已清除內容與輸入 token 的實用統計資料。
{
"id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
"type": "message",
"role": "assistant",
"content": [
// ...
],
"usage": {
// ...
},
"context_management": {
"applied_edits": [
// When using `clear_thinking_20251015`
{
"type": "clear_thinking_20251015",
"cleared_thinking_turns": 3,
"cleared_input_tokens": 15000
},
// When using `clear_tool_uses_20250919`
{
"type": "clear_tool_uses_20250919",
"cleared_tool_uses": 8,
"cleared_input_tokens": 50000
}
]
}
}對於串流(streaming)回應,上下文編輯會包含在最後的 message_delta 事件中:
{
"type": "message_delta",
"delta": {
"stop_reason": "end_turn",
"stop_sequence": null
},
"usage": {
"output_tokens": 1024
},
"context_management": {
"applied_edits": [
// ...
]
}
}Token 計數
Token 計數端點支援上下文管理,讓您能預覽套用上下文編輯後您的提示將使用多少 token。
response = client.beta.messages.count_tokens(
model="claude-opus-5-5",
messages=[{"role": "user", "content": "Continue our conversation..."}],
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"
){
"input_tokens": 25000,
"context_management": {
"original_input_tokens": 70000
}
}回應會同時顯示套用上下文管理後的最終 token 數(input_tokens)以及任何清除發生前的原始 token 數(original_input_tokens)。
搭配記憶工具使用
上下文編輯可以與記憶工具結合使用。當您的對話上下文接近設定的清除閾值時,Claude 會收到自動警告以保留重要資訊。這讓 Claude 能在工具結果或上下文從對話歷史中被清除之前,將其儲存到記憶檔案中。
此組合讓您能夠:
- 保留重要上下文: Claude 可以在工具結果被清除之前,將其中的關鍵資訊寫入記憶檔案
- 維持長時間執行的工作流程: 透過將資訊卸載至持久性儲存空間,實現原本會超出上下文限制的代理工作流程
- 按需存取資訊: Claude 可以在需要時從記憶檔案中查詢先前已清除的資訊,而非將所有內容保留在作用中的上下文視窗內
例如,在 Claude 執行許多操作的檔案編輯工作流程中,Claude 可以隨著上下文增長將已完成的變更摘要寫入記憶檔案。當工具結果被清除時,Claude 仍可透過其記憶系統存取該資訊,並能繼續有效地工作。
若要同時使用這兩項功能,請在您的 API 請求中啟用它們:
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
messages=[{"role": "user", "content": "Hello"}],
tools=[{"type": "memory_20250818", "name": "memory"}],
betas=["context-management-2025-06-27"],
context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
)如需完整的記憶工具參考資料(包含指令與範例),請參閱記憶工具。
用戶端壓縮(SDK)
「Compaction」(壓縮)是一項 SDK 功能,會在 token 用量增長過大時透過產生摘要來自動管理對話上下文。與清除內容的伺服器端上下文編輯策略不同,壓縮會指示 Claude 摘要對話歷史,然後以該摘要取代完整歷史。這讓 Claude 能繼續處理原本會超出上下文視窗的長時間執行任務。
壓縮的運作方式
啟用壓縮後,SDK 會在每次模型回應後監控 token 用量:
- 閾值檢查: SDK 將總 token 數計算為
input_tokens + cache_creation_input_tokens + cache_read_input_tokens + output_tokens(關於快取 token 欄位,請參閱提示快取)。 - 摘要產生: 超過閾值時,會以使用者輪次的形式注入摘要提示,Claude 會產生包裹在
<summary></summary>標籤中的結構化摘要。 - 上下文取代: SDK 擷取摘要並以其取代整個訊息歷史。
- 繼續: 對話從摘要處恢復,Claude 從中斷處接續。
使用壓縮
在您的 tool_runner 呼叫中加入 compaction_control,以便在 token 用量超過閾值時啟用自動摘要。
壓縮期間會發生什麼
隨著對話增長,訊息歷史會不斷累積:
壓縮前(接近 100k token):
[
{ "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 ...
]當 token 超過閾值時,SDK 會注入摘要請求,Claude 會產生摘要。接著整個歷史會被取代:
壓縮後(回到約 2–3k token):
[
{
"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 會從此摘要繼續工作,如同它是原始的對話歷史一般。
設定選項
| 參數 | 類型 | 必填 | 預設值 | 說明 |
|---|---|---|---|---|
enabled | boolean | 是 | - | 是否啟用自動壓縮 |
context_token_threshold | number | 否 | 100,000 | 觸發壓縮的 token 數 |
model | string | 否 | 與主模型相同 | 用於產生摘要的模型 |
summary_prompt | string | 否 | 請參閱預設摘要提示 | 用於產生摘要的自訂提示 |
選擇 token 閾值
閾值決定壓縮何時發生。較低的閾值意味著更頻繁的壓縮與較小的上下文視窗。較高的閾值允許更多上下文,但有觸及限制的風險。
使用不同的模型產生摘要
您可以使用更快或更便宜的模型來產生摘要:
自訂摘要提示
您可以針對特定領域的需求提供自訂提示。您的提示應指示 Claude 將其摘要包裹在 <summary></summary> 標籤中。
預設摘要提示
內建的摘要提示會指示 Claude 建立結構化的接續摘要,其中包含:
- 任務概覽: 使用者的核心請求、成功標準與限制條件。
- 目前狀態: 已完成的內容、已修改的檔案與已產出的成果。
- 重要發現: 技術限制、已做出的決策、已解決的錯誤與失敗的方法。
- 後續步驟: 所需的具體行動、阻礙因素與優先順序。
- 需保留的上下文: 使用者偏好、特定領域的細節與已做出的承諾。
此結構讓 Claude 能有效率地恢復工作,而不會遺失重要上下文或重複犯錯。
You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.限制
伺服器端工具
使用伺服器端工具時,SDK 可能會錯誤計算 token 用量,導致壓縮在錯誤的時間觸發。
例如,在網頁搜尋操作之後,API 回應可能顯示:
{
"usage": {
"input_tokens": 63000,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 270000,
"output_tokens": 1400
}
}SDK 將總用量計算為 63,000 + 0 + 270,000 + 1,400 = 334,400 個 token。然而,cache_read_input_tokens 的值包含了伺服器端工具所進行的多次內部 API 呼叫累積的讀取量,而非您實際的對話上下文。您真正的上下文長度可能只有 63,000 個 input_tokens,但 SDK 看到的是 334k,因而過早觸發壓縮。
因應方法:
- 使用 token 計數端點取得準確的上下文長度
- 大量使用伺服器端工具時避免使用壓縮
工具使用的邊界情況
當 SDK 在工具使用回應尚待處理時觸發壓縮,它會在產生摘要之前從訊息歷史中移除該工具使用區塊。如果仍有需要,Claude 會在從摘要恢復後重新發出該工具呼叫。
監控壓縮
了解壓縮何時觸發有助於您調整閾值並驗證預期行為。
何時使用壓縮
適合的使用情境:
- 處理許多檔案或資料來源的長時間執行代理任務
- 累積大量資訊的研究工作流程
- 具有明確、可衡量進度的多步驟任務
- 會產出在對話之外持續存在的成果(檔案、報告)的任務
較不理想的使用情境:
- 需要精確回憶對話早期細節的任務
- 大量使用伺服器端工具的工作流程
- 需要在許多變數之間維持精確狀態的任務
後續步驟
Was this page helpful?