Claude Platform Docs
  • Messages
  • Managed Agents
  • 管理

Search...
⌘K
第一步
Claude 簡介快速入門
使用 Claude 進行建構
功能概覽使用 Messages API停止原因與備援拒絕與備援備援額度
模型能力
擴展思考自適應思考Effort任務預算(測試版)快速模式(研究預覽)結構化輸出引用串流 Messages批次處理搜尋結果串流拒絕多語言支援嵌入
工具
概覽工具使用的運作方式教學:建構使用工具的代理定義工具處理工具呼叫平行工具使用Tool Runner (SDK)嚴格工具使用工具使用與提示快取伺服器工具疑難排解網頁搜尋工具網頁擷取工具程式碼執行工具顧問工具記憶工具Bash 工具電腦使用工具文字編輯器工具
工具基礎架構
工具參考管理工具上下文工具組合工具搜尋程式化工具呼叫細粒度工具串流
上下文管理
上下文視窗壓縮上下文編輯提示快取對話中系統訊息建構協調模式快取診斷(測試版)Token 計數
處理檔案
Files APIPDF 支援圖片與視覺
技能
概覽快速入門最佳實務企業技能API 中的技能
MCP
遠端 MCP 伺服器MCP 連接器
雲端平台上的 Claude
Amazon BedrockAmazon Bedrock(舊版)AWS 上的 Claude PlatformMicrosoft FoundryVertex AI

Log in
壓縮
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Platform Docs

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Claude on AWS
  • Claude on Google Cloud

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

壓縮

伺服器端上下文壓縮,用於管理接近上下文視窗限制的長對話。

Was this page helpful?

  • 支援的模型
  • 壓縮的運作方式
  • 基本用法
  • 參數
  • 觸發設定
  • 自訂摘要指示
  • 壓縮後暫停
  • 使用壓縮區塊
  • 回傳壓縮區塊
  • 串流
  • 提示快取
  • 了解使用量
  • 與其他功能結合使用
  • 伺服器工具
  • Token 計數
  • 範例
  • 目前的限制
  • 後續步驟


此功能符合「Zero Data Retention」(零資料保留),即 ZDR 的資格。當您的組織具有 ZDR 安排時,透過此功能傳送的資料在 API 回應返回後不會被儲存。



伺服器端壓縮是管理長時間執行對話和代理工作流程中上下文的建議策略。它能以最少的整合工作自動處理上下文管理。

「Compaction」(壓縮)透過在接近「context window」(上下文視窗)限制時自動摘要較舊的上下文,來延長長時間執行對話和任務的有效上下文長度。這不僅僅是為了保持在 token 上限之下。隨著對話變長,模型難以在完整歷史記錄中保持專注。壓縮透過以簡潔的摘要取代過時內容,使活躍的上下文保持專注且高效能。



若要深入了解為何長上下文會降低效能以及壓縮如何提供幫助,請參閱 Effective context engineering。

這非常適合:

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

壓縮目前處於測試階段。請在您的 API 請求中包含 beta header compact-2026-01-12 以使用此功能。

支援的模型

壓縮支援以下模型:

  • Claude Fable 5(claude-fable-5)
  • Claude Mythos 5(claude-mythos-5)
  • Claude Mythos Preview(claude-mythos-preview)
  • Claude Opus 4.8(claude-opus-4-8)
  • Claude Opus 4.7(claude-opus-4-7)
  • Claude Opus 4.6(claude-opus-4-6)
  • Claude Sonnet 4.6(claude-sonnet-4-6)

壓縮的運作方式

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

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

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

顯示壓縮流程的流程圖:當輸入 token 超過觸發閾值時,Claude 會在 compaction 區塊中產生摘要,並使用壓縮後的上下文繼續回應

基本用法

透過在 Messages API 請求的 context_management.edits 中新增 compact_20260112 策略來啟用壓縮。

參數

參數類型預設值說明
typestring必填必須為 "compact_20260112"
triggerobject150,000 個 token觸發壓縮的時機。必須至少為 50,000 個 token。
pause_after_compactionbooleanfalse是否在產生壓縮摘要後暫停
instructionsstringnull自訂摘要提示。提供時會完全取代預設提示。

觸發設定

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

自訂摘要指示

