Sub topic 3
Using Provider SDKs for Reliable LLM Calls
Assume you know Python, async/await, HTTP status codes, and how to call an LLM through an SDK. Provider SDKs often include retry behavior, so configure it before writing custom retry code.
Use the SDK's retry settings
An SDK can retry connection errors, timeouts, HTTP 408, 429, and many 5xx responses. Set both a retry limit and a request timeout. A timeout limits one request; your application should also enforce an overall deadline.
from openai import OpenAI
client = OpenAI(max_retries=5, timeout=20.0)
response = client.with_options(
max_retries=2,
timeout=10.0,
).chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say hello."}],
)
print(response.choices[0].message.content)Check your provider's documentation. Retry defaults and retryable errors differ between SDKs.
Stay under limits with client-side throttling
A rate limit restricts request volume or token volume. Requests per minute counts calls. Tokens per minute counts input and output tokens. A 429 response usually means one of these limits was exceeded.
Use a shared limiter before sending requests. Limit both concurrency and request rate. Count estimated tokens when the provider exposes token limits. This prevents bursts from creating avoidable 429 responses.
Handle failures during streaming
A stream can fail after producing partial text. Do not blindly append a restarted stream to the partial result. Either discard the incomplete answer and retry, or resume using a provider-supported mechanism. Tell the caller that the answer is incomplete when recovery is not safe.
Stop sustained outages
A circuit breaker opens after several failures. While open, it rejects calls quickly for a cool-down period. Afterward, it permits a probe request. A successful probe closes the breaker.
Degrade gracefully
A fallback can use a smaller model, a cached answer, or a reduced feature set. Make the fallback explicit and log which path served the response. Never hide a safety or authorization failure behind a fallback.
Observe and test failures
Log request ID, model, attempt number, status or exception type, delay, and final outcome. Avoid logging prompts or responses if they contain sensitive data. Measure retry count, 429 rate, timeout rate, breaker-open time, and fallback rate.
Test with simulated 429, timeout, 500, malformed responses, and a stream that ends early. Verify that permanent errors are not retried and that the maximum attempt count is honored.
Exercise
Why should a client throttle requests when the SDK already retries 429 responses?
Show answer
Throttling prevents bursts from exceeding the limit. Retries recover temporary failures, but they do not reduce the load that caused the 429 responses.