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
| Concept | Description |
|---|---|
| Messages / Responses API | The main chat interfaces. Anthropic uses the Messages API; OpenAI recommends the Responses API for new projects (the older Chat Completions API still works) |
| Token | The unit of billing and context length. Input tokens and output tokens are priced separately |
max_tokens | The 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 |
| Streaming | The server pushes tokens chunk by chunk over SSE (Server-Sent Events), which greatly reduces time to first token (TTFT) |
stop_reason / finish_reason | Tells 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)
| SDK | Default retries | Errors retried | Default timeout |
|---|---|---|---|
anthropic (Python) | 2, exponential backoff | Connection errors, 408, 409, 429, ≥500 | 10 minutes |
openai (Python) | 2, exponential backoff + jitter | Connection errors, 408, 409, 429, ≥500 | 10 minutes |
- Both SDKs let you override
max_retries=andtimeout=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=Trueinstead. - 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_retriesto 0 or 1 and let your own Gateway control retries centrally.
3. Error classes (decide whether to retry or fail fast)
| Class | Examples | Handling |
|---|---|---|
| Retryable transient errors | 429 rate limit, 5xx, 529 overloaded, connection timeout | Exponential backoff + jitter, respect the retry-after response header |
| Non-retryable request errors | 400 bad parameters, 401 auth, 413 too large | Fail immediately and alert; retrying only burns quota |
| Content-level failures | Truncated (max_tokens), refusal, JSON that doesn't match the schema | Not 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 happenedThe Gateway handles multi-provider adapters, timeouts, classified retries, fallback, token/cost accounting and call logs. Business code only knows LLMRequest/LLMResult.
Common pitfalls
- Using a sync client inside an
async defroute: it blocks the event loop and every request slows down. UseAsyncAnthropic/AsyncOpenAI. - Not checking
stop_reason: output truncated bymax_tokensfails JSON parsing and gets retried as if the model "produced garbage". - Stacked retries: the SDK already retries twice by default; retrying 3 more times outside means one failure can fire up to 9 requests.
- Upstream keeps generating after the client disconnects: a streaming endpoint must cancel the upstream request when the client disconnects, or you pay for nothing.
- 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
- How do you detect 429s, timeouts, 5xx and truncated output? Which ones should be retried?
- Do the official SDKs retry by default? How does your Gateway layer relate to that?
- What affects time to first token versus total latency? How do you optimize each?
- When the user closes the page, how does the backend stop an in-progress streaming generation?
- Which fields do you log for every LLM call, and why?
How it relates to my projects
- AI Document Review Pipeline: the W2 LLM Gateway is this page put into practice; the
llm_calltable fields followlog_llm_callabove.
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.pyor the Retries / Timeouts sections of the README).
Sources
- Anthropic Python SDK docs (Retries / Timeouts sections) — 2 retries by default, 10-minute default timeout, long requests need streaming
- anthropic-sdk-python on GitHub — defaults defined in
_constants.py - openai-python GitHub README — Retries and Timeouts sections
- Anthropic Docs: Streaming Messages
- Anthropic Docs: Errors — error codes and 529 overloaded
- OpenAI Docs: Error codes
