Sub topic 9
Handling errors, timeouts, and retries
This chapter assumes you can already send a chat completion to a local server with the OpenAI Python client. It also assumes you know the base URL and model name for your server. Here you will learn how the client reports failures, how to set timeouts and retries, and how to tell the common failures apart.
Why local servers fail differently
A hosted API rarely refuses a connection. A local server often does. The process may not be running, it may still be loading a model into memory, or it may listen on a different port than you expect. Requests can also take a long time. A first request may wait while the server loads the model, and a long answer on a CPU can take minutes.
So you need to decide three things: how long to wait, how often to retry, and what to do when a request still fails.
Configuring timeout and retries
The OpenAI client takes both settings when you create it.
timeoutis the number of seconds the client waits for the server before it gives up.max_retriesis how many times the client repeats a failed request. The default is 2.
The client retries on its own for connection errors, timeouts, and some status codes: 408, 409, 429, and any 5xx. It waits a short, growing delay between attempts. It does not retry a 404 or 400, because repeating them cannot help.
Pick a timeout that covers model loading. A value of 60 seconds is a reasonable start for small models on a GPU. Raise it for large models or CPU-only machines.
Catching errors by type
The client raises different exception classes. Catch the specific ones first and the general one last, because the specific classes are subclasses of the general 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.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.APIStatusError as e:
print(f"Server returned status {e.status_code}")APITimeoutError is a subclass of APIConnectionError. The first except branch therefore also catches timeouts. If you want a separate message for timeouts, put except openai.APITimeoutError before it.
What each failure usually means
| Exception | Typical cause on a local server | What to check |
|---|---|---|
| `APIConnectionError` | Server not running, wrong host or port | Start the server. Check the port in `base_url`. |
| `APITimeoutError` | Model still loading, or generation is slow | Raise `timeout`. Send a short warm-up request. |
| `NotFoundError` (404) | Model not downloaded, or the path is missing `/v1` | List models. Check the URL ends in `/v1`. |
| `BadRequestError` (400) | Unsupported parameter or a prompt longer than the context window | Remove optional parameters. Shorten the input. |
| `InternalServerError` (5xx) | Server ran out of memory or crashed | Read the server log. Try a smaller model. |
The flow of a failing request
Common mistakes
- Setting a short timeout such as 5 seconds, then seeing failures only on the first request. The model was loading. Raise the timeout or warm the model up first.
- Treating every error as retryable. A 404 for a missing model will fail every time. Fix the name instead.
- Setting a high
max_retriestogether with a long timeout. Each retry can wait the full timeout, so a failing call may block for minutes.
Overriding settings for one request
You can change the limits for a single call without building a new client.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
slow_client = client.with_options(timeout=300.0, max_retries=0)
response = slow_client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Write a long story."}],
)
print(response.choices[0].message.content)with_options returns a copy of the client. The original keeps its own settings.
Exercise
Your script works on the second run but always fails on the first run each morning with an APITimeoutError at 10 seconds. What is the likely cause, and what are two ways to fix it?
Show answer
The server unloads the model when idle, and the first request waits while the model loads, which takes longer than 10 seconds. Fix it by raising the client timeout, for example to 60 seconds or more, or by sending a short warm-up request before the real work and allowing it extra time.
Exercise
Why does a request with a misspelled model name fail immediately even though max_retries is 2?
Show answer
The server answers with a 404 status. The client does not retry 404 responses because repeating the same request returns the same result. The fix is to correct the model name.