| name | claude-api |
| description | Python 및 TypeScript를 위한 Anthropic Claude API 패턴. Messages API, 스트리밍, 도구 사용(tool use), 비전, 확장 추론(extended thinking), 배치 처리, 프롬프트 캐싱 및 Claude 에이전트 SDK를 다룹니다. Claude API 또는 Anthropic SDK를 사용하여 애플리케이션을 구축할 때 사용하세요. |
| origin | ECC |
Claude API
Anthropic Claude API 및 SDK를 사용하여 애플리케이션을 구축합니다.
활성화 시점
- Claude API를 호출하는 애플리케이션 구축 시
- 코드에
anthropic (Python) 또는 @anthropic-ai/sdk (TypeScript) 임포트가 있을 때
- 사용자가 Claude API 패턴, 도구 사용, 스트리밍 또는 비전에 대해 질문할 때
- Claude 에이전트 SDK를 사용하여 에이전트 워크플로우 구현 시
- API 비용, 토큰 사용량 또는 대기 시간 최적화 시
모델 선택
| 모델 | ID | 용도 |
|---|
| Opus 4.1 | claude-opus-4-1 | 복잡한 추론, 아키텍처, 조사 |
| Sonnet 4 | claude-sonnet-4-0 | 균형 잡힌 코딩, 대부분의 개발 작업 |
| Haiku 3.5 | claude-3-5-haiku-latest | 빠른 응답, 대량 처리, 비용 민감 작업 |
심층 추론(Opus)이나 속도/비용 최적화(Haiku)가 필요한 작업이 아니라면 Sonnet 4를 기본으로 사용하세요. 프로덕션 환경에서는 별칭(alias)보다 고정된 스냅샷 ID를 사용하는 것이 좋습니다.
Python SDK
설치
pip install anthropic
기본 메시지
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain async/await in Python"}
]
)
print(message.content[0].text)
스트리밍
with client.messages.stream(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about coding"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
시스템 프롬프트
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system="You are a senior Python developer. Be concise.",
messages=[{"role": "user", "content": "Review this function"}]
)
TypeScript SDK
설치
npm install @anthropic-ai/sdk
기본 메시지
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const message = await client.messages.create({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [
{ role: "user", content: "Explain async/await in TypeScript" }
],
});
console.log(message.content[0].text);
스트리밍
const stream = client.messages.stream({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a haiku" }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text);
}
}
도구 사용 (Tool Use)
도구를 정의하고 Claude가 이를 호출하도록 합니다:
tools = [
{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in SF?"}]
)
for block in message.content:
if block.type == "tool_use":
result = get_weather(**block.input)
follow_up = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in SF?"},
{"role": "assistant", "content": message.content},
{: , : [
{: , : block., : (result)}
]}
]
)
비전 (Vision)
분석을 위해 이미지 보내기:
import base64
with open("diagram.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}},
{"type": "text", "text": "Describe this diagram"}
]
}]
)
확장 추론 (Extended Thinking)
복잡한 추론 작업 시:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[{"role": "user", "content": "Solve this math problem step by step..."}]
)
for block in message.content:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "text":
print(f"Answer: {block.text}")
프롬프트 캐싱 (Prompt Caching)
비용을 줄이기 위해 대규모 시스템 프롬프트나 컨텍스트를 캐싱합니다:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system=[
{"type": "text", "text": large_system_prompt, "cache_control": {"type": "ephemeral"}}
],
messages=[{"role": "user", "content": "Question about the cached context"}]
)
print(f"Cache read: {message.usage.cache_read_input_tokens}")
print(f"Cache creation: {message.usage.cache_creation_input_tokens}")
배치 처리 API (Batches API)
대량의 요청을 비동기적으로 처리하여 비용을 50% 절감합니다:
import time
batch = client.messages.batches.create(
requests=[
{
"custom_id": f"request-{i}",
"params": {
"model": "claude-sonnet-4-0",
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}]
}
}
for i, prompt in enumerate(prompts)
]
)
while True:
status = client.messages.batches.retrieve(batch.id)
if status.processing_status == "ended":
break
time.sleep(30)
for result in client.messages.batches.results(batch.id):
print(result.result.message.content[0].text)
Claude 에이전트 SDK
멀티스텝 에이전트 구축:
import anthropic
tools = [{
"name": "search_codebase",
"description": "Search the codebase for relevant code",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
}]
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Review the auth module for security issues"}]
while True:
response = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=4096,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
break
messages.append({"role": "assistant", "content": response.content})
비용 최적화
| 전략 | 절감 효과 | 사용 시기 |
|---|
| 프롬프트 캐싱 | 캐시된 토큰에 대해 최대 90% | 반복되는 시스템 프롬프트 또는 컨텍스트 |
| 배치 처리 API | 50% | 시간에 민감하지 않은 대량 처리 |
| Sonnet 대신 Haiku | 약 75% | 단순 작업, 분류, 추출 |
| 짧은 max_tokens | 가변적 | 출력물이 짧을 것으로 예상될 때 |
| 스트리밍 | 없음 (동일 비용) | 더 나은 UX 제공 시 |
에러 처리
import time
from anthropic import APIError, RateLimitError, APIConnectionError
try:
message = client.messages.create(...)
except RateLimitError:
time.sleep(60)
except APIConnectionError:
pass
except APIError as e:
print(f"API error {e.status_code}: {e.message}")
환경 설정
export ANTHROPIC_API_KEY="your-api-key-here"
export ANTHROPIC_MODEL="claude-sonnet-4-0"
API 키를 절대 코드에 하드코딩하지 마세요. 항상 환경 변수를 사용하세요.