Claude Platform Docs
Messages壓縮

在 token 閾值時進行壓縮

當對話達到您設定的 token 閾值時,讓 API 在一般請求中自動摘要較舊的上下文。

「Threshold compaction」(閾值壓縮)是自動形式的「compaction」(壓縮):您在一般請求上設定 token 閾值,一旦達到該閾值,API 就會在請求進行途中摘要較舊的上下文。它與「on-demand compaction」(隨需壓縮)一同受到支援,在隨需壓縮中,由您決定何時撰寫摘要(請參閱隨需壓縮)。若要在兩者之間做選擇,請參閱選擇如何壓縮

壓縮會在接近「context window」(上下文視窗)限制時自動摘要較舊的上下文,藉此延長長時間執行的對話與任務的有效上下文長度。它也能讓作用中的上下文保持精簡:隨著對話增長,回應品質會下降,因此壓縮會以簡潔的摘要取代較舊的內容。

這非常適合:

  • 以聊天為基礎的多輪對話,您希望使用者能長時間使用同一個聊天
  • 需要大量後續工作(通常是「tool use」(工具使用))且可能超出上下文視窗的任務導向提示

壓縮的運作方式

啟用壓縮後,當對話達到所設定的 token 閾值時,Claude 會自動摘要您的對話。API 會:

  1. 偵測輸入 token 何時達到您指定的觸發閾值。
  2. 產生目前對話的摘要。
  3. 建立包含該摘要的 compaction 區塊。
  4. 以壓縮後的上下文繼續產生回應。

在後續請求中,請將回應附加到您的訊息中。API 會自動捨棄 compaction 區塊之前的所有內容區塊,並從摘要繼續對話。

ServerInput tokens exceed trigger thresholdConversation is summarizedCompaction block created with summaryResponse continues with compacted contextnext requestClientAppend response to messagesMessages before the compaction block are dropped on next request

基本用法

在您的 Messages API 請求中,將 compact_20260112 策略加入 context_management.edits 即可啟用壓縮。

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-5-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)

# 附加回應(包括任何 compaction 區塊)以繼續對話
messages.append({"role": "assistant", "content": response.content})

參數

參數類型預設值說明
typestring必填必須為 "compact_20260112"
triggerobject{"type": "input_tokens", "value": 150000}何時觸發壓縮。input_tokens 是唯一支援的觸發類型。value 必須至少為 50,000 個 token。
pause_after_compactionbooleanfalse產生壓縮摘要後是否暫停
instructionsstringnull自訂摘要提示。提供時會完全取代預設提示。

觸發設定

使用 trigger 參數設定壓縮的觸發時機:

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-5-5",
    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-5-5",
    max_tokens=4096,
    messages=messages,
    context_management={
        "edits": [
            {
                "type": "compact_20260112",
                "instructions": "Focus on preserving code snippets, variable names, and technical decisions.",
            }
        ]
    },
)

在 Claude 5.1 及更新的模型上,帶有自訂 instructions 的請求只會根據可見的對話進行摘要:先前的思考區塊不會成為摘要器輸入的一部分。

壓縮後暫停

使用 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-5-5",
    max_tokens=4096,
    messages=messages,
    context_management={
        "edits": [{"type": "compact_20260112", "pause_after_compaction": True}]
    },
)

# 檢查 compaction(壓縮)是否觸發了暫停
if response.stop_reason == "compaction":
    # 回應僅包含 compaction 區塊
    messages.append({"role": "assistant", "content": response.content})

    # 繼續該請求
    response = client.beta.messages.create(
        betas=["compact-2026-01-12"],
        model="claude-opus-5-5",
        max_tokens=4096,
        messages=messages,
        context_management={"edits": [{"type": "compact_20260112"}]},
    )

強制執行總 token 預算

當模型處理包含多次工具使用迭代的長時間任務時,總 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-5-5",
    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 區塊。

長時間執行的對話可能會產生多次壓縮。最後一個壓縮區塊反映提示的最終狀態,並以產生的摘要取代其之前的內容。

Output
{
  "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-5-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)
# 收到含有 compaction 區塊的回應後
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-5-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)

在 Python 中,請如本頁範例所示使用 client.beta.messages。如果您呼叫 client.messages 並自行序列化區塊,單純的 model_dump() 會在 compaction 區塊中加入 text: nullcitations: null。API 接著會以 400 錯誤(Extra inputs are not permitted)拒絕該請求。請改用 to_dict()model_dump(exclude_none=True)從摘要繼續針對隨需壓縮也提供了相同的建議。

當 API 收到 compaction 區塊時,其之前的所有內容區塊都會被忽略。您可以選擇:

  • 將原始訊息保留在清單中,讓 API 處理移除已壓縮內容的工作
  • 手動捨棄已壓縮的訊息,只包含從壓縮區塊開始的內容

在 Claude Fable 5.1、Claude Mythos 5.1 和 Claude Opus 5.5 上,compaction 區塊之前的思考區塊不會被延續下去,因此摘要就是模型對先前工作所擁有的全部資訊。如果您撰寫自己的 instructions,請告訴模型摘要必須保留哪些內容;請參閱告訴模型在壓縮摘要中要保留什麼

