Was this page helpful?
This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.
サーバー側の圧縮は、長時間実行される会話とエージェントワークフローでコンテキストを管理するための推奨戦略です。最小限の統合作業で自動的にコンテキスト管理を処理します。
圧縮は、コンテキストウィンドウの制限に近づいた場合に古いコンテキストを自動的に要約することで、長時間実行される会話とタスクの有効なコンテキスト長を拡張します。これは単にトークン上限以下に留まることだけではありません。会話が長くなるにつれて、モデルは完全な履歴全体にわたって焦点を維持するのに苦労します。圧縮は、古いコンテンツを簡潔な要約に置き換えることで、アクティブなコンテキストを焦点を絞った状態で高性能に保ちます。
長いコンテキストが低下する理由と圧縮がどのように役立つかについてのより詳しい説明については、 効果的なコンテキストエンジニアリングを参照してください。
これは以下の場合に理想的です:
圧縮はベータ版です。この機能を使用するには、APIリクエストにベータヘッダー compact-2026-01-12を含めてください。
圧縮は以下のモデルでサポートされています:
claude-mythos-preview)claude-opus-4-7)claude-opus-4-6)claude-sonnet-4-6)圧縮が有効になると、Claude は設定されたトークン閾値に近づいた場合に会話を自動的に要約します。API は:
compaction ブロックを作成します。後続のリクエストでは、応答をメッセージに追加します。API は compaction ブロックの前のすべてのメッセージブロックを自動的に削除し、要約から会話を続けます。
Messages API リクエストの context_management.edits に compact_20260112 ストラテジーを追加することで圧縮を有効にします。
| パラメータ | 型 | デフォルト | 説明 |
|---|---|---|---|
type | string | 必須 | "compact_20260112" である必要があります |
trigger | object | 150,000 トークン | 圧縮をトリガーするタイミング。最低 50,000 トークンである必要があります。 |
pause_after_compaction | boolean | false | 圧縮要約の生成後に一時停止するかどうか |
instructions | string | null | カスタム要約プロンプト。提供された場合、デフォルトプロンプトを完全に置き換えます。 |
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 停止理由を含むメッセージを返します:
モデルが多くのツール使用イテレーションを伴う長いタスクに取り組む場合、総トークン消費量は大幅に増加する可能性があります。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-7",
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})
# Estimate total tokens consumed; prompt wrap-up if over budget
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 に返す必要があります。最も簡単な方法は、応答全体のコンテンツをメッセージに追加することです:
API が compaction ブロックを受け取ると、その前のすべてのコンテンツブロックは無視されます。以下のいずれかを実行できます:
コンパクションが有効な状態で応答をストリーミングする場合、コンパクションが開始されると 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はレスポンスで詳細な使用情報を返します:
{
"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反復と完全に一致します。これは圧縮以外の反復が1つだけであるためです。最終反復のトークンカウントは、圧縮後の有効なコンテキストサイズを反映しています。
トップレベルのinput_tokensとoutput_tokensは圧縮反復の使用状況を含みません。これらはすべての非圧縮反復の合計を反映しています。リクエストで消費および請求されたトークンの合計を計算するには、usage.iterations配列のすべてのエントリを合計してください。
以前にusage.input_tokensとusage.output_tokensをコスト追跡または監査に使用していた場合、圧縮が有効な場合はusage.iterations全体で集計するようにトラッキングロジックを更新する必要があります。iterations配列は、リクエスト中に新しい圧縮がトリガーされた場合にのみ入力されます。以前のcompactionブロックを再適用しても、追加の圧縮コストは発生せず、その場合トップレベルの使用フィールドは正確なままです。
サーバーツール(Webサーチなど)を使用する場合、圧縮トリガーは各サンプリング反復の開始時にチェックされます。トリガーしきい値と生成される出力の量に応じて、単一のリクエスト内で圧縮が複数回発生する可能性があります。
トークンカウントエンドポイント(/v1/messages/count_tokens)はプロンプト内の既存のcompactionブロックを適用しますが、新しい圧縮をトリガーしません。これを使用して、以前の圧縮後の有効なトークンカウントを確認します:
圧縮を使用した長時間実行の会話の完全な例を次に示します:
pause_after_compactionを使用して、前の交換と現在のユーザーメッセージ(合計3つのメッセージ)を要約する代わりに逐語的に保持する例を次に示します:
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-7",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
# Append the response (including any compaction block) to continue the conversation
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-7",
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-7",
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-7",
max_tokens=4096,
messages=messages,
context_management={
"edits": [{"type": "compact_20260112", "pause_after_compaction": True}]
},
)
# Check if compaction triggered a pause
if response.stop_reason == "compaction":
# Response contains only the compaction block
messages.append({"role": "assistant", "content": response.content})
# Continue the request
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-7",
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-7",
max_tokens=4096,
messages=messages,
context_management={"edits": [{"type": "compact_20260112"}]},
)
# After receiving a response with a compaction block
messages.append({"role": "assistant", "content": response.content})
# Continue the conversation
messages.append({"role": "user", "content": "Now add error handling"})
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-7",
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-7",
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)} chars")
elif event.delta.type == "text_delta":
print(event.delta.text, end="", flush=True)
# Get the final accumulated message
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-7",
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-7",
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-7",
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-7",
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-7",
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"))
# ... 必要に応じて続行ツール結果クリアリングと思考ブロッククリアリングなど、会話コンテキストを管理するための他の戦略を探索します。