Loading...
    • 개발자 가이드
    • API 레퍼런스
    • MCP
    • 리소스
    • 릴리스 노트
    Search...
    ⌘K
    시작하기
    Claude 소개빠른 시작
    모델 및 가격
    모델 개요모델 선택Claude 4.6의 새로운 기능마이그레이션 가이드모델 지원 중단가격
    Claude로 구축하기
    기능 개요Messages API 사용중지 사유 처리프롬프트 모범 사례
    모델 기능
    확장 사고적응형 사고노력도빠른 모드 (연구 프리뷰)구조화된 출력인용스트리밍 메시지배치 처리PDF 지원검색 결과다국어 지원임베딩비전
    도구
    개요도구 사용 구현 방법웹 검색 도구웹 페치 도구코드 실행 도구메모리 도구Bash 도구컴퓨터 사용 도구텍스트 편집기 도구
    도구 인프라
    도구 검색프로그래밍 방식 도구 호출세분화된 도구 스트리밍
    컨텍스트 관리
    컨텍스트 윈도우압축컨텍스트 편집프롬프트 캐싱토큰 카운팅
    파일 및 자산
    Files API
    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를 포함하세요.

    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.

    지원 모델

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

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

    압축 작동 방식

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

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

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

    압축 프로세스를 보여주는 흐름도: 입력 토큰이 트리거 임계값을 초과하면 Claude가 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}]
        },
    )
    
    # 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-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})
    
        # 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 블록을 반환합니다.

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

    {
      "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에 다시 전달해야 합니다. 가장 간단한 방법은 전체 응답 콘텐츠를 메시지에 추가하는 것입니다:

    # 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-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)
    
        # Get the final accumulated message
        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 중단점을 추가하세요. 이렇게 하면 시스템 프롬프트가 대화와 별도로 캐시되므로 압축이 발생할 때:

    • 시스템 프롬프트 캐시는 유효한 상태로 유지되며 캐시에서 읽힙니다
    • 압축 요약만 새 캐시 항목으로 기록하면 됩니다
    response = client.beta.messages.create(
        betas=["compact-2026-01-12"],
        model="claude-opus-4-6",
        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": 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},
                    }
                ]
            },
        )
    
        # Append response (compaction blocks are automatically included)
        messages.append({"role": "assistant", "content": response.content})
    
        # Return the text content
        return next(block.text for block in response.content if block.type == "text")
    
    
    # Run a long conversation
    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"))
    # ... continue as long as needed

    다음은 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,
                    }
                ]
            },
        )
    
        # Check if compaction occurred and paused
        if response.stop_reason == "compaction":
            # Get the compaction block from the response
            compaction_block = response.content[0]
    
            # Preserve the last 2 messages (1 user + 1 assistant turn)
            # by including them after the compaction block
            preserved_messages = messages[-2:] if len(messages) >= 2 else messages
    
            # Build new message list: compaction + preserved messages
            new_assistant_content = [compaction_block]
            messages_after_compaction = [
                {"role": "assistant", "content": new_assistant_content}
            ] + preserved_messages
    
            # Continue the request with the compacted context + 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"}]},
            )
    
            # Update our message list to reflect the compaction
            messages.clear()
            messages.extend(messages_after_compaction)
    
        # Append the final response
        messages.append({"role": "assistant", "content": response.content})
    
        # Return the text content
        return next(block.text for block in response.content if block.type == "text")
    
    
    # Run a long conversation
    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"))
    # ... continue as long as needed

    현재 제한 사항

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

    다음 단계

    압축 쿡북

    쿡북에서 실용적인 예제와 구현을 살펴보세요.

    컨텍스트 윈도우

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

    컨텍스트 편집

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

    Was this page helpful?