Skip to content
Goal: Deep understanding✓ Sources verified 2026-11-24OpenAIAnthropicStreamingSDK

LLM API Integration: Calls, Streaming and Error Handling ​

Integrating a model API on the backend is the foundation of shipping any LLM feature. This page collects what you need to know, from making the first call to running it reliably in production. It is the layer of the pipeline that most often breaks in production, and "how do you handle timeouts / 429s / truncated output" is a guaranteed interview question.

Core concepts ​

ConceptDescription
Messages / Responses APIThe main chat interfaces. Anthropic uses the Messages API; OpenAI recommends the Responses API for new projects (the older Chat Completions API still works)
TokenThe unit of billing and context length. Input tokens and output tokens are priced separately
max_tokensThe output cap. When it is reached the reply is truncated: Anthropic returns stop_reason: "max_tokens", and OpenAI's Responses API marks the response as incomplete
StreamingThe server pushes tokens chunk by chunk over SSE (Server-Sent Events), which greatly reduces time to first token (TTFT)
stop_reason / finish_reasonTells you whether the call ended normally, was truncated, wants to call a tool, or was refused. Log it on every call

How it works ​

1. Lifecycle of a single call ​

Client → (connect/TLS) → gateway queue → model inference (prefill processes the input → decode generates token by token) → response
  • The prefill phase scales with input length and determines time to first token; the decode phase scales with output length and determines total time.
  • So for "long input + short output" extraction tasks, focus on shortening the input or using prompt caching; for "short input + long output" generation tasks, focus on streaming the output to the user.

2. Retries and timeouts built into the official SDKs (know the defaults before reading the source) ​

SDKDefault retriesErrors retriedDefault timeout
anthropic (Python)2, exponential backoffConnection errors, 408, 409, 429, ≥50010 minutes
openai (Python)2, exponential backoff + jitterConnection errors, 408, 409, 429, ≥50010 minutes
  • Both SDKs let you override max_retries= and timeout= on the client or per request.
  • The Anthropic SDK raises an error for non-streaming requests expected to take longer than about 10 minutes, and tells you to use stream=True instead.
  • Implication: if you wrap calls in another layer of tenacity retries, the actual number of requests is the product of the two layers, which easily amplifies 429s. In production, set the SDK's max_retries to 0 or 1 and let your own Gateway control retries centrally.

3. Error classes (decide whether to retry or fail fast) ​

ClassExamplesHandling
Retryable transient errors429 rate limit, 5xx, 529 overloaded, connection timeoutExponential backoff + jitter, respect the retry-after response header
Non-retryable request errors400 bad parameters, 401 auth, 413 too largeFail immediately and alert; retrying only burns quota
Content-level failuresTruncated (max_tokens), refusal, JSON that doesn't match the schemaNot a network problem: raise max_tokens, change the prompt, or regenerate with the error message included

In practice ​

Streaming a call and logging metadata (Anthropic Python SDK) ​

python
import time, anthropic

client = anthropic.AsyncAnthropic(max_retries=1, timeout=60)

async def stream_answer(messages, model: str):
    t0 = time.monotonic()
    first_token_at = None
    async with client.messages.stream(model=model, max_tokens=2048, messages=messages) as stream:
        async for text in stream.text_stream:
            if first_token_at is None:
                first_token_at = time.monotonic()
            yield text
        final = await stream.get_final_message()
    # Write to the llm_call table: for tracing and cost reporting
    log_llm_call(
        model=model,
        stop_reason=final.stop_reason,
        input_tokens=final.usage.input_tokens,
        output_tokens=final.usage.output_tokens,
        ttft_ms=int((first_token_at - t0) * 1000) if first_token_at else None,
        total_ms=int((time.monotonic() - t0) * 1000),
    )

Minimal interface for a unified LLM Gateway ​

python
class LLMRequest(BaseModel):
    task: str               # business task name, e.g. "contract_extract"
    prompt_version: str     # e.g. "contract_extract@v3"
    messages: list[dict]
    schema: dict | None     # pass when structured output is needed
    timeout_s: float = 60

class LLMResult(BaseModel):
    content: str | dict
    provider: str
    model: str
    stop_reason: str
    usage: dict
    latency_ms: int
    fallback_from: str | None = None   # original model when a fallback happened

The Gateway handles multi-provider adapters, timeouts, classified retries, fallback, token/cost accounting and call logs. Business code only knows LLMRequest/LLMResult.

Common pitfalls ​

  1. Using a sync client inside an async def route: it blocks the event loop and every request slows down. Use AsyncAnthropic / AsyncOpenAI.
  2. Not checking stop_reason: output truncated by max_tokens fails JSON parsing and gets retried as if the model "produced garbage".
  3. Stacked retries: the SDK already retries twice by default; retrying 3 more times outside means one failure can fire up to 9 requests.
  4. Upstream keeps generating after the client disconnects: a streaming endpoint must cancel the upstream request when the client disconnects, or you pay for nothing.
  5. Hard-coding model names in business code: models change fast. Put model names in config and record them in every call log.

Common interview questions ​

  1. How do you detect 429s, timeouts, 5xx and truncated output? Which ones should be retried?
  2. Do the official SDKs retry by default? How does your Gateway layer relate to that?
  3. What affects time to first token versus total latency? How do you optimize each?
  4. When the user closes the page, how does the backend stop an in-progress streaming generation?
  5. Which fields do you log for every LLM call, and why?

How it relates to my projects ​

To be verified / may go stale

  • Model names, context lengths and prices change quickly, so this page deliberately names no specific models. Check the official Models / Pricing pages before use.
  • SDK defaults come from the current README / docs. Re-check after a major SDK upgrade (see _constants.py or the Retries / Timeouts sections of the README).

Sources ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section