प्रोडक्शन 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 मज़बूत बनाना इटरेशन और लागत पर सीमा लगाएँ, टूल इनपुट को वैलिडेट करें, और सीक्रेट्स को env वैरिएबल्स में रखें। स्वायत्त उपयोग के लिए, पढ़ें एजेंट्स को सुरक्षित करना। :::