此功能符合「Zero Data Retention」(零資料保留),即 ZDR 的資格。當您的組織具有 ZDR 安排時,透過此功能傳送的資料在 API 回應返回後不會被儲存。
伺服器端壓縮是管理長時間執行對話和代理工作流程中上下文的建議策略。它會自動處理上下文管理,無需客戶端摘要程式碼。
「Compaction」(壓縮)透過在接近上下文視窗限制時自動摘要較舊的上下文,來延長長時間執行對話和任務的有效上下文長度。它還能保持活動上下文的精簡:隨著對話增長,回應品質會下降,因此壓縮會以簡潔的摘要取代較舊的內容。
若要深入了解為何長上下文會導致品質下降以及壓縮如何提供幫助,請參閱 Effective context engineering。
這非常適合:
壓縮目前處於測試階段。請在您的 API 請求中包含 beta header compact-2026-01-12 以使用此功能。
壓縮支援以下模型:
啟用壓縮後,當對話達到設定的 token 閾值時,Claude 會自動摘要您的對話。API 會:
compaction 區塊。在後續請求中,將回應附加到您的訊息中。API 會自動捨棄 compaction 區塊之前的所有內容區塊,從摘要繼續對話。
透過在 Messages API 請求的 context_management.edits 中新增 compact_20260112 策略來啟用壓縮。
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Help me build a website"}]
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
# 將回應(包含任何壓縮區塊)附加至對話以繼續進行
messages.append({"role": "assistant", "content": response.content})| 參數 | 類型 | 預設值 | 說明 |
|---|---|---|---|
type | string | 必填 | 必須為 "compact_20260112" |
trigger | object | {"type": "input_tokens", "value": 150000} | 觸發壓縮的時機。input_tokens 是唯一支援的觸發類型。value 必須至少為 50,000 個 token。 |
pause_after_compaction | boolean | false | 是否在產生壓縮摘要後暫停 |
instructions | string | null | 自訂摘要提示。提供時會完全取代預設提示。 |
使用 trigger 參數設定壓縮觸發的時機:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 150000},
}
]
},
)預設的摘要提示因模型而異。每個預設提示都會指示 Claude 在 <summary></summary> 標籤內撰寫摘要,包含在未來上下文視窗中繼續任務所需的資訊。例如,某些模型使用以下提示:
You have written a partial transcript for the initial task above. Please write a summary of the transcript. The purpose of this summary is to provide continuity so you can continue to make progress towards solving the task in a future context, where the raw history above may not be accessible and will be replaced with this summary. Write down anything that would be helpful, including the state, next steps, learnings etc. You must wrap your summary in a <summary></summary> block.您可以透過 instructions 參數提供自訂指示。自訂指示不會補充預設提示,而是完全取代它:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={
"edits": [
{
"type": "compact_20260112",
"instructions": "Focus on preserving code snippets, variable names, and technical decisions.",
}
]
},
)使用 pause_after_compaction 可在產生壓縮摘要後暫停 API。這讓您可以在 API 繼續回應之前新增額外的內容區塊(例如保留最近的訊息或特定的指示導向訊息)。
啟用後,API 會在產生壓縮區塊後回傳帶有 compaction 停止原因的訊息:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={
"edits": [{"type": "compact_20260112", "pause_after_compaction": True}]
},
)
# 檢查壓縮是否觸發了暫停
if response.stop_reason == "compaction":
# 回應僅包含壓縮區塊
messages.append({"role": "assistant", "content": response.content})
# 繼續請求
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)當模型處理包含許多工具使用迭代的長時間任務時,總 token 消耗量可能會大幅增加。您可以結合 pause_after_compaction 與壓縮計數器來估算累積使用量,並在達到預算後優雅地結束任務。
此範例僅以 SDK 語言呈現:其價值在於圍繞請求的預算追蹤邏輯。原始請求結合了觸發設定中的 trigger 與壓縮後暫停中的 pause_after_compaction。
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
TRIGGER_THRESHOLD = 100_000
TOTAL_TOKEN_BUDGET = 3_000_000
n_compactions = 0
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": TRIGGER_THRESHOLD},
"pause_after_compaction": True,
}
]
},
)
if response.stop_reason == "compaction":
n_compactions += 1
messages.append({"role": "assistant", "content": response.content})
# 估算已消耗的總 token 數;若超出預算則提示收尾
if n_compactions * TRIGGER_THRESHOLD >= TOTAL_TOKEN_BUDGET:
messages.append(
{
"role": "user",
"content": "Please wrap up your current work and summarize the final state.",
}
)當壓縮被觸發時,API 會在助理回應的開頭回傳一個 compaction 區塊。
長時間執行的對話可能會產生多次壓縮。最後一個壓縮區塊反映提示的最終狀態,以產生的摘要取代其之前的內容。
{
"content": [
{
"type": "compaction",
"content": "Summary of the conversation: The user requested help building a web scraper..."
},
{
"type": "text",
"text": "Based on our conversation so far..."
}
]
}您必須在後續請求中將 compaction 區塊傳回 API,以使用縮短的提示繼續對話。最簡單的方法是將整個回應內容附加到您的訊息中:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
# 收到包含壓縮區塊的回應後
messages.append({"role": "assistant", "content": response.content})
# 繼續對話
messages.append({"role": "user", "content": "Now add error handling"})
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)當 API 收到 compaction 區塊時,其之前的所有內容區塊都會被忽略。您可以:
壓縮區塊的串流方式與文字區塊不同。您會收到一個 content_block_start 事件,接著是包含完整摘要內容的單一 content_block_delta(沒有中間串流),然後是 content_block_stop 事件。
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
with client.beta.messages.stream(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
) as stream:
for event in stream:
if event.type == "content_block_start":
if event.content_block.type == "compaction":
print("Compaction started...")
elif event.content_block.type == "text":
print("Text response started...")
elif event.type == "content_block_delta":
if event.delta.type == "compaction_delta":
print(f"Compaction complete: {len(event.delta.content or '')} chars")
elif event.delta.type == "text_delta":
print(event.delta.text, end="", flush=True)
# 取得最終累積的訊息
message = stream.get_final_message()
messages.append({"role": "assistant", "content": message.content})壓縮與提示快取搭配良好。您可以在壓縮區塊上新增 cache_control 斷點來快取摘要內容。
{
"role": "assistant",
"content": [
{
"type": "compaction",
"content": "[summary text]",
"cache_control": { "type": "ephemeral" }
},
{
"type": "text",
"text": "Based on our conversation..."
}
]
}當壓縮發生時,摘要會成為需要寫入快取的新內容。如果沒有額外的快取斷點,這也會使任何已快取的系統提示失效,需要與壓縮摘要一起重新快取。
為了最大化快取命中率,請在系統提示的末尾新增 cache_control 斷點。這會將系統提示與對話分開快取,因此當壓縮發生時:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
system=[
{
"type": "text",
"text": "You are a helpful coding assistant...",
"cache_control": {
"type": "ephemeral"
}, # Cache the system prompt separately
}
],
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)這可讓長系統提示在整個對話的多次壓縮事件中保持快取狀態。
壓縮需要額外的取樣步驟,這會計入速率限制和計費。API 會在回應中回傳詳細的使用量資訊:
{
"usage": {
"input_tokens": 23000,
"output_tokens": 1000,
"iterations": [
{
"type": "compaction",
"input_tokens": 180000,
"output_tokens": 3500
},
{
"type": "message",
"input_tokens": 23000,
"output_tokens": 1000
}
]
}
}iterations 陣列顯示每次取樣迭代的使用量。當壓縮發生時,您會看到一個 compaction 迭代,接著是主要的 message 迭代。在此範例中,頂層的 input_tokens 和 output_tokens 與 message 迭代完全相符,因為只有一個非壓縮迭代。最後一個迭代的 token 計數反映壓縮後的有效上下文大小。
頂層的 input_tokens 和 output_tokens 不包含壓縮迭代的使用量。它們反映所有非壓縮迭代的總和。若要計算請求消耗和計費的總 token 數,請加總 usage.iterations 陣列中的所有項目。
如果您先前依賴 usage.input_tokens 和 usage.output_tokens 進行成本追蹤或稽核,則在啟用壓縮時,您需要更新追蹤邏輯以彙總 usage.iterations 中的所有項目。啟用壓縮測試版後,每個回應都會包含 usage.iterations,即使沒有發生壓縮也是如此。只有在請求期間觸發新的壓縮時,才會出現 compaction 項目。重新套用先前的 compaction 區塊不會產生額外的壓縮成本,在這種情況下,頂層使用量欄位仍然準確。
使用伺服器工具(例如網頁搜尋)時,會在每次取樣迭代開始時檢查壓縮觸發條件。根據您的觸發閾值和產生的輸出量,壓縮可能在單一請求中發生多次。
Token 計數端點(/v1/messages/count_tokens)會套用提示中現有的 compaction 區塊,但不會觸發新的壓縮。使用它來檢查先前壓縮後的有效 token 計數:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
count_response = client.beta.messages.count_tokens(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
print(f"Current tokens: {count_response.input_tokens}")
print(f"Original tokens: {count_response.context_management.original_input_tokens}")以下是使用壓縮的長時間執行對話的完整範例:
client = anthropic.Anthropic()
messages: list[dict] = []
def chat(user_message: str) -> str:
messages.append({"role": "user", "content": user_message})
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 100000},
}
]
},
)
# 附加回應(壓縮區塊會自動包含在內)
messages.append({"role": "assistant", "content": response.content})
# 回傳文字內容
return next(block.text for block in response.content if block.type == "text")
# 執行長對話
print(chat("Help me build a Python web scraper"))
print(chat("Add support for JavaScript-rendered pages"))
print(chat("Now add rate limiting and error handling"))
# 依對話需求持續呼叫 chat()以下範例使用 pause_after_compaction 來逐字保留先前的對話交流和目前的使用者訊息(共三則訊息),而非對其進行摘要:
from typing import Any
client = anthropic.Anthropic()
messages: list[dict[str, Any]] = []
def chat(user_message: str) -> str:
messages.append({"role": "user", "content": user_message})
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages,
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 100000},
"pause_after_compaction": True,
}
]
},
)
# 檢查是否發生壓縮並暫停
if response.stop_reason == "compaction":
# 從回應中取得壓縮區塊
compaction_block = response.content[0]
# 保留先前的對話交換與目前的使用者訊息(共 3 則訊息)
# 方法是將它們附加在壓縮區塊之後
preserved_messages = messages[-3:] if len(messages) >= 3 else messages
# 建立新的訊息列表:壓縮區塊 + 保留的訊息
new_assistant_content = [compaction_block]
messages_after_compaction = [
{"role": "assistant", "content": new_assistant_content}
] + preserved_messages
# 使用壓縮後的上下文與保留的訊息繼續請求
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-8",
max_tokens=4096,
messages=messages_after_compaction,
context_management={"edits": [{"type": "compact_20260112"}]},
)
# 更新我們的訊息列表以反映壓縮結果
messages.clear()
messages.extend(messages_after_compaction)
# 附加最終回應
messages.append({"role": "assistant", "content": response.content})
# 回傳文字內容
return next(block.text for block in response.content if block.type == "text")
# 執行一段長對話
print(chat("Help me build a Python web scraper"))
print(chat("Add support for JavaScript-rendered pages"))
print(chat("Now add rate limiting and error handling"))
# 依對話所需持續呼叫 chat()使用相同模型進行摘要: 您請求中指定的模型會用於摘要。沒有選項可使用不同的(例如更便宜的)模型來產生摘要。
定義工具時壓縮可能會失敗: 當您的請求包含 tools 時,模型偶爾會在內部摘要步驟中呼叫工具,而非撰寫摘要。發生這種情況時,回應會包含 content: null 的 compaction 區塊。為防止此情況,請將 instructions 設定為明確告知模型不要呼叫工具的提示,例如:
Summarize the transcript inside <summary></summary> tags. Include relevant information in the summary for continuing the task in the next context window. Do not call any tools while writing this summary; respond with text only.透過上下文編輯,在對話上下文增長時自動管理它。
了解上下文視窗大小和管理策略。
探索一個實際的實作範例,使用背景執行緒和提示快取,透過即時工作階段記憶體壓縮來管理長時間執行的對話。
Was this page helpful?