Sub topic 11
Using OpenAI-compatible clients against Ollama
Many tools and libraries already know how to talk to OpenAI's API. Ollama exposes a compatible endpoint, so you can often point existing code at your own machine by changing a URL. This chapter shows how that works, what it covers, and where it stops.
This chapter assumes you have a running Ollama server on localhost:11434, a pulled llama3.2 model, and the native /api/chat call from the REST API chapter. It also assumes basic Python and pip.
How the compatibility layer works
Ollama serves two families of routes from the same port. The native routes start with /api. The compatible routes start with /v1 and follow the shape of OpenAI's API. Ollama accepts an OpenAI-style request, converts it to its own internal request, runs the model, and converts the result back.
Nothing leaves your computer. The client library never contacts OpenAI when its base URL points at localhost.
Supported endpoints
The main routes are:
| Route | Purpose |
|---|---|
| `/v1/chat/completions` | Chat with message roles, streaming, and tools |
| `/v1/completions` | Plain prompt completion |
| `/v1/models` | List local models |
| `/v1/embeddings` | Generate embedding vectors |
Ollama adds and changes supported fields between releases. Treat the documentation for your installed version as the final word on any specific field.
The minimal Python client
Install the official library with pip install openai. Then change two settings: the base URL and the API key.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
result = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Give me one tip for writing clear commit messages."}],
)
print(result.choices[0].message.content)The client library requires an API key and refuses to start without one. Ollama ignores the value, so any non-empty string works. The model field must match a name from ollama list.
Configuring through environment variables
The OpenAI Python library also reads OPENAI_BASE_URL and OPENAI_API_KEY from the environment. This lets you redirect an existing program without editing its source.
export OPENAI_BASE_URL=http://localhost:11434/v1
export OPENAI_API_KEY=ollama
python your_existing_script.pyThe script must create its client with no explicit arguments, as in OpenAI(). If it hard-codes a base URL, the environment variables have no effect.
Using curl against the v1 route
Testing with curl removes the client library from the picture. This helps when you need to tell a library bug from a server problem.
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "llama3.2",
"messages": [
{"role": "system", "content": "You answer in one short sentence."},
{"role": "user", "content": "What is quantization?"}
]
}'The response uses OpenAI's layout. The text is at choices[0].message.content, not at the top-level message.content of the native API. Token counts appear under usage.
curl http://localhost:11434/v1/modelsThis returns the models you have pulled, in OpenAI's list format. Many third-party tools call this route to fill a model dropdown.
Streaming
Streaming in the compatible API uses server-sent events, not the newline-delimited JSON of the native API. Each event is a line beginning with data: , and the stream ends with data: [DONE]. The Python client hides this format from you.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "List three uses of a local LLM."}],
stream=True,
)
for chunk in stream:
if not chunk.choices:
continue
piece = chunk.choices[0].delta.content
if piece:
print(piece, end="", flush=True)
print()Two guards matter here. Some chunks have an empty choices list, and the final content delta can be None. Without the checks, the loop may crash on the last chunk.
Embeddings
The embeddings route uses the same client. You need an embedding model, which differs from a chat model. Pull one first with ollama pull nomic-embed-text.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
response = client.embeddings.create(
model="nomic-embed-text",
input=["local models", "open-weight inference"],
)
for item in response.data:
print(len(item.embedding))Each input string yields one vector. Always embed documents and queries with the same model. Vectors from different models cannot be compared.
What the compatible API does not cover
The compatibility layer is a subset. Expect these gaps:
- Context size. You cannot set
num_ctxthrough an OpenAI request. The model uses the default, or whatever its Modelfile sets. If long prompts get truncated, build a model with a largernum_ctxand request that model by name. - Ollama-only options. Settings such as
keep_aliveandtop_kbelong to the native API. Compatible requests may ignore or reject them, depending on version. - Unsupported fields. Some OpenAI parameters, such as
logit_bias, have no effect. A field that is silently ignored will not raise an error, so a successful response does not prove the setting worked. - Model-dependent features. Tool calling, JSON output, and image input only work when the chosen model supports them. A small model may accept a tools list and still produce poor calls.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Connection error` | Server not running, or wrong port | Run `ollama ps` or open `http://localhost:11434` in a browser |
| `404` with "model not found" | Name is not pulled locally | Check `ollama list`, then `ollama pull` the exact name |
| `404` on the route | Base URL lacks `/v1` | Use `http://localhost:11434/v1` |
| Missing key error from the client | No `api_key` set | Pass any non-empty string |
| Replies cut off or forget earlier text | Default context window too small | Create a model with a larger `num_ctx` |
The missing /v1 is the most frequent mistake. The client appends /chat/completions to whatever base URL you give it. Without /v1, it requests a route Ollama does not serve.
Choosing between native and compatible APIs
Use the compatible route when you have existing code, libraries, or tools built for OpenAI, or when you want to move between local and hosted models easily. Use the native API when you need Ollama-specific controls such as keep_alive, per-request options, or model management calls like pulling and deleting. Both talk to the same server and the same loaded model, so you can mix them in one project.
Exercise
A script uses OpenAI(base_url="http://localhost:11434", api_key="ollama") and fails with a 404 on every call, although curl http://localhost:11434/api/chat works. What is wrong, and how do you fix it? Also name one thing you cannot control through this client that you would set in a Modelfile.
Show answer
The base URL is missing the /v1 suffix. The client appends /chat/completions, producing a route Ollama does not serve. Change the base URL to http://localhost:11434/v1. The context window (num_ctx) cannot be set through the OpenAI-compatible request. Set it in a Modelfile with PARAMETER num_ctx, create the model, and request that model by name.
Exercise
Why does a streaming loop over chunk.choices[0].delta.content sometimes crash on the final chunk, and what two checks prevent it?
Show answer
The final chunk may have an empty choices list, and the last delta's content can be None. Check that chunk.choices is non-empty before indexing, and check that content is truthy before printing it.