skip to content

When does a client need Ollama's native /api/chat rather than /v1/chat/completions, and how do you read its streamed response?

level: middleimportance: should knowfreq 12%

answer

  1. fields the OpenAI shape lacks
  2. options, keep_alive, think, format
  3. one JSON object per line
  4. done true carries the stats
  5. errors arrive as a stream line

basics

~20 s

Use /api/chat when a request needs Ollama's own controls directly: per-request options such as num_ctx, think levels, or a JSON schema in format. It streams by default as newline-delimited JSON; the last object has done: true and the timings.

solid answer

~50 s

In Ollama 0.35.0 the native route takes fields the OpenAI shape has no room for: `options` (any Modelfile parameter per request, including `num_ctx`, `temperature`, `seed`), `keep_alive` (how long the model stays loaded, default `5m`; on `/v1` only an undocumented extension), `think` (a boolean or a level the model supports, with the trace returned in `message.thinking`), and `format` (`"json"` or a JSON schema). Tool calls come back with `arguments` as a JSON object rather than a string. Streaming is on unless you send `"stream": false`, and the body is `application/x-ndjson`: one JSON object per line, each with a `message.content` fragment, the last with `"done": true`, `done_reason` and counts such as `eval_count` and `eval_duration` in nanoseconds. A failure after streaming has begun arrives as a line with an `error` key while the status stays 200, so the reader checks every line.

code

python · 21 lines
python
import json
import requests

body = {
    "model": "llama3.2",
    "messages": [{"role": "user", "content": "Why is the sky blue?"}],
    "options": {"num_ctx": 16384, "temperature": 0.2},
    "keep_alive": "30m",
}
with requests.post("http://localhost:11434/api/chat", json=body, stream=True) as r:
    r.raise_for_status()
    for line in r.iter_lines():
        if not line:
            continue
        chunk = json.loads(line)
        if "error" in chunk:  # mid-stream failure, status is still 200
            raise RuntimeError(chunk["error"])
        print(chunk["message"]["content"], end="", flush=True)
        if chunk["done"]:
            tps = chunk["eval_count"] / chunk["eval_duration"] * 1e9
            print(f"\n{chunk.get('done_reason')}: {tps:.1f} tokens/s")

go deeper

for a junior

Recall that /api/chat streams by default as one JSON object per line, and that the last object has done set to true.

for a middle

Explain which controls the native route exposes directly — options, keep_alive, think, format — and how tool-call arguments and thinking output are shaped there.

for a senior

Show a robust stream reader: per-line parsing, error lines under a 200 status, nanosecond timings, and load_duration as the sign that a model was reloaded.

for a principal

Judge where the boundary goes: a thin native adapter for Ollama-only controls, or one OpenAI-shaped client for every backend, and what each costs the team to maintain.

