Calling LLM APIs robustly

Messages, streaming, async fan-out, retries and rate limits, token accounting, across Anthropic, OpenAI and Azure.

Intermediate about 4 h

The picture

  1. 01

    Build messages

    system + turns

  2. 02

    Call

    with timeout

  3. 03

    Stream

    first-token latency

  4. 04

    Retry

    backoff + jitter

  5. 05

    Account

    tokens, cost

The shape of every call

Whatever the vendor, a chat call is: optional system instructions, a list of alternating user/assistant messages, sampling parameters, and a limit on output tokens. You get back content plus usage (input and output tokens), which is what you are billed on.

import anthropic

client = anthropic.Anthropic(max_retries=3, timeout=60)      # reads ANTHROPIC_API_KEY

msg = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=512,
    temperature=0,
    system="You are a precise assistant. Answer in two sentences.",
    messages=[{"role": "user", "content": "Why does attention scale quadratically?"}],
)
print(msg.content[0].text)
print(msg.usage.input_tokens, msg.usage.output_tokens, msg.stop_reason)

The same shape with the OpenAI-compatible SDK, including Azure, where you pass a deployment name as the model:

import os
from openai import OpenAI, AzureOpenAI

client = OpenAI()                                        # reads OPENAI_API_KEY
azure = AzureOpenAI(
    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    api_version=os.environ["AZURE_OPENAI_API_VERSION"],
)
r = azure.chat.completions.create(
    model=os.environ["AZURE_OPENAI_DEPLOYMENT"],
    messages=[{"role": "user", "content": "Say hello in one word."}],
)
print(r.choices[0].message.content, r.usage.prompt_tokens, r.usage.completion_tokens)

Keep model names and versions in configuration, not scattered through code. They change.

Streaming

Streaming does not make generation faster; it makes it feel faster by showing the first tokens immediately. Measure time-to-first-token separately from total time.

import time
t0 = time.perf_counter()
first = None
with client.messages.stream(model="claude-sonnet-5-5", max_tokens=400,
                            messages=[{"role": "user", "content": "Explain KV caching."}]) as stream:
    for text in stream.text_stream:
        first = first or time.perf_counter() - t0
        print(text, end="", flush=True)
print(f"\nTTFT {first:.2f}s, total {time.perf_counter() - t0:.2f}s")

Async fan-out with limits

import asyncio, anthropic

aclient = anthropic.AsyncAnthropic()

async def ask(q: str, sem: asyncio.Semaphore):
    async with sem:
        m = await aclient.messages.create(model="claude-sonnet-5-5", max_tokens=200,
                                          messages=[{"role": "user", "content": q}])
        return m.content[0].text, m.usage.input_tokens, m.usage.output_tokens

async def run(questions, concurrency=8):
    sem = asyncio.Semaphore(concurrency)
    results = await asyncio.gather(*(ask(q, sem) for q in questions))
    print("input tokens", sum(r[1] for r in results), "output tokens", sum(r[2] for r in results))
    return [r[0] for r in results]

Retries: what is safe

Retry 429 (rate limited), 5xx and network timeouts with exponential backoff and jitter. Do not retry 400 or 401: they will fail the same way. Both SDKs retry transient errors for you with max_retries; wrap your own loop only when you need extra logic such as falling back to another model.

import random, time
def with_backoff(fn, tries=5, base=1.0):
    for i in range(tries):
        try:
            return fn()
        except (anthropic.RateLimitError, anthropic.APIConnectionError, anthropic.InternalServerError):
            if i == tries - 1:
                raise
            time.sleep(base * 2**i + random.random())

Token accounting and cost

Log input tokens, output tokens, latency and model on every call from day one. Cost is input_tokens × input_price + output_tokens × output_price, and output tokens are priced several times higher, so a verbose answer costs far more than a long prompt. Check current prices in the provider's pricing page rather than hard-coding them.

Common mistakes

  • Putting keys in code or a notebook.
  • Unbounded max_tokens and no timeout.
  • Retrying non-idempotent side effects (a tool that sends an email) blindly.
  • Ignoring stop_reason: max_tokens means the answer was cut off.

Exercises

  1. Build an async batch runner that respects a rate limit and writes results and token counts to a JSONL file.
  2. Measure TTFT and total latency for a 100-token and a 1,000-token answer.

You are done when you can…

  • Make a call with a timeout, retries with backoff and a streamed response
  • Fan out 50 requests with bounded concurrency and aggregate token cost
  • Explain which errors are safe to retry and which are not