Sub topic 1
How LLM API Calls Fail: Client, Server, Network, and Content Errors
Prerequisites
This chapter assumes you can do the following:
- Write Python functions and handle exceptions with
tryandexcept. - Read HTTP status codes and headers.
- Call an LLM API at least once, either through a provider SDK or an HTTP client such as
httpx.
You don't need any retry logic yet. This chapter only teaches you to recognize and sort failures. Later chapters build the responses on top of that sorting.
Why classify failures first
Every reliability technique for LLM APIs starts from one question: what kind of failure is this? A retry fixes a dropped connection. It can't fix a malformed request, and it can make an overloaded server worse. If you treat all errors the same, you will either give up on failures that would have cleared or hammer the API with requests that can never succeed.
An LLM call has more ways to fail than an ordinary REST call:
- Responses are slow, often 5 to 60 seconds, so timeouts are common.
- Providers enforce limits on requests and on tokens.
- A request can succeed at the HTTP level and still return unusable output.
- Streaming adds failures that happen after the response has already started.
This chapter groups failures into four families: client, server, network, and content.
Client errors (4xx)
A client error means the server understood the request and rejected it. The usual cause is something your code sent. Most of these are permanent: sending the same request again returns the same error.
| Status | Typical meaning | Fix |
|---|---|---|
| 400 | Malformed request, bad parameter, or context window exceeded | Correct the request or shorten the prompt |
| 401 | Missing or invalid API key | Fix credentials |
| 403 | Key is valid but lacks permission, or the region or model is not allowed | Fix account or project access |
| 404 | Unknown model name or endpoint | Check the model identifier |
| 413 | Request body too large | Reduce the payload |
| 422 | Request is well formed but fails validation | Fix the field the error names |
| 429 | Rate limit or quota exceeded | Wait, then retry. See the next two chapters |
Two details trip people up.
First, 429 is a 4xx status but is usually temporary. It is the main exception to "client errors are permanent". Some providers also use 429 for an exhausted billing quota, which no amount of waiting fixes. Read the error body to tell a rate limit from a quota.
Second, "context length exceeded" arrives as a 400. The status says "bad request", and only the message names the real problem. Retrying is pointless, but trimming the prompt solves it.
Server errors (5xx)
A server error means the provider failed while handling a valid request. You can't fix it by changing the request, but it often clears on its own.
- 500 is an internal error. It is sometimes a one-off and sometimes a bug triggered by your input.
- 502 and 504 come from a gateway or proxy between you and the model server. They are usually transient.
- 503 means the service is unavailable or overloaded.
- 529 is used by some providers, such as Anthropic, to signal overload.
Server errors are generally worth retrying a limited number of times. They also tend to come in bursts during incidents. When many clients retry at once, the retries can prolong the incident. Later chapters cover backoff, jitter, and circuit breakers for this reason.
Network errors
A network error means no complete HTTP response arrived. There is no status code to inspect, so your HTTP library raises an exception instead.
Common causes:
- Connect timeout: the TCP or TLS connection could not be established.
- Read timeout: the connection opened but the server sent nothing for too long. This is the most common LLM failure, because generation is slow and the server may take a long time before sending its first byte.
- Connection reset or closed early: a load balancer dropped the connection, or the server restarted.
- DNS failure: the hostname could not be resolved.
A network error has an awkward property: you don't know whether the server processed the request. A read timeout may mean the model never started, or it may mean the answer was generated and lost on the way back. For a plain text completion, that uncertainty costs only some tokens. If your request triggers a tool call with side effects, it matters a lot. The idempotency chapter returns to this.
Content errors
A content error is a successful HTTP response (status 200) whose body is not what your application needs. These are the easiest failures to miss, because no exception is raised. Common forms:
- Truncation. The model hit your
max_tokenslimit mid-sentence. OpenAI-style APIs reportfinish_reason: "length". Anthropic reportsstop_reason: "max_tokens". - Content filtering. The provider blocked or cut the output. You may see
finish_reason: "content_filter", or a response with an empty message. - Refusal. The model declines the task. Some APIs mark this explicitly, such as a
refusalfield orstop_reason: "refusal", and others return it as ordinary text. - Invalid structured output. You asked for JSON and got prose, a trailing comma, or JSON cut off by truncation.
- Empty output. The response contains no text, for example when a reasoning model spends its whole token budget on hidden reasoning.
Content errors need different handling from the other three families. A blind retry may return the same refusal. A truncated answer needs a larger max_tokens or a shorter prompt. Invalid JSON can sometimes be fixed by retrying, because sampling is random, but a retry that repeats the same prompt at low temperature often returns the same mistake. Check for these cases explicitly after every successful call.
A first classifier
The following code sorts a status code or exception into a family and says whether retrying is plausible. It is deliberately simple. The next chapter refines the "retryable" decision.
import httpx
def classify(error: Exception) -> tuple[str, bool]:
"""Return (family, plausibly_retryable) for an httpx exception."""
if isinstance(error, httpx.HTTPStatusError):
status = error.response.status_code
if status in (408, 429):
return "client", True
if 400 <= status < 500:
return "client", False
if status >= 500:
return "server", True
if isinstance(error, httpx.TransportError):
# Timeouts, connection errors, and read errors all land here.
return "network", True
return "unknown", False
def classify_finish_reason(reason: str) -> str:
"""Map an OpenAI-style finish_reason to a content-error label."""
return {
"stop": "ok",
"tool_calls": "ok",
"length": "truncated",
"content_filter": "filtered",
}.get(reason, "unknown")
def status_error(code: int) -> httpx.HTTPStatusError:
request = httpx.Request("POST", "https://api.example.com/v1/chat")
response = httpx.Response(code, request=request)
return httpx.HTTPStatusError(f"HTTP {code}", request=request, response=response)
if __name__ == "__main__":
samples = [
status_error(400),
status_error(429),
status_error(503),
httpx.ReadTimeout("read timed out"),
ValueError("bug in our code"),
]
for err in samples:
print(type(err).__name__, classify(err))
for reason in ("stop", "length", "content_filter"):
print(reason, classify_finish_reason(reason))Running it prints client False for the 400, client True for the 429, server True for the 503, network True for the timeout, and unknown False for the ValueError. That last result is intentional. A bug in your own code should surface, not be retried.
Common mistakes
- Catching everything. A bare
except Exceptionretry loop retries401errors and your own typos. Classify first. - Treating 200 as success. Always inspect the finish reason and validate structured output.
- Ignoring the error body. The status code gives the family. The body names the cause, such as a context overflow versus a malformed field. Log the body.
- Assuming a timeout means failure. The server may have finished the work. Think about side effects before retrying.
- Using one timeout for everything. Connect and read phases fail differently and need separate limits. The timeouts chapter covers this.
Exercise
Your code calls a model and receives HTTP 200 with finish_reason: "length" and a JSON answer cut off mid-object. Which family is this, and should you retry the same request unchanged?
Show answer
This is a content error (truncation), not a network or server error. Retrying the same request unchanged will likely truncate again at the same max_tokens limit. Raise max_tokens, shorten the prompt or requested output, and then retry.
Exercise
A call raises a read timeout. Which family is it, and why is it riskier to retry when the request triggers a tool with side effects?
Show answer
It is a network error. A read timeout does not prove the server skipped the work. The server may have completed it and the response was lost, so a retry could repeat the side effect.