Anthropic 채팅 형식 (Messages)¶
📝 소개¶
텍스트 및/또는 이미지 콘텐츠를 포함한 구조화된 입력 메시지 목록을 전달하면, 모델이 다음 대화 메시지를 생성합니다. Messages API는 단일 요청과 상태를 유지하지 않는 다중 턴 대화 모두에 사용할 수 있습니다.
🤖 지원 모델¶
현재 지원되는 모델:
| 모델 | 설명 |
|---|---|
| claude-opus-4-6 | Claude Opus 4.6 chat model |
| claude-opus-4-5 | Claude Opus 4.5 chat model |
| claude-sonnet-4-6 | Claude Sonnet 4.6 chat model |
| claude-sonnet-4-5 | Claude Sonnet 4.5 chat model |
| claude-haiku-4-5 | Claude Haiku 4.5 chat model |
💡 요청 예시¶
기본 텍스트 대화 ✅¶
curl https://ssanai-workspace.atto-lab.cc/v1/messages \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $API_KEY" \
--data \
'{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, world"}
]
}'
응답 예시:
{
"content": [
{
"text": "Hi! My name is Claude.",
"type": "text"
}
],
"id": "msg_013Zva2CMHLNnXjNJKqJ2EF",
"model": "claude-opus-4-6",
"role": "assistant",
"stop_reason": "end_turn",
"stop_sequence": null,
"type": "message",
"usage": {
"input_tokens": 2095,
"output_tokens": 503
}
}
이미지 분석 대화 ✅¶
curl https://ssanai-workspace.atto-lab.cc/v1/messages \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $API_KEY" \
--data \
'{
"model": "claude-opus-4-6",
"messages": [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}
},
{
"type": "text",
"text": "What's in this image?"
}
]
}
]
}'
응답 예시:
{
"content": [
{
"text": "This image shows an orange cat sunbathing on a windowsill. The cat looks very relaxed, squinting its eyes while enjoying the sunlight. Some green plants can be seen outside the window.",
"type": "text"
}
],
"id": "msg_013Zva2CMHLNnXjNJKqJ2EF",
"model": "claude-opus-4-6",
"role": "assistant",
"stop_reason": "end_turn",
"stop_sequence": null,
"type": "message",
"usage": {
"input_tokens": 3050,
"output_tokens": 892
}
}
도구 호출 ✅¶
curl https://ssanai-workspace.atto-lab.cc/v1/messages \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $API_KEY" \
--data \
'{
"model": "claude-opus-4-6",
"messages": [
{
"role": "user",
"content": "What's the weather like in Beijing today?"
}
],
"tools": [
{
"name": "get_weather",
"description": "Get the current weather for a specified location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g.: Beijing"
}
},
"required": ["location"]
}
}
]
}'
응답 예시:
{
"content": [
{
"type": "tool_use",
"id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"name": "get_weather",
"input": { "location": "Beijing" }
}
],
"id": "msg_013Zva2CMHLNnXjNJKqJ2EF",
"model": "claude-opus-4-6",
"role": "assistant",
"stop_reason": "tool_use",
"stop_sequence": null,
"type": "message",
"usage": {
"input_tokens": 2156,
"output_tokens": 468
}
}
스트리밍 응답 ✅¶
curl https://ssanai-workspace.atto-lab.cc/v1/messages \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $API_KEY" \
--data \
'{
"model": "claude-opus-4-6",
"messages": [
{
"role": "user",
"content": "Tell me a story"
}
],
"stream": true
}'
응답 예시:
{
"type": "message_start",
"message": {
"id": "msg_013Zva2CMHLNnXjNJKqJ2EF",
"model": "claude-opus-4-6",
"role": "assistant",
"type": "message"
}
}
{
"type": "content_block_start",
"index": 0,
"content_block": {
"type": "text"
}
}
{
"type": "content_block_delta",
"index": 0,
"delta": {
"text": "옛날 옛적에"
}
}
{
"type": "content_block_delta",
"index": 0,
"delta": {
"text": "한 마리의"
}
}
{
"type": "content_block_delta",
"index": 0,
"delta": {
"text": "작은 토끼가..."
}
}
{
"type": "content_block_stop",
"index": 0
}
{
"type": "message_delta",
"delta": {
"stop_reason": "end_turn",
"usage": {
"input_tokens": 2045,
"output_tokens": 628
}
}
}
{
"type": "message_stop"
}
📮 요청¶
엔드포인트¶
인증 방법¶
요청 헤더에 다음 값을 포함하여 API 키 인증을 수행하세요:
$API_KEY는 발급받은 API 키입니다. API 키는 콘솔에서 발급할 수 있으며, 각 키는 하나의 워크스페이스에 연결됩니다.
요청 헤더¶
anthropic-beta¶
- 유형: String
- 필수: No
사용할 베타 버전을 지정합니다. beta1,beta2처럼 쉼표로 구분해 여러 값을 전달하거나, 동일 헤더를 여러 번 지정할 수 있습니다.
anthropic-version¶
- 유형: String
- 필수: Yes
사용할 API 버전을 지정합니다.
요청 본문 파라미터¶
max_tokens¶
- 유형: Integer
- 필수: Yes
생성할 최대 토큰 수입니다. 모델별 제한이 다르므로 모델 문서를 참고하세요. 범위는 x > 1입니다.
messages¶
- 유형: Array of objects
- 필수: Yes
입력 메시지 목록입니다. 모델은 사용자와 어시스턴트가 번갈아 대화하는 형태로 학습되었습니다. 새 메시지를 생성할 때 messages에 이전 대화 턴을 포함하면, 모델이 다음 메시지를 생성합니다. 연속된 사용자 메시지 또는 어시스턴트 메시지는 하나의 턴으로 병합됩니다.
각 메시지는 role과 content 필드를 포함해야 합니다. 단일 사용자 메시지만 보낼 수도 있고, 사용자/어시스턴트 메시지를 여러 턴으로 함께 보낼 수도 있습니다. 마지막 메시지가 어시스턴트 역할이면, 응답은 해당 메시지의 내용에서 이어서 생성되므로 출력 형식을 제어하는 데 활용할 수 있습니다.
단일 사용자 메시지 예시:
다중 턴 대화 예시:
[
{"role": "user", "content": "안녕하세요."},
{"role": "assistant", "content": "안녕하세요! 저는 Claude입니다. 무엇을 도와드릴까요?"},
{"role": "user", "content": "LLM이 무엇인지 쉽게 설명해 주세요."}
]
부분 채움 응답 예시:
[
{"role": "user", "content": "태양의 그리스어 이름은 무엇인가요? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "정답은 ("}
]
각 메시지의 content는 문자열 또는 콘텐츠 블록 배열이 될 수 있습니다. 문자열은 "text" 타입 콘텐츠 블록 배열의 축약형과 동일합니다. 아래 두 표현은 같은 의미입니다:
Claude 3 모델부터는 이미지 콘텐츠 블록도 함께 보낼 수 있습니다:
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}
},
{
"type": "text",
"text": "What's in this image?"
}
]
}
현재 지원 이미지 형식: base64, image/jpeg, image/png, image/gif, image/webp
messages.role¶
- 유형: String
- 필수: Yes
- Optional Values: user, assistant
참고: Messages API에는 "system" 역할이 없습니다. 시스템 프롬프트가 필요하면 최상위 system 파라미터를 사용하세요.
messages.content¶
- 유형: String or Array of objects
- 필수: Yes
메시지의 콘텐츠는 다음 타입 중 하나를 사용할 수 있습니다:
텍스트 콘텐츠 (Text)¶
{
"type": "text", // Required, enum value: "text"
"text": "Hello, Claude", // Required, minimum length: 1
"cache_control": {
"type": "ephemeral" // Optional, enum value: "ephemeral"
}
}
이미지 콘텐츠 (Image)¶
{
"type": "image", // Required, enum value: "image"
"source": { // Required
"type": "base64", // Required, enum value: "base64"
"media_type": "image/jpeg", // Required, supported: image/jpeg, image/png, image/gif, image/webp
"data": "/9j/4AAQSkZJRg..." // Required, base64 encoded image data
},
"cache_control": {
"type": "ephemeral" // Optional, enum value: "ephemeral"
}
}
도구 사용 (Tool Use)¶
{
"type": "tool_use", // Required, enum value: "tool_use", default value
"id": "toolu_xyz...", // Required, unique identifier for tool use
"name": "get_weather", // Required, tool name, minimum length: 1
"input": { // Required, object containing tool input parameters
// Tool input parameters, specific format defined by tool's input_schema
},
"cache_control": {
"type": "ephemeral" // Optional, enum value: "ephemeral"
}
}
도구 결과 (Tool Result)¶
{
"type": "tool_result", // Required, enum value: "tool_result"
"tool_use_id": "toolu_xyz...", // Required
"content": "Result content", // Required, can be string or array of content blocks
"is_error": false, // Optional, boolean
"cache_control": {
"type": "ephemeral" // Optional, enum value: "ephemeral"
}
}
content가 콘텐츠 블록 배열인 경우, 각 블록은 텍스트 또는 이미지가 될 수 있습니다:
{
"type": "tool_result",
"tool_use_id": "toolu_xyz...",
"content": [
{
"type": "text", // Required, enum value: "text"
"text": "Analysis result", // Required, minimum length: 1
"cache_control": {
"type": "ephemeral" // Optional, enum value: "ephemeral"
}
},
{
"type": "image", // Required, enum value: "image"
"source": { // Required
"type": "base64", // Required, enum value: "base64"
"media_type": "image/jpeg",
"data": "..."
},
"cache_control": {
"type": "ephemeral"
}
}
]
}
문서 (Document)¶
{
"type": "document", // Required, enum value: "document"
"source": { // Required
// Document source data
},
"cache_control": {
"type": "ephemeral" // Optional, enum value: "ephemeral"
}
}
참고:
1. 각 타입에는 콘텐츠 캐시 제어를 위한 cache_control 필드를 선택적으로 포함할 수 있습니다.
2. 텍스트 콘텐츠의 최소 길이는 1입니다.
3. 모든 type 필드는 필수 enum 문자열입니다.
4. 도구 결과의 content는 문자열 또는 텍스트/이미지 콘텐츠 블록 배열을 지원합니다.
model¶
- 유형: String
- 필수: Yes
사용할 모델 이름입니다. 자세한 내용은 모델 문서를 참고하세요. 길이 범위는 1 - 256자입니다.
metadata¶
- 유형: Object
- 필수: No
요청 메타데이터를 설명하는 객체입니다. 다음 선택 필드를 포함할 수 있습니다:
user_id: 요청과 연결된 사용자의 외부 식별자입니다. uuid, 해시, 기타 난독화 식별자를 사용하세요. 이름/이메일/전화번호 같은 개인정보는 포함하지 마세요. 최대 길이: 256
stop_sequences¶
- 유형: Array of strings
- 필수: No
생성을 중단할 사용자 지정 문자열 시퀀스입니다.
stream¶
- 유형: Boolean
- 필수: No
서버 전송 이벤트(SSE)로 응답 콘텐츠를 점진적으로 반환할지 여부입니다.
system¶
- 유형: String
- 필수: No
Claude에 배경 정보와 지침을 제공하는 시스템 프롬프트입니다. 모델에 컨텍스트와 구체적인 목표/역할을 전달할 때 사용합니다. 이는 messages의 role과 다르며, Messages API 자체에는 "system" 역할이 없습니다.
temperature¶
- 유형: Number
- 필수: No
- 기본값: 1.0
생성의 무작위성을 제어합니다(0.0 - 1.0). 범위는 0 < x < 1입니다. 분석/객관식 작업은 0.0에 가깝게, 창의/생성 작업은 1.0에 가깝게 설정하는 것을 권장합니다.
참고: temperature를 0.0으로 설정해도 결과가 완전히 결정적이지는 않습니다.
🆕 thinking¶
- 유형: Object
- 필수: No
Claude의 확장 추론(thinking) 기능을 설정합니다. 활성화하면 최종 답변 전 추론 과정을 보여주는 콘텐츠 블록이 응답에 포함됩니다. 최소 1,024 토큰 예산이 필요하며 max_tokens 한도에 포함되어 계산됩니다.
다음 두 가지 모드 중 하나로 설정할 수 있습니다:
1. 활성화 모드¶
type: 필수, enum 값"enabled"budget_tokens: 필수, 정수. Claude가 내부 추론에 사용할 토큰 수를 지정합니다. 예산이 클수록 복잡한 질문에서 더 깊은 분석이 가능해져 응답 품질이 향상됩니다.>= 1024이고max_tokens보다 작아야 합니다. 범위x > 1024
2. 비활성화 모드¶
type: 필수, enum 값"disabled"
tool_choice¶
- 유형: Object
- 필수: No
모델이 제공된 도구를 사용하는 방식을 제어합니다. 다음 3가지 타입 중 하나를 사용합니다:
1. Auto 모드 (자동 선택)¶
{
"type": "auto", // Required, enum value: "auto"
"disable_parallel_tool_use": false // Optional, default false. If true, the model will only use one tool at most
}
2. Any 모드 (임의 도구)¶
{
"type": "any", // Required, enum value: "any"
"disable_parallel_tool_use": false // Optional, default false. If true, the model will exactly use one tool
}
3. Tool 모드 (특정 도구)¶
{
"type": "tool", // Required, enum value: "tool"
"name": "get_weather", // Required, specify the tool name to use
"disable_parallel_tool_use": false // Optional, default false. If true, the model will exactly use one tool
}
참고: 1. Auto 모드: 모델이 도구 사용 여부를 스스로 결정 2. Any 모드: 모델이 반드시 도구를 사용하되, 사용 도구는 선택 가능 3. Tool 모드: 모델이 지정된 도구를 반드시 사용
tools¶
- 유형: Array of objects
- 필수: No
모델이 사용할 수 있는 도구를 정의합니다. 도구는 사용자 정의 도구 또는 내장 도구 타입을 사용할 수 있습니다:
1. 사용자 정의 도구 (Tool)¶
각 사용자 정의 도구 정의에는 다음이 포함됩니다:
type: Optional, enum value: "custom"name: Tool name, required, 1-64 charactersdescription: Tool description, recommended to be as detailed as possibleinput_schema: JSON Schema definition for tool input, requiredcache_control: Cache control, optional, type is "ephemeral"
예시:
[
{
"type": "custom",
"name": "get_weather",
"description": "Get the current weather for a specified location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g.: Beijing"
}
},
"required": ["location"]
}
}
]
2. 컴퓨터 도구 (ComputerUseTool)¶
{
"type": "computer_20241022", // Required
"name": "computer", // Required, enum value: "computer"
"display_width_px": 1024, // Required, display width (pixels)
"display_height_px": 768, // Required, display height (pixels)
"display_number": 0, // Optional, X11 display number
"cache_control": {
"type": "ephemeral" // Optional
}
}
3. Bash 도구 (BashTool)¶
{
"type": "bash_20241022", // Required
"name": "bash", // Required, enum value: "bash"
"cache_control": {
"type": "ephemeral" // Optional
}
}
4. 텍스트 편집기 도구 (TextEditor)¶
{
"type": "text_editor_20241022", // Required
"name": "str_replace_editor", // Required, enum value: "str_replace_editor"
"cache_control": {
"type": "ephemeral" // Optional
}
}
모델이 도구를 사용하면 tool_use 콘텐츠 블록을 반환합니다:
[
{
"type": "tool_use",
"id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"name": "get_weather",
"input": { "location": "Beijing" }
}
]
도구 실행 결과는 tool_result 콘텐츠 블록으로 반환할 수 있습니다:
[
{
"type": "tool_result",
"tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV",
"content": "The weather in Beijing today is sunny, with a temperature of 25°C"
}
]
top_k¶
- 유형: Integer
- 필수: No
- Range: x > 0
상위 K개 토큰 후보에서 샘플링합니다. 확률이 낮은 "롱테일" 응답을 줄이는 데 사용됩니다. 일반적으로는 temperature 조정만으로 충분하며, 고급 사용 사례에서만 사용하는 것을 권장합니다.
top_p¶
- 유형: Number
- 필수: No
- Range: 0 < x < 1
누클리어스 샘플링을 사용합니다. 다음 토큰 확률을 내림차순으로 누적해 top_p에 도달할 때 후보를 잘라냅니다. temperature와 top_p는 동시에 조정하지 않고 하나만 조정하는 것을 권장합니다.
📥 응답¶
성공 응답¶
채팅 완료 객체를 반환하며, 다음 필드를 포함합니다:
content¶
- 유형: Array of objects
- 필수: Yes
모델이 생성한 콘텐츠입니다. 여러 콘텐츠 블록으로 구성되며, 각 블록은 타입에 따라 구조가 달라집니다. 가능한 타입은 다음과 같습니다:
텍스트 콘텐츠 블록 (Text)¶
{
"type": "text", // Required, enum value: "text", default value
"text": "안녕하세요, 저는 Claude입니다." // Required, maximum length: 5000000, minimum length: 1
}
도구 사용 콘텐츠 블록 (Tool Use)¶
{
"type": "tool_use", // Required, enum value: "tool_use", default value
"id": "toolu_xyz...", // Required, unique identifier for tool use
"name": "get_weather", // Required, tool name, minimum length: 1
"input": { // Required, object containing tool input parameters
// Tool input parameters, specific format defined by tool's input_schema
}
}
예시:
// Text content example
[{"type": "text", "text": "안녕하세요, 저는 Claude입니다."}]
// Tool use example
[{
"type": "tool_use",
"id": "toolu_xyz...",
"name": "get_weather",
"input": { "location": "Beijing" }
}]
// Mixed content example
[
{"type": "text", "text": "날씨 조회 결과에 따르면:"},
{
"type": "tool_use",
"id": "toolu_xyz...",
"name": "get_weather",
"input": { "location": "Beijing" }
}
]
요청의 마지막 메시지가 어시스턴트 역할이면, 응답은 해당 메시지에서 이어서 생성됩니다. 예:
// Request
[
{"role": "user", "content": "태양의 그리스어 이름은 무엇인가요? (A) Sol (B) Helios (C) Sun"},
{"role": "assistant", "content": "정답은 ("}
]
// Response
[{"type": "text", "text": "B)"}]
id¶
- 유형: String
- 필수: Yes
응답의 고유 식별자입니다.
model¶
- 유형: String
- 필수: Yes
사용된 모델 이름입니다.
role¶
- 유형: String
- 필수: Yes
- 기본값: assistant
생성된 메시지의 역할이며 항상 "assistant"입니다.
stop_reason¶
- 유형: String or null
- 필수: Yes
생성이 중단된 이유입니다. 가능한 값은 다음과 같습니다:
"end_turn": Model reached a natural stopping point"max_tokens": Exceeded requested max_tokens or model's maximum limit"stop_sequence": Generated one of the custom stop sequences"tool_use": Model called one or more tools
이 값은 비스트리밍 모드에서 항상 비어 있지 않습니다. 스트리밍 모드에서는 message_start 이벤트에서 null이며, 그 이후에는 null이 아닙니다.
stop_sequence¶
- 유형: String or null
- 필수: Yes
생성 중 감지된 사용자 지정 중지 시퀀스입니다. stop_sequences에 지정된 값이 실제로 감지되면 해당 값이 반환되며, 그렇지 않으면 null입니다.
type¶
- 유형: String
- 필수: Yes
- 기본값: message
- Optional: message
객체 타입입니다. Messages API에서는 항상 "message"입니다.
usage¶
- 유형: Object
- 필수: Yes
과금 및 레이트 리밋 관련 사용량 통계입니다. 다음 필드를 포함합니다:
input_tokens: Number of input tokens used, required, range x > 0output_tokens: Number of output tokens used, required, range x > 0cache_creation_input_tokens: Number of input tokens used to create cache entries (if applicable), required, range x > 0cache_read_input_tokens: Number of input tokens read from cache (if applicable), required, range x > 0
참고: API 내부 변환 및 파싱 과정 때문에 토큰 수가 요청/응답의 가시 텍스트와 정확히 일치하지 않을 수 있습니다. 예를 들어 빈 문자열 응답도 output_tokens가 0이 아닐 수 있습니다.
오류 응답¶
요청 처리 중 문제가 발생하면 API는 4XX-5XX 범위의 HTTP 상태 코드와 함께 오류 응답 객체를 반환합니다.
주요 오류 상태 코드¶
401 Unauthorized: Invalid API key or not provided400 Bad Request: Invalid request parameters429 Too Many Requests: Exceeded API call limit500 Internal Server Error: Server internal error
오류 응답 예시:
{
"error": {
"type": "invalid_request_error",
"message": "Invalid API key provided",
"code": "invalid_api_key"
}
}
주요 오류 타입:
invalid_request_error: 요청 파라미터 오류authentication_error: 인증 관련 오류rate_limit_error: 요청 한도 초과server_error: 서버 내부 오류