Loading...
  • 빌드
  • 관리
  • 모델 및 가격
  • 클라이언트 SDK
  • API 참조
Search...
⌘K
Log in
압축
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
빌드/컨텍스트 관리

압축

긴 대화가 컨텍스트 윈도우 제한에 접근할 때 관리하기 위한 서버 측 컨텍스트 압축.

Was this page helpful?

This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.

서버 측 압축은 긴 실행 대화 및 에이전트 워크플로우에서 컨텍스트를 관리하기 위한 권장 전략입니다. 최소한의 통합 작업으로 컨텍스트 관리를 자동으로 처리합니다.

압축은 컨텍스트 윈도우 제한에 접근할 때 이전 컨텍스트를 자동으로 요약하여 긴 실행 대화 및 작업의 효과적인 컨텍스트 길이를 확장합니다. 이것은 단순히 토큰 상한선 이하로 유지하는 것만이 아닙니다. 대화가 길어질수록 모델은 전체 기록에 걸쳐 초점을 유지하기 어려워집니다. 압축은 오래된 콘텐츠를 간결한 요약으로 바꾸어 활성 컨텍스트를 집중적이고 성능 있게 유지합니다.

긴 컨텍스트가 성능 저하되는 이유와 압축이 어떻게 도움이 되는지에 대한 더 깊은 이해를 위해 효과적인 컨텍스트 엔지니어링을 참조하세요.

이는 다음의 경우에 이상적입니다:

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

압축은 베타 버전입니다. 이 기능을 사용하려면 API 요청에 베타 헤더 compact-2026-01-12를 포함하세요.

지원되는 모델

압축은 다음 모델에서 지원됩니다:

  • Claude Mythos Preview (claude-mythos-preview)
  • Claude Opus 4.7 (claude-opus-4-7)
  • Claude Opus 4.6 (claude-opus-4-6)
  • Claude Sonnet 4.6 (claude-sonnet-4-6)

압축 작동 방식

압축이 활성화되면 Claude는 구성된 토큰 임계값에 접근할 때 자동으로 대화를 요약합니다. API는:

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

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

입력 토큰이 트리거 임계값을 초과할 때 Claude가 압축 블록에서 요약을 생성하고 압축된 컨텍스트로 응답을 계속하는 압축 프로세스를 보여주는 흐름 다이어그램

기본 사용법

Messages API 요청의 context_management.edits에 compact_20260112 전략을 추가하여 압축을 활성화합니다.

매개변수

매개변수유형기본값설명
typestring필수"compact_20260112"이어야 합니다
triggerobject150,000 토큰압축을 트리거할 시기입니다. 최소 50,000 토큰이어야 합니다.
pause_after_compactionbooleanfalse압축 요약 생성 후 일시 중지할지 여부
instructionsstringnull사용자 정의 요약 프롬프트입니다. 제공될 때 기본 프롬프트를 완전히 대체합니다.

트리거 구성

trigger 매개변수를 사용하여 압축이 트리거되는 시기를 구성합니다:

사용자 정의 요약 지침

기본적으로 압축은 다음 요약 프롬프트를 사용합니다:

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 매개변수를 통해 사용자 정의 지침을 제공하여 이 프롬프트를 완전히 대체할 수 있습니다. 사용자 정의 지침은 기본값을 보완하지 않으며 완전히 대체합니다:

압축 후 일시 중지

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

활성화되면 API는 압축 블록을 생성한 후 compaction 중지 이유가 있는 메시지를 반환합니다:

총 토큰 예산 적용

모델이 많은 도구 사용 반복이 있는 장기 작업을 수행할 때 총 토큰 소비가 크게 증가할 수 있습니다. pause_after_compaction을 압축 카운터와 결합하여 누적 사용량을 추정하고 예산에 도달하면 작업을 우아하게 마무리할 수 있습니다:

Python
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-7",
    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})

    # Estimate total tokens consumed; prompt wrap-up if over budget
    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 블록을 반환합니다.

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

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..."
    }
  ]
}

압축 블록 다시 전달

후속 요청에서 API에 compaction 블록을 다시 전달하여 단축된 프롬프트로 대화를 계속해야 합니다. 가장 간단한 방법은 전체 응답 콘텐츠를 메시지에 추가하는 것입니다:

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

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

스트리밍

압축이 활성화된 상태에서 응답을 스트리밍할 때 압축이 시작되면 content_block_start 이벤트를 받게 됩니다. 압축 블록은 텍스트 블록과 다르게 스트리밍됩니다. content_block_start 이벤트를 받은 후 완전한 요약 콘텐츠가 포함된 단일 content_block_delta(중간 스트리밍 없음)를 받고 content_block_stop 이벤트를 받게 됩니다.

프롬프트 캐싱

압축은 프롬프트 캐싱과 잘 작동합니다. 압축 블록에 cache_control 중단점을 추가하여 요약된 콘텐츠를 캐시할 수 있습니다. 원본 압축된 콘텐츠는 무시됩니다.

{
  "role": "assistant",
  "content": [
    {
      "type": "compaction",
      "content": "[summary text]",
      "cache_control": { "type": "ephemeral" }
    },
    {
      "type": "text",
      "text": "Based on our conversation..."
    }
  ]
}

시스템 프롬프트로 캐시 히트 최대화

