프로덕션 API 스니펫
API 위에서 무언가를 구축하기 위한 실전 검증된 형태들입니다. 여러분의 스택에 맞게 적용하고 견고하게 다듬으세요.
견고한 호출 래퍼 (재시도 + 백오프)
- Python
- TypeScript
import time, random, anthropic
client = anthropic.Anthropic()
def ask(messages, model="claude-sonnet-4-6", max_tokens=1024, system=None):
for attempt in range(5):
try:
return client.messages.create(
model=model, max_tokens=max_tokens,
system=system or anthropic.NOT_GIVEN, messages=messages,
)
except (anthropic.RateLimitError, anthropic.APIStatusError) as e:
if attempt == 4:
raise
time.sleep(min(2 ** attempt + random.random(), 30))
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
export async function ask(messages, { model = "claude-sonnet-4-6", maxTokens = 1024, system } = {}) {
for (let attempt = 0; attempt < 5; attempt++) {
try {
return await client.messages.create({ model, max_tokens: maxTokens, system, messages });
} catch (e: any) {
if (attempt === 4 || ![429, 500, 529].includes(e?.status)) throw e;
await new Promise((r) => setTimeout(r, Math.min(2 ** attempt * 1000 + Math.random() * 1000, 30000)));
}
}
}
(SDK 역시 기본적으로 일시적 오류를 재시도합니다 — 자체 재시도 로직을 쌓기 전에 클라이언트의 동작을 파악하세요. 오류 및 속도 제한을 참조하세요.)
스트리밍 채팅
with client.messages.stream(model="claude-sonnet-4-6", max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}]) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
도구 사용 루프 (골격)
messages = [{"role": "user", "content": "What's the weather in Rome?"}]
while True:
resp = client.messages.create(model="claude-sonnet-4-6", max_tokens=1024,
tools=TOOLS, messages=messages)
if resp.stop_reason != "tool_use":
break
messages.append({"role": "assistant", "content": resp.content})
results = [run_tool(b) for b in resp.content if b.type == "tool_use"]
messages.append({"role": "user", "content": results}) # tool_result blocks
:::warning 견고하게 만들기 반복 횟수와 비용에 상한을 두고, 도구 입력을 검증하며, 비밀 값은 환경 변수에 보관하세요. 자율적으로 사용하려면 에이전트 보안을 읽어보세요. :::