Sub topic 9
Handling errors, timeouts, and retries
This chapter covers how requests to a local OpenAI-compatible server fail, how the OpenAI Python client reports each failure, and how to set timeouts and retries so your program recovers from temporary problems without hiding real ones.
It assumes you can already send a chat completion to your local server, as in the earlier chapters. It also assumes you know the basics of Python exceptions and HTTP status codes. The examples use Ollama on port 11434 with the llama3.2 model. Change the base URL and model name to match your server.
Why local servers fail differently
A hosted API fails mostly because of quotas, outages, and network paths you do not control. A local server fails for different reasons:
- The server process is not running, or is still starting.
- The base URL has the wrong port or is missing the
/v1path. - The model name does not match a model that has been downloaded.
- The model is loading into memory, so the first request is slow.
- The machine runs out of memory or GPU memory in the middle of a request.
- A long generation on slow hardware takes longer than your timeout.
Most of these are not bugs in your code. They are states of the machine. Good error handling separates problems that a retry can fix from problems that need a person to change something.
The exception hierarchy
The OpenAI Python client raises exceptions that all inherit from openai.OpenAIError. The ones you will meet with a local server fall into two branches.
The two branches mean different things.
APIConnectionErrormeans no usable HTTP response arrived. The server is down, the port is wrong, DNS failed, or the connection dropped.APITimeoutErroris a subclass that means the request took longer than the timeout.APIStatusErrormeans the server answered with a 4xx or 5xx status. The exception carriesstatus_code,response, and usually abodywith the server's error message.
Because APITimeoutError is a subclass of APIConnectionError, you must catch it first if you want to treat it differently.
Common status codes from local servers
| Status | Client exception | Typical local cause |
|---|---|---|
| 400 | `BadRequestError` | Malformed JSON, a parameter the server rejects, or a prompt longer than the context window |
| 404 | `NotFoundError` | Wrong model name, or a base URL missing `/v1` |
| 422 | `UnprocessableEntityError` | Valid JSON with a field of the wrong type (common in vLLM) |
| 429 | `RateLimitError` | Rare locally. Some servers return it when all request slots are busy |
| 500 | `InternalServerError` | The model crashed or ran out of memory during generation |
| 503 | `InternalServerError` | The server is up but the model is still loading |
Exact codes vary between servers. Treat this table as a starting point and read the error body from your own server.
Catching errors in order
Put the most specific exceptions first. Python uses the first matching except clause, so a general class placed too early hides the specific ones.
import openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=60.0,
max_retries=2,
)
try:
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)
except openai.APITimeoutError:
print("The request timed out. The model may be loading or the prompt is large.")
except openai.APIConnectionError:
print("Cannot reach the server. Is it running, and is the base URL correct?")
except openai.NotFoundError:
print("The server returned 404. Check the model name and the /v1 path.")
except openai.BadRequestError as e:
print(f"The server rejected the request: {e.message}")
except openai.APIStatusError as e:
print(f"Server returned status {e.status_code}: {e.response.text}")The last clause prints e.response.text. For a local server this is often the most useful diagnostic you have, because the server usually names the exact problem, such as model 'llama3.3' not found.
Timeouts
A timeout is the longest the client waits before giving up. The default in the OpenAI client is 600 seconds (10 minutes). That is far too long for an interactive tool, but it can be too short for a large model on a CPU.
You can pass a plain number of seconds, which applies to each phase of the request. For finer control, use httpx.Timeout.
import httpx
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=httpx.Timeout(120.0, connect=5.0),
)This sets a 5-second limit to open the connection and 120 seconds for the other phases (write, read, and pool). The split matters locally.
- Connect timeout. If the server is on
localhostand running, a connection succeeds in milliseconds. A short connect timeout makes a stopped server fail fast. - Read timeout. This is the longest gap between bytes from the server. For a non-streaming request, the server sends nothing until the whole answer is ready, so the read timeout must cover the full generation time. For a streaming request, bytes arrive steadily, so a smaller read timeout is enough once the first token has appeared.
You can also override the timeout for one call without changing the client:
response = client.with_options(timeout=300.0).chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Summarize the history of Rome."}],
max_tokens=800,
)The cold-start problem
Servers such as Ollama load a model into memory on the first request and unload it after a period of inactivity. That first request can take many seconds while weights are read from disk. A timeout tuned on a warm model can then fail on the first call of the day.
There are three practical answers:
- Set a generous read timeout for the first call, then use a tighter one afterward.
- Send a small warm-up request when your application starts.
- Configure the server to keep the model loaded longer, if it supports that.
Retries
The client retries some failures automatically. The max_retries option defaults to 2, so a request can be attempted up to three times. Between attempts it waits with exponential backoff, which means the delay grows after each failure, with a small random jitter.
The client retries these conditions:
- Connection errors
- Request timeouts (408)
- Conflicts (409)
- Rate limits (429)
- Server errors (500 and above)
It does not retry 400, 401, 403, 404, or 422, because repeating the same bad request returns the same result.
You can change the count on the client or for a single call:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local", max_retries=0)
response = client.with_options(max_retries=4).chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)When automatic retries are not enough
The built-in retries last only a few seconds. If the server is restarting or loading a model, you may want to wait longer. Write your own loop around the call and retry only the errors that can clear on their own.
import time
import openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=60.0,
max_retries=0,
)
def chat_with_retry(messages, model="llama3.2", attempts=5, base_delay=1.0):
for attempt in range(1, attempts + 1):
try:
return client.chat.completions.create(model=model, messages=messages)
except (openai.APIConnectionError, openai.InternalServerError) as e:
if attempt == attempts:
raise
delay = base_delay * 2 ** (attempt - 1)
print(f"Attempt {attempt} failed ({type(e).__name__}). Retrying in {delay:.0f}s.")
time.sleep(delay)
reply = chat_with_retry([{"role": "user", "content": "Hello"}])
print(reply.choices[0].message.content)The loop sets max_retries=0 on the client so the two layers do not multiply. It retries connection failures, timeouts, and 5xx errors. It lets 400 and 404 errors pass straight up, because they need a code or configuration change.
Retrying a 500 from an out-of-memory crash can make things worse. If the server dies on every large prompt, repeated attempts only repeat the crash. Cap the attempts and log the error body.
Errors during streaming
With stream=True, the request can fail in two places.
- Before the first chunk. The call to
createraises the same exceptions as before, and the client's automatic retries apply. - After some chunks have arrived. The connection can drop partway through. The client raises an exception while you iterate, and it does not retry, because part of the answer has already been delivered.
Wrap the loop, not only the call, and keep what you received so far.
import openai
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
parts = []
try:
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Write a haiku about servers."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
text = chunk.choices[0].delta.content
parts.append(text)
print(text, end="", flush=True)
except openai.APIError as e:
print(f"\nStream interrupted: {type(e).__name__}")
partial = "".join(parts)
print(f"\nReceived {len(partial)} characters.")Decide in advance what a partial answer means for your program. Showing it with a marker may be fine for a chat window. Using it as input to a parser is usually a bug.
Errors inside a successful response
An HTTP 200 does not guarantee a complete answer. Check finish_reason on the choice.
| `finish_reason` | Meaning | What to do |
|---|---|---|
| `stop` | The model ended naturally | Use the answer |
| `length` | The `max_tokens` cap or the context window cut it off | Raise `max_tokens`, shorten the prompt, or accept the truncation |
| `tool_calls` | The model asked to call a tool | Handle the tool call |
Truncation is the most common silent failure on local models, because many servers use a small default context window. A reply that stops in the middle of a sentence usually has finish_reason == "length".
choice = response.choices[0]
if choice.finish_reason == "length":
print("Warning: the reply was cut off.")Logging for diagnosis
When a failure is not obvious, turn on the client's debug logging. It prints the request URL, headers (with the key redacted), and response status.
export OPENAI_LOG=debug
python app.pyThe URL in the log shows immediately whether the request went to /v1/chat/completions or to a wrong path.
Which failures to retry
Exercise
Your program calls client.chat.completions.create(model="llama3.2", ...) with timeout=30.0 and max_retries=2 against a server that is hung and never answers. About how long can the call block before it raises an exception, and which exception do you expect?
Show answer
Up to roughly 90 seconds, because there are three attempts of 30 seconds each, plus short backoff delays between them. The final exception is openai.APITimeoutError, which is a subclass of openai.APIConnectionError.
Exercise
A request returns HTTP 200, and the reply ends mid-sentence. Which field do you check, and which value confirms the cause?
Show answer
Check response.choices[0].finish_reason. The value "length" confirms the reply was cut off by max_tokens or the context limit. Raise max_tokens or shorten the prompt.
Exercise
Why does the custom retry function set max_retries=0 on the client, and why does it not retry NotFoundError?
Show answer
With max_retries=0 the client does no retries of its own, so the custom loop controls the total number of attempts and the total wait. Without it, each of your attempts would trigger up to two more inside the client. A 404 means the model name or path is wrong, and sending the same request again returns the same 404, so the code or configuration has to change instead.