압축이 발생하면 요약이 캐시에 작성해야 하는 새로운 콘텐츠가 됩니다. 추가 캐시 중단점이 없으면 캐시된 시스템 프롬프트도 무효화되어 압축 요약과 함께 다시 캐시해야 합니다.

캐시 히트율을 최대화하려면 시스템 프롬프트의 끝에 cache_control 중단점을 추가하세요. 이렇게 하면 시스템 프롬프트가 대화와 별도로 캐시되므로 압축이 발생할 때:

  • 시스템 프롬프트 캐시는 유효하게 유지되고 캐시에서 읽혀집니다
  • 압축 요약만 새로운 캐시 항목으로 작성되어야 합니다

이 접근 방식은 특히 긴 시스템 프롬프트에 유용하며, 대화 전체에서 여러 압축 이벤트에도 캐시된 상태로 유지됩니다.

사용량 이해

압축은 추가 샘플링 단계가 필요하며, 이는 속도 제한 및 청구에 기여합니다. 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_tokens 및 output_tokens는 압축되지 않은 반복이 하나뿐이므로 message 반복과 정확히 일치합니다. 최종 반복의 토큰 수는 압축 후 효과적인 컨텍스트 크기를 반영합니다.

최상위 input_tokens 및 output_tokens는 압축 반복 사용량을 포함하지 않습니다. 이들은 모든 압축되지 않은 반복의 합계를 반영합니다. 요청에 대해 소비되고 청구되는 총 토큰을 계산하려면 usage.iterations 배열의 모든 항목을 합산하세요.

이전에 비용 추적 또는 감사를 위해 usage.input_tokens 및 usage.output_tokens에 의존했다면, 압축이 활성화되었을 때 usage.iterations에서 집계하도록 추적 로직을 업데이트해야 합니다. iterations 배열은 요청 중에 새로운 압축이 트리거될 때만 채워집니다. 이전 compaction 블록을 다시 적용하면 추가 압축 비용이 발생하지 않으며, 그 경우 최상위 사용량 필드는 정확하게 유지됩니다.

다른 기능과 결합

서버 도구

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

토큰 계산

토큰 계산 엔드포인트(/v1/messages/count_tokens)는 프롬프트의 기존 compaction 블록을 적용하지만 새로운 압축을 트리거하지 않습니다. 이를 사용하여 이전 압축 후 효과적인 토큰 수를 확인하세요:

예제

다음은 압축을 사용한 장시간 실행되는 대화의 완전한 예제입니다:

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

현재 제한 사항

  • 요약을 위한 동일한 모델: 요청에 지정된 모델이 요약에 사용됩니다. 요약을 위해 다른(예: 더 저렴한) 모델을 사용할 수 있는 옵션은 없습니다.

다음 단계

세션 메모리 압축 cookbook

백그라운드 스레딩과 프롬프트 캐싱을 사용하여 장시간 실행되는 대화를 관리하는 즉시 세션 메모리 압축의 실제 구현을 살펴보세요.

컨텍스트 윈도우

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

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-7",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)

# Append the response (including any compaction block) to continue the conversation
messages.append({"role": "assistant", "content": response.content})
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-4-7",
    max_tokens=4096,
    messages=messages,
    context_management={
        "edits": [
            {
                "type": "compact_20260112",
                "trigger": {"type": "input_tokens", "value": 150000},
            }
        ]
    },
)
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-4-7",
    max_tokens=4096,
    messages=messages,
    context_management={
        "edits": [
            {
                "type": "compact_20260112",
                "instructions": "Focus on preserving code snippets, variable names, and technical decisions.",
            }
        ]
    },
)
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-4-7",
    max_tokens=4096,
    messages=messages,
    context_management={
        "edits": [{"type": "compact_20260112", "pause_after_compaction": True}]
    },
)

# Check if compaction triggered a pause
if response.stop_reason == "compaction":
    # Response contains only the compaction block
    messages.append({"role": "assistant", "content": response.content})

    # Continue the request
    response = client.beta.messages.create(
        betas=["compact-2026-01-12"],
        model="claude-opus-4-7",
        max_tokens=4096,
        messages=messages,
        context_management={"edits": [{"type": "compact_20260112"}]},
    )
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-4-7",
    max_tokens=4096,
    messages=messages,
    context_management={"edits": [{"type": "compact_20260112"}]},
)
# After receiving a response with a compaction block
messages.append({"role": "assistant", "content": response.content})

# Continue the conversation
messages.append({"role": "user", "content": "Now add error handling"})

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

with client.beta.messages.stream(
    betas=["compact-2026-01-12"],
    model="claude-opus-4-7",
    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)

    # Get the final accumulated message
    message = stream.get_final_message()
    messages.append({"role": "assistant", "content": message.content})
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Hello, Claude"}]
response = client.beta.messages.create(
    betas=["compact-2026-01-12"],
    model="claude-opus-4-7",
    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"}]},
)
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-7",
    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-7",
        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"))
# ... 필요한 만큼 계속
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-7",
        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-7",
            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"))
# ... 필요한 만큼 계속
컨텍스트 편집

도구 결과 지우기 및 생각 블록 지우기와 같은 대화 컨텍스트 관리를 위한 다른 전략을 살펴보세요.