Local RAG with Ollama: how retrieval-augmented generation works
What RAG is, how each stage works (chunking, embeddings, retrieval and generation), and how to build a local, private version with Ollama and Python.
In short
RAG (Retrieval-Augmented Generation) is a technique in which, before a language model answers, the system retrieves the most relevant passages from your own knowledge base and adds them to the prompt. The answer is then grounded in documents the model never saw during training. With Ollama, both embeddings and generation run locally, without sending data to external services.
The problem RAG solves
A language model only knows what was in its training data. It doesn't know your company's internal documentation, your product manual or what changed last week. Asked about any of that, it tends to answer confidently and get it wrong.
RAG, described by Lewis and colleagues in 2020, separates two jobs: retrieving information from a trusted source and generating the answer in natural language. The model stops being the source of knowledge and becomes the writer of an answer based on the context it is given. Updating knowledge becomes a matter of re-indexing documents, not retraining a model.
The stages of a RAG pipeline
- Ingestion: extract text from the sources (Markdown, PDFs, web pages, tickets).
- Chunking: split documents into pieces of a few hundred words.
- Embeddings: turn each chunk into a numeric vector that represents its meaning.
- Storage: keep chunks and vectors (in memory, in a file or in a vector database).
- Retrieval: turn the question into a vector and find the closest chunks.
- Generation: send the question and chunks to the model, with instructions to answer only from them.
Running Ollama locally
Ollama serves language and embedding models through a local HTTP API, on port 11434 by default. With Docker:
docker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollama
docker exec ollama ollama pull nomic-embed-text
docker exec ollama ollama pull llama3.2
These are two models with different roles: nomic-embed-text produces the vectors and llama3.2 writes the answers. Any equivalent pair works, as long as the same embedding model is used to index the documents and to embed the questions. Changing the embedding model means re-indexing everything, because vectors from different models aren't comparable.
A minimal RAG in Python
The example below uses only the requests library and cosine similarity computed in plain Python. It's meant for understanding the mechanism; for thousands of chunks, use a vector index.
import math
import requests
OLLAMA = "http://localhost:11434"
def embed(texts):
response = requests.post(f"{OLLAMA}/api/embed",
json={"model": "nomic-embed-text", "input": texts})
response.raise_for_status()
return response.json()["embeddings"]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
chunks = [
"The Pro plan allows up to 10 users and includes email support.",
"Refunds can be requested within 7 days of purchase.",
"The API is limited to 100 requests per minute per key.",
]
vectors = embed(["search_document: " + c for c in chunks])
def retrieve(question, k=2):
q = embed(["search_query: " + question])[0]
ranked = sorted(zip(chunks, vectors), key=lambda cv: cosine(q, cv[1]), reverse=True)
return [chunk for chunk, _ in ranked[:k]]
def answer(question):
context = "\n".join(f"[{i + 1}] {c}" for i, c in enumerate(retrieve(question)))
messages = [
{"role": "system", "content": (
"Answer only from the provided context. "
"If the answer is not in the context, say you don't know. "
"Cite the passages you used as [n].")},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
]
response = requests.post(f"{OLLAMA}/api/chat",
json={"model": "llama3.2", "messages": messages, "stream": False})
response.raise_for_status()
return response.json()["message"]["content"]
print(answer("How long do I have to ask for a refund?"))
The search_document: and search_query: prefixes are a convention specific to nomic-embed-text, which was trained to tell documents and questions apart. Other embedding models have their own conventions or none at all; check the model's page.
The decisions that most affect quality
Chunk size and boundaries
Chunks that are too large dilute meaning and eat into the model's context; chunks that are too small lose information needed to answer. A common starting point is 200 to 500 words with some overlap between neighbors. More important than the number is respecting the document's structure: splitting by section or heading avoids cutting an explanation in half.
How many chunks to retrieve
Raising k increases the chance that the right chunk is in the context, but it also adds noise and slows generation on local models. Tune it with real questions, not intuition.
Where to store the vectors
For a few thousand chunks, an in-memory list is enough. Beyond that, a vector index avoids comparing the question with every vector. If the application already uses PostgreSQL, the pgvector extension stores embeddings next to the data and offers approximate indexes (HNSW and IVFFlat); the same practices for choosing and validating indexes with EXPLAIN ANALYZE apply.
Evaluate retrieval separately from generation
When a RAG system answers wrongly, the cause is usually in one of two stages: the right chunk wasn't retrieved, or it was retrieved and the model didn't use it well. Mixing the two leads to tweaking the prompt when the problem was chunking.
A simple and effective practice is to build a list of real questions together with the chunk that should answer each one, and measure, before any generation, how often that chunk appears in the top k. Only once retrieval is good is it worth tuning the prompt and the generation model.
Limitations
- RAG reduces made-up answers, but doesn't eliminate them; the model can still misread the context.
- Questions that require aggregating information across many documents ("how many customers complained about this?") aren't well served by similarity search.
- Small local models are faster and private, but follow instructions less strictly than larger ones.
In production, a RAG assistant is a service like any other: it needs uptime monitoring and alerting, especially when it depends on a separate model server.
Related writing
All writing-
Software Engineering · · 3 min read
PostgreSQL indexes: B-tree, GIN and partial indexes, validated with EXPLAIN ANALYZE
How to choose between B-tree, GIN, composite and partial indexes in PostgreSQL, read the plan with EXPLAIN ANALYZE, and create indexes without locking production.
-
Software Engineering · · 4 min read
Uptime monitoring: why you should alert only after consecutive failures
How to build an availability monitor that catches real outages without false alarms: consecutive failures, detection time, states and a C# example.
-
Software Engineering · · 3 min read
N+1 queries in Rails: how to find them, fix them and keep them from coming back
What the N+1 problem is in Active Record, when to use includes, preload or eager_load, and how strict_loading stops regressions.