An LLM call can fail as a transport error, a rate limit, a content filter, a context-length overflow, a refusal, or malformed output that returns HTTP 200 and is semantically wrong. Each class needs its own handling.
Routing failures by status and finish reason
| Failure | Response |
|---|---|
429 too many requests | Back off, then retry, so the service can recover. A 429 for an exhausted quota will not clear on retry, so check the error body |
400 with context_length_exceeded | Truncate or summarize the input, then re-issue |
| Content filter block | Fall back, for example to a human operator. Retrying the same request will likely fail again |
| 200 OK with output that breaks the schema | Validate, then re-ask the model with the validation error appended |
Check the HTTP status first. For every failure, log the raw response and the finish reason, so a truncated response is never read as a complete answer.
HTTP 200 with malformed output
Typed exception hierarchies are the usual software model: catch each type and handle it. LLM calls add a case that no exception covers. The response is 200 OK, the content is wrong, and nothing throws. The status code gives no signal, so the system must validate the output itself.
Libraries such as Pydantic and Instructor validate structure and can retry on a parse failure.
Why a blanket retry fails
A single try/except: retry treats all errors the same. It cannot tell a retryable error from one that cannot succeed, such as a moderation block or a schema mismatch. The result is a loop on an error that never clears, or a truncated answer passed on as complete. The cause is missing per-class handling.
Consider the content-filter row. Resending the identical prompt repeats the block, so a retry there only adds load and delay. Context overflow and rate limits are different: the request itself can succeed once the input is shorter or the call is spaced out.
Repair loops and retry caps
- For structured-output pipelines, combine schema validation with a repair loop and a retry cap, so retries cannot run forever.
- For free-form chat, concentrate on finish reasons and on handling refusals.
With this in place, recoverable failures retry automatically and unrecoverable ones escalate to a fallback or a person.
Malformed output on 15% of calls
Example scenario: 15% of calls return HTTP 200 with malformed output. The figure is illustrative.
The response meets the API contract but fails the semantic expectation, possibly because ambiguous or unexpected input confused the model.
- Check the logs for the inputs that led to malformed output.
- Measure the frequency of malformed output across input types.
- Test variations of the problematic inputs to find patterns.
Stricter validation and input preprocessing reduce ambiguity, at a small cost in latency. Track the malformed-output rate and user feedback.