「zero data retention」(ゼロデータ保持)、すなわちZDRがこの機能にどのように適用されるかについては、APIとデータ保持を参照してください。
サーバーサイドのコンパクションは、長時間実行される会話やエージェント型ワークフローにおけるコンテキスト管理の推奨戦略です。クライアント側の要約コードなしで、コンテキスト管理を自動的に処理します。
「compaction」(コンパクション)は、コンテキストウィンドウの制限に近づいたときに古いコンテキストを自動的に要約することで、長時間実行される会話やタスクの実効的なコンテキスト長を拡張します。また、アクティブなコンテキストを小さく保ちます。会話が長くなるにつれて応答品質が低下するため、コンパクションは古いコンテンツを簡潔な要約に置き換えます。
長いコンテキストが品質低下を引き起こす理由と、コンパクションがどのように役立つかについて詳しくは、 効果的なコンテキストエンジニアリングを参照してください。
これは以下のような場合に最適です。
コンパクションはベータ版です。この機能を使用するには、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-5",
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-5",
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-5",
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-5",
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-5",
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-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})
# 消費された合計トークン数を推定し、予算超過の場合はまとめを促す
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-5",
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-5",
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-5",
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-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"}]},
)これにより、会話全体を通じて複数のコンパクションイベントにわたって、長いシステムプロンプトがキャッシュされたままになります。
コンパクションには追加のサンプリングステップが必要であり、これはレート制限と課金に影響します。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-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",
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-5",
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-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: 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?