Sub topic 3
Timeouts, Retries, and Reliable LLM API Calls
Assume you know basic Python, JSON, HTTP status codes, and environment variables. This chapter focuses on making LLM calls dependable after the first request works.
Timeouts, retries, and exponential backoff
Always set a timeout. Without one, a network call can wait indefinitely. Retry temporary failures such as timeouts, connection errors, HTTP 429 rate limits, and HTTP 5xx server errors. Do not automatically retry most 4xx errors, because they usually indicate an invalid request or authentication problem.
Exponential backoff increases the delay after each failure. Jitter adds a small random delay so many clients do not retry simultaneously.
import random
import time
import requests
def call_with_retries(url, headers, payload, attempts=4):
for attempt in range(attempts):
try:
response = requests.post(
url, headers=headers, json=payload, timeout=(5, 60)
)
if response.status_code not in {429, 500, 502, 503, 504}:
response.raise_for_status()
return response.json()
except (requests.ConnectionError, requests.Timeout):
pass
if attempt == attempts - 1:
break
delay = min(30, 2 ** attempt) + random.random()
time.sleep(delay)
raise RuntimeError("Request failed after bounded retries")Streaming, SDKs, and structured results
With streaming enabled, the server sends partial output as it generates it. Your program processes each event immediately instead of waiting for the complete response. This improves perceived latency, but the connection can fail halfway through, so handle incomplete output.
An official SDK usually manages authentication, request serialization, response parsing, and streaming events. Raw HTTP gives more control and exposes the wire format. Use the SDK for normal application code; use raw HTTP when debugging compatibility or implementing a provider-neutral adapter.
For structured output, request a defined schema when the provider supports it. Then parse and validate the returned JSON. Validation is essential because model output is still untrusted text.
Tool calls, cost, and production practice
A tool call lets the model request a named function with structured arguments. Your application must validate those arguments, authorize the operation, execute it, and send the result back. Never treat a tool request as permission to perform an unrestricted action.
Usage metadata commonly includes input and output tokens. Estimate cost by multiplying each token count by the provider’s published per-token price. Latency includes network time, queueing, and generation time, so record both total duration and time to first streamed token.
Keep API keys in environment variables or a secret manager. Redact keys and sensitive prompts from logs. Log request IDs, model names, status codes, retry counts, token usage, and durations. Apply output limits and validate generated content before displaying or executing it.
Exercise
Which failures should normally be retried, and why should retries use backoff?
Show answer
Retry timeouts, connection errors, rate limits, and temporary server errors. Backoff spaces attempts apart and reduces another overload spike.