Claude를 위한 API 사용 입문서
이 가이드는 Claude에게 Claude API 사용의 기본 사항을 제공하기 위해 작성되었습니다. 모델 ID/기본 Messages API, 도구 사용, 스트리밍, 사고에 대한 설명과 예시를 제공하며, 그 외의 내용은 다루지 않습니다.
Claude를 위한 API 사용 입문서
이 가이드는 Claude에게 Claude API 사용의 기본 사항을 제공하기 위해 작성되었습니다. 모델 ID/기본 Messages API, 도구 사용, 스트리밍, 사고에 대한 설명과 예시를 제공하며, 그 외의 내용은 다루지 않습니다.
모델
Recommended default for most work, including complex agentic coding: Claude Opus 5: claude-opus-5
Step up for the hardest long-running agentic and research tasks, at 2x Claude Opus 5 pricing: Claude Fable 5.1: claude-fable-5-1
Previous Opus model: Claude Opus 4.8: claude-opus-4-8
Smart model: Claude Sonnet 5: claude-sonnet-5
For fast, cost-effective tasks: Claude Haiku 4.5: claude-haiku-4-5-20251001API 호출하기
기본 요청 및 응답
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message){
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello!"
}
],
"model": "claude-opus-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}여러 대화 턴
Messages API는 상태를 저장하지 않으므로(stateless), 항상 전체 대화 기록을 API에 전송해야 합니다. 이 패턴을 사용하여 시간이 지남에 따라 대화를 쌓아 나갈 수 있습니다. 이전 대화 턴이 반드시 실제로 Claude로부터 생성된 것일 필요는 없습니다. 합성된 assistant 메시지를 사용할 수 있습니다.
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"},
],
)
print(message)Claude의 응답 미리 채우기
입력 메시지 목록의 마지막 위치에 Claude 응답의 일부를 미리 채울(prefill) 수 있습니다. 이 기법을 사용하여 Claude의 응답을 원하는 형태로 유도할 수 있습니다. 다음 예시는 "max_tokens": 1을 사용하여 Claude로부터 단일 객관식 답변을 얻습니다.
import anthropic
message = anthropic.Anthropic().messages.create(
model="claude-sonnet-4-5",
max_tokens=1,
messages=[
{
"role": "user",
"content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
},
{"role": "assistant", "content": "The answer is ("},
],
)
print(message.content[0].text)비전
Claude는 요청에서 텍스트와 이미지를 모두 읽을 수 있습니다. 이미지에는 base64와 url 소스 유형이 모두 지원되며, image/jpeg, image/png, image/gif, image/webp 미디어 유형이 지원됩니다.
import anthropic
import base64
import httpx2
# 옵션 1: Base64로 인코딩된 이미지
image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")
message = anthropic.Anthropic().messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(next(block.text for block in message.content if block.type == "text"))
# 옵션 2: URL로 참조된 이미지
message_from_url = anthropic.Anthropic().messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://platform.claude.com/docs/images/vision-example.jpg",
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(next(block.text for block in message_from_url.content if block.type == "text"))사고
사고(thinking)는 때때로 매우 어려운 작업에서 Claude에게 도움이 될 수 있습니다. 현재 메커니즘은 adaptive thinking(적응형 사고)입니다(thinking: {"type": "adaptive"}). Claude가 언제 얼마나 사고할지 결정하며, 토큰 예산 대신 effort 매개변수로 사고 깊이를 조절합니다. 적응형 사고는 Claude 4.6 이상 모델과 Claude Mythos Preview에서 지원됩니다. Claude 5 모델과 Claude Mythos Preview에서는 thinking 매개변수를 생략하면 사고가 기본적으로 켜져 있습니다.
모든 모델에서 사고가 활성화된 경우 temperature는 1로 설정하거나 설정하지 않은 상태로 두어야 합니다. Claude 4.7 이상 모델과 Claude Mythos Preview에서는 temperature가 지원 중단되었으며, 사고가 꺼져 있는 경우에도 기본값만 허용됩니다.
사고는 다음 모델에서 지원됩니다:
- Claude Opus 5 (, 적응형 사고만 지원, 기본적으로 켜짐)
- Claude Sonnet 5 (
claude-sonnet-5, 적응형 사고만 지원, 기본적으로 켜짐) - Claude Opus 4.8 (, 적응형 사고만 지원)
- Claude Opus 4.7 (
claude-opus-4-7, 적응형 사고만 지원) - Claude Opus 4.6 (
claude-opus-4-6, 적응형 또는 레거시 수동 사고) - Claude Sonnet 4.6 (
claude-sonnet-4-6, 적응형 또는 레거시 수동 사고) - Claude Opus 4.5 (
claude-opus-4-5-20251101, 레거시 수동 사고만 지원) - Claude Sonnet 4.5 (
claude-sonnet-4-5-20250929, 레거시 수동 사고만 지원) - Claude Haiku 4.5 (
claude-haiku-4-5-20251001, 레거시 수동 사고만 지원)
사고의 작동 방식
사고가 켜져 있으면 Claude는 내부 추론을 출력하는 thinking 콘텐츠 블록을 생성합니다. API 응답에는 thinking 콘텐츠 블록이 포함되고, 그 뒤에 text 콘텐츠 블록이 이어집니다.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
messages=[
{
"role": "user",
"content": "Are there an infinite number of prime numbers such that n mod 4 == 3?",
}
],
)
# 응답에는 요약된 사고 블록과 텍스트 블록이 포함됩니다
for block in response.content:
if block.type == "thinking":
print(f"\nThinking summary: {block.thinking}")
elif block.type == "text":
print(f"\nResponse: {block.text}")수동 확장 사고(thinking: {"type": "enabled", "budget_tokens": N})는 레거시 메커니즘입니다. 이는 사고를 지원하는 Claude 4부터 4.6까지의 모델에서만 작동합니다. Claude 4.7 이상 모델은 type: enabled를 400 오류로 거부하며 대신 적응형 사고를 사용합니다. 수동 확장 사고에서 budget_tokens는 Claude가 내부 추론 과정에 사용할 수 있는 최대 토큰 수를 설정합니다. 이 제한은 요약된 출력이 아닌 전체 사고 토큰에 적용됩니다. 인터리브 사고를 사용하지 않는 한, 사고가 완료된 후 Claude가 응답을 작성할 공간을 확보할 수 있도록 budget_tokens는 max_tokens보다 작아야 합니다.
도구 사용과 함께하는 사고
사고는 도구 사용(tool use)과 함께 사용할 수 있으며, 이를 통해 Claude가 도구 선택과 결과 처리를 추론할 수 있습니다.
중요한 제한 사항:
- 도구 선택 제한:
tool_choice: {"type": "auto"}(기본값) 또는tool_choice: {"type": "none"}만 지원합니다. - 사고 블록 보존: 도구 사용 중에는 마지막 assistant 메시지에 대해
thinking블록을 API에 다시 전달해야 합니다.
사고 블록 보존하기
import anthropic
client = anthropic.Anthropic()
weather_tool = {
"name": "get_weather",
"description": "Get the current weather for a location.",
"input_schema": {
"type": "object",
"properties": {"location": {"type": "string", "description": "The city name."}},
"required": ["location"],
},
}
weather_data = {"temperature": 72}
# 첫 번째 요청 - Claude가 사고 블록과 도구 요청으로 응답합니다
response = client.messages.create(
model="claude-opus-5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
)
# 사고 블록과 도구 사용 블록을 추출합니다
thinking_block = next(
(block for block in response.content if block.type == "thinking"), None
)
tool_use_block = next(
(block for block in response.content if block.type == "tool_use"), None
)
# 두 번째 요청 - 사고 블록과 도구 결과를 포함합니다
continuation = client.messages.create(
model="claude-opus-5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
tools=[weather_tool],
messages=[
{"role": "user", "content": "What's the weather in Paris?"},
# tool_use_block뿐만 아니라 thinking_block도 함께 전달된다는 점에 유의하세요
{"role": "assistant", "content": [thinking_block, tool_use_block]},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_block.id,
"content": f"Current temperature: {weather_data['temperature']}°F",
}
],
},
],
)
for block in continuation.content:
if block.type == "text":
print(block.text)인터리브 사고
인터리브 사고(interleaved thinking)는 Claude가 도구 호출 사이에 사고하여, 다음 단계를 결정하기 전에 도구 결과에 대해 추론할 수 있게 합니다.
수동 확장 사고를 사용하는 이전 모델(Claude 4, 4.5 및 Sonnet 4.6 모델)에서는 API 요청에 베타 헤더 interleaved-thinking-2025-05-14를 추가하여 인터리브 사고를 활성화하세요:
import anthropic
client = anthropic.Anthropic()
calculator_tool = {
"name": "calculator",
"description": "Perform arithmetic calculations.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The math expression to evaluate.",
}
},
"required": ["expression"],
},
}
database_tool = {
"name": "database_query",
"description": "Query the product database.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The database query."}
},
"required": ["query"],
},
}
response = client.beta.messages.create(
model="claude-sonnet-4-6",
max_tokens=16000,
thinking={"type": "enabled", "budget_tokens": 10000},
tools=[calculator_tool, database_tool],
messages=[
{
"role": "user",
"content": "What's the total revenue if we sold 150 units of product A at $50 each?",
}
],
betas=["interleaved-thinking-2025-05-14"],
)
for block in response.content:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "tool_use":
print(f"Tool call: {block.name}({block.input})")
elif block.type == "text":
print(f"Response: {block.text}")인터리브 사고를 사용할 때, 그리고 오직 인터리브 사고를 사용할 때만(일반 수동 확장 사고가 아닌), budget_tokens가 max_tokens 매개변수를 초과할 수 있습니다. 이 경우 budget_tokens는 하나의 assistant 턴 내 모든 사고 블록에 걸친 총 예산을 나타내기 때문입니다.
도구 사용
클라이언트 도구 지정하기
클라이언트 도구는 API 요청의 최상위 매개변수 tools에 지정됩니다. 각 도구 정의에는 다음이 포함됩니다:
| 매개변수 | 설명 |
|---|---|
name | 도구의 이름입니다. 정규식 ^[a-zA-Z0-9_-]{1,128}$과 일치해야 합니다. |
description | 도구가 수행하는 작업, 사용해야 하는 시점, 동작 방식에 대한 상세한 일반 텍스트 설명입니다. |
input_schema | 도구에 필요한 매개변수를 정의하는 JSON Schema 객체입니다. |
{
"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"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "The unit of temperature, either 'celsius' or 'fahrenheit'"
}
},
"required": ["location"]
}
}도구 정의 모범 사례
매우 상세한 설명을 제공하세요. 이것이 도구 성능에 있어 단연 가장 중요한 요소입니다. 설명에는 다음을 포함하여 도구에 대한 모든 세부 사항이 담겨야 합니다:
- 도구가 무엇을 하는지
- 언제 사용해야 하는지(그리고 언제 사용하지 말아야 하는지)
- 각 매개변수가 무엇을 의미하며 도구의 동작에 어떤 영향을 미치는지
- 중요한 주의 사항이나 제한 사항
복잡한 도구에는 input_examples 사용을 고려하세요. 중첩된 객체, 선택적 매개변수 또는 형식에 민감한 입력이 있는 도구의 경우, input_examples 필드(베타)를 사용하여 구체적인 예시를 제공할 수 있습니다. 이는 Claude가 예상되는 입력 패턴을 이해하는 데 도움이 됩니다. 자세한 내용은 도구 사용 예시 제공하기를 참조하세요.
좋은 도구 설명의 예시:
{
"name": "get_stock_price",
"description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
}
},
"required": ["ticker"]
}
}Claude의 출력 제어하기
도구 사용 강제하기
tool_choice 필드에 도구를 지정하여 Claude가 특정 도구를 사용하도록 강제할 수 있습니다:
tool_choice = {"type": "tool", "name": "get_weather"}tool_choice 매개변수를 사용할 때 네 가지 옵션이 있습니다:
auto는 Claude가 제공된 도구를 호출할지 여부를 스스로 결정하도록 합니다(기본값).any는 Claude에게 제공된 도구 중 하나를 반드시 사용해야 한다고 알려줍니다.tool은 Claude가 항상 특정 도구를 사용하도록 강제합니다.none은 Claude가 어떤 도구도 사용하지 못하게 합니다.
Claude Fable 5.1과 Claude Mythos 5.1에서는 any와 tool이 400 오류를 반환합니다. tool_choice를 auto로 두고 도구 정의에 "strict": true를 설정하여 Claude가 수행하는 모든 호출이 도구의 input_schema와 일치하도록 보장하세요. 엄격한 도구 사용을 참조하세요.
JSON 출력
도구가 반드시 클라이언트 함수일 필요는 없습니다. 모델이 제공된 스키마를 따르는 JSON 출력을 반환하기를 원할 때 언제든지 도구를 사용할 수 있습니다.
사고의 연쇄
도구를 사용할 때 Claude는 종종 "chain of thought"(사고의 연쇄), 즉 문제를 분해하고 어떤 도구를 사용할지 결정하는 데 사용하는 단계별 추론을 보여줍니다.
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "<thinking>To answer this question, I will: 1. Use the get_weather tool to get the current weather in San Francisco. 2. Use the get_time tool to get the current time in the America/Los_Angeles timezone, which covers San Francisco, CA.</thinking>"
},
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": { "location": "San Francisco, CA" }
}
]
}병렬 도구 사용
기본적으로 Claude는 사용자 쿼리에 답하기 위해 여러 도구를 사용할 수 있습니다. disable_parallel_tool_use=true를 설정하여 이 동작을 비활성화할 수 있습니다.
도구 사용 및 도구 결과 콘텐츠 블록 처리하기
클라이언트 도구의 결과 처리하기
응답은 tool_use의 stop_reason과 다음을 포함하는 하나 이상의 tool_use 콘텐츠 블록을 가집니다:
id: 이 특정 도구 사용 블록의 고유 식별자입니다.name: 사용되는 도구의 이름입니다.input: 도구에 전달되는 입력을 담은 객체입니다.
도구 사용 응답을 받으면 다음을 수행해야 합니다:
tool_use블록에서name,id,input을 추출합니다.- 해당 도구 이름에 대응하는 실제 도구를 코드베이스에서 실행합니다.
tool_result가 포함된 새 메시지를 전송하여 대화를 계속합니다:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "15 degrees"
}
]
}max_tokens 중지 사유 처리하기
도구 사용 중 max_tokens 제한에 도달하여 Claude의 응답이 잘린 경우, 더 높은 max_tokens 값으로 요청을 다시 시도하세요.
pause_turn 중지 사유 처리하기
웹 검색과 같은 서버 도구를 사용할 때 API가 pause_turn 중지 사유를 반환할 수 있습니다. 일시 중지된 응답을 후속 요청에 그대로 다시 전달하여 대화를 계속하세요.
오류 문제 해결
도구 실행 오류
도구 자체가 실행 중 오류를 발생시키는 경우, "is_error": true와 함께 오류 메시지를 반환하세요:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "ConnectionError: the weather service API is not available (HTTP 500)",
"is_error": true
}
]
}잘못된 도구 이름
Claude의 도구 사용 시도가 유효하지 않은 경우(예: 필수 매개변수 누락), 도구 정의에 더 상세한 description 값을 넣어 요청을 다시 시도하세요.
메시지 스트리밍
Message를 생성할 때 "stream": true를 설정하면 "server-sent events"(서버 전송 이벤트), 즉 SSE를 사용하여 응답을 점진적으로 스트리밍할 수 있습니다.
SDK로 스트리밍하기
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
model="claude-opus-5",
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)이벤트 유형
각 서버 전송 이벤트에는 이름이 지정된 이벤트 유형과 관련 JSON 데이터가 포함됩니다. 각 스트림은 다음 이벤트 흐름을 사용합니다:
message_start: 빈content를 가진Message객체를 포함합니다.- 일련의 콘텐츠 블록으로, 각각
content_block_start, 하나 이상의content_block_delta이벤트, 그리고content_block_stop으로 구성됩니다. - 최종
Message객체에 대한 최상위 변경 사항을 나타내는 하나 이상의message_delta이벤트. - 마지막
message_stop이벤트.
경고: message_delta 이벤트의 usage 필드에 표시되는 토큰 수는 누적 값입니다.
콘텐츠 블록 델타 유형
텍스트 델타
{
"type": "content_block_delta",
"index": 0,
"delta": { "type": "text_delta", "text": "Hello frien" }
}입력 JSON 델타
tool_use 콘텐츠 블록의 경우, 델타는 부분 JSON 문자열입니다:
{"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}사고 델타
스트리밍과 함께 사고를 사용하는 경우:
{
"type": "content_block_delta",
"index": 0,
"delta": {
"type": "thinking_delta",
"thinking": "Let me solve this step by step..."
}
}기본 스트리밍 요청 예시
event: message_start
data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-5", "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: 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"}Was this page helpful?