이 가이드는 Claude에게 Claude API 사용의 기본을 제공하도록 설계되었습니다. 모델 ID/기본 messages API, 도구 사용, 스트리밍, 사고에 대한 설명과 예제를 제공하며, 그 외의 내용은 다루지 않습니다.
For complex agentic coding and enterprise work: Claude Opus 5: claude-opus-5
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-20251001import anthropic
import os
message = anthropic.Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY")
).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의 응답을 원하는 형태로 유도할 수 있습니다. 다음 예제는 "max_tokens": 1을 사용하여 Claude로부터 단일 객관식 답변을 얻습니다.
Claude 4.6 및 이후 모델과 Claude Mythos Preview는 assistant 메시지 미리 채우기를 지원하지 않습니다. 해당 모델에 대한 요청은 user 메시지로 끝나야 합니다. 아래 예제는 미리 채우기를 지원하는 모델을 사용합니다.
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 httpx
# 옵션 1: Base64로 인코딩된 이미지
image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx.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://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.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에게 도움이 될 수 있습니다. 현재 메커니즘은 적응형 사고(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가 더 이상 사용되지 않으며(deprecated), 사고가 꺼져 있더라도 기본값만 허용됩니다.
사고는 다음 모델에서 지원됩니다:
claude-sonnet-5, 적응형 사고만 지원, 기본 활성화)claude-opus-4-7, 적응형 사고만 지원)claude-opus-4-6, 적응형 또는 레거시 수동 사고)claude-sonnet-4-6, 적응형 또는 레거시 수동 사고)claude-opus-4-5-20251101, 레거시 수동 사고만 지원)claude-sonnet-4-5-20250929, 레거시 수동 사고만 지원)claude-haiku-4-5-20251001, 레거시 수동 사고만 지원)Claude 4.7 및 이후 모델에서는 수동 확장 사고(budget_tokens 값과 함께 type: enabled)가 지원되지 않으며 400 오류를 반환합니다. 대신 적응형 사고(type: adaptive)를 사용하세요.
사고가 활성화되면 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보다 작아야 합니다.
사고는 도구 사용과 함께 사용할 수 있으며, Claude가 도구 선택과 결과 처리에 대해 추론할 수 있게 합니다.
중요한 제한 사항:
tool_choice: {"type": "auto"}(기본값) 또는 tool_choice: {"type": "none"}만 지원합니다.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가 도구 호출 사이에 사고할 수 있게 하여, 다음 단계를 결정하기 전에 도구 결과에 대해 추론할 수 있도록 합니다.
적응형 사고(thinking: {type: "adaptive"})를 사용하는 모델에서는 인터리브 사고가 자동으로 활성화됩니다. 베타 헤더가 필요하지 않습니다. Sonnet 4.6은 수동 확장 사고와 함께 사용하는 interleaved-thinking-2025-05-14 베타 헤더와 적응형 사고를 모두 지원합니다.
수동 확장 사고를 사용하는 이전 모델(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,64}$와 일치해야 합니다. |
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"]
}
}tool_choice 필드에 도구를 지정하여 Claude가 특정 도구를 사용하도록 강제할 수 있습니다:
tool_choice = {"type": "tool", "name": "get_weather"}tool_choice 매개변수를 사용할 때 네 가지 옵션이 있습니다:
auto는 Claude가 제공된 도구를 호출할지 여부를 결정할 수 있게 합니다(기본값).any는 Claude가 제공된 도구 중 하나를 반드시 사용해야 함을 알립니다.tool은 Claude가 항상 특정 도구를 사용하도록 강제합니다.none은 Claude가 어떤 도구도 사용하지 못하게 합니다.도구가 반드시 클라이언트 함수일 필요는 없습니다. 모델이 제공된 스키마를 따르는 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 값을 사용하여 요청을 다시 시도하세요.
메시지를 생성할 때 "stream": true를 설정하여 서버 전송 이벤트(SSE)를 사용해 응답을 점진적으로 스트리밍할 수 있습니다.
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" }
}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?