AI and machine learning · Beginner · 16 min
Call any OpenAI-compatible API from Python
By Padding · Updated 26 Nov 2026
Ubuntu 26.04 · Ollama 0.40.18 · qwen3:0.6b · Python 3.15 · openai (Python) 3.60.0
You will point the openai Python SDK at a local Ollama model through its /v1 endpoint, list models, send and stream chat completions, read token usage and handle errors, with the base URL, key and model kept in environment variables so a provider switch is a config change.
On this page
OpenAI's Chat Completions API became a de facto wire format. Many other servers accept the same requests and send back the same JSON: Ollama and llama.cpp on your own machine, vLLM on a GPU server, and a number of hosted providers. If your code speaks that format, you can move between them by changing three settings: the base URL, the API key and the model name.
In this tutorial you use the official openai Python package, version 3.60, against Ollama's OpenAI-compatible endpoint at http://127.0.0.1:11434/v1. The model is qwen3:0.6b, a 0.6-billion-parameter model small enough for a laptop CPU. You build a small module that reads its settings from the environment, then use it to list models, send a chat request, stream a reply, read the token counts and handle the errors a real provider will give you.
A local model costs nothing per request once it is downloaded. If you pay for mobile data by the gigabyte, as many developers in Lagos, Accra or Nairobi do, that makes it a good place to practise, and the same code then runs against a hosted provider when you need a bigger model.
Step 1 · Pull the model and find the /v1 endpoint
Check that Ollama is running and download the model. It is about 520 MB, so on a metered connection start the download while you are on Wi-Fi:
ollama --version
ollama pull qwen3:0.6bOllama has its own API under /api, and an OpenAI-compatible one under /v1. Ask the second for its list of models with curl, before any Python is involved:
curl -fsS http://127.0.0.1:11434/v1/modelsCheck it worked
ollama --version prints something like ollama version is 0.40.18. The curl command prints one line of JSON shaped like OpenAI's model list: {"object":"list","data":[{"id":"qwen3:0.6b","object":"model",...}]}. If you see Connection refused, Ollama is not running; start it as in the Ollama tutorial and try again.
Step 2 · Create the project and install the SDK
Create a throwaway project folder with Python 3.15 and the openai package. The exact pin stops a new release from changing the client under you:
mkdir -p ~/openai-compat-demo
cd ~/openai-compat-demo
uv init --no-package --python 3.15
uv add "openai==3.60.0"Check it worked
uv run python -c "import sys, openai; print(sys.version.split()[0], openai.__version__)"The output is a 3.15 version number and 3.60.0.
Step 3 · Keep the provider in environment variables
Three values decide which server you talk to. Put them in environment variables, not in code, so that moving from Ollama to another provider never needs an edit:
export LLM_BASE_URL="http://127.0.0.1:11434/v1"
export LLM_API_KEY="ollama"
export LLM_MODEL="qwen3:0.6b"Ollama ignores the key, but the SDK refuses to build a client without one, so any non-empty value works here. For a hosted provider the key is a real secret; the last step shows how to set it without leaving it in your shell history.
The names start with LLM_ on purpose. The SDK reads OPENAI_API_KEY and OPENAI_BASE_URL by itself if you pass nothing. If you keep a real OpenAI key in OPENAI_API_KEY and point the base URL at another company's server, that key goes to the other company with every request. Your own variable names, passed explicitly, make that mistake impossible.
Create llm.py, the one place that knows how to build a client:
cat > llm.py <<'PY'
import os
from openai import OpenAI
def setting(name):
value = os.environ.get(name, "").strip()
if not value:
raise SystemExit(f"Set {name} first, for example: export {name}=...")
return value
def make_client(max_retries=2):
return OpenAI(
base_url=setting("LLM_BASE_URL"),
api_key=setting("LLM_API_KEY"),
timeout=60.0,
max_retries=max_retries,
)
def model_name():
return setting("LLM_MODEL")
PYThe timeout is generous because a small CPU can take a while to load a model on the first request. max_retries=2 is the SDK's default, written out so you can see it: on a dropped connection, a timeout, a 429 or a 5xx, the client waits and tries again before it raises.
Check it worked
uv run python -c "from llm import make_client, model_name; c = make_client(); print(c.base_url, model_name())"
env -u LLM_MODEL uv run python -c "from llm import model_name; model_name()" || echo "refused as expected"The first line prints the base URL and model, something like http://127.0.0.1:11434/v1/ qwen3:0.6b. The second command runs without LLM_MODEL and prints Set LLM_MODEL first, for example: export LLM_MODEL=... followed by refused as expected. A clear message at start-up beats a confusing error from the server later.
Step 4 · List the models the server offers
Every compatible server answers GET /models, and the SDK wraps it as client.models.list(). It is the cheapest way to check that the base URL and key are right, because it does not run a model:
cat > models.py <<'PY'
from llm import make_client, model_name
client = make_client()
ids = sorted(m.id for m in client.models.list())
for model_id in ids:
print(model_id)
wanted = model_name()
print("configured model available:", wanted in ids)
PY
uv run models.pyCheck it worked
The output lists qwen3:0.6b, plus any other models you have pulled, and ends with configured model available: True. A hosted provider lists its own model names here, which is where you find the exact string to put in LLM_MODEL.
Step 5 · Send a chat completion and read the usage
Create chat.py. It sends a system message and a user message, then prints the reply, why the model stopped, and the token counts:
cat > chat.py <<'PY'
import sys
from llm import make_client, model_name
client = make_client()
question = " ".join(sys.argv[1:]) or "Name three uses for a solar lantern, one line each."
response = client.chat.completions.create(
model=model_name(),
messages=[
{"role": "system", "content": "You answer in plain English, briefly."},
{"role": "user", "content": question},
],
temperature=0,
seed=42,
max_tokens=200,
extra_body={"reasoning_effort": "none"},
)
choice = response.choices[0]
text = (choice.message.content or "").strip()
if choice.finish_reason == "length" and not text:
print("The model used up max_tokens before writing an answer. Raise max_tokens.")
else:
print(text)
if choice.finish_reason == "length":
print("[answer cut off at max_tokens]")
usage = response.usage
print(f"finish_reason={choice.finish_reason} prompt={usage.prompt_tokens} "
f"completion={usage.completion_tokens} total={usage.total_tokens}")
PY
uv run chat.pyA few parts of this request are worth knowing:
temperature=0andseed=42make repeated runs give the same answer, which helps when you are testing code rather than the model. Not every provider honoursseed.max_tokenscaps the reply length and so the cost. Models that think before answering spend part of that budget on hidden reasoning, and a reply can stop withfinish_reasonlengthand no text at all. The script handles that case instead of printing an empty line.extra_bodyadds fields to the JSON the SDK sends. Use it for settings one provider understands and another does not. Herereasoning_effort: "none"asks Ollama to switch Qwen3's thinking off. Keep such fields in one place, because they are what you review when you change provider.usageis how hosted providers bill you: you pay for prompt tokens and completion tokens, often at different rates. Log it from the first day.
Check it worked
uv run chat.py "Reply with one short sentence about Python." | tee chat-out.txt
grep -E '^finish_reason=(stop|length) prompt=[1-9][0-9]* completion=[1-9][0-9]* total=[1-9][0-9]*$' chat-out.txtYou see a short answer, then a line such as finish_reason=stop prompt=31 completion=18 total=49. Your numbers and the wording will differ, and a model this small gets facts wrong, so read the answer before you rely on it. total is always the sum of the other two.
Step 6 · Stream the reply as it is written
Waiting for the whole reply feels slow in a chat window. With stream=True the server sends the answer in small chunks as the model produces them. Ask for usage too, with stream_options, because a stream has no response.usage at the end:
cat > stream.py <<'PY'
import sys
from llm import make_client, model_name
client = make_client()
question = " ".join(sys.argv[1:]) or "Explain in three sentences what an API key is."
stream = client.chat.completions.create(
model=model_name(),
messages=[{"role": "user", "content": question}],
temperature=0,
seed=42,
max_tokens=200,
stream=True,
stream_options={"include_usage": True},
extra_body={"reasoning_effort": "none"},
)
chunks = 0
usage = None
for chunk in stream:
if chunk.usage:
usage = chunk.usage
for choice in chunk.choices:
piece = choice.delta.content or ""
if piece:
chunks += 1
print(piece, end="", flush=True)
print()
print(f"chunks={chunks}")
if usage:
print(f"prompt={usage.prompt_tokens} completion={usage.completion_tokens}")
else:
print("this server did not send usage for the stream")
PY
uv run stream.pyEach chunk holds a delta with a few characters of text, and flush=True puts them on screen at once. The usage arrives in one extra chunk at the very end, whose choices list is empty; that is why the loop checks chunk.usage separately and loops over choices instead of reading choices[0].
Check it worked
uv run stream.py "Count from one to five in words." | tee stream-out.txt
grep -E '^chunks=[2-9]|^chunks=[1-9][0-9]+' stream-out.txt
grep -E '^prompt=[1-9][0-9]* completion=[1-9][0-9]*$' stream-out.txtThe text appears a few words at a time rather than all at once, followed by a chunks= line with a number above one and a prompt=... completion=... line. If a provider prints this server did not send usage for the stream, it ignores stream_options, and you need its own documentation for counting tokens.
Step 7 · Handle the errors a provider gives you
Two kinds of failure matter. The server can answer with an error status, such as 404 for a model it does not have or 401 for a bad key, and the SDK raises APIStatusError (or a subclass such as NotFoundError). Or no answer comes back at all, and the SDK raises APIConnectionError. Create errors.py to trigger both:
cat > errors.py <<'PY'
import os
import openai
from openai import OpenAI
def ask(client, model):
try:
client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "Hi"}],
max_tokens=5,
)
print("ok")
except openai.APIStatusError as err:
print(f"server said {err.status_code}: {type(err).__name__}")
except openai.APIConnectionError as err:
print(f"no answer: {type(err).__name__}")
key = os.environ["LLM_API_KEY"]
good_server = OpenAI(base_url=os.environ["LLM_BASE_URL"], api_key=key, max_retries=0)
ask(good_server, "no-such-model:1b")
wrong_port = OpenAI(base_url="http://127.0.0.1:9/v1", api_key=key, max_retries=0, timeout=5.0)
ask(wrong_port, os.environ["LLM_MODEL"])
PY
uv run errors.pyBoth clients set max_retries=0 so the demonstration fails at once. In your real code keep the retries: they absorb short outages and rate limits. Both are subclasses of openai.APIError, so you can catch that one class if you only need a single handler. The SDK retries only timeouts, connection errors, 408, 409, 429 and 5xx responses, so a 404 fails at once, and asking again with the same model name will not help.
Check it worked
uv run errors.py | tee errors-out.txt
grep -E '^server said 4[0-9][0-9]: ' errors-out.txt
grep -x 'no answer: APIConnectionError' errors-out.txtThe output is two lines: server said 404: NotFoundError for the missing model, and no answer: APIConnectionError for port 9, where nothing listens. Hosted providers add 401 (bad key), 429 (rate limit or no credit left) and 5xx (their side). The err.response object holds the body, which usually explains the problem in words.
Step 8 · Switch provider by changing the settings
Nothing in models.py, chat.py or stream.py names Ollama. Prove it by overriding the settings for a single command, here with localhost in place of 127.0.0.1, and ask the same question as before:
LLM_BASE_URL="http://localhost:11434/v1" uv run chat.py "Reply with one short sentence about Python." | tee switch-out.txt
grep -E '^finish_reason=' switch-out.txtMoving to another server is the same move with different values. These are typical settings; the port and model name depend on how each server is started, so check them against its documentation:
# llama.cpp's llama-server, which has its own tutorial
export LLM_BASE_URL="http://127.0.0.1:8080/v1"
export LLM_MODEL="the model name llama-server reports at /v1/models"
# vLLM on a GPU machine, started with: vllm serve <model>
export LLM_BASE_URL="http://127.0.0.1:8000/v1"
export LLM_MODEL="the Hugging Face model id you served"For a hosted provider, read the key without echoing it, so it never lands in your shell history or on screen:
export LLM_BASE_URL="https://api.openai.com/v1" # replace with your provider's base URL
export LLM_MODEL="a model id from that provider's /models list"
read -rs -p "API key: " LLM_API_KEY; echo
export LLM_API_KEY
uv run models.pyHosted providers charge per token, so run models.py first: it checks the URL and key without paying for a completion.
"Compatible" rarely means identical. Before you switch, check the new provider's compatibility page for the features you use:
- Which endpoints exist. Chat Completions and
/modelsare near universal. OpenAI's newer Responses API (client.responses.create) is not: Ollama supports only its stateless form, with noprevious_response_id, and some servers do not offer it at all. Code built on Chat Completions moves more easily. - Tool calling. Many servers accept
tools, but support fortool_choicevaries; Ollama does not support it. Small local models also call tools less reliably than large hosted ones. - JSON output.
response_format={"type": "json_object"}works on Ollama, while support for a full JSON schema differs from server to server. Validate what comes back either way. - Extra fields. Anything in
extra_body, such asreasoning_effort, may be ignored or rejected elsewhere. - Claude. Anthropic offers an OpenAI SDK compatibility endpoint, but documents it as a way to test and compare models, not as a production path. To use Claude in an application, use Anthropic's own SDK, as in Call an LLM API from Python.
Check it worked
The localhost run prints an answer and a finish_reason= line, exactly as before, without a single edit to the scripts. If a small model gets stuck repeating itself, Ollama stops it and the SDK raises InternalServerError with a message like 500 - prediction aborted, token repeat limit reached; rephrase the question and try again. When you later export settings for a hosted provider, uv run models.py ending in configured model available: True tells you the switch worked.
Step 9 · Clean up
Remove the demo project. Ollama and uv stay installed:
cd ~
rm -rf ~/openai-compat-demo
unset LLM_BASE_URL LLM_API_KEY LLM_MODELThe model stays in Ollama for the other tutorials. When you no longer need it, free its 520 MB:
ollama rm qwen3:0.6bCheck it worked
Confirm that both are gone. The block stops with an error if either is still there:
test ! -e ~/openai-compat-demo
echo "demo folder removed"
if ollama list | grep -q 'qwen3:0.6b'; then echo "qwen3:0.6b is still installed"; false; fi
echo "model removed"You see demo folder removed and model removed.
Next steps
You now have a small client module that works with any server speaking the OpenAI format, and a habit of checking usage and errors from the first request.
- Learn more about the server, context length and model sizes in Run a language model on your own machine with Ollama.
- Serve a GGUF model with another compatible server in Serve a GGUF model with llama.cpp.
- Call Claude with Anthropic's own SDK in Call an LLM API from Python.
- Get replies your code can parse in Get structured JSON output from an LLM.
Part of these paths
Related tutorials
- How to Call a Large Language Model API from PythonYou will store an API key safely, install Anthropic's Python SDK 2.8.0, send Claude Sonnet 5.5 a first request, give it instructions and a conversation history, handle the errors an API call can raise, and work out what each call costs.
- Run a language model on your own machine with OllamaYou will have Ollama 0.40 serving a small model on 127.0.0.1:11434, answering from the command line and over its REST API, with a custom model of your own built from a Modelfile.
- Serve a quantised GGUF model with llama.cppYou will build llama.cpp v1.1.0 for CPU, compare a Q4_K_M and a Q8_0 copy of the same small model for size, memory and speed, and answer chat requests from its OpenAI-compatible server behind an API key.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials