Sub topic 3
Pointing the Client at Your Server
This chapter covers the two settings that redirect the standard OpenAI Python client to a local server: the base URL and the API key. It assumes you can install packages with pip and read JSON. It also assumes you have a local server running with at least one model downloaded. The examples use Ollama on its default port, 11434, with the llama3.2 model.
Why two settings are enough
A local server that is OpenAI-compatible accepts the same HTTP requests as the hosted API: same paths, same JSON bodies, same response shapes. The client library only needs to know where to send those requests and what credential to attach.
- The base URL tells the client which server to contact.
- The API key is sent in an
Authorizationheader. A local server usually ignores it, but the client refuses to start without one.
Everything else in your code, such as client.chat.completions.create(...), stays the same as it would be against the hosted service.
Installing the client
Install the official package with pip:
pip install openaiYou use the same package for hosted and local servers. No special local-model library is needed.
Setting the base URL
The base URL is the prefix the client puts in front of every endpoint path. For chat completions, the client appends /chat/completions. For model listing, it appends /models.
For Ollama, the base URL is:
http://localhost:11434/v1The /v1 part matters. The client does not add it for you. If you leave it off, the client requests http://localhost:11434/chat/completions, which does not exist on the server, and you get a 404 response.
Here is a minimal client:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
for m in client.models.list():
print(m.id)If this prints at least one model name, the connection works and the server speaks the expected protocol. The next chapter covers model listing in more detail. For now, treat it as a connection check.
Common base URLs
Each server picks its own default port. The values below are the usual defaults. Check your server's settings, because they can be changed.
| Server | Typical base URL |
|---|---|
| Ollama | `http://localhost:11434/v1` |
| llama.cpp `llama-server` | `http://localhost:8080/v1` |
| LM Studio | `http://localhost:1234/v1` |
| vLLM | `http://localhost:8000/v1` |
All four follow the same pattern: scheme, host, port, then /v1.
How the URL is assembled
The client joins the base URL and the endpoint path. A trailing slash on the base URL is handled for you, so http://localhost:11434/v1/ and http://localhost:11434/v1 behave the same. The result for a chat request is:
http://localhost:11434/v1/chat/completionsYou can confirm this with curl, which sends the same request without Python:
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "llama3.2", "messages": [{"role": "user", "content": "Say hello in one sentence."}]}'If curl works and the Python client does not, the problem is in your Python configuration. If curl fails too, the problem is the server, the port, or the model name. This is a quick way to split a problem in half.
Setting the API key
The hosted API uses the key to authenticate and bill you. A local server on your own machine usually has no accounts, so it does not check the key. The client library, however, raises an error at construction time if no key is available:
openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variableThe fix is to pass any non-empty string. The value "local" is a common choice, and "not-needed" or "ollama" also work. The string is a placeholder and has no meaning to the server.
There are exceptions:
- vLLM can be started with an
--api-keyoption, and then it rejects requests that do not carry that exact key. llama-serveraccepts an--api-keyoption as well.- A server exposed through a reverse proxy or on a shared network may require a real token.
When a server enforces a key, a wrong value produces a 401 response, which the client raises as openai.AuthenticationError.
Using environment variables
Hard-coding the URL ties your script to one machine. The client reads two environment variables when you omit the arguments:
OPENAI_BASE_URLsets the base URL.OPENAI_API_KEYsets the key.
Set them in your shell:
export OPENAI_BASE_URL="http://localhost:11434/v1"
export OPENAI_API_KEY="local"Then create the client with no arguments:
from openai import OpenAI
client = OpenAI()
for m in client.models.list():
print(m.id)This lets the same script run against a local server on your laptop, a vLLM server on another machine, or the hosted API, with only the environment changed. Explicit arguments take precedence over environment variables, so a value you pass in code always wins.
A small configuration helper
For scripts you plan to reuse, put the settings in one place. The following version reads from the environment and falls back to local defaults:
import os
from openai import OpenAI
def make_client() -> OpenAI:
return OpenAI(
base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=os.environ.get("LLM_API_KEY", "local"),
)
if __name__ == "__main__":
client = make_client()
for m in client.models.list():
print(m.id)The variable names LLM_BASE_URL and LLM_API_KEY are your own choice. Using names different from the library's own avoids the accidental key leak described in the warning above, because a stray OPENAI_API_KEY is never picked up.
Other client options set at construction
The constructor accepts more than the URL and key. Two options matter for local use, and the chapter on errors covers them fully:
timeoutsets how long the client waits, in seconds. Local models can be slow on the first request because the server loads the model into memory, so the default may be too short for large models.max_retriessets how many times the client retries after certain failures. The default is 2.
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=120.0,
max_retries=1,
)Checking your setup
Work through these checks in order when a new client does not behave as expected.
- Confirm the server is running. Ollama, for example, answers a plain request at its root address.
- Confirm the port matches what the server reports at startup.
- Confirm the base URL ends in
/v1. - Run the model listing code and check that your model name appears in the output.
- Send a
curlrequest. If it succeeds, compare it with what your Python code sends.
The check in step 4 is the most useful. The names printed there are the exact strings the server accepts in the model argument. Ollama names often include a tag, such as llama3.2:latest, and you can copy the string from the listing.
Edge cases
localhostversus127.0.0.1. On some systemslocalhostresolves to the IPv6 address::1first. If the server listens only on IPv4, the connection can fail or lag. Try127.0.0.1iflocalhostmisbehaves.- Servers in containers. If your Python code runs inside a container and the server runs on the host,
localhostrefers to the container itself. Use the host's address instead, such ashost.docker.internalon Docker Desktop. - Remote servers. If the server listens only on the loopback interface, other machines cannot reach it. Servers usually need a setting to bind to all interfaces, and you should add authentication before doing so.
- HTTPS. Local servers normally use plain
http://. Usinghttps://against a server that does not terminate TLS fails with an SSL error that looks like a connection problem. - Proxies. Corporate proxy variables such as
HTTP_PROXYcan intercept requests tolocalhoston some setups. SettingNO_PROXY=localhost,127.0.0.1keeps local traffic direct.
Summary of the settings
| Setting | Constructor argument | Environment variable | Local value |
|---|---|---|---|
| Base URL | `base_url` | `OPENAI_BASE_URL` | Server address ending in `/v1` |
| API key | `api_key` | `OPENAI_API_KEY` | Any non-empty placeholder, unless the server enforces a key |
| Timeout | `timeout` | none | Larger than default for big models |
| Retries | `max_retries` | none | Default of 2 is usually fine |
Exercise
Your script creates the client with baseurl="http://localhost:11434" (no /v1) and apikey="local". Running client.models.list() fails with a 404 error, but the server is running and the port is correct. What is wrong, and how can you confirm the fix with curl?
Show answer
The base URL is missing the /v1 path prefix, so the client requests http://localhost:11434/models, which does not exist. Change the base URL to http://localhost:11434/v1. To confirm, run curl http://localhost:11434/v1/models. If it returns a JSON list of models, the corrected URL is right and the Python client will work with it.
Exercise
You export OPENAIAPIKEY with your real hosted key and then set OPENAIBASEURL to a local server address. Why is this a risk, and what is a safer approach?
Show answer
The client sends the key in the Authorization header of every request. A local server on your own machine is harmless, but if the base URL is later changed to a remote host you do not control, your real key is sent to it. Safer approaches are to pass apikey explicitly with a placeholder in code, or to use separate environment variable names such as LLMBASEURL and LLMAPI_KEY that the library never reads on its own.