An Ollama RAG needs two models and four steps: split your documents into chunks, turn each chunk into a vector with an embedding model, find the chunks closest to the question and pass them to a chat model with the instruction to answer only from them and cite them. Here are 47 lines of Python that do all four.
We built it on 27 November 2026 with Ollama 0.40.18, the latest stable release that day: the official Linux binary (checksum verified), no GPU, embeddinggemma and nomic-embed-text for the vectors and qwen3:1.7b and qwen3:0.6b for the answers. As the library we used the Ollama FAQ itself (docs/faq.mdx of version 0.40.18: 19,361 characters, about 5,200 tokens) and 12 questions written in our own words, each with a sentence in the FAQ that answers it. That way, “did it find the right chunk?” has a yes or no answer, not an opinion.
OllamaRuntime sheet
What an Ollama RAG needs: two models and four steps
RAG (retrieval-augmented generation) is a simple idea with a fancy name: before asking the model, you look up the right passage in your documents and paste it into the prompt. The model doesn’t learn anything new; it reads. That’s why it works with small models and why it’s so good for private documents: nothing leaves your machine.
In Ollama, it all happens through two endpoints of the local API:
- Chunk. Cut the text into pieces small enough to be precise and big enough to carry the answer. This is the step that moved our results the most.
- Embed.
POST /api/embedwith an embedding model returns one vector per chunk. You do it once and save the result. How these models compare is in our Ollama embeddings guide; here we use two of them. - Retrieve. Embed the question with the same model and keep the chunks with the highest score. Ollama returns normalised vectors (we checked: length 1.0 in both models), so a dot product is the cosine.
- Answer.
POST /api/chatwith the chunks numbered in the system message and the order to cite them.
Download both models first:
ollama pull embeddinggemma
ollama pull qwen3:1.7b
Both stay loaded at the same time while you ask questions. This is how ollama ps looked on our machine in the middle of a test:

The whole script: ollama_rag.py
No framework and no vector database: requests and a JSON file as the index. This is the exact file we ran for every answer on this page:
# ollama_rag.py: a complete local RAG with Ollama (chunk -> embed -> retrieve -> answer with citations).
# Usage: python ollama_rag.py faq.mdx "your question"
import json, os, re, sys, requests
OLLAMA = os.environ.get("OLLAMA_HOST", "http://localhost:11434")
EMBED, CHAT = os.environ.get("EMBED", "embeddinggemma"), os.environ.get("MODEL", "qwen3:1.7b")
SIZE, TOP_K = int(os.environ.get("CHUNK", "1600")), int(os.environ.get("TOP_K", "3"))
def chunks(text, size): # one chunk per "## " section, split if longer than `size`
out = []
for section in re.split(r"\n(?=## )", text):
cur = ""
for para in section.split("\n\n"):
if cur and len(cur) + len(para) > size:
out.append(cur); cur = ""
cur = f"{cur}\n\n{para}" if cur else para
if cur: out.append(cur)
return out
def embed(texts):
r = requests.post(f"{OLLAMA}/api/embed", json={"model": EMBED, "input": texts})
r.raise_for_status()
return r.json()["embeddings"] # already normalised: dot product = cosine
path, question = sys.argv[1], sys.argv[2]
index_file = f"{path}.{EMBED.replace(':', '_')}.{SIZE}.json"
if os.path.exists(index_file):
docs, vecs = json.load(open(index_file))
else:
docs = chunks(open(path, encoding="utf-8").read(), SIZE)
vecs = embed(docs)
json.dump([docs, vecs], open(index_file, "w"))
qv = embed([question])[0]
best = sorted(range(len(docs)), key=lambda i: -sum(a * b for a, b in zip(qv, vecs[i])))[:TOP_K]
sources = "\n\n".join(f"[{n}] {docs[i]}" for n, i in enumerate(best, 1))
r = requests.post(f"{OLLAMA}/api/chat", json={
"model": CHAT, "stream": False, "think": False, "options": {"temperature": 0},
"messages": [
{"role": "system", "content": "Answer using only the numbered sources the user gives you. After every "
"sentence, write the number of its source in brackets, like [2]. "
"If the sources don't contain the answer, say you don't know."},
{"role": "user", "content": f"Sources:\n\n{sources}\n\nQuestion: {question}"}]})
r.raise_for_status()
j = r.json()
print(j["message"]["content"])
print(f"\nchunks {len(docs)} · used {[i for i in best]} · prompt tokens {j['prompt_eval_count']}")
Three decisions in there are the result of the tests below. The chunks follow the ## headings of the document (one section, one chunk) and only split a section if it goes over 1,600 characters. The index is saved with the name of the embedding model in the file name, so changing models can’t mix vectors (more on that trap further down). And "think": false with temperature 0 keeps qwen3 short and repeatable.
To use it, run python ollama_rag.py faq.mdx "your question". The first run builds the index; the following ones only embed the question.
![Terminal with Ollama 0.40.18: ollama_rag.py answers two questions about the Ollama FAQ with qwen3:1.7b, citing source [1] and printing the prompt tokens](https://localaiscope.com/wp-content/uploads/2026/11/las-ollama-rag-respuesta.webp)
How to chunk documents for RAG: 8 ways tested on the same FAQ
We measured how many of the 12 questions got the right chunk in first place (top-1) and among the first three (top-3, which is what the script passes to the model). Same document, same questions, only the way of cutting changes:
| How we cut | Chunks | embeddinggemma top-1 / top-3 | nomic-embed-text top-1 / top-3 |
|---|---|---|---|
| Paragraphs packed up to 200 characters | 102 | 4 / 10 | 4 / 11 |
| Up to 400 characters | 58 | 7 / 9 | 8 / 9 |
| Up to 800 characters | 29 | 8 / 10 | 9 / 11 |
| Up to 1,600 characters | 13 | 7 / 11 | 9 / 11 |
| Up to 3,200 characters | 7 | 7 / 11 | 8 / 10 |
By ## heading, split above 800 |
39 | 9 / 12 | 10 / 12 |
By ## heading, split above 1,600 |
31 | 11 / 12 | 12 / 12 |
By ## heading, whole sections |
29 | 11 / 12 | 12 / 12 |
Measured on Ollama 0.40.18, 27 November 2026, docs/faq.mdx of that version, 12 questions. “Packed” = whole paragraphs added until the next one would go over the limit, so a long paragraph stays whole.
The lesson is clear: in a document that’s already organised by questions, cutting by size breaks answers in half. With 200-character chunks, the right one came first only 4 times out of 12, probably because the line with the variable and the sentence explaining it end up in different chunks. Following the headings, the first result was the right one 11 or 12 times out of 12.
Big chunks have their own trick. With 7 chunks of up to 3,200 characters, the top-3 already brings back 3 of the 7 pieces of the whole document, so “finding” the answer is easy, but you pay for it in prompt tokens and the model has more text to get lost in.

We also tried a regex that split at any line starting with #, ## or ###. It scored worse (9 out of 12 in top-1 with embeddinggemma) and produced more chunks (37 to 44, against 29 to 39 with the heading-based cuts): in this FAQ it also cut at the ### subsections and at a shell comment inside a code block, which starts with # too.
Which embedding model for an Ollama RAG
In this test, nomic-embed-text came out slightly ahead: 12 out of 12 with the heading-based chunks, against 11 out of 12 for embeddinggemma, which in one question didn’t put the right section first, though it was in its top three. With size-based chunks, nomic-embed-text matched or beat it in top-1 in all 5 rows, and top-3 was even. With 12 questions, one question is the whole difference, so we wouldn’t crown either one: both work, and the choice depends more on what we compared in the embeddings guide (vector size, languages, memory).
Indexing the FAQ (31 chunks, 5,186 tokens for embeddinggemma and 5,536 for nomic-embed-text, which splits the same text into more tokens) took 7.5 seconds with embeddinggemma and 5.6 with nomic-embed-text on our CPU (AMD Ryzen 7 7730U). We measured it once while another program was also using that CPU, so read those figures as a ceiling. You only pay for that once: after that, each question is a single short embedding.
Opens on YouTube (no cookies) only when you press play.
Just over 9 minutes, from August 2024 and part of a free course on Ollama. Its chapters follow the same path as this page, from the document type and getting the text out to chunking, embeddings, vector stores and querying. It explains the why; this page measures the how on version 0.40.18.
Answers with citations: what qwen3 did with 12 questions
With the right chunks in hand, qwen3:1.7b got 11 of the 12 answers right: the proxy variable, the models folder, OLLAMA_MAX_QUEUE for the 503, the Chrome extension origin, the KV cache type, the public key path, the 8K context, 0.0.0.0 for the home network, the cloud switch, the Cloudflare tunnel and ollama ps. Every answer came with its citation.
That last part took a second attempt. In our first version, the sources and the “cite them” order went together in the system message, and the 1.7B model cited a source in only 1 answer out of 12. We moved the sources into the user message, next to the question, and asked for the number after every sentence: 12 out of 12 answers came with a citation, for 20 extra prompt tokens. The script above is that second version.
The miss was the funniest one. Asked how to keep a model in RAM forever, the model replied with ollama stop, which does the opposite: it unloads it. The right chunk ("keep_alive": -1) was in first place among its sources. With the 0.6B model and the first prompt, the score was 10 out of 12 and only 1 answer with a citation; it also got the RAM question wrong (it said it can’t be done) and the home network one.
For comparison, we asked qwen3:1.7b the same 12 questions with no context (answers cut at 200 tokens). None of the 12 mentioned the Ollama setting that solves it: it answered in general terms, and in two of them it described Ollama as a version of the Llama model.

What the retrieved context costs: tokens and seconds
Without context, our questions took 25 to 35 prompt tokens. With the 3 retrieved chunks, 351 to 894: the context weighs roughly 10 to 36 times more than the question, and that is exactly what makes the answers right. It’s also what you wait for, because on a CPU the model has to read the whole prompt before writing the first word.
| qwen3:1.7b on CPU | Prompt tokens | Seconds per answer |
|---|---|---|
| Question only, no RAG | 25-35 | — |
| RAG, 3 chunks (the script) | 351-894 | 5.8-11.9 |
| RAG, 10 chunks | 1,538-1,989 | — |
| RAG, 20 chunks | 2,908-3,567 | — |
Measured on Ollama 0.40.18, 27 November 2026, AMD Ryzen 7 7730U without GPU, embedding of the question included in the seconds. One run per question, with another program using the same CPU: the seconds are a ceiling, the tokens don’t change.
More chunks isn’t always worse. With 10 chunks instead of 3, the same qwen3:1.7b got the RAM question right (keep_alive with -1), which it had missed with 3. So TOP_K is a dial between precision and speed: start with 3 and raise it if the answers fall short.
When the context goes over num_ctx: silent truncation
This is the trap that doesn’t make a sound. With 20 chunks the prompt reached 3,567 tokens; Ollama 0.40.18 loaded qwen3:1.7b with a 4,096-token context, so it fit, and the answers were correct. Then we lowered num_ctx to 2,048 with the same 20 chunks. Ollama answered with an HTTP 200, no error, and this line in its log:
level=WARN source=llama_server.go:350 msg="truncating input prompt" limit=1026 prompt=2908 keep=4 new=1026
Of 2,908 tokens, it kept the first 4 and the last 1,022 and threw away the middle. Going by the code that writes that line (llm/llama_server.go), the system instruction went, and so did the first sources, including source [1], the right one: what was left was the tail of the other sources and the question. The model, without its sources, made up a path (~/.ollama/public_key) and explained it with total confidence. It’s a bit like answering an exam after someone tore out the middle pages.

The clue is in the response itself: prompt_eval_count came back as 1,026 when the prompt had 2,908 tokens. Our script prints that number on every answer, so it’s easy to spot. If you need more context, raise num_ctx (in options or with OLLAMA_CONTEXT_LENGTH), knowing that it costs memory; our Ollama context length guide explains how.
“does not support embeddings”, “model not found” and the silent error of mixing models
These are the errors we hit while setting it up, with their literal text:
- A chat model as the embedding model (
EMBED=qwen3:1.7b):/api/embedanswers HTTP 501,{"error":"This server does not support embeddings. Start it with `--embeddings`"}, and the script shows it asrequests.exceptions.HTTPError: 501 Server Error: Not Implemented. The fix in a RAG is to use an embedding model inEMBED. - A model you haven’t downloaded (
MODEL=qwen3:4b): HTTP 404,{"error":"model 'qwen3:4b' not found"}. The fix isollama pull qwen3:4b. - Ollama isn’t running or listens on another port:
requests.exceptions.ConnectionError … [Errno 111] Connection refused. CheckOLLAMA_HOST.

The worst one gives no error at all. embeddinggemma and nomic-embed-text both return vectors of 768 numbers, so you can compare a question embedded with one against an index built with the other and Python won’t complain. We did it on purpose: with the index from embeddinggemma and the questions from nomic-embed-text, the right chunk came first in 1 of the 12 questions and in the top-3 also in 1, against 11 and 12 with the same model on both sides. That’s why our script puts the model name in the index file name: change EMBED and it builds a new index.
Three places this leads
- Ollama embeddings: the four embedding models compared,
/api/embedand its errors. - Ollama context length: how to raise
num_ctxand what it costs in memory. - Ollama MCP: when the model needs tools instead of documents.
Our Ollama runtime page has the version we track and what it runs on.