預設情況下,壓縮使用以下摘要提示:

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 參數提供自訂指示來完全取代此提示。自訂指示不會補充預設提示;而是完全取代它:

壓縮後暫停

使用 pause_after_compaction 可在產生壓縮摘要後暫停 API。這讓您可以在 API 繼續回應之前新增額外的內容區塊(例如保留最近的訊息或特定的指示導向訊息)。

啟用後,API 會在產生壓縮區塊後回傳帶有 compaction 停止原因的訊息:

強制執行總 token 預算

當模型處理具有許多工具使用迭代的長時間任務時,總 token 消耗可能會大幅增加。您可以將 pause_after_compaction 與壓縮計數器結合使用,以估算累積使用量,並在達到預算後優雅地結束任務:

Python
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 區塊。

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

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,以使用縮短的提示繼續對話。最簡單的方法是將整個回應內容附加到您的訊息中:

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

  • 將原始訊息保留在清單中,讓 API 處理移除已壓縮的內容
  • 手動捨棄已壓縮的訊息,僅包含壓縮區塊及其之後的內容

串流

在啟用壓縮的情況下進行「streaming」(串流)回應時,當壓縮開始時您會收到 content_block_start 事件。壓縮區塊的串流方式與文字區塊不同。您會收到一個 content_block_start 事件,接著是一個包含完整摘要內容的單一 content_block_delta(沒有中間串流),然後是一個 content_block_stop 事件。

提示快取

壓縮與提示快取搭配使用效果良好。您可以在壓縮區塊上新增 cache_control 斷點以快取摘要內容。原始的已壓縮內容會被忽略。

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

使用系統提示最大化快取命中率

當壓縮發生時,摘要會成為需要寫入快取的新內容。如果沒有額外的快取斷點,這也會使任何已快取的系統提示失效,需要與壓縮摘要一起重新快取。

為了最大化快取命中率,請在系統提示的末尾新增 cache_control 斷點。這會使系統提示與對話分開快取,因此當壓縮發生時:

  • 系統提示快取保持有效並從快取中讀取
  • 只有壓縮摘要需要作為新的快取項目寫入

這種方法對於長系統提示特別有益,因為即使在整個對話中發生多次壓縮事件,它們仍保持快取狀態。

了解使用量

壓縮需要額外的取樣步驟,這會計入速率限制和計費。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_tokens 和 output_tokens 與 message 迭代完全相符,因為只有一個非壓縮迭代。最後一個迭代的 token 計數反映壓縮後的有效上下文大小。



頂層的 input_tokens 和 output_tokens 不包含壓縮迭代的使用量。它們反映所有非壓縮迭代的總和。若要計算請求消耗和計費的總 token 數,請加總 usage.iterations 陣列中的所有項目。

如果您先前依賴 usage.input_tokens 和 usage.output_tokens 進行成本追蹤或稽核,則在啟用壓縮時,您需要更新追蹤邏輯以彙總 usage.iterations 中的資料。iterations 陣列僅在請求期間觸發新壓縮時才會填入。重新套用先前的 compaction 區塊不會產生額外的壓縮成本,在這種情況下,頂層使用量欄位仍然準確。

與其他功能結合使用

伺服器工具

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

Token 計數

Token 計數端點(/v1/messages/count_tokens)會套用提示中現有的 compaction 區塊,但不會觸發新的壓縮。使用它來檢查先前壓縮後的有效 token 計數:

範例

以下是使用壓縮的長時間執行對話的完整範例:

以下範例使用 pause_after_compaction 來逐字保留先前的交流和目前的使用者訊息(共三則訊息),而非對其進行摘要:

目前的限制

  • 摘要使用相同模型: 您請求中指定的模型會用於摘要。沒有選項可以使用不同的(例如更便宜的)模型來產生摘要。

  • 定義工具時壓縮可能會失敗: 當您的請求包含 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.

後續步驟


工作階段記憶體壓縮 Cookbook


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

上下文視窗

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

上下文編輯

探索管理對話上下文的其他策略,例如工具結果清除和思考區塊清除。

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})
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},
            }
        ]
    },
)
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.",
            }
        ]
    },
)
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"}]},
    )
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"}]},
)
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})
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"}]},
)
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"))
# ... 視需要繼續
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"))
# ... 視需要繼續進行