この機能はZero Data Retention(ZDR)の対象です。組織がZDR契約を締結している場合、この機能を通じて送信されたデータは、APIレスポンスが返された後に保存されることはありません。
サーバーサイドのコンパクションは、長時間実行される会話やエージェント型ワークフローでコンテキストを管理するための推奨戦略です。クライアント側で要約コードを書くことなく、コンテキスト管理を自動的に処理します。
「compaction」(コンパクション)は、コンテキストウィンドウの上限に近づいた際に古いコンテキストを自動的に要約することで、長時間実行される会話やタスクの実効的なコンテキスト長を拡張します。また、アクティブなコンテキストを小さく保ちます。会話が長くなるにつれて応答品質は低下するため、コンパクションは古いコンテンツを簡潔な要約に置き換えます。
長いコンテキストがなぜ劣化するのか、そしてコンパクションがどのように役立つのかについて詳しくは、 Effective context engineeringを参照してください。
これは以下のような場合に最適です。
コンパクションはベータ版です。この機能を使用するには、APIリクエストにベータヘッダー compact-2026-01-12 を含めてください。
コンパクションは以下のモデルでサポートされています。
コンパクションが有効になっている場合、会話が設定されたトークンしきい値に達すると、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トークン以上である必要があります。 |
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},
}
]
},
)デフォルトの要約プロンプトはモデルによって異なります。各デフォルトは、将来のコンテキストウィンドウでタスクを続行するために必要な情報を含む要約を <summary></summary> タグ内に書くようClaudeに指示します。たとえば、一部のモデルでは以下のプロンプトが使用されます。
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"}]},
)モデルが多くのツール使用イテレーションを伴う長いタスクに取り組む場合、合計トークン消費量が大幅に増加する可能性があります。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})
# 消費トークンの合計を推定し、予算超過なら終了を促す
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 イテレーションが表示されます。この例では、コンパクション以外のイテレーションが1つしかないため、トップレベルの input_tokens と output_tokens は message イテレーションと完全に一致します。最終イテレーションのトークン数は、コンパクション後の実効コンテキストサイズを反映しています。
トップレベルの input_tokens と output_tokens には、コンパクションイテレーションの使用量は含まれません。これらはコンパクション以外のすべてのイテレーションの合計を反映しています。リクエストで消費および課金された合計トークン数を計算するには、usage.iterations 配列のすべてのエントリを合計してください。
これまでコスト追跡や監査のために usage.input_tokens と usage.output_tokens に依存していた場合、コンパクションが有効な場合は usage.iterations 全体を集計するように追跡ロジックを更新する必要があります。コンパクションベータが有効な場合、コンパクションが発生しなかった場合でも、すべての応答に usage.iterations が含まれます。compaction エントリは、リクエスト中に新しいコンパクションがトリガーされた場合にのみ表示されます。以前の compaction ブロックを再適用しても追加のコンパクションコストは発生せず、その場合トップレベルの使用量フィールドは正確なままです。
サーバーツール(ウェブ検索など)を使用する場合、コンパクショントリガーは各サンプリングイテレーションの開始時にチェックされます。トリガーしきい値と生成される出力量によっては、単一のリクエスト内でコンパクションが複数回発生する可能性があります。
トークンカウントエンドポイント(/v1/messages/count_tokens)は、プロンプト内の既存の compaction ブロックを適用しますが、新しいコンパクションはトリガーしません。以前のコンパクション後の実効トークン数を確認するために使用します。
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 を使用して、直前のやり取りと現在のユーザーメッセージ(合計3つのメッセージ)を要約せずにそのまま保持する例です。
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?