메시지 생성
텍스트 및 이미지 입력, 적응형 사고, 프롬프트 캐싱, 스트리밍(Streaming), 도구를 지원하는 CometAPI Messages 엔드포인트를 통해 Claude를 호출합니다.
POST /v1/messages로 Anthropic 메시지 형식의 Claude 요청을 전송합니다.
예제에서는 공식 Anthropic SDK를 CometAPI 기본 URL로 구성하고
$COMETAPI_KEY에서 API 키를 읽습니다.
x-api-key 또는 Authorization: Bearer로 인증합니다. Anthropic SDK는
x-api-key를 사용합니다. HTTP 예제에는 anthropic-version: 2023-06-01가 포함됩니다.빠른 시작
다음 예제는 세 개의 검색 쿼리를 요청합니다. 실행하기 전에$COMETAPI_KEY을 설정한 뒤
실행하세요. Python용으로 anthropic를, JavaScript용으로 @anthropic-ai/sdk를 설치하세요:
content 배열이 포함됩니다. type이 text인 블록을 읽으세요;
사고 및 도구 블록은 텍스트보다 앞에 나타날 수 있습니다.
적응형 사고 제어
thinking.type을 adaptive로 설정하고 output_config.effort 값을 선택하세요.
다음 예에서는 xhigh를 사용하고 스트림에서 완료된 메시지를 읽습니다:
max_tokens 출력 제한에 포함됩니다. 최종
답변과 사고를 위한 여유 공간을 남겨 두세요. 응답에는 표시되는
사고 블록 없이 텍스트가 포함될 수 있습니다. 대화
기록에서 반환된 사고 블록은 변경하지 않고 유지하세요.
모델별 사고 구성에 대한 자세한 내용은
사고에서 확인하세요..
이 예에서는 temperature, top_p, top_k을 생략합니다. 샘플링 제어를 추가하기 전에 선택한
모델의 매개변수 문서를 참조하세요.
프롬프트(Prompt) 캐시
요청 간에 재사용하는 참조 자료에 캐시 브레이크포인트를 배치하세요. 참조 자료를 UTF-8reference.txt 파일에 저장한 후 이
예제를 실행하세요. 선택한 모델의
최소 캐시 가능 길이를 충족하는 접두사를 사용하세요.:
cache_creation_input_tokens캐시에 기록된 토큰(Token) 수를 나타냅니다.cache_read_input_tokens캐시에서 읽은 토큰(Token) 수를 나타냅니다.input_tokens해당 캐시 카운터 외부에서 처리된 입력량을 나타냅니다.
cache_read_input_tokens은 캐시에서 읽은 입력 토큰(Token) 수를
보고합니다. OpenAPI 프롬프트(Prompt) 캐시
예제에는 완전한 가상의 참조 자료가 포함되어 있으며, 샘플을 사용해 보려면 이를
reference.txt 로 저장하세요.
응답 스트리밍
Server-Sent Events에stream: true를 설정합니다. SDK는 텍스트 조각을
도착하는 즉시 노출합니다:
message_start, 콘텐츠 블록 이벤트, message_delta,
및 message_stop가 포함됩니다. 콘텐츠 블록에는 텍스트, 사고 과정 또는 도구 활동이 포함될 수 있습니다.
텍스트 블록의 경우 content_block_delta에는 text_delta가 포함됩니다. 최종 사용량
과 중지 이유는 message_delta에서 확인합니다.
노력 수준 제어
추론량을 조정하려면output_config.effort을 설정합니다. 이 예제에서는
low 를 사용하여 짧은 설명을 생성하고 완료된 스트리밍 메시지를 기다립니다:
max_tokens을 별도로 설정합니다.
서버 도구 사용
서버 도구는 API 요청 중에 실행되며 결과 블록을 Claude의 답변과 함께 반환합니다.- 웹 가져오기
- 웹 검색
web_fetch_tool_result 블록을 모두 검사합니다:server_tool_use 블록과 web_fetch_tool_result를 함께 제공하며
여기에는 가져온 문서 또는 도구 오류가 포함됩니다.클라이언트 도구 결과 반환
클라이언트 도구의 경우 Claude는tool_use 블록을 반환합니다. 애플리케이션 함수를 실행하고
일치하는 tool_result 블록으로 결과를 전송합니다. tool_use_id가 일치해야 합니다.
두 요청 간에 완전한 어시스턴트 콘텐츠를 보존하세요.
이 예에서는 가상의 주문 결과를 제공하고 Claude에게 해당 결과를 사용하도록 요청합니다:
응답 예시
스트리밍되지 않는 요청은 메시지 객체를 반환합니다. 다음 예에서는 예시 메시지 식별자와 함께 해당 메시지의 텍스트 및 사용량 필드를 보여 줍니다:end_turn는 응답이 완료되었음을 의미하고,
max_tokens 출력이 제한에 도달했음을 의미하며, tool_use는 클라이언트 도구 결과를 요청합니다.
pause_turn를 반환하는 서버 도구 턴의 경우, 변경하지 않은
반환된 어시스턴트 콘텐츠로 계속 진행합니다.인증
Your CometAPI key passed via the x-api-key header. Authorization: Bearer $COMETAPI_KEY is also supported.
헤더
The Anthropic API version to use. Defaults to 2023-06-01.
"2023-06-01"
Comma-separated feature identifiers required by a specific beta API feature. Omit this header for the examples on this page.
본문
The Claude model to use. See the Models page for available Claude model IDs.
"claude-opus-5"
Conversation history. Use user and assistant messages with text strings or content-block arrays. Return complete assistant content blocks when continuing a tool call.
The maximum number of tokens to generate. The model may stop before reaching this limit. When using thinking, the thinking tokens count towards this limit.
x >= 11024
System prompt providing context and instructions to Claude. Can be a plain string or an array of content blocks (useful for prompt caching).
Sampling temperature. The examples omit sampling overrides.
0 <= x <= 1Nucleus sampling threshold. The examples omit sampling overrides.
0 <= x <= 1Limits sampling to the k most likely tokens. The examples omit sampling overrides.
x >= 0If true, stream the response incrementally using Server-Sent Events (SSE). Events include message_start, content_block_start, content_block_delta, content_block_stop, message_delta, and message_stop.
Custom strings that cause the model to stop generating when encountered. The stop sequence is not included in the response.
Thinking configuration. The adaptive example uses type adaptive and sets output_config.effort separately.
Client tools define a name and input_schema. Server tools use a versioned type and name, such as the web_fetch and web_search examples on this page.
Controls how the model uses tools.
Request metadata for tracking and analytics.
Configuration for reasoning effort and structured output.
The service tier to use. auto tries priority capacity first, standard_only uses only standard capacity.
auto, standard_only 응답
Successful response. When stream is true, the response is a stream of SSE events.
Message identifier returned by the API.
Always message.
message Always assistant.
assistant The response content blocks. May include text, thinking, tool_use, and other block types.
Model ID reported by the response.
Why the model stopped generating. refusal can be returned as a successful HTTP response when the model declines a request.
end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal The stop sequence that caused the model to stop, if applicable.
Token usage statistics.