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
    기능

    메시지 스트리밍

    Message를 생성할 때 "stream": true를 설정하여 서버 전송 이벤트 (SSE)를 사용하여 응답을 점진적으로 스트리밍할 수 있습니다.

    SDK를 사용한 스트리밍

    Python 및 TypeScript SDK는 여러 가지 스트리밍 방법을 제공합니다. Python SDK는 동기 및 비동기 스트림을 모두 지원합니다. 자세한 내용은 각 SDK의 문서를 참조하세요.

    import anthropic
    
    client = anthropic.Anthropic()
    
    with client.messages.stream(
        max_tokens=1024,
        messages=[{"role": "user", "content": "Hello"}],
        model="claude-opus-4-6",
    ) as stream:
      for text in stream.text_stream:
          print(text, end="", flush=True)

    이벤트 처리 없이 최종 메시지 가져오기

    텍스트가 도착하는 대로 처리할 필요가 없는 경우, SDK는 내부적으로 스트리밍을 사용하면서 완전한 Message 객체를 반환하는 방법을 제공합니다 — .create()가 반환하는 것과 동일합니다. 이는 max_tokens 값이 큰 요청에서 특히 유용하며, SDK가 HTTP 타임아웃을 방지하기 위해 스트리밍을 필요로 하는 경우에 해당합니다.

    import anthropic
    
    client = anthropic.Anthropic()
    
    with client.messages.stream(
        max_tokens=128000,
        messages=[{"role": "user", "content": "Write a detailed analysis..."}],
        model="claude-opus-4-6",
    ) as stream:
        message = stream.get_final_message()
    
    print(message.content[0].text)

    .stream() 호출은 서버 전송 이벤트로 HTTP 연결을 유지한 다음, .get_final_message() (Python) 또는 .finalMessage() (TypeScript)가 모든 이벤트를 축적하여 완전한 Message 객체를 반환합니다. 이벤트 처리 코드가 필요하지 않습니다.

    이벤트 유형

    각 서버 전송 이벤트에는 명명된 이벤트 유형과 관련 JSON 데이터가 포함됩니다. 각 이벤트는 SSE 이벤트 이름(예: event: message_stop)을 사용하며, 데이터에 일치하는 이벤트 type을 포함합니다.

    각 스트림은 다음과 같은 이벤트 흐름을 사용합니다:

    1. message_start: 빈 content를 가진 Message 객체를 포함합니다.
    2. 일련의 콘텐츠 블록으로, 각각 content_block_start, 하나 이상의 content_block_delta 이벤트, 그리고 content_block_stop 이벤트를 가집니다. 각 콘텐츠 블록에는 최종 Message content 배열의 인덱스에 해당하는 index가 있습니다.
    3. 최종 Message 객체에 대한 최상위 변경 사항을 나타내는 하나 이상의 message_delta 이벤트.
    4. 최종 message_stop 이벤트.

    message_delta 이벤트의 usage 필드에 표시되는 토큰 수는 누적입니다.

    Ping 이벤트

    이벤트 스트림에는 임의의 수의 ping 이벤트가 포함될 수도 있습니다.

    오류 이벤트

    이벤트 스트림에서 오류를 가끔 전송할 수 있습니다. 예를 들어, 사용량이 많은 기간에는 overloaded_error를 받을 수 있으며, 이는 비스트리밍 컨텍스트에서 일반적으로 HTTP 529에 해당합니다:

    오류 예시
    event: error
    data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}

    기타 이벤트

    버전 관리 정책에 따라 새로운 이벤트 유형을 추가할 수 있으며, 코드는 알 수 없는 이벤트 유형을 우아하게 처리해야 합니다.

    콘텐츠 블록 델타 유형

    각 content_block_delta 이벤트에는 주어진 index의 content 블록을 업데이트하는 유형의 delta가 포함됩니다.

    텍스트 델타

    text 콘텐츠 블록 델타는 다음과 같습니다:

    텍스트 델타
    event: content_block_delta
    data: {"type": "content_block_delta","index": 0,"delta": {"type": "text_delta", "text": "ello frien"}}

    입력 JSON 델타

    tool_use 콘텐츠 블록의 델타는 블록의 input 필드에 대한 업데이트에 해당합니다. 최대 세분성을 지원하기 위해 델타는 _부분 JSON 문자열_이며, 최종 tool_use.input은 항상 _객체_입니다.

    문자열 델타를 축적하고 content_block_stop 이벤트를 받으면 JSON을 파싱할 수 있습니다. Pydantic과 같은 라이브러리를 사용하여 부분 JSON 파싱을 수행하거나, 파싱된 증분 값에 접근하는 헬퍼를 제공하는 SDK를 사용할 수 있습니다.

    tool_use 콘텐츠 블록 델타는 다음과 같습니다:

    입력 JSON 델타
    event: content_block_delta
    data: {"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}

    참고: 현재 모델은 input에서 한 번에 하나의 완전한 키와 값 속성만 출력하는 것을 지원합니다. 따라서 도구를 사용할 때 모델이 작업하는 동안 스트리밍 이벤트 사이에 지연이 있을 수 있습니다. input 키와 값이 축적되면 청크된 부분 JSON으로 여러 content_block_delta 이벤트로 출력하여 향후 모델에서 더 세밀한 세분성을 자동으로 지원할 수 있는 형식을 제공합니다.

    사고 델타

    스트리밍이 활성화된 상태에서 확장된 사고를 사용할 때, thinking_delta 이벤트를 통해 사고 콘텐츠를 받게 됩니다. 이러한 델타는 thinking 콘텐츠 블록의 thinking 필드에 해당합니다.

    사고 콘텐츠의 경우, content_block_stop 이벤트 직전에 특별한 signature_delta 이벤트가 전송됩니다. 이 서명은 사고 블록의 무결성을 검증하는 데 사용됩니다.

    일반적인 사고 델타는 다음과 같습니다:

    사고 델타
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I need to find the GCD of 1071 and 462 using the Euclidean algorithm.\n\n1071 = 2 × 462 + 147"}}

    서명 델타는 다음과 같습니다:

    서명 델타
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."}}

    전체 HTTP 스트림 응답

    스트리밍 모드를 사용할 때는 클라이언트 SDK를 사용하는 것을 강력히 권장합니다. 그러나 직접 API 통합을 구축하는 경우 이러한 이벤트를 직접 처리해야 합니다.

    스트림 응답은 다음으로 구성됩니다:

    1. message_start 이벤트
    2. 잠재적으로 여러 콘텐츠 블록, 각각 다음을 포함:
      • content_block_start 이벤트
      • 잠재적으로 여러 content_block_delta 이벤트
      • content_block_stop 이벤트
    3. message_delta 이벤트
    4. message_stop 이벤트

    응답 전체에 ping 이벤트가 분산되어 있을 수도 있습니다. 형식에 대한 자세한 내용은 이벤트 유형을 참조하세요.

    기본 스트리밍 요청

    curl https://api.anthropic.com/v1/messages \
         --header "anthropic-version: 2023-06-01" \
         --header "content-type: application/json" \
         --header "x-api-key: $ANTHROPIC_API_KEY" \
         --data \
    '{
      "model": "claude-opus-4-6",
      "messages": [{"role": "user", "content": "Hello"}],
      "max_tokens": 256,
      "stream": true
    }'
    Response
    event: message_start
    data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-6", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}
    
    event: content_block_start
    data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
    
    event: ping
    data: {"type": "ping"}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}
    
    event: content_block_stop
    data: {"type": "content_block_stop", "index": 0}
    
    event: message_delta
    data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}
    
    event: message_stop
    data: {"type": "message_stop"}
    

    도구 사용이 포함된 스트리밍 요청

    도구 사용은 매개변수 값에 대한 세밀한 스트리밍을 지원합니다. eager_input_streaming으로 도구별로 활성화하세요.

    이 요청에서는 Claude에게 도구를 사용하여 날씨를 알려달라고 요청합니다.

      curl https://api.anthropic.com/v1/messages \
        -H "content-type: application/json" \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2023-06-01" \
        -d '{
          "model": "claude-opus-4-6",
          "max_tokens": 1024,
          "tools": [
            {
              "name": "get_weather",
              "description": "Get the current weather in a given location",
              "input_schema": {
                "type": "object",
                "properties": {
                  "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                  }
                },
                "required": ["location"]
              }
            }
          ],
          "tool_choice": {"type": "any"},
          "messages": [
            {
              "role": "user",
              "content": "What is the weather like in San Francisco?"
            }
          ],
          "stream": true
        }'
    Response
    event: message_start
    data: {"type":"message_start","message":{"id":"msg_014p7gG3wDgGV9EUtLvnow3U","type":"message","role":"assistant","model":"claude-opus-4-6","stop_sequence":null,"usage":{"input_tokens":472,"output_tokens":2},"content":[],"stop_reason":null}}
    
    event: content_block_start
    data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
    
    event: ping
    data: {"type": "ping"}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Okay"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":","}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" let"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'s"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" check"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" the"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" weather"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" for"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" San"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" Francisco"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":","}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" CA"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":":"}}
    
    event: content_block_stop
    data: {"type":"content_block_stop","index":0}
    
    event: content_block_start
    data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01T1x1fJ34qAmk2tNTrN7Up6","name":"get_weather","input":{}}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":""}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"location\":"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" \"San"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" Francisc"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"o,"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" CA\""}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":", "}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"\"unit\": \"fah"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"renheit\"}"}}
    
    event: content_block_stop
    data: {"type":"content_block_stop","index":1}
    
    event: message_delta
    data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":89}}
    
    event: message_stop
    data: {"type":"message_stop"}

    확장된 사고가 포함된 스트리밍 요청

    이 요청에서는 스트리밍과 함께 확장된 사고를 활성화하여 Claude의 단계별 추론을 확인합니다.

    curl https://api.anthropic.com/v1/messages \
         --header "x-api-key: $ANTHROPIC_API_KEY" \
         --header "anthropic-version: 2023-06-01" \
         --header "content-type: application/json" \
         --data \
    '{
        "model": "claude-opus-4-6",
        "max_tokens": 20000,
        "stream": true,
        "thinking": {
            "type": "enabled",
            "budget_tokens": 16000
        },
        "messages": [
            {
                "role": "user",
                "content": "What is the greatest common divisor of 1071 and 462?"
            }
        ]
    }'
    Response
    event: message_start
    data: {"type": "message_start", "message": {"id": "msg_01...", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-6", "stop_reason": null, "stop_sequence": null}}
    
    event: content_block_start
    data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I need to find the GCD of 1071 and 462 using the Euclidean algorithm.\n\n1071 = 2 × 462 + 147"}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\n462 = 3 × 147 + 21"}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\n147 = 7 × 21 + 0"}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\nThe remainder is 0, so GCD(1071, 462) = 21."}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."}}
    
    event: content_block_stop
    data: {"type": "content_block_stop", "index": 0}
    
    event: content_block_start
    data: {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}
    
    event: content_block_delta
    data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "The greatest common divisor of 1071 and 462 is **21**."}}
    
    event: content_block_stop
    data: {"type": "content_block_stop", "index": 1}
    
    event: message_delta
    data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}}
    
    event: message_stop
    data: {"type": "message_stop"}

    웹 검색 도구 사용이 포함된 스트리밍 요청

    이 요청에서는 Claude에게 현재 날씨 정보를 웹에서 검색하도록 요청합니다.

    curl https://api.anthropic.com/v1/messages \
         --header "x-api-key: $ANTHROPIC_API_KEY" \
         --header "anthropic-version: 2023-06-01" \
         --header "content-type: application/json" \
         --data \
    '{
        "model": "claude-opus-4-6",
        "max_tokens": 1024,
        "stream": true,
        "tools": [
            {
                "type": "web_search_20250305",
                "name": "web_search",
                "max_uses": 5
            }
        ],
        "messages": [
            {
                "role": "user",
                "content": "What is the weather like in New York City today?"
            }
        ]
    }'
    Response
    event: message_start
    data: {"type":"message_start","message":{"id":"msg_01G...","type":"message","role":"assistant","model":"claude-opus-4-6","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2679,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":3}}}
    
    event: content_block_start
    data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"I'll check"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" the current weather in New York City for you"}}
    
    event: ping
    data: {"type": "ping"}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"."}}
    
    event: content_block_stop
    data: {"type":"content_block_stop","index":0}
    
    event: content_block_start
    data: {"type":"content_block_start","index":1,"content_block":{"type":"server_tool_use","id":"srvtoolu_014hJH82Qum7Td6UV8gDXThB","name":"web_search","input":{}}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":""}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"query"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"\":"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" \"weather"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" NY"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"C to"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"day\"}"}}
    
    event: content_block_stop
    data: {"type":"content_block_stop","index":1 }
    
    event: content_block_start
    data: {"type":"content_block_start","index":2,"content_block":{"type":"web_search_tool_result","tool_use_id":"srvtoolu_014hJH82Qum7Td6UV8gDXThB","content":[{"type":"web_search_result","title":"Weather in New York City in May 2025 (New York) - detailed Weather Forecast for a month","url":"https://world-weather.info/forecast/usa/new_york/may-2025/","encrypted_content":"Ev0DCioIAxgCIiQ3NmU4ZmI4OC1k...","page_age":null},...]}}
    
    event: content_block_stop
    data: {"type":"content_block_stop","index":2}
    
    event: content_block_start
    data: {"type":"content_block_start","index":3,"content_block":{"type":"text","text":""}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":"Here's the current weather information for New York"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":" City:\n\n# Weather"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":" in New York City"}}
    
    event: content_block_delta
    data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":"\n\n"}}
    
    ...
    
    event: content_block_stop
    data: {"type":"content_block_stop","index":17}
    
    event: message_delta
    data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":10682,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":510,"server_tool_use":{"web_search_requests":1}}}
    
    event: message_stop
    data: {"type":"message_stop"}

    오류 복구

    네트워크 문제, 타임아웃 또는 기타 오류로 인해 스트리밍 요청이 중단된 경우, 스트림이 중단된 지점부터 재개하여 복구할 수 있습니다. 이 접근 방식은 전체 응답을 다시 처리하지 않아도 됩니다.

    기본 복구 전략은 다음과 같습니다:

    1. 부분 응답 캡처: 오류가 발생하기 전에 성공적으로 수신된 모든 콘텐츠를 저장합니다
    2. 연속 요청 구성: 부분 어시스턴트 응답을 새 어시스턴트 메시지의 시작 부분으로 포함하는 새 API 요청을 생성합니다
    3. 스트리밍 재개: 중단된 지점부터 나머지 응답을 계속 수신합니다

    오류 복구 모범 사례

    1. SDK 기능 사용: SDK의 내장 메시지 축적 및 오류 처리 기능을 활용하세요
    2. 콘텐츠 유형 처리: 메시지에는 여러 콘텐츠 블록(text, tool_use, thinking)이 포함될 수 있다는 점에 유의하세요. 도구 사용 및 확장된 사고 블록은 부분적으로 복구할 수 없습니다. 가장 최근의 텍스트 블록에서 스트리밍을 재개할 수 있습니다.

    Was this page helpful?

    • SDK를 사용한 스트리밍
    • Ping 이벤트
    • 입력 JSON 델타
    • 전체 HTTP 스트림 응답