Loading...
    • 개발자 가이드
    • API 레퍼런스
    • MCP
    • 리소스
    • 릴리스 노트
    Search...
    ⌘K
    시작하기
    Claude 소개빠른 시작
    모델 및 가격
    모델 개요모델 선택Claude 4.6의 새로운 기능마이그레이션 가이드모델 지원 중단가격
    Claude로 구축하기
    기능 개요Messages API 사용중지 사유 처리프롬프트 모범 사례
    컨텍스트 관리
    컨텍스트 윈도우압축컨텍스트 편집
    기능
    프롬프트 캐싱확장 사고적응형 사고노력 수준메시지 스트리밍배치 처리인용다국어 지원토큰 카운팅임베딩비전PDF 지원Files API검색 결과구조화된 출력
    도구
    개요도구 사용 구현 방법세분화된 도구 스트리밍Bash 도구코드 실행 도구프로그래밍 방식 도구 호출컴퓨터 사용 도구텍스트 편집기 도구웹 페치 도구웹 검색 도구메모리 도구도구 검색 도구
    Agent Skills
    개요빠른 시작모범 사례엔터프라이즈용 SkillsAPI로 Skills 사용
    Agent SDK
    개요빠른 시작TypeScript SDKTypeScript V2 (미리보기)Python SDK마이그레이션 가이드
    API에서 MCP
    MCP 커넥터원격 MCP 서버
    서드파티 플랫폼의 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    프롬프트 엔지니어링
    개요프롬프트 생성기프롬프트 템플릿 사용프롬프트 개선기명확하고 직접적으로 작성예시 사용 (멀티샷 프롬프팅)Claude에게 생각하게 하기 (CoT)XML 태그 사용Claude에게 역할 부여 (시스템 프롬프트)복잡한 프롬프트 연결긴 컨텍스트 팁확장 사고 팁
    테스트 및 평가
    성공 기준 정의테스트 케이스 개발평가 도구 사용지연 시간 줄이기
    가드레일 강화
    환각 줄이기출력 일관성 높이기탈옥 방지스트리밍 거부프롬프트 유출 줄이기Claude 캐릭터 유지
    관리 및 모니터링
    Admin API 개요데이터 상주워크스페이스사용량 및 비용 APIClaude Code Analytics API제로 데이터 보존
    Console
    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
    • Catalog
    • 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
    • Catalog
    • 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
    컨텍스트 관리

    압축(Compaction)

    컨텍스트 윈도우 한계에 근접하는 긴 대화를 관리하기 위한 서버 측 컨텍스트 압축.

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

    압축은 컨텍스트 윈도우 한계에 근접할 때 이전 컨텍스트를 자동으로 요약하여 장시간 실행되는 대화 및 작업의 유효 컨텍스트 길이를 확장합니다. 이는 다음과 같은 경우에 이상적입니다:

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

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

    지원 모델

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

    • Claude Opus 4.6 (claude-opus-4-6)

    압축 작동 방식

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

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

    후속 요청에서는 응답을 메시지에 추가하세요. 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"
                }
            ]
        }
    }'

    매개변수

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

    트리거 구성

    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을 압축 카운터와 결합하여 누적 사용량을 추정하고 예산에 도달하면 작업을 우아하게 마무리할 수 있습니다:

    Python
    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 블록을 수신하면 그 이전의 모든 콘텐츠 블록은 무시됩니다. 다음 중 하나를 선택할 수 있습니다:

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

    스트리밍

    압축이 활성화된 상태에서 응답을 스트리밍할 때 압축이 시작되면 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?