서버 측 압축은 장시간 실행되는 대화 및 에이전트 워크플로에서 컨텍스트를 관리하기 위한 권장 전략입니다. 최소한의 통합 작업으로 컨텍스트 관리를 자동으로 처리합니다.
압축은 컨텍스트 윈도우 한계에 근접할 때 이전 컨텍스트를 자동으로 요약하여 장시간 실행되는 대화 및 작업의 유효 컨텍스트 길이를 확장합니다. 이는 다음과 같은 경우에 이상적입니다:
압축은 현재 베타 상태입니다. 이 기능을 사용하려면 API 요청에 베타 헤더 compact-2026-01-12를 포함하세요.
압축은 다음 모델에서 지원됩니다:
claude-opus-4-6)압축이 활성화되면 Claude는 구성된 토큰 임계값에 근접할 때 자동으로 대화를 요약합니다. API는:
compaction 블록을 생성합니다.후속 요청에서는 응답을 메시지에 추가하세요. API는 compaction 블록 이전의 모든 메시지 블록을 자동으로 삭제하고 요약에서부터 대화를 계속합니다.
Messages API 요청에서 context_management.edits에 compact_20260112 전략을 추가하여 압축을 활성화합니다.
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "anthropic-beta: compact-2026-01-12" \
--header "content-type: application/json" \
--data \
'{
"model": "claude-opus-4-6",
"max_tokens": 4096,
"messages": [
{
"role": "user",
"content": "Help me build a website"
}
],
"context_management": {
"edits": [
{
"type": "compact_20260112"
}
]
}
}'| 매개변수 | 타입 | 기본값 | 설명 |
|---|---|---|---|
type | string | 필수 | "compact_20260112"이어야 합니다 |
trigger | object | 150,000 토큰 | 압축을 트리거할 시점. 최소 50,000 토큰이어야 합니다. |
pause_after_compaction | boolean | false | 압축 요약 생성 후 일시 중지할지 여부 |
instructions | string | null | 사용자 정의 요약 프롬프트. 제공 시 기본 프롬프트를 완전히 대체합니다. |
trigger 매개변수를 사용하여 압축이 트리거되는 시점을 구성합니다:
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-6",
max_tokens=4096,
messages=messages,
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {
"type": "input_tokens",
"value": 150000
}
}
]
}
)기본적으로 압축은 다음 요약 프롬프트를 사용합니다:
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 매개변수를 통해 사용자 정의 지침을 제공하여 이 프롬프트를 완전히 대체할 수 있습니다. 사용자 정의 지침은 기본값을 보완하는 것이 아니라 완전히 대체합니다:
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-6",
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 중지 사유와 함께 메시지를 반환합니다:
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-4-6",
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-6",
max_tokens=4096,
messages=messages,
context_management={
"edits": [{"type": "compact_20260112"}]
}
)모델이 많은 도구 사용 반복이 있는 긴 작업을 수행할 때 총 토큰 소비량이 크게 증가할 수 있습니다. pause_after_compaction을 압축 카운터와 결합하여 누적 사용량을 추정하고 예산에 도달하면 작업을 우아하게 마무리할 수 있습니다:
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-6",
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에 다시 전달해야 합니다. 가장 간단한 방법은 전체 응답 콘텐츠를 메시지에 추가하는 것입니다:
# 압축 블록이 포함된 응답을 받은 후
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-6",
max_tokens=4096,
messages=messages,
context_management={
"edits": [{"type": "compact_20260112"}]
}
)API가 compaction 블록을 수신하면 그 이전의 모든 콘텐츠 블록은 무시됩니다. 다음 중 하나를 선택할 수 있습니다:
압축이 활성화된 상태에서 응답을 스트리밍할 때 압축이 시작되면 content_block_start 이벤트를 수신합니다. 압축 블록은 텍스트 블록과 다르게 스트리밍됩니다. content_block_start 이벤트를 수신한 후 완전한 요약 콘텐츠가 포함된 단일 content_block_delta(중간 스트리밍 없음)를 수신하고 그 다음 content_block_stop 이벤트를 수신합니다.
import anthropic
client = anthropic.Anthropic()
with client.beta.messages.stream(
betas=["compact-2026-01-12"],
model="claude-opus-4-6",
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)
# 최종 누적 메시지를 가져옵니다
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..."
}
]
}압축은 추가 샘플링 단계가 필요하며, 이는 속도 제한 및 청구에 기여합니다. API는 응답에서 상세한 사용량 정보를 반환합니다:
{
"usage": {
"input_tokens": 45000,
"output_tokens": 1234,
"iterations": [
{
"type": "compaction",
"input_tokens": 180000,
"output_tokens": 3500
},
{
"type": "message",
"input_tokens": 23000,
"output_tokens": 1000
}
]
}
}iterations 배열은 각 샘플링 반복의 사용량을 보여줍니다. 압축이 발생하면 compaction 반복 다음에 메인 message 반복이 표시됩니다. 최종 반복의 토큰 수는 압축 후 유효 컨텍스트 크기를 반영합니다.
최상위 input_tokens 및 output_tokens에는 압축 반복 사용량이 포함되지 않습니다—이는 모든 비압축 반복의 합계를 반영합니다. 요청에 대해 소비되고 청구되는 총 토큰을 계산하려면 usage.iterations 배열의 모든 항목을 합산하세요.
이전에 비용 추적이나 감사를 위해 usage.input_tokens 및 usage.output_tokens에 의존했다면, 압축이 활성화된 경우 usage.iterations 전체를 집계하도록 추적 로직을 업데이트해야 합니다. iterations 배열은 요청 중에 새로운 압축이 트리거될 때만 채워집니다. 이전 compaction 블록을 다시 적용하면 추가 압축 비용이 발생하지 않으며, 이 경우 최상위 사용량 필드는 정확한 상태를 유지합니다.
서버 도구(예: 웹 검색)를 사용할 때 압축 트리거는 각 샘플링 반복의 시작 시 확인됩니다. 트리거 임계값과 생성된 출력량에 따라 단일 요청 내에서 압축이 여러 번 발생할 수 있습니다.
토큰 카운팅 엔드포인트(/v1/messages/count_tokens)는 프롬프트에 있는 기존 compaction 블록을 적용하지만 새로운 압축을 트리거하지는 않습니다. 이전 압축 후 유효 토큰 수를 확인하는 데 사용하세요:
count_response = client.beta.messages.count_tokens(
betas=["compact-2026-01-12"],
model="claude-opus-4-6",
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}")다음은 압축을 사용한 장시간 실행 대화의 전체 예제입니다:
import anthropic
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-6",
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"))
# ... 필요한 만큼 계속합니다다음은 pause_after_compaction을 사용하여 마지막 두 메시지(사용자 1개 + 어시스턴트 1개 턴)를 요약하지 않고 그대로 보존하는 예제입니다:
import anthropic
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-6",
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]
# 마지막 2개 메시지(사용자 1개 + 어시스턴트 1개 턴)를
# 압축 블록 뒤에 포함하여 보존합니다
preserved_messages = messages[-2:] if len(messages) >= 2 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-6",
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"))
# ... 필요한 만큼 계속합니다쿡북에서 실용적인 예제와 구현을 살펴보세요.
컨텍스트 윈도우 크기와 관리 전략에 대해 알아보세요.
도구 결과 삭제 및 사고 블록 삭제와 같은 대화 컨텍스트 관리를 위한 다른 전략을 살펴보세요.
Was this page helpful?