Claude Platform Docs
Messages압축

토큰 임계값 기반 압축

대화가 설정한 토큰 임계값에 도달하면 일반 요청 내에서 API가 이전 컨텍스트를 자동으로 요약하도록 합니다.

"Threshold compaction"(임계값 압축)은 자동 방식의 "compaction"(압축)입니다. 일반 요청에 토큰 임계값을 설정하면, 임계값에 도달했을 때 API가 요청 도중에 이전 컨텍스트를 요약합니다. 이 방식은 요약이 작성되는 시점을 직접 결정하는 온디맨드 압축과 함께 지원됩니다(온디맨드 압축 참조). 둘 중 어떤 방식을 사용할지 선택하려면 압축 방식 선택하기을 참조하세요.

압축은 "context window"(컨텍스트 윈도우) 한도에 가까워질 때 이전 컨텍스트를 자동으로 요약하여, 장기 실행 대화 및 작업의 유효 컨텍스트 길이를 확장합니다. 또한 활성 컨텍스트를 작게 유지합니다. 대화가 길어질수록 응답 품질이 저하되므로, 압축은 이전 콘텐츠를 간결한 요약으로 대체합니다.

이 기능은 다음과 같은 경우에 이상적입니다:

  • 사용자가 하나의 채팅을 오랜 기간 사용하기를 원하는 채팅 기반 멀티턴 대화
  • 컨텍스트 윈도우를 초과할 수 있는 많은 후속 작업(주로 "tool use"(도구 사용))이 필요한 작업 지향 프롬프트

압축 작동 방식

압축이 활성화되면, Claude는 대화가 구성된 토큰 임계값에 도달할 때 자동으로 대화를 요약합니다. API는 다음을 수행합니다:

  1. 입력 토큰이 지정한 트리거 임계값에 도달하는 시점을 감지합니다.
  2. 현재 대화의 요약을 생성합니다.
  3. 요약을 포함하는 compaction 블록을 생성합니다.
  4. 압축된 컨텍스트로 응답을 계속합니다.

후속 요청에서는 응답을 메시지에 추가하세요. API는 compaction 블록 이전의 모든 콘텐츠 블록을 자동으로 삭제하고, 요약에서부터 대화를 이어갑니다.

ServerInput tokens exceed trigger thresholdConversation is summarizedCompaction block created with summaryResponse continues with compacted contextnext requestClientAppend response to messagesMessages before the compaction block are dropped on next request

기본 사용법

Messages API 요청의 context_management.editscompact_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-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)

# 대화를 이어가려면 응답(compaction 블록 포함)을 추가하세요
messages.append({"role": "assistant", "content": response.content})

매개변수

매개변수타입기본값설명
typestring필수"compact_20260112"이어야 합니다
triggerobject{"type": "input_tokens", "value": 150000}압축을 트리거할 시점입니다. input_tokens가 유일하게 지원되는 트리거 타입입니다. value는 최소 50,000 토큰이어야 합니다.
pause_after_compactionbooleanfalse압축 요약을 생성한 후 일시 중지할지 여부
instructionsstringnull사용자 지정 요약 프롬프트입니다. 제공되면 기본 프롬프트를 완전히 대체합니다.

트리거 구성

trigger 매개변수를 사용하여 압축이 트리거되는 시점을 구성하세요:

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-5-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-5",
    max_tokens=4096,
    messages=messages,
    context_management={
        "edits": [
            {
                "type": "compact_20260112",
                "instructions": "Focus on preserving code snippets, variable names, and technical decisions.",
            }
        ]
    },
)

Claude 5.1 이상 모델에서는 사용자 지정 instructions가 포함된 요청이 보이는 대화만을 기반으로 요약합니다. 이전 thinking 블록은 요약기의 입력에 포함되지 않습니다.

압축 후 일시 중지

pause_after_compaction을 사용하면 압축 요약을 생성한 후 API를 일시 중지할 수 있습니다. 이를 통해 API가 응답을 계속하기 전에 추가 콘텐츠 블록(예: 최근 메시지 보존 또는 특정 지침 중심 메시지)을 추가할 수 있습니다.

이 옵션이 활성화되면, API는 compaction 블록을 생성한 후 compaction 중지 사유와 함께 메시지를 반환합니다:

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=messages,
    context_management={
        "edits": [{"type": "compact_20260112", "pause_after_compaction": True}]
    },
)

# compaction(압축)으로 인해 일시 중지가 발생했는지 확인합니다
if response.stop_reason == "compaction":
    # 응답에 compaction 블록만 포함되어 있습니다
    messages.append({"role": "assistant", "content": response.content})

    # 요청을 계속 진행합니다
    response = client.beta.messages.create(
        betas=["compact-2026-01-12"],
        model="claude-opus-5-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-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 블록을 반환합니다.

장기 실행 대화에서는 여러 번의 압축이 발생할 수 있습니다. 마지막 compaction 블록은 프롬프트의 최종 상태를 반영하며, 그 이전의 콘텐츠를 생성된 요약으로 대체합니다.

Output
{
  "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-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)
# compaction 블록이 포함된 응답을 받은 후
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-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)

Python에서는 이 페이지의 샘플처럼 client.beta.messages를 사용하세요. client.messages를 호출하고 블록을 직접 직렬화하는 경우, 일반 model_dump()compaction 블록에 text: nullcitations: null을 추가합니다. 그러면 API는 400 오류(Extra inputs are not permitted)와 함께 요청을 거부합니다. 대신 to_dict() 또는 model_dump(exclude_none=True)를 사용하세요. 요약에서 이어서 진행하기에서도 온디맨드 압축에 대해 동일한 조언을 제공합니다.

API가 compaction 블록을 받으면, 그 이전의 모든 콘텐츠 블록은 무시됩니다. 다음 중 하나를 선택할 수 있습니다:

  • 원본 메시지를 목록에 유지하고 API가 압축된 콘텐츠 제거를 처리하도록 합니다
  • 압축된 메시지를 수동으로 삭제하고 compaction 블록부터만 포함합니다

Claude Fable 5.1, Claude Mythos 5.1 및 Claude Opus 5.5에서는 compaction 블록 이전의 thinking 블록이 이후로 전달되지 않으므로, 모델이 이전 작업에 대해 가진 정보는 요약이 전부입니다. 직접 instructions를 작성하는 경우, 요약에 반드시 유지해야 할 내용을 모델에 알려주세요. 압축 요약에서 보존할 내용을 모델에 알려 주기를 참조하세요.

스트리밍

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-5",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
) as stream:
    for event in stream:
        match event.type:
            case "content_block_start":
                block = event.content_block
                match block.type:
                    case "compaction":
                        print("Compaction started...")
                    case "text":
                        print("Text response started...")

            case "content_block_delta":
                delta = event.delta
                match delta.type:
                    case "compaction_delta":
                        print(f"Compaction complete: {len(delta.content or '')} chars")
                    case "text_delta":
                        print(delta.text, end="", flush=True)

    # 최종 누적된 메시지를 가져옵니다
    message = stream.get_final_message()
    messages.append({"role": "assistant", "content": message.content})

