Sub topic 12
Where Local Servers Differ from the Hosted API
This chapter assumes you can already point the OpenAI Python client at a local server, list models, send a chat completion, and stream a reply. Here you learn which parts of the OpenAI contract local servers keep, which parts they bend, and how to test for the differences before your code depends on them.
Why "compatible" is not "identical"
An OpenAI-compatible server accepts the same URL paths, JSON request fields, and response shapes as the hosted API. The client library does not know the difference. That compatibility covers the core of the contract, which is /v1/models, /v1/chat/completions, and often /v1/embeddings.
Compatibility is a goal each project pursues on its own schedule. Ollama, llama.cpp's llama-server, LM Studio, and vLLM each implement a subset. They differ in which fields they honor, which they accept and silently ignore, and which they reject. Hosted OpenAI models also change over time, so a server that matched the API last year may lag behind today.
Three kinds of difference cause most surprises:
- Missing features. The server returns an error for a field or endpoint it does not implement.
- Ignored fields. The server accepts a field and does nothing with it. This is the most dangerous kind, because nothing fails.
- Different behavior. The field works, but the result depends on the model. Examples are the quality of tool calls, the exact token counts, and the format of model names.
Differences that commonly appear
The table summarizes areas where local servers diverge from the hosted API. Treat it as a checklist of things to test, not as a statement about any specific version.
| Area | Hosted OpenAI API | Typical local server behavior |
|---|---|---|
| API key | Required and validated | Usually not checked, but the client still needs a non-empty value |
| Model names | Fixed names such as `gpt-4o-mini` | Names you chose or downloaded, such as `llama3.2` or a file path or repository ID |
| Model availability | Always listed | Only models that are downloaded or loaded |
| Sampling fields | All documented fields honored | Some ignored, such as `seed`, `logit_bias`, or `n` greater than 1 |
| Token counts in `usage` | Exact for the model | May be approximate or missing, especially while streaming |
| Structured output | JSON schema enforced | Varies by server and version, sometimes via a different mechanism |
| Tool calling | Reliable across models | Depends on both the server and the model's training |
| Embeddings | Fixed embedding models | Needs a dedicated embedding model, and vector length depends on that model |
| Context length | Fixed per model | Set by server configuration, and often smaller than the model's maximum |
| Concurrency | Scales by provider | Limited by your hardware, with requests queued or slowed |
| Rate-limit headers | Present | Usually absent |
Model names and loading
Hosted model names are stable strings. Local names depend on the server, so a name that works on one server can return a 404 on another.
- Ollama uses tags such as
llama3.2orllama3.2:3b. The model must be pulled first. - LM Studio lists the identifier of the loaded model, and some versions load models on demand.
llama-serverserves the model it was started with. Many builds ignore themodelfield or accept any string.- vLLM serves the model it was launched with, and the
modelfield must match the name it reports in/v1/models.
Do not hardcode a name and hope. Ask the server what it offers, as in the earlier chapter on listing models:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
available = [m.id for m in client.models.list()]
print(available)
wanted = "llama3.2"
if wanted not in available:
raise SystemExit(f"Model {wanted!r} not found. Server offers: {available}")A server that ignores the model field can hide a typo. Your request succeeds, but you may be talking to a different model than you think. Check the model field in the response, which most servers fill in with the model that answered.
Ignored parameters
Some servers accept a parameter and do not apply it. You can test whether a parameter has an effect by running the same request twice and comparing results.
The test below checks whether seed makes output repeatable. With temperature above zero and a working seed, two calls should return the same text.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
def ask(seed):
response = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Name a random fruit."}],
temperature=1.0,
max_tokens=10,
seed=seed,
)
return response.choices[0].message.content
first = ask(42)
second = ask(42)
print("seed honored:", first == second)A False result does not prove the server ignores seed. Some backends are not deterministic across runs on a GPU. A True result across several runs, with a different outcome when you change the seed, is stronger evidence. The same pattern works for other fields: change the value, and check that the output changes in the expected direction.
Context length and silent truncation
Hosted models document a context window and return an error when you exceed it. Local servers often do something less obvious. Ollama, for example, applies a default context length that can be much smaller than the model supports. If your prompt is longer, the server may drop the earliest tokens and answer anyway. The reply then ignores the start of your conversation, such as your system message.
Signs of truncation:
- The model forgets instructions you placed at the start of a long prompt.
usage.prompt_tokensstops growing as you add more text.- Long documents are summarized as if only the end was visible.
Check usage.prompt_tokens against your own estimate, and raise the context setting in the server's configuration when needed. A larger context uses more memory, so there is a trade-off between context size and speed or whether the model fits on your hardware at all.
Structured output and tool calling
The hosted API supports response_format with a JSON schema and a tools list with reliable function calls. Local support varies in two layers.
The server layer decides whether the field is accepted and how it is enforced. Some servers constrain generation with a grammar, which guarantees valid JSON. Others only add instructions to the prompt, which does not guarantee anything.
The model layer decides how well tool calls work in practice. A model not trained for tool use may ignore the tools list or produce malformed arguments, even if the server accepts the request.
Always validate the output. This example asks for JSON and refuses to trust it without parsing:
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
response = client.chat.completions.create(
model="llama3.2",
messages=[
{
"role": "user",
"content": 'Reply with JSON only: {"city": string, "country": string} for Paris.',
}
],
response_format={"type": "json_object"},
temperature=0,
)
text = response.choices[0].message.content
try:
data = json.loads(text)
print("Parsed:", data)
except json.JSONDecodeError:
print("Server or model did not return valid JSON:", text)If the server rejects response_format, you will get a 400 error. If it ignores the field, the except branch catches the failure. Both outcomes are better than passing unparsed text downstream.
Embeddings
Embeddings differ in more ways than chat does. A chat model usually cannot produce embeddings. You need a dedicated embedding model, such as nomic-embed-text, loaded on the server. The vector length depends on that model, so a 768-dimension vector from one model is not interchangeable with a 1536-dimension vector from a hosted model.
Two rules follow from this:
- Store the model name alongside every vector you save.
- Never compare vectors from different embedding models. Re-embed the whole collection if you switch models.
Some servers also differ in input handling. A server may accept a list of strings, or only a single string, and may limit the batch size. If a list fails, try one string per request.
Concurrency and performance
A hosted API handles many parallel requests. A local server shares one GPU or CPU among all callers. Sending ten requests at once usually does not make them ten times faster. Depending on the server, requests are queued, run in a batch, or compete for memory.
- vLLM is built for batching and handles concurrent requests well.
- Single-user servers may process requests one at a time.
- A first request can be slow because the model is loading into memory. Later requests are faster.
This affects your timeout settings. A timeout that suits the hosted API can be too short for the first local request. Set a generous timeout, and expect the first call to be slower than the rest.
A capability probe
Rather than guess, write a small probe that records what a given server does. Run it when you set up a new server or upgrade an existing one.
import json
import openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=120.0,
max_retries=0,
)
MODEL = "llama3.2"
def probe(name, fn):
try:
result = fn()
print(f"{name}: ok ({result})")
except openai.APIStatusError as e:
print(f"{name}: rejected with status {e.status_code}")
except Exception as e:
print(f"{name}: failed ({type(e).__name__})")
def chat():
r = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Say hi."}],
max_tokens=10,
)
return r.model
def usage():
r = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Say hi."}],
max_tokens=10,
)
return r.usage.total_tokens if r.usage else "no usage reported"
def json_mode():
r = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": 'Return {"a": 1} as JSON.'}],
response_format={"type": "json_object"},
)
json.loads(r.choices[0].message.content)
return "valid JSON"
def tools():
r = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "What is the weather in Paris?"}],
tools=[
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
],
)
calls = r.choices[0].message.tool_calls
return f"{len(calls)} tool call(s)" if calls else "no tool call made"
for label, fn in [("chat", chat), ("usage", usage), ("json_mode", json_mode), ("tools", tools)]:
probe(label, fn)Setting max_retries=0 keeps the probe honest. Automatic retries could hide a flaky response behind a success. The chat probe prints the model name from the response, which shows which model actually answered.
Decision criteria
Use these questions when deciding how much to rely on a feature:
- Is the feature core? Chat completions and model listing are widely supported. Build on them directly.
- Does failure show up? Prefer features that fail loudly. For ignored fields, add a check in code.
- Does the code need to run on both hosted and local? Keep the base URL, key, and model name in configuration, and wrap optional features in a fallback.
- Can you pin versions? Servers change quickly. Record the server version and model tag you tested against.
Summary
Local servers copy the shape of the OpenAI API, not every behavior behind it. Expect differences in model names, ignored parameters, context limits, structured output, tool calling, embeddings, token counts, and concurrency. Query the server for what it offers, test optional features once, validate model output, and record the versions that worked.
Exercise
You send seed=7 and temperature=1.0 to a local server twice, and the two replies differ. A colleague concludes that the server rejects seed. Why is the conclusion not justified, and what would you check next?
Show answer
The request did not fail, so the server accepted the field. It may ignore it, or it may apply it while GPU computation stays non-deterministic. Next, repeat the pair of calls several times, then compare with a different seed value and with temperature=0. Also check the server's documentation for the version in use. Consistent identical output for the same seed across repeats suggests the seed works. Differing output every time suggests it is ignored or not deterministic on that backend.
Exercise
A long prompt begins with a system message that says "Always answer in French". The local model replies in English once the conversation grows. Give a likely cause that does not exist on the hosted API in the same form, and how you would confirm it.
Show answer
The server's configured context length may be smaller than the prompt, so the earliest tokens, including the system message, were silently dropped. Confirm by comparing usage.prompt_tokens with your own estimate of the prompt size. If it plateaus or is lower than expected, raise the context setting in the server configuration, or shorten the conversation.
Exercise
You save embeddings from nomic-embed-text in a database. Later you switch to a different embedding model for new documents and keep the old vectors. What goes wrong, and what should you have stored?
Show answer
Vectors from different models live in different spaces and may have different lengths, so similarity scores between old and new vectors are meaningless or the comparison fails. You should store the model name with every vector, and re-embed the whole collection when you change models.