# How do I call a local model from code?

> Point any OpenAI-compatible client at your local server with a dummy key. That base URL and a model name is the whole integration.

Every local runtime serves the same HTTP API that OpenAI's own servers use. Change the base URL, pass any string as the key, name a model, and code written for the cloud runs against your machine.

## Every runtime speaks the same format

The format is OpenAI's chat completions API: you POST a list of messages to `/v1/chat/completions` and get a message back. [Ollama](https://localagi.co/ollama), [LM Studio](https://localagi.co/lm-studio), [llama-server](https://localagi.co/llama-cpp), [mlx-lm](https://localagi.co/mlx), [vLLM and SGLang](https://localagi.co/vllm-and-sglang) and [BaseRT](https://localagi.co/basert) all speak it. So do most of the [What other runtimes are there?](https://localagi.co/other-runtimes).

That means you rarely need a runtime-specific library. The official `openai` packages for Python and JavaScript work as they are. So do most tools with a "custom OpenAI endpoint" or "OpenAI-compatible" option.

Many runtimes also speak Anthropic's Messages format at `/v1/messages`, which some coding tools expect. Support varies by runtime and version, so check the docs of yours. Superfluid, the server behind `basert serve`, lists both formats plus Ollama's. 

## Base URL, dummy key, model name

Three values are the whole integration.

| Value | What to put | Example |
| --- | --- | --- |
| Base URL | Your runtime's address plus `/v1` | `http://localhost:11434/v1` |
| API key | Any non-empty string. Local servers ignore it by default | `local` |
| Model name | The name your runtime lists for the model | `qwen3:8b` in Ollama |

Ask the server what names it knows. Every runtime above answers `GET /v1/models`.

```bash
curl http://localhost:11434/v1/models
```

**The catch.** 
The key is a dummy only while the server listens on `localhost`. If you expose it to your network, anyone who can reach the port can use it. llama-server, vLLM and SGLang accept an `--api-key` option to require a real one. [Is local AI actually private?](https://localagi.co/privacy-and-security) covers the rest.

## Examples

The examples use Ollama's port. Swap in the port for your runtime from the table further down.

### curl

```bash
curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer local" \
  -d '{
    "model": "qwen3:8b",
    "messages": [
      {"role": "system", "content": "Answer in one sentence."},
      {"role": "user", "content": "What is a KV cache?"}
    ]
  }'
```

The answer is in `choices[0].message.content`. The `usage` field tells you how many tokens the prompt and answer used.

### Python

```bash
pip install openai
```

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")

reply = client.chat.completions.create(
    model="qwen3:8b",
    messages=[{"role": "user", "content": "What is a KV cache?"}],
)
print(reply.choices[0].message.content)
```

To stream tokens as they arrive, pass `stream=True` and loop over the result.

```python
stream = client.chat.completions.create(
    model="qwen3:8b",
    messages=[{"role": "user", "content": "Write a short poem about RAM."}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

### JavaScript

```bash
npm install openai
```

```js
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:11434/v1", apiKey: "local" });

const reply = await client.chat.completions.create({
  model: "qwen3:8b",
  messages: [{ role: "user", content: "What is a KV cache?" }],
});
console.log(reply.choices[0].message.content);
```

Save it as `ask.mjs` and run `node ask.mjs`. In a browser, a local server may also need its CORS setting opened before a web page can call it.

**Try it.** 
Run the Python example twice, once against Ollama on port 11434 and once against LM Studio on port 1234, changing only the base URL and model name. Same code, two runtimes.

## Default ports

Each runtime has its own default port. Two runtimes on the same port cannot run at once, which is a common reason a server "will not start".

| Runtime | Port |
| --- | --- |
| Ollama | 11434 |
| LM Studio | 1234 |
| llama.cpp (llama-server) | 8080 |
| vLLM | 8000 |
| SGLang | 30000 |
| BaseRT | – |
| Superfluid | 8453 |

`mlx_lm.server` also defaults to port 8080, the same as llama-server. Every runtime lets you change the port with a flag or a setting.

BaseRT shows no port in the table because `basert serve` starts Superfluid. Its README example passes `--port 8080`, which clashes with llama-server, so pick another if you run both.

**Rule of thumb.** 
Keep the base URL and model name in an environment variable or config file, never in the code. Then switching runtime is a one-line change.

## Streaming, tool calls and structured output

The basic chat call works everywhere. The extras work in most places, with caveats that come from the model as much as the runtime.

| Feature | What it does | Support |
| --- | --- | --- |
| Streaming | Sends tokens as they are made | Every runtime on this page |
| Tool calls | The model asks your code to run a function | Most runtimes. Needs a model trained for it. llama-server needs `--jinja` |
| Structured output | Forces the answer to match a JSON schema | Most runtimes, through `response_format`. Ollama's native API also has a `format` field |
| Vision input | Images in the messages | Only with a vision model, and not in every runtime |

Tool calls fail more often from the model than from the runtime. Small models miss arguments or call tools that do not exist. [How do tools and MCP work with local models?](https://localagi.co/tools-and-mcp) covers which models handle tools well, and [Can I run a coding agent on a local model?](https://localagi.co/coding-agents) covers the agents that depend on them.

**The catch.** 
Context length is set on the server, not in the API call, for most runtimes. If an agent forgets things, raise the context in the runtime. [How do I use Ollama?](https://localagi.co/ollama) has the most common case.

## Go deeper

### Chat completions versus the Responses API

OpenAI also has a newer Responses API at `/v1/responses`. Some runtimes support it and some do not.

When a tool offers a choice, pick chat completions for local use. It is the one every runtime implements. 

### Native APIs

Most runtimes also have their own API next to the OpenAI one. Ollama's lives under `/api`, for example `/api/chat`, and exposes settings like `num_ctx` and `keep_alive` per request. llama-server has `/completion` with its own sampling options. Use these when you need a setting the OpenAI format has no field for.

### Embeddings

The same base URL usually serves `/v1/embeddings`, for turning text into vectors. You need an embedding model loaded, not a chat model. [How do I chat with my documents?](https://localagi.co/chat-with-documents) covers what that is for.

### Timeouts

The first request to a model that is not loaded waits for the load, which can take a while for a large model. Client libraries have default timeouts that can fire first. Raise the timeout, or load the model before the first call.
