Sub topic 2
What OpenAI-compatible means
This chapter assumes you can write basic Python and install packages with pip. It also assumes you can read JSON and know what an HTTP request is. You should have a local model server installed with at least one model downloaded. The examples use Ollama on port 11434 with llama3.2, but the ideas apply to any server.
By the end you should be able to say exactly what a server promises when it calls itself "OpenAI-compatible", and what it does not promise.
A contract, not a product
OpenAI published a web API for its hosted models. The API defines URL paths, JSON request bodies, JSON response bodies, and an authentication header. Many developers wrote client libraries and applications against that shape.
Local inference servers such as Ollama, llama.cpp's llama-server, LM Studio, and vLLM run models on your own hardware. They copied the same paths and JSON shapes. A program written for the hosted API can then talk to a local server by changing one address.
"OpenAI-compatible" therefore means the server implements some subset of the OpenAI HTTP interface. It does not mean the server runs OpenAI models, uses OpenAI code, or is made by OpenAI. The contract is the interface, and the model behind it can be anything.
The parts of the contract
The contract has four parts. A server can implement each one fully, partly, or not at all.
Endpoints
Each operation has a path, usually under the prefix /v1.
| Method and path | Purpose | Covered in |
|---|---|---|
| `GET /v1/models` | List the model IDs the server offers | Listing models |
| `POST /v1/chat/completions` | Send a conversation, get a reply | Chat completions |
| `POST /v1/embeddings` | Turn text into vectors | Embeddings |
| `POST /v1/completions` | Older plain-text completion | Not used in this tutorial |
Chat completions is the endpoint you will use most. Nearly every compatible server supports it. Support for the others varies.
Request format
A chat request is a JSON object. Two fields are essential: model, a string naming the model, and messages, a list of objects that each have a role and content. Optional fields control sampling and length, such as temperature and max_tokens, and behavior such as stream.
Response format
A non-streaming reply is one JSON object. It contains a list called choices, and each choice holds a message with the assistant's text. It also contains a usage object with token counts. Here is an illustrative reply:
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1767000000,
"model": "llama3.2",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Hello there!"},
"finish_reason": "stop"
}
],
"usage": {"prompt_tokens": 31, "completion_tokens": 4, "total_tokens": 35}
}The finish_reason field tells you why generation ended. The value stop means the model finished naturally. The value length means it hit the max_tokens limit and the text may be cut off.
Authentication and errors
The hosted API expects an Authorization: Bearer <key> header. Failures come back as an HTTP status code with a JSON error body. For example, a missing model typically produces status 404. Client libraries turn these statuses into typed exceptions, which is why the same error-handling code can work against different servers.
Seeing the contract on the wire
Everything above is plain HTTP. You can test the contract without any client library. This command sends a chat request to a local Ollama server:
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 the server is up and the model is downloaded, you get a JSON object shaped like the one above. The values in id, created, and the text will differ.
You can do the same in Python with the requests package (pip install requests). This script pulls out the fields that the contract defines:
import requests
url = "http://localhost:11434/v1/chat/completions"
payload = {
"model": "llama3.2",
"messages": [{"role": "user", "content": "Say hello in one sentence."}],
}
reply = requests.post(url, json=payload, timeout=60)
reply.raise_for_status()
data = reply.json()
print(data["object"])
print(data["choices"][0]["message"]["content"])
print(data["choices"][0]["finish_reason"])
print(data["usage"])This script is not tied to any official library. Compatibility lives at the HTTP level, so any language that can send JSON over HTTP can use the server.
Why people use the official client
The official openai Python package (pip install openai) wraps this HTTP contract. It builds the request, sends it, parses the JSON into objects, retries some failures, and raises typed exceptions. You only need to change where it sends requests. The same code then works with the hosted API or a local server:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
for m in client.models.list():
print(m.id)The base_url argument replaces the hosted address. The api_key is a placeholder, because most local servers do not check it, but the client refuses to start without some value. The next chapter covers this configuration in detail.
The practical benefits of this arrangement:
- Portability. You can develop against a local model, then switch to a hosted one by changing configuration.
- Tool support. Frameworks and applications that accept an OpenAI base URL work with your local server.
- One mental model. You learn one request and response shape instead of one per server.
What compatible does not mean
The word "compatible" hides a gap. No server copies the whole hosted API, and no local server can reproduce the hosted models. Four differences matter most.
- Partial endpoint coverage. A server may implement chat completions but not embeddings, or the reverse. Calling a missing endpoint returns an error, usually 404.
- Partial parameter support. A server may accept a field and silently ignore it, or reject it. Features such as structured JSON output, tool calling, and sampling options like
seedorlogprobsvary between servers and between models. - Different model names. The hosted API uses fixed names such as
gpt-4o. A local server uses whatever name it assigned to the model you downloaded, such asllama3.2or a file path. Sending a hosted name to a local server fails. - Different behavior. The same prompt gives different text on different models. Context window size, speed, and quality depend on the model and your hardware, not on the API shape.
A related point is that many servers also offer their own native API. Ollama, for example, has /api/chat alongside /v1/chat/completions. The native API may expose features the compatible one lacks, but code written for it only works with that server. The compatible layer trades some features for portability.
A practical checklist
Before relying on a server, run through these steps:
- Confirm the base URL and the
/v1prefix withGET /v1/models. - Copy a model ID from that list exactly as it appears.
- Send a minimal chat request and check
choices[0].message.content. - Check
finish_reasonto see whether the reply was cut off. - Test optional features one at a time: streaming, embeddings, JSON output, tools.
A failure at step 1 or 2 points to configuration. A failure in a later step usually points to a feature the server or model does not support. Later chapters in this tutorial treat each of these steps in turn.
Summary
An OpenAI-compatible server exposes the same HTTP paths, JSON shapes, and authentication style as the hosted OpenAI API. This lets the standard client library talk to a model running on your machine after a change to the base URL. The compatibility is a subset: endpoints, parameters, and model names vary, so you verify each feature before you depend on it.
Exercise
A teammate says, "Our local server is OpenAI-compatible, so any request that works against the hosted API will work unchanged." Give two reasons this can fail, and name the field in your request that is most likely to need changing first.
Show answer
Reasons include: the server may not implement every endpoint (for example it may lack embeddings, so the call returns 404), and it may ignore or reject parameters such as tool definitions or JSON output settings that the hosted API supports. The model name may also differ. The field most likely to need changing first is model, because hosted names like gpt-4o do not exist on a local server, which uses the name of the model you downloaded, such as llama3.2.
Exercise
You send a chat request to a local server and get a reply whose finish_reason is length. What does that mean, and which request field would you adjust?
Show answer
It means generation stopped because the token limit was reached, so the reply may be cut off mid-sentence. Increase max_tokens, or check whether the server or model has its own lower limit.