コンパクションは、「context window」(コンテキストウィンドウ)の上限に近づいたときに古いコンテキストを自動的に要約することで、長時間実行される会話やタスクの実効的なコンテキスト長を拡張します。また、アクティブなコンテキストを小さく保ちます。会話が長くなるにつれて応答品質が低下するため、コンパクションは古いコンテンツを簡潔な要約に置き換えます。
これは以下のような場合に最適です。
コンパクションが有効になっている場合、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イテレーションと正確に一致します。最後のイテレーションのトークン数は、コンパクション後の実効コンテキストサイズを反映しています。
サーバーツール(ウェブ検索など)を使用する場合、コンパクショントリガーは各サンプリングイテレーションの開始時にチェックされます。トリガーしきい値と生成される出力量によっては、単一のリクエスト内でコンパクションが複数回発生する可能性があります。
トークンカウントエンドポイント(/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.コンテキスト編集により、会話コンテキストが増大するにつれて自動的に管理します。
コンテキストウィンドウのサイズと管理戦略について学びます。
バックグラウンドスレッディングとプロンプトキャッシングを使用した即時セッションメモリコンパクションで、長時間実行される会話を管理する実践的な実装を探索します。
| Supported models |
|
|---|---|
| Supported platforms |
|
Was this page helpful?