## Two routes, one model Ollama exposes the same loaded model through two chat endpoints. `/v1/chat/completions` accepts the OpenAI request shape so existing SDKs work; `/api/chat` is Ollama's own interface, where every Ollama control is a first-class field. Both run through the same chat handler, so the model, its template and its loaded state are shared. The differences are which knobs a request can reach and how the response is framed. ## Fields only the native request carries | Field | What it does | The `/v1` situation | |---|---|---| | `options` | any Modelfile parameter for this request: `num_ctx`, `temperature`, `seed`, `num_predict`, `stop` | the OpenAI body has no generic options object | | `keep_alive` | how long the model stays loaded after the request (default `5m`; `0` unloads) | not in the OpenAI schema; 0.35.0 accepts it on `/v1/chat/completions` only as an undocumented extension | | `think` | `true`, `false`, or a named level for thinking models | `/v1` maps `reasoning_effort` onto it, with model-specific aliasing | | `format` | `"json"` or a full JSON schema | reachable only through `response_format` | | `images` | base64 images on a message | data URLs inside content parts | Two consequences stand out. First, **context size per request**: `"options": {"num_ctx": 16384}` is the only way to choose it from a request; on `/v1` you need a Modelfile-built model or a server variable. What a larger context costs in memory is the offload material's subject. Second, **thinking output** is separated cleanly: `message.thinking` holds the reasoning trace and `message.content` the answer. Which levels a model accepts is model-specific; the API reference lists `"low"`, `"medium"`, `"high"` and `"max"`, and `/api/show` reports the values a given model supports. Tool calling differs in a small way that breaks naive ports: native `tool_calls[].function.arguments` is a **JSON object**, while the OpenAI shape carries it as a JSON-encoded **string**. A client switching routes must stop decoding it a second time. ## Reading the native stream Streaming is **on by default** for `/api/chat` and `/api/generate`, while `/v1/chat/completions` follows the OpenAI default of off. The native body is **newline-delimited JSON** (`application/x-ndjson`), not an event stream: no `data:` prefixes and no `[DONE]` sentinel. A reader should: 1. Read the body line by line and parse each non-empty line as a standalone JSON object. 2. Check for an `error` key first. A failure mid-generation is written as `{"error": "..."}`, and the status code, already sent as 200, does not change. 3. Append `message.content` (and `message.thinking`, if requested) from each object. 4. Stop at the object with `"done": true`. It carries `done_reason` (for example `"stop"`) and the statistics: `prompt_eval_count`, `eval_count`, `load_duration`, `eval_duration`, `total_duration`. All durations are **nanoseconds**, so tokens per second is `eval_count / eval_duration * 10^9`. A large `load_duration` on a request means the model was loaded for it: it had not been loaded yet, or had been unloaded since the previous call. With `"stream": false` the same fields come back in one `application/json` object, which is simpler for short calls or when the output is parsed as a whole, as with a `format` schema. Two request fields change what the stream looks like. With `format` set to a schema, the text only parses as JSON once it is complete, so most callers send `"stream": false` and decode `message.content` once. With `think` enabled, the docs note that reasoning tokens stream before answer tokens: early lines carry `message.thinking` fragments, so a reader that prints only `content` appears to stall until the answer starts. When tools are involved, accumulate the thinking and the tool calls from the chunks, because they must be sent back in the next request's `messages`. ## When to choose which - **Stay on `/v1`** when portability matters, because the same code must also call a hosted API, and the defaults are acceptable. - **Use `/api/chat`** when you need per-request `num_ctx` or sampling options, a documented `keep_alive`, the thinking trace in its own field, or a JSON schema passed straight through as `format`. - **Use `/api/generate`** for single-prompt completion. It takes `prompt`, `suffix`, `system`, `template` and `raw` (skip the template entirely); its `context` field for carrying state is deprecated, so multi-turn state belongs in an `/api/chat` `messages` history. Neither route keeps conversation state on the server: `/api/chat` is stateless, and the client resends the full `messages` array on every turn.

  • An NDJSON reader crashes with a KeyError on 'message' halfway through a long answer — what happened?
    The model failed mid-stream and Ollama wrote an object carrying only an `error` key. The 200 status was already sent, so the status line cannot report it. Check each line for `error` before touching `message`, and surface it as a failure rather than a truncated answer.
  • How do you compute generation speed from a native response?
    Take the final object's `eval_count` and `eval_duration`. Durations are nanoseconds, so tokens per second is `eval_count / eval_duration * 1e9`. `prompt_eval_duration` covers prompt processing, and a large `load_duration` means the model was loaded for this request.
  • A client ported from /v1 to /api/chat fails while parsing tool arguments — why?
    Native `tool_calls` carry `function.arguments` as a JSON object, already parsed, while the OpenAI shape sends a JSON-encoded string. Code that decoded the string now receives a dict and raises a type error. Read the object directly.

  • Ollama's native /api/chat streams event-stream data: lines ending in [DONE].
  • Native streaming is off unless the request sets stream to true.
  • A failure mid-stream changes the HTTP status to 500.
  • eval_duration in the final object is measured in milliseconds.
  • /api/chat remembers the conversation between requests.
  • num_ctx can be set per request on /v1 just as on /api/chat.

Assumes Ollama 0.35.0; the native field set, the think levels and the NDJSON stream format are read from that release's API reference.