LocalAI’s main trick is compatibility: it speaks the OpenAI API shape, so code written for OpenAI works against a local model by changing one setting — the base URL. The docs describe LocalAI as exposing an OpenAI-compatible API, and the chat completions endpoint as POST /v1/chat/completions.
Point the client at LocalAI
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:8080/v1",
api_key="your-localai-api-key",
)
response = client.chat.completions.create(
model="llama-3.2-1b-instruct",
messages=[{"role": "user", "content": "Reply with one sentence saying you are ready."}],
)
print(response.choices[0].message.content)
Replace the model name with a model you actually installed — list them with curl http://localhost:8080/v1/models first. If you did not set an API key, the client still needs some string for api_key; use a placeholder and keep the real key, when you set one, in an environment variable rather than in the script.
What changes, and what does not
Nothing else in the code changes: the same chat.completions.create call, the same message list, the same response shape. That is the point of the compatibility — you can develop against LocalAI and switch the base URL back to OpenAI later, or the reverse. The difference is on the server side: your prompt and the model’s reply stay on your machine.
| Check | What you should see | If you do not see it |
|---|---|---|
| Client connects | The script prints a reply from the local model | LocalAI is not running, or the base URL is wrong — it must end in /v1 |
| Model name matches | The model in the call is in the /v1/models list | A gallery display name was used instead of the served model name |
| Key accepted | No 401 error | An API key is set on the server — pass it as the Bearer key |
Expected result. We checked the LocalAI text-and-retrieval docs for the OpenAI-compatible chat completions endpoint and the start page for the local address and gallery install. We did not run LocalAI or the Python client, so the code above is UNTESTED on this machine.
Limits
Compatibility covers the API shape, not model behaviour: a local model answers differently from a frontier cloud model, and some OpenAI parameters may not be supported. Check the response for errors rather than assuming every parameter works.
Sources
- LocalAI Text and retrieval — LocalAI exposes an OpenAI-compatible API; chat completions POST /v1/chat/completions
- LocalAI Start here — open http://localhost:8080; install a model from the gallery
Sources checked 2026-11-28.
