此功能符合「Zero Data Retention」(零資料保留),即 ZDR 的資格。當您的組織具有 ZDR 安排時,透過此功能傳送的資料在 API 回應返回後不會被儲存。
伺服器端壓縮是管理長時間執行對話和代理工作流程中上下文的建議策略。它能以最少的整合工作自動處理上下文管理。
「Compaction」(壓縮)透過在接近「context window」(上下文視窗)限制時自動摘要較舊的上下文,來延長長時間執行對話和任務的有效上下文長度。這不僅僅是為了保持在 token 上限之下。隨著對話變長,模型難以在完整歷史記錄中保持專注。壓縮透過以簡潔的摘要取代過時內容,使活躍的上下文保持專注且高效能。
若要深入了解為何長上下文會降低效能以及壓縮如何提供幫助,請參閱 Effective context engineering。
這非常適合:
壓縮目前處於測試階段。請在您的 API 請求中包含 beta header compact-2026-01-12 以使用此功能。
壓縮支援以下模型:
claude-fable-5)claude-mythos-5)啟用壓縮後,當對話接近設定的 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 | 150,000 個 token | 觸發壓縮的時機。必須至少為 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},
}
]
},
)預設情況下,壓縮使用以下摘要提示:
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 與壓縮計數器結合使用,以估算累積使用量,並在達到預算後優雅地結束任務:
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 區塊時,其之前的所有內容區塊都會被忽略。您可以:
在啟用壓縮的情況下進行「streaming」(串流)回應時,當壓縮開始時您會收到 content_block_start 事件。壓縮區塊的串流方式與文字區塊不同。您會收到一個 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 中的資料。iterations 陣列僅在請求期間觸發新壓縮時才會填入。重新套用先前的 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"))
# ... 視需要繼續以下範例使用 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"))
# ... 視需要繼續進行摘要使用相同模型: 您請求中指定的模型會用於摘要。沒有選項可以使用不同的(例如更便宜的)模型來產生摘要。
定義工具時壓縮可能會失敗: 當您的請求包含 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?