Sub topic 13
Troubleshooting common failures
This chapter assumes you can run a local model server such as Ollama, have at least one model downloaded, and have installed the openai Python package. It also assumes you have read the earlier chapters on the base URL, listing models, chat completions, and error handling. Here you will turn those pieces into a repeatable way to find out why a call fails.
Work from the outside in
Most failures fall into a small number of layers. Check them in order, from the network up to the model. Each check rules out one layer before you look at the next.
- Is the server process running and listening on the port you expect?
- Does the base URL, including the
/v1path, match what the server exposes? - Does the server list the model name you are sending?
- Does the request body use features the server supports?
- Does the request finish within your timeout?
Skipping ahead is the usual mistake. People tune prompts or sampling settings when the real problem is a wrong port.
Step 1: Is the server reachable?
Test the server without any Python. A plain curl call removes the client library from the picture.
curl -i http://localhost:11434/v1/modelsThe -i flag prints the status line and headers. Three outcomes are common.
| What you see | Meaning | Next step |
|---|---|---|
| `curl: (7) Failed to connect` | Nothing is listening on that host and port | Start the server or correct the port |
| `HTTP/1.1 200 OK` with JSON | The server and path are correct | Move to the model check |
| `HTTP/1.1 404 Not Found` | The server runs but the path is wrong | Check the `/v1` prefix |
In Python, a connection failure surfaces as openai.APIConnectionError. Note that the client retries connection errors before raising, so with max_retries=2 you wait for three attempts. If the error seems slow to appear, that is why.
Default ports differ between servers, so confirm yours rather than assuming.
| Server | Typical default port |
|---|---|
| Ollama | 11434 |
| llama.cpp `llama-server` | 8080 |
| LM Studio | 1234 |
| vLLM | 8000 |
Check the documentation of the version you run, since defaults can change and you can override them with flags.
Host problems
Several host problems look like a dead server.
- Server bound to localhost only. If the server runs on another machine, a default bind to
127.0.0.1refuses outside connections. Configure the server to listen on the interface you need, and think about who else on the network could then reach it. Most local servers have no authentication by default. - Container networking. Inside a Docker container,
localhostmeans the container itself. Use the host's address or the container network name instead. - IPv6 versus IPv4. On some systems
localhostresolves to::1while the server listens only on IPv4. Trying127.0.0.1explicitly settles this. - Proxy variables. If
HTTP_PROXYorHTTPS_PROXYis set, requests to a local address may be routed through the proxy and fail. SettingNO_PROXY=localhost,127.0.0.1fixes this.
Step 2: Is the base URL right?
The OpenAI client appends endpoint paths to the base URL. With base_url="http://localhost:11434/v1", a chat call goes to http://localhost:11434/v1/chat/completions. Two mistakes are common.
- Missing
/v1. Withbase_url="http://localhost:11434", the client requests/chat/completions, which does not exist on the server. You get a 404, and the client raisesopenai.NotFoundError. - Full endpoint in the base URL. Setting the base URL to
.../v1/chat/completionsmakes the client request.../v1/chat/completions/chat/completions. Also a 404.
A 404 does not tell you whether the path or the model is wrong, because both produce the same status. The error body usually tells you which. Print it.
import openai
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
try:
client.chat.completions.create(
model="no-such-model",
messages=[{"role": "user", "content": "Hello"}],
)
except openai.NotFoundError as e:
print(e.status_code)
print(e.response.text)Servers word this differently. Ollama, for instance, typically says that the model was not found and suggests pulling it, while a wrong path often returns a generic "not found" or an empty page. Read the text rather than guessing from the status code alone.
A short helper that checks the setup before real work saves time:
import openai
from openai import OpenAI
def check_server(base_url: str, api_key: str = "local") -> list[str]:
client = OpenAI(base_url=base_url, api_key=api_key, timeout=5.0, max_retries=0)
try:
return [m.id for m in client.models.list()]
except openai.APIConnectionError:
raise SystemExit(f"Cannot connect to {base_url}. Is the server running?")
except openai.NotFoundError:
raise SystemExit(f"{base_url} answered 404. Check that it ends in /v1.")
except openai.APIStatusError as e:
raise SystemExit(f"Server returned status {e.status_code}: {e.response.text}")
if __name__ == "__main__":
print(check_server("http://localhost:11434/v1"))The short timeout and max_retries=0 make the check fail fast instead of waiting through retries.
Step 3: Is the model available?
A model name must match what the server reports, character for character. Common mismatches:
- Missing tag. Ollama names often carry a tag, such as
llama3.2:latestorllama3.2:3b. A bare name usually resolves tolatest, but a name that exists only under another tag will not. - Not downloaded. The model is known by name but not on disk. With Ollama, run
ollama pull llama3.2. Do not expect the server to download it for you during a request. - Not loaded. Servers such as
llama-serverserve the model passed at startup, and some ignore themodelfield. Others, such as LM Studio, may need the model loaded in the application first. - Wrong kind of model. Sending an embedding model to the chat endpoint, or a chat model to the embeddings endpoint, fails or returns poor results. In the embeddings example,
nomic-embed-textis an embedding model and cannot answer chat messages.
List the IDs with the call from the earlier chapter and copy one exactly.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
for m in client.models.list():
print(repr(m.id))Printing with repr exposes stray whitespace or case differences that are hard to see otherwise.
Step 4: Does the request use unsupported features?
Local servers implement a subset of the hosted API, as covered in the chapter on compatibility differences. When a request that works with a bare prompt breaks after you add a parameter, suspect that parameter.
Bisect the request. Start from the smallest working call and add one field at a time.
- Send one user message and nothing else.
- Add the system message.
- Add
temperatureandmax_tokens. - Add
stream=True. - Add structured output or tool definitions.
The step where it breaks names the cause. Typical symptoms:
- A 400 status often means the server rejected a field it does not accept or a value out of range.
- A silently ignored field is harder to spot. The call succeeds, but the output ignores your
response_formator tool list. Check the content of the reply, not only the status. - A malformed tool call. Small models may produce a tool call as plain text, or JSON that does not parse. Validate with
json.loadsand handle failure.
Step 5: Timeouts and slow responses
Local inference is bounded by your hardware. The first request after startup is often much slower than later ones because the server loads the model into memory. A 60-second timeout that works on a warm server may fail on a cold one.
A timeout raises openai.APITimeoutError, which is a subclass of APIConnectionError. Catch the timeout first if you want to treat it differently:
import openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=120.0,
max_retries=1,
)
try:
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Summarize what a timeout is."}],
max_tokens=150,
)
print(response.choices[0].message.content)
except openai.APITimeoutError:
print("Timed out. The model may still be loading, or the prompt is too long.")
except openai.APIConnectionError:
print("Cannot reach the server.")If timeouts persist, work through these causes:
- Cold start. Send a tiny request first to warm the model, then time the real one.
- Model too large for memory. If the model spills to disk or runs on CPU only, generation can be very slow. Try a smaller or more heavily quantized model.
- Long prompt. Processing time grows with prompt length. Shorten the history or the input.
- Large
max_tokens. Generation runs until it hits a stop token or the cap. Lower the cap while testing. - Streaming as a diagnostic. With
stream=True, you see whether the server is producing tokens slowly or not starting at all. A long pause before the first chunk points to loading or prompt processing. A steady slow trickle points to slow generation.
Note that for streaming, the client timeout applies to the wait between reads, not to the whole response, so a long stream can outlast it.
Other symptoms
| Symptom | Likely cause | What to try |
|---|---|---|
| Reply cuts off mid-sentence | `max_tokens` reached | Check `finish_reason`. A value of `length` confirms it. Raise the cap |
| Reply ignores earlier turns | History not resent | Send the full `messages` list each time |
| Model forgets the start of a long chat | Prompt exceeded the context window | Trim older messages, or raise the server's context size if it allows |
| Empty `content` | A tool call was returned, or generation stopped immediately | Inspect `message.tool_calls` and `finish_reason` |
| Authentication error from a local server | Server started with a key requirement | Pass the key it expects |
| Error mentioning the OpenAI key when no key was given | `api_key` missing and no `OPENAI_API_KEY` set | Pass a placeholder explicitly |
| Requests go to the hosted API by accident | `base_url` not set, or an environment variable overrides it | Set `base_url` in code, and check `OPENAI_BASE_URL` |
That last row matters for privacy. If base_url is omitted, the client targets the hosted service. Check the variable your shell exports, and make the destination explicit in code when the data must stay local.
Read the server logs
The client shows only what came back. The server log shows what it received and why it refused. Run the server in a terminal where you can watch it, or open its log view. Logs typically reveal:
- The exact path requested, which exposes a wrong base URL.
- Model load messages and memory errors.
- Parameter validation failures with the field name.
- Context-length truncation warnings.
When you ask for help, include the server name and version, the base URL, the failing request body, the full error text, and the relevant log lines.
A reusable debugging checklist
import json
import sys
import openai
from openai import OpenAI
BASE_URL = "http://localhost:11434/v1"
MODEL = "llama3.2"
client = OpenAI(base_url=BASE_URL, api_key="local", timeout=120.0, max_retries=0)
try:
ids = [m.id for m in client.models.list()]
print("models:", ids)
if MODEL not in ids:
sys.exit(f"{MODEL!r} is not in the list. Use one of the IDs above.")
reply = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Reply with the word ok."}],
max_tokens=10,
)
choice = reply.choices[0]
print("content:", json.dumps(choice.message.content))
print("finish_reason:", choice.finish_reason)
except openai.APITimeoutError:
sys.exit("Timeout: the model may be loading, or generation is slow.")
except openai.APIConnectionError:
sys.exit("Connection failed: check that the server runs and the host and port are right.")
except openai.NotFoundError as e:
sys.exit(f"404: {e.response.text}")
except openai.APIStatusError as e:
sys.exit(f"HTTP {e.status_code}: {e.response.text}")This script lists the models, confirms yours is present, makes a minimal chat call, and prints the finish reason. If it passes, the server, path, and model are healthy, and any later failure comes from the request you added on top.
Exercise
Your code sets base_url="http://localhost:11434" and calls client.chat.completions.create(...). The server is running and the model is downloaded, but you get openai.NotFoundError. What is the most likely cause, and how do you confirm it?
Show answer
The base URL lacks the /v1 prefix, so the client requests /chat/completions, which the server does not serve. Confirm by running curl -i http://localhost:11434/v1/models (it should return 200) and by reading e.response.text or the server log to see the requested path. Fix it by setting base_url="http://localhost:11434/v1".
Exercise
A request works when you send one user message, but fails with a 400 after you add response_format and a tools list. What method do you use to find the cause, and what else can go wrong when the call succeeds?
Show answer
Bisect the request. Start from the smallest working call and add one field at a time until the failure returns; the last field added is the cause. When the call succeeds, the server may still have ignored the field, so check the reply content, such as whether it is valid JSON or whether message.tool_calls is populated, and not only the status code.
Exercise
The first request after starting the server times out at 60 seconds, but later requests finish in two seconds. Why, and what are two ways to handle it?
Show answer
The first request includes the time to load the model into memory. Warm the model with a tiny request before the real one, or raise the client timeout (for example to 120 seconds) so the cold start can finish. Using stream=True also helps show whether the delay is before the first token.