Self-hosted Models (Ollama) — AI Web

Self-hosting means running an open-weight model (its weights may be downloaded) on your own machine. Ollama (a program that downloads and runs models) does…

A model with 4 billion parameters runs on a 16 GB M1 Pro laptop and answers a stock question at 43 tokens a second, with no API key and no per-token bill. The way to do it is self-hosting: running an open-weight model (one whose weight files you may download) on your own machine instead of calling a provider's API. Ollama is a program that downloads models, runs them, and opens an HTTP API on localhost:11434 (an address on your own computer).

Self-hosting is like cooking in your own kitchen instead of ordering delivery (calling a provider's API). You buy the ingredients once, like a model you download once. You pay for the stove and gas, like the machine and its power. There's no charge per portion (no per-token bill), and nobody else knows what you cook (the data doesn't leave). But your kitchen has one stove: if ten guests arrive at once, they wait in line, just like requests that reach Ollama at the same time.

Ollama in four commands

The latest release on GitHub as of October 2026: Ollama 0.40.2 (released 8 October 2026). Install it from ollama.com/download, then run these commands in a terminal:

ollama pull qwen3:4b-instruct   # download the model, 2.5 GB
ollama run qwen3:4b-instruct "Hello"  # try it right in the terminal
ollama ps                        # loaded models, their size, GPU or CPU
ollama stop qwen3:4b-instruct    # unload it from memory

Popular models in Ollama's library (ollama.com/library, the list of models you can download): Llama (Meta, for example llama3.2), Mistral (Mistral AI, mistral 7B), Gemma (Google, gemma4) and Qwen (qwen3). OpenAI's main GPT models and every Claude model can't be self-hosted. Their weights aren't shared, so those models are only available through an API. The exception is gpt-oss, an open-weight model from OpenAI (Apache 2.0 licence) that is in Ollama's library. "Open-weight" doesn't mean free for any use. Licences (the rules for using a model) differ per model, for example qwen3:4b's metadata (the information that comes with the model) says apache-2.0. So check before using one for business.

Its API: /api/chat streams NDJSON

The Bookshop server calls Ollama like any other API, only with no API key. The difference from the Streaming Responses lesson: Ollama doesn't use SSE but NDJSON (newline-delimited JSON): one complete JSON object per line. Below is a real response recorded from Ollama 0.40.2 on a 16 GB M1 Pro laptop on 11 October 2026, for a stock question with <stock_data>. The Lab replays the same run. The timings and counts are that run's, and the reply text is shown in English:

{"model":"qwen3:4b-instruct","created_at":"2026-10-11T03:56:52.850956Z","message":{"role":"assistant","content":"Yes"},"done":false}
{"model":"qwen3:4b-instruct","created_at":"2026-10-11T03:56:52.876316Z","message":{"role":"assistant","content":","},"done":false}
... 16 more lines ...
{"model":"qwen3:4b-instruct","created_at":"2026-10-11T03:56:53.289062Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":2356862167,"load_duration":1603703000,"prompt_eval_count":116,"prompt_eval_cached_count":0,"prompt_eval_duration":299435000,"eval_count":19,"eval_duration":439680000}

If you join the content of every line, you get "Yes, The Rainbow Troops is still in stock, with 12 copies left." The last line ("done": true) carries times in nanoseconds (billionths of a second): 2.36 s in total, 1.60 s of it to load the model, and 19 output tokens in 0.44 s = 43 tokens per second. The server code below reads that stream line by line:

const res = await fetch("http://localhost:11434/api/chat", {
  method: "POST",
  body: JSON.stringify({ model: "qwen3:4b-instruct", messages }),
});
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let rest = "";
for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  rest += value;
  const lines = rest.split("\n");
  rest = lines.pop(); // the last line may be incomplete
  for (const line of lines) {
    if (!line.trim()) continue;
    const part = JSON.parse(line);
    sendToBrowser(part.message.content);
    if (part.done) console.log(part.eval_count / (part.eval_duration / 1e9), "tokens/s");
  }
}

/api/embed and the OpenAI-compatible endpoint

Embeddings for RAG can be made locally too. POST /api/embed with {"model":"all-minilm","input":["Is The Rainbow Troops still in stock?","Is there a novel about a school in Belitung?"]} replies {"embeddings":[[...],[...]]}. Measured: each vector has 384 numbers, and its length is 1.

Ollama also opens OpenAI-shaped endpoints under /v1: /v1/chat/completions, /v1/responses (without previous_response_id) and /v1/embeddings. You only point the openai SDK there with baseURL:

import OpenAI from "openai";
const ollama = new OpenAI({ baseURL: "http://localhost:11434/v1/", apiKey: "ollama" }); // required, but ignored
const r = await ollama.chat.completions.create({ model: "qwen3:4b-instruct", messages });
// r.choices[0].message.content: "No, This Earth of Mankind is out of stock: 0 left."

Model size: compute the memory

Memory for the weights = parameters × bits per weight ÷ 8 (8 bits = 1 byte). Quantisation means storing the weights in fewer bits: the model is smaller and faster, but slightly less accurate. Q4_K_M, Q8_0 and F16 are names of quantisation levels. According to the README of llama.cpp's llama-quantize (measured on Llama 3.1 8B), Q4_K_M uses 4.89 bits per weight (about 0.61 bytes), Q8_0 8.50 bits, and F16 16 bits (2 bytes).

Model Q4_K_M Q8_0 F16
4B (4.02 billion parameters) 2.46 GB (Ollama library: 2.5 GB) 4.27 GB (4.3 GB) 8.04 GB (8.1 GB)
12B 7.34 GB 12.75 GB 24 GB

Before you read on, guess: qwen3:4b-instruct, a 4-billion-parameter model, runs under Ollama on a 16 GB M1 Pro laptop. How much memory does it use while answering: about 1 GB, about 3 GB, or about 8 GB?

On top of the weights come the KV cache and buffers (temporary holding places). The KV cache stores the work done for each token in the context (how many tokens the model can handle at once). The longer the context, the bigger the KV cache. Measured for qwen3:4b-instruct on that laptop, from /api/ps: 3.18 GB, with a 4,096-token context and 100% on the GPU. That's the 2.50 GB weights file, plus 0.68 GB of KV cache and buffers. The KV cache size follows from the model's metadata: 36 layers × 8 KV heads × 128 dimensions × 2 (key and value) × 2 bytes × 4,096 tokens = 0.60 GB.

On that laptop, Ollama saw 11.8 GiB (about 12.7 GB) of the 16 GiB of memory as usable by the GPU. A GiB is a unit slightly bigger than a GB. With the weights plus 0.68 GB of KV cache and buffers (the 4B model's measurement above), a 12B model at Q4_K_M (about 8 GB) fits, and Q8_0 (13.4 GB) doesn't. Ollama uses a 4,096-token context when GPU memory is under 24 GiB. A longer context, or OLLAMA_NUM_PARALLEL (how many requests are handled at the same time) above 1, adds KV cache. Check the PROCESSOR column in ollama ps: if part of the model moves to the CPU, answers get much slower.

Speed, measured honestly

Measured on the same laptop, with other programs running. Measure on your own machine too:

What happened Time
First request, the model loads first 2.36 s (1.60 s loading the model)
Next request, the model already in memory 0.50 s (115 of 116 prompt tokens from Ollama's cache)
4 requests at once done at 0.61, 1.05, 1.50, 1.95 s
The thinking qwen3:4b, same question 30.9 s: 938 output tokens for one sentence

Privacy, and when a hosted API is cheaper

Self-hosting's main advantage: the data stays on your own server and there's no per-request cost to a third party. That matters for data that must not leave (medical notes, internal documents), offline work, and trying prompts hundreds of times with no bill. For comparison, OpenAI's "Your data" page (October 2026) says three things. API data isn't used to train models unless you opt in, abuse-monitoring logs may be kept for up to 30 days, and the Responses API stores responses for 30 days unless store: false.

Self-hosting isn't automatically cheaper than a hosted API (a model the provider runs on its own servers). The Bookshop assistant on gpt-6-luna (400 tokens in, 40 out): 10,000 questions a day = $0.60 a day, $18 a month. A GPU machine of your own, its power and the time to maintain it clearly cost more than $18 a month. A 4B model may also not pass the eval set (the test questions from the Evaluating AI Output lesson) as well as gpt-6-luna does. Self-hosting only wins on cost at large, steady volume, or when the data simply can't leave.

⚠️ Getting memory, speed and cost wrong

TL;DR: Self-hosting means running an open-weight model (its weights may be downloaded) on your own machine. Ollama (a program that downloads and runs models) does this for Llama, Mistral, Gemma and Qwen: ollama pull, ollama run, ollama ps, with an API on localhost:11434. /api/chat streams NDJSON, one JSON per line, and the "done": true line carries durations in nanoseconds. /api/embed makes embeddings. /v1 works with the OpenAI SDK (baseURL: "http://localhost:11434/v1/", any apiKey). Memory ≈ parameters × bits per weight ÷ 8, plus the KV cache (stored work for each token being handled). Bits per weight depend on the quantisation (weights stored in fewer bits): Q4_K_M 4.89 bits, Q8_0 8.50, F16 16. qwen3:4b-instruct uses 3.18 GB on a 16 GB M1 Pro, and a 12B model at Q4_K_M about 8 GB. Measured: 43 tokens per second, 2.36 s for the first request, 0.50 s for the next, and requests sent at the same time wait in line. The main advantage is that data stays on your own server with no per-request cost. For small volumes like the Bookshop's ($18 a month on gpt-6-luna), a hosted API (a model on the provider's servers) is cheaper.

⚡ Open-weight models on your machine

Write:

ollama pull qwen3:4b-instruct
Guess first: Ollama runs open-weight models, models whose weight files you may download, on your own machine. Can GPT or Claude run on Ollama?

OpenAI's main GPT models and Claude can't. Their weights aren't shared, so those models are only available through an API. The exception is gpt-oss, an open-weight model from OpenAI that is on Ollama.

Meaning: ollama pull downloads a model to your machine, here qwen3:4b-instruct. Popular open-weight models on Ollama: Llama, Mistral, Gemma and Qwen. Licences differ per model, so check before using one for business.

⚡ NDJSON, not SSE

Write:

rest = lines.pop(); // the last line may be incomplete

Meaning: Ollama's /api/chat sends its answer as NDJSON: one complete JSON object per line, not SSE as in the Streaming Responses lesson. One network piece can hold half a line. So lines.pop() takes the last line, which may be incomplete, out of the list of lines, and keeps it in rest until the next piece arrives.

⚡ Compute the memory

Guess first: qwen3:4b-instruct has 4 billion parameters, and its weights file is 2.5 GB. On a 16 GB M1 Pro laptop, how much memory does it use while answering: 1, 3 or 8 GB?

About 3 GB: 3.18 GB, the 2.50 GB weights plus 0.68 GB of KV cache (stored work for each token being handled) and buffers.

Meaning: Memory ≈ parameters × bits per weight ÷ 8, plus the KV cache. Bits per weight depend on the quantisation, a way of storing the weights in fewer bits (for example 4.89 bits at the Q4_K_M level). If the model doesn't fit in the GPU's memory, part of it moves to the CPU, and answers get much slower.

⚡ Self-hosting isn't automatically cheaper

Meaning: Self-hosting means running the model on your own machine. The Bookshop assistant through the gpt-6-luna API costs just $18 a month, less than a GPU machine, its power and its upkeep. Self-hosting only wins at large, steady volume, or when the data simply can't leave.

What you will learn