串流

壓縮區塊的「streaming」(串流)方式與文字區塊不同。您會收到一個 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-5-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
) as stream:
    for event in stream:
        match event.type:
            case "content_block_start":
                block = event.content_block
                match block.type:
                    case "compaction":
                        print("Compaction started...")
                    case "text":
                        print("Text response started...")

            case "content_block_delta":
                delta = event.delta
                match delta.type:
                    case "compaction_delta":
                        print(f"Compaction complete: {len(delta.content or '')} chars")
                    case "text_delta":
                        print(delta.text, end="", flush=True)

    # 取得最終累積的訊息
    message = stream.get_final_message()
    messages.append({"role": "assistant", "content": message.content})

提示快取

壓縮能與「prompt caching」(提示快取)良好搭配。您可以在壓縮區塊上加入 cache_control 中斷點,以快取摘要後的內容。

{
  "role": "assistant",
  "content": [
    {
      "type": "compaction",
      "content": "[summary text]",
      "cache_control": { "type": "ephemeral" }
    },
    {
      "type": "text",
      "text": "Based on our conversation..."
    }
  ]
}

透過系統提示最大化快取命中

發生壓縮時,摘要會成為需要寫入快取的新內容。若沒有額外的快取中斷點,這也會使任何已快取的「system prompt」(系統提示)失效,導致系統提示需要與壓縮摘要一起重新快取。

若要最大化快取命中率,請在系統提示的結尾加入 cache_control 中斷點。這會讓系統提示與對話分開快取,因此當發生壓縮時:

  • 系統提示的快取仍然有效,並會從快取中讀取
  • 只有壓縮摘要需要寫入為新的快取項目
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-5-5",
    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"}]},
)

這能讓冗長的系統提示在整個對話的多次壓縮事件中持續保持快取狀態。

了解用量

壓縮需要額外的取樣步驟,這會計入「rate limit」(速率限制)與計費。API 會在回應中回傳詳細的用量資訊:

Output
{
  "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_tokensoutput_tokensmessage 迭代完全相符,因為只有一個非壓縮迭代。最後一次迭代的 token 數量反映壓縮後的有效上下文大小。

與其他功能結合

伺服器工具

使用伺服器工具(例如網頁搜尋)時,會在每次取樣迭代開始時檢查壓縮觸發條件。視您的觸發閾值與產生的輸出量而定,單一請求中可能會發生多次壓縮。

Token 計數

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-5-5",
    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-5-5",
        max_tokens=4096,
        messages=messages,
        context_management={
            "edits": [
                {
                    "type": "compact_20260112",
                    "trigger": {"type": "input_tokens", "value": 100000},
                }
            ]
        },
    )

    # 附加回應(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()

在 Claude Fable 5.1 和 Claude Opus 5.5 上,請從您在壓縮區塊之後重新插入的任何助理輪次中移除 thinkingredacted_thinking 區塊,或搭配 thinking-binding-controls-2026-08-01 beta 標頭傳送 thinking.block_binding.prefix_mismatch_behavior: "drop_block"。這些區塊是在完整歷史記錄存在時產生的,因此它們不再能通過對話檢查。在強制執行該檢查的情況下,延續請求會以 400 錯誤遭到拒絕。保留的文字與工具區塊可以維持原樣。讓 API 摘要所有內容,而不重新插入先前的輪次,即可避免此問題。

以下範例使用 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-5-5",
        max_tokens=4096,
        messages=messages,
        context_management={
            "edits": [
                {
                    "type": "compact_20260112",
                    "trigger": {"type": "input_tokens", "value": 100000},
                    "pause_after_compaction": True,
                }
            ]
        },
    )

    # 檢查是否已發生 compaction(壓縮)並暫停
    if response.stop_reason == "compaction":
        # 從回應中取得 compaction 區塊
        compaction_block = response.content[0]

        # 保留先前的對話交換與目前的使用者訊息(共 3 則訊息)
        # 方法是將它們放在 compaction 區塊之後
        preserved_messages = messages[-3:] if len(messages) >= 3 else messages

        # 建立新的訊息清單:compaction 區塊 + 保留的訊息
        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-5-5",
            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: nullcompaction 區塊。為避免此情況,請將 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.

後續步驟

透過上下文編輯,在對話上下文增長時自動加以管理。

了解上下文視窗的大小與管理策略。

探索一個實際的實作,它使用背景執行緒與提示快取,透過即時工作階段記憶壓縮來管理長時間執行的對話。

Compatibility

Supported models
  • Fable 5 and 5.1
  • Mythos 5, 5.1, and Preview
  • Opus 4.6, 4.7, 4.8, 5, and 5.5
  • Sonnet 4.6 and 5
Supported platforms
  • Claude APIBeta
  • Claude Platform on AWSBeta
  • Amazon BedrockBeta
  • Google CloudBeta
  • Microsoft FoundryBeta

Was this page helpful?