La tua prima chiamata API in produzione (attenta ai costi)
Una chiamata API di esempio è una sola riga. Una chiamata di produzione gestisce gli errori, trasmette l'output in streaming, tiene d'occhio i costi e protegge i segreti. Costruiamola, passo dopo passo.
Passo 1 — Segreti e modello dalla configurazione
export ANTHROPIC_API_KEY="sk-ant-..." # never in source control
Tieni l'ID del modello nella configurazione, non in valori letterali sparsi nel codice, così la migrazione è banale (perché). Scegli con criterio — Scegliere un modello.
Passo 2 — Una chiamata resiliente in streaming
- 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)));
}
}
}
Passo 3 — Tieni d'occhio i costi
- Registra l'uso dei token (qui sopra) così puoi vedere quanto costa ogni chiamata.
- Dimensiona correttamente
max_tokense il modello; limita l'input con prompt mirati. - Per prefissi stabili e ripetuti, aggiungi il prompt caching.
- Vedi Token e prezzi e Costo e latenza.
Passo 4 — Gestisci i percorsi infelici
- Riprova gli errori transitori (429/5xx) con backoff (qui sopra); non riprovare i 400.
- Gestisci i rifiuti in modo elegante.
- Imposta un timeout e un budget di costo/iterazioni per qualsiasi cosa agentica.
Verifica
Eseguila: dovresti vedere l'output in streaming, una riga con l'uso dei token e un comportamento robusto se forzi un errore (ad es. una chiave errata → messaggio pulito, non un crash).