RAG basics: answer questions from your documents
RAG (retrieval-augmented generation) lets an LLM answer from your own documents. You split documents into chunks, find the chunks most relevant to the question, and paste them into the prompt with an instruction to answer only from that context. The model then answers with your facts instead of guessing.
The three steps
| Step | What happens | Typical tools |
|---|---|---|
| 1. Index | Split documents into chunks and store them with a searchable representation | Text splitters, embedding models, vector databases |
| 2. Retrieve | Find the chunks most similar to the question | Cosine similarity, keyword search, or both |
| 3. Generate | Send the question plus those chunks to an LLM | Any LLM API |
We'll build a tiny version in plain Python that runs in your browser, so every step is visible. Real systems swap in better parts but keep the same shape.
Step 1: chunking
handbook = """Holidays: employees get 25 paid holiday days per year. Unused days expire on 31 March.
Remote work: you may work from home up to three days per week. Agree the days with your manager.
Expenses: submit receipts within 30 days. Meals are reimbursed up to 25 euros per day when travelling.
Laptops: request a new laptop through the IT portal. Replacements are every three years."""
chunks = [line.strip() for line in handbook.splitlines() if line.strip()]
for i, c in enumerate(chunks):
print(i, c[:45] + "...")0 Holidays: employees get 25 paid holiday days ... 1 Remote work: you may work from home up to thr... 2 Expenses: submit receipts within 30 days. Mea... 3 Laptops: request a new laptop through the IT ...
Each chunk should hold one idea and enough context to make sense on its own. Real documents are usually split into pieces of a few hundred words, often with a small overlap so sentences aren't cut in half.
Step 2: retrieval
import math
import re
from collections import Counter
chunks = [
"Holidays: employees get 25 paid holiday days per year. Unused days expire on 31 March.",
"Remote work: you may work from home up to three days per week. Agree the days with your manager.",
"Expenses: submit receipts within 30 days. Meals are reimbursed up to 25 euros per day when travelling.",
"Laptops: request a new laptop through the IT portal. Replacements are every three years.",
]
STOP = {"the", "a", "to", "are", "is", "up", "per", "you", "your", "on", "with", "of", "how", "many", "can", "i", "do", "when", "get", "my", "from"}
def vectorise(text: str) -> Counter:
words = re.findall(r"[a-z]+", text.lower())
return Counter(w for w in words if w not in STOP)
def cosine(a: Counter, b: Counter) -> float:
dot = sum(a[w] * b[w] for w in a)
norm = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values()))
return dot / norm if norm else 0.0
def retrieve(question: str, k: int = 1) -> list[tuple[float, str]]:
q = vectorise(question)
scored = [(round(cosine(q, vectorise(c)), 3), c) for c in chunks]
return sorted(scored, reverse=True)[:k]
for question in ["How many holiday days do I get?", "Can I work from home?", "When are meals reimbursed?"]:
score, best = retrieve(question)[0]
print(f"{score:.3f} {best[:40]}...")0.612 Holidays: employees get 25 paid holiday ... 0.548 Remote work: you may work from home up t... 0.447 Expenses: submit receipts within 30 days...
Here each chunk becomes a bag of word counts and we compare them with cosine similarity — the same maths as in the NumPy lesson. It only matches exact words, though: "vacation" would not find "holiday".
Step 3: a grounded prompt
def build_prompt(question: str, context: list[str]) -> str:
sources = "\n".join(f"[{i + 1}] {c}" for i, c in enumerate(context))
return (
"Answer the question using only the sources below. "
"Cite sources like [1]. If the answer isn't in the sources, say you don't know.\n\n"
f"Sources:\n{sources}\n\nQuestion: {question}"
)
context = ["Holidays: employees get 25 paid holiday days per year. Unused days expire on 31 March."]
print(build_prompt("How many holiday days do I get?", context))Answer the question using only the sources below. Cite sources like [1]. If the answer isn't in the sources, say you don't know. Sources: [1] Holidays: employees get 25 paid holiday days per year. Unused days expire on 31 March. Question: How many holiday days do I get?
- "Only the sources below" keeps the model from mixing in guesses.
- Citations let users check the answer against the original text.
- Permission to say "I don't know" is the single best defence against made-up answers.
Upgrading to embeddings
import numpy as np
# embed() calls an embedding model from your provider or a local library;
# each text becomes a vector of hundreds of numbers that captures its meaning.
chunk_vectors = np.array([embed(c) for c in chunks])
chunk_vectors /= np.linalg.norm(chunk_vectors, axis=1, keepdims=True)
def retrieve(question: str, k: int = 3) -> list[str]:
q = embed(question)
q /= np.linalg.norm(q)
scores = chunk_vectors @ q # cosine similarity with every chunk at once
best = np.argsort(scores)[::-1][:k]
return [chunks[i] for i in best]Embeddings match meaning, so "vacation allowance" finds the holidays chunk. For thousands of documents, a vector database (pgvector, Chroma, Qdrant and others) stores the vectors and searches them quickly. Many production systems combine embedding search with keyword search for the best results.
Practice
Build the simplest retriever: score each chunk by how many words of the question it contains (lowercase, split on spaces), and print the best chunk for the question "when do laptops get replaced".
laptops are replaced every three years