本番向け 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 堅牢化 反復回数とコストに上限を設け、ツールの入力を検証し、シークレットは環境変数に保管してください。自律的な用途については、エージェントのセキュリティ確保を読んでください。 :::