첫 번째 프로덕션 API 호출 (비용을 고려한)
장난감 수준의 API 호출은 한 줄이면 됩니다. 하지만 프로덕션 호출은 오류를 처리하고, 출력을 스트리밍하고, 비용을 감시하며, 비밀 값을 안전하게 보관합니다. 이를 단계별로 만들어 봅시다.
1단계 — 설정에서 비밀 값과 모델 가져오기
export ANTHROPIC_API_KEY="sk-ant-..." # never in source control
리터럴 값을 여기저기 흩뿌리지 말고 모델 ID를 설정에 두어 마이그레이션을 간단하게 만드세요(이유). 신중하게 선택하세요 — 모델 선택하기.
2단계 — 견고한 스트리밍 호출
- Python
- TypeScript
import os, time, random, anthropic
client = anthropic.Anthropic()
MODEL = os.environ.get("CLAUDE_MODEL", "claude-sonnet-4-6")
def ask_stream(prompt, system=None, max_tokens=1024):
for attempt in range(5):
try:
with client.messages.stream(
model=MODEL, max_tokens=max_tokens,
system=system or anthropic.NOT_GIVEN,
messages=[{"role": "user", "content": prompt}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print()
usage = final.usage
print(f"\n[tokens in/out: {usage.input_tokens}/{usage.output_tokens}]")
return final
except (anthropic.RateLimitError, anthropic.APIStatusError):
if attempt == 4: raise
time.sleep(min(2 ** attempt + random.random(), 30))
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const MODEL = process.env.CLAUDE_MODEL ?? "claude-sonnet-4-6";
export async function askStream(prompt: string, system?: string, maxTokens = 1024) {
for (let attempt = 0; attempt < 5; attempt++) {
try {
const stream = client.messages.stream({ model: MODEL, max_tokens: maxTokens, system,
messages: [{ role: "user", content: prompt }] });
for await (const e of stream)
if (e.type === "content_block_delta") process.stdout.write(e.delta.text ?? "");
const final = await stream.finalMessage();
console.error(`\n[tokens in/out: ${final.usage.input_tokens}/${final.usage.output_tokens}]`);
return final;
} 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, 30000)));
}
}
}
3단계 — 비용에 유의하기
- 토큰 사용량을 로깅하세요(위 코드 참고) — 각 호출의 비용을 파악할 수 있도록.
max_tokens와 모델을 적정 크기로 맞추고, 집중된 프롬프트로 입력을 제한하세요.- 반복되는 안정적인 프리픽스에는 프롬프트 캐싱을 추가하세요.
- 토큰 & 가격과 비용 & 지연시간을 참고하세요.
4단계 — 잘못된 경로 처리하기
- 일시적인 오류(429/5xx)는 백오프와 함께 재시도하세요(위 코드 참고); 400 오류는 재시도하지 마세요.
- 거부를 우아하게 처리하세요.
- 에이전트성 작업에는 타임아웃과 비용/반복 예산을 설정하세요.
확인하기
실행해 보세요: 스트리밍 출력, 토큰 사용량 줄, 그리고 오류를 일부러 발생시켰을 때(예: 잘못된 키 → 크래시가 아니라 깔끔한 메시지)의 우아한 동작을 볼 수 있어야 합니다.