프롬프트 캐싱

압축은 프롬프트 캐싱과 함께 잘 작동합니다. compaction 블록에 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-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"}]},
)

이렇게 하면 대화 전반에 걸쳐 여러 번의 압축 이벤트가 발생해도 긴 시스템 프롬프트가 캐시된 상태로 유지됩니다.

사용량 이해하기

압축에는 추가 샘플링 단계가 필요하며, 이는 "rate limit"(속도 제한) 및 청구에 반영됩니다. API는 응답에서 자세한 사용량 정보를 반환합니다:

Output
{
  "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_tokensoutput_tokensmessage 반복과 정확히 일치합니다. 마지막 반복의 토큰 수는 압축 후의 유효 컨텍스트 크기를 반영합니다.

다른 기능과 결합하기

서버 도구

서버 도구(예: 웹 검색)를 사용할 때, 압축 트리거는 각 샘플링 반복의 시작 시점에 확인됩니다. 트리거 임계값과 생성된 출력량에 따라 단일 요청 내에서 압축이 여러 번 발생할 수 있습니다.

토큰 카운팅

토큰 카운팅 엔드포인트(/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-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-5",
        max_tokens=4096,
        messages=messages,
        context_management={
            "edits": [
                {
                    "type": "compact_20260112",
                    "trigger": {"type": "input_tokens", "value": 100000},
                }
            ]
        },
    )

    # 응답을 추가합니다(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()을 계속 호출합니다

Claude Fable 5.1 및 Claude Opus 5.5에서는 compaction 블록 뒤에 다시 삽입하는 모든 어시스턴트 턴에서 thinkingredacted_thinking 블록을 제거하거나, thinking-binding-controls-2026-08-01 베타 헤더와 함께 thinking.block_binding.prefix_mismatch_behavior: "drop_block"을 전송하세요. 해당 블록은 전체 기록이 존재할 때 생성되었으므로 더 이상 대화 검사를 통과하지 못합니다. 검사가 적용되는 경우, 후속 요청은 400 오류와 함께 거부됩니다. 보존된 텍스트 및 도구 블록은 그대로 두어도 됩니다. 이전 턴을 다시 삽입하지 않고 API가 모든 내용을 요약하도록 하면 이 문제를 피할 수 있습니다.

다음은 pause_after_compaction을 사용하여 이전 교환과 현재 사용자 메시지(총 세 개의 메시지)를 요약하지 않고 그대로 보존하는 예제입니다:

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-5",
        max_tokens=4096,
        messages=messages,
        context_management={
            "edits": [
                {
                    "type": "compact_20260112",
                    "trigger": {"type": "input_tokens", "value": 100000},
                    "pause_after_compaction": True,
                }
            ]
        },
    )

    # compaction이 발생하여 일시 중지되었는지 확인합니다
    if response.stop_reason == "compaction":
        # 응답에서 compaction 블록을 가져옵니다
        compaction_block = response.content[0]

        # 이전 교환과 현재 사용자 메시지(메시지 3개)를 보존합니다
        # compaction 블록 뒤에 포함하는 방식으로
        preserved_messages = messages[-3:] if len(messages) >= 3 else messages

        # 새 메시지 목록 구성: compaction + 보존된 메시지
        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-5",
            max_tokens=4096,
            messages=messages_after_compaction,
            context_management={"edits": [{"type": "compact_20260112"}]},
        )

        # compaction을 반영하도록 메시지 목록을 업데이트합니다
        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: nullcompaction 블록이 포함됩니다. 이를 방지하려면 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.

다음 단계

컨텍스트 편집을 사용하여 대화가 길어짐에 따라 대화 컨텍스트를 자동으로 관리하세요.

컨텍스트 윈도우 크기와 관리 전략에 대해 알아보세요.

백그라운드 스레딩과 프롬프트 캐싱을 활용한 즉각적인 세션 메모리 압축으로 장기 실행 대화를 관리하는 실용적인 구현을 살펴보세요.

Compatibility

Supported models
  • Fable 5 and 5.1
  • Mythos 5, 5.1, and Preview
  • Opus 4.6, 4.7, 4.8, 5, and 5.5
  • Sonnet 4.6 and 5
Supported platforms
  • Claude APIBeta
  • Claude Platform on AWSBeta
  • Amazon BedrockBeta
  • Google CloudBeta
  • Microsoft FoundryBeta

Was this page helpful?