Build your first RAG system from scratch in plain Python
Chunk, embed, store, retrieve, prompt and answer with citations in about 120 lines of standard-library Python, then measure retrieval with hit@k.
A language model only knows what was in its training data. Ask it about your shop's deposit rules or last week's policy change and it will either guess or tell you it can't know. Retrieval-augmented generation (RAG), described in the 2020 paper by Lewis et al., fixes that by looking up the relevant text first and pasting it into the prompt. The model then answers from the text in front of it, not from memory.
Most first RAG tutorials start with pip install and four libraries, and the actual mechanism stays hidden inside a framework. This post builds every step by hand: chunking, embedding, a vector store, similarity search, the prompt and an answer with citations. The whole thing is one file of standard-library Python. The only outside piece is a local Ollama server for the two models, and the generation step can run on a stub if you don't have one. At the end, a ten-question test measures whether retrieval finds the right text, which is the step most beginner builds skip.
If you already have this working and want a persistent index, RAM sizing or refusal thresholds, read the local RAG app with Ollama and sqlite-vec. This post is the step before that one.
The six steps#
INDEX (once) QUERY (every question)
docs/*.txt "When do I get my deposit back?"
| |
v v
1. chunk: one paragraph per chunk embed the question
| ("search_query: ...")
v |
2. embed each chunk ------------------> 4. cosine similarity against
("search_document: ...") every stored vector, keep top 3
| |
v v
3. store: index.json 5. prompt: numbered sources + question
[{id, source, text, vector}, ...] |
v
6. model answers, cites [1] [2] [3]
|
v
check the citations point at real sources
Indexing runs once per change to the documents. The query side runs on every question and costs one embedding call plus one chat call.
Setup#
The code needs Python 3 and nothing from PyPI (it was run on Python 3.15 with Ollama 0.40.16). Install Ollama, then pull one embedding model and one small chat model:
ollama pull nomic-embed-text
ollama pull qwen3:4b-instruct
nomic-embed-text is 274 MB and returns 768 numbers per text. qwen3:4b-instruct is 2.5 GB and runs on a 16 GB laptop. Both talk over Ollama's HTTP API on localhost:11434, so urllib from the standard library is enough to call them. If you'd rather not run Ollama for embeddings, sentence-transformers with all-MiniLM-L6-v2 works as a drop-in for the embed function (384 dimensions, runs on CPU); only that one function changes.
The test documents are two short text files for an invented bike rental shop: rental terms (hours, prices, deposits, ID, late returns) and care rules (helmets, batteries, punctures, damage, cancellations). Each file is a title line followed by labelled paragraphs:
Pedalwise Cycle Rentals: rental terms
Opening hours. The Indiranagar shop opens at 7 am and closes at 9 pm every day except Tuesday, when it is closed for servicing. The Koramangala shop opens at 8 am and closes at 8 pm, seven days a week.
Deposit. Every rental needs a refundable deposit: 2,000 rupees for a city bike and 5,000 rupees for an electric bike. The deposit is returned to the original payment method within three working days after the bike comes back undamaged.
Invented documents are deliberate. You know every fact in them, so a wrong answer is obvious at a glance. Together the two files are 410 words.
Step 1: chunking#
Retrieval returns chunks, not documents, so the chunk is the unit of everything that follows. A chunk that is too big buries the answer in unrelated text and wastes prompt space. A chunk that is too small splits a fact from the sentence that explains it.
The first version of this code split the text into sentences and packed them into 60-word windows. It looked fine until the chunks were printed in full. The paragraph labels ("Batteries.", "Punctures.") end in a full stop, so the sentence splitter treated each label as a sentence of its own, and one chunk ended with the dangling word Batteries. while the battery facts went into the next chunk. Always print your chunks before you embed them.
The version below respects the structure the author already gave the text. One paragraph becomes one chunk. Only a paragraph longer than max_words is cut into sentence windows, and each window repeats the last sentence of the previous one so a fact on the boundary appears in both. Every chunk also starts with the document title, so a chunk about deposits still says which document it came from.
# 1. Chunk: one paragraph per chunk; long paragraphs become overlapping sentence windows.
def sentence_windows(paragraph, max_words, overlap):
sentences = re.split(r"(?<=[.!?])\s+", paragraph)
windows, cur = [], []
for s in sentences:
if cur and len(" ".join(cur + [s]).split()) > max_words:
windows.append(" ".join(cur))
cur = cur[-overlap:] if overlap else [] # repeat the last sentence(s) in the next window
cur.append(s)
windows.append(" ".join(cur))
return windows
def chunk(text, max_words=80, overlap=1):
title, *paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
chunks = []
for p in paragraphs:
pieces = [p] if len(p.split()) <= max_words else sentence_windows(p, max_words, overlap)
chunks += [f"{title}. {piece}" for piece in pieces] # every chunk says which document it is from
return chunks
With the default of 80 words, every paragraph fits, so the ten paragraphs become ten chunks of 33 to 59 words. Forcing max_words=30 shows the overlap at work. The battery paragraph splits in two, and the range sentence appears in both windows:
31 'Pedalwise Cycle Rentals: care and safety. Batteries. An electric bike battery gives about 45 km of range on a full charge in eco mode and about 25 km in sport mode.'
40 'Pedalwise Cycle Rentals: care and safety. An electric bike battery gives about 45 km of range on a full charge in eco mode and about 25 km in sport mode. Charging from empty takes four hours with the supplied charger.'
Words are a rough stand-in for tokens, and an 80-word chunk is far below the embedding model's limit. The limit still matters, because Ollama's /api/embed truncates over-long input by default rather than failing, and the cut-off part of the chunk is then missing from its vector.
Step 2: embedding#
An embedding model turns a piece of text into a fixed-length list of numbers, positioned so that texts with similar meaning end up close together. "When do I get my deposit back?" and "The deposit is returned within three working days" share only one word, but their vectors point in nearly the same direction.
# 2. Embed: one HTTP call to Ollama's /api/embed for a batch of texts.
def post(path, payload):
req = urllib.request.Request(OLLAMA + path, data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=120) as r:
return json.load(r)
def embed(texts, kind):
prefix = "search_query: " if kind == "query" else "search_document: " # nomic-embed-text wants these
return post("/api/embed", {"model": EMBED_MODEL, "input": [prefix + t for t in texts]})["embeddings"]
/api/embed takes a list in input and returns one vector per item, so all chunks from a file go in one request. The prefixes come from the nomic-embed-text model card: it was trained with search_document: on stored text and search_query: on questions. Leaving them out raises no error but shifts the similarity scores; the local RAG post measures by how much. Other embedding models have their own conventions, and all-MiniLM-L6-v2 uses none.
Whatever model you pick, chunks and questions must be embedded by the same one. Change models and you re-embed the whole corpus.
Step 3: the vector store#
For a few thousand chunks, a vector store can be a list of dictionaries saved as JSON:
# 3. Store: a list of {id, source, text, vector} written to a JSON file.
def build_index(folder, **chunk_args):
records = []
for path in sorted(pathlib.Path(folder).glob("*.txt")):
pieces = chunk(path.read_text(), **chunk_args)
for i, (text, vec) in enumerate(zip(pieces, embed(pieces, "document"))):
records.append({"id": f"{path.stem}#{i}", "source": path.name, "text": text, "vector": vec})
pathlib.Path(INDEX).write_text(json.dumps(records))
return records
$ python3 rag.py index docs
indexed 10 chunks, 768 dims each
The file is 106 KB for ten chunks, about 10 KB per chunk, almost all of it the 768 numbers written as decimal text. That scales to about 1 GB at 100,000 chunks, which is where you switch to a real store. The id field (rentals#2) is what makes citations possible later: it ties every retrieved chunk back to its file and position.
Step 4: retrieval with cosine similarity#
Cosine similarity measures the angle between two vectors: 1.0 means they point the same way, 0 means unrelated. With three-dimensional toy vectors you can check it by hand:
q = [1, 2, 0] a = [2, 4, 1] b = [0, 1, 3]
cos(q, a) = (1*2 + 2*4 + 0*1) / (sqrt(5) * sqrt(21)) = 10 / 10.247 = 0.976
cos(q, b) = (1*0 + 2*1 + 0*3) / (sqrt(5) * sqrt(10)) = 2 / 7.071 = 0.283
So a is the better match for q. Real embeddings do the same sum over 768 dimensions. Retrieval scores the question against every stored chunk and keeps the best k:
# 4. Retrieve: cosine similarity against every chunk, keep the top k.
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)))
def retrieve(records, question, k=3):
[q] = embed([question], "query")
scored = sorted(((cosine(q, r["vector"]), r) for r in records), key=lambda p: p[0], reverse=True)
return scored[:k]
This is a brute-force search: every question touches every vector. In pure Python that is fine for thousands of chunks and slow for millions. Vector databases explained rebuilds this search in numpy and then measures the HNSW and IVF indexes that make large collections fast.
Step 5: the prompt#
The prompt numbers each retrieved chunk, asks for those numbers after each fact, and gives the model an exact phrase to use when the answer is missing:
# 5. Prompt: number the chunks so the model can cite them.
PROMPT = """Answer the question using only the numbered sources below.
Put the source number in brackets after each fact, like this: "The shop opens at 7 am [2]."
If the sources do not contain the answer, reply exactly: I don't know.
{sources}
Question: {question}"""
def build_prompt(question, hits):
sources = "\n\n".join(f"[{i}] ({r['id']}) {r['text']}" for i, (_, r) in enumerate(hits, 1))
return PROMPT.format(sources=sources, question=question)
The example sentence inside the instructions is there for small models. A 4B model follows a shown format much more reliably than a described one. The fixed refusal phrase lets your code detect "no answer" with a string comparison.
Step 6: generation and citation checks#
The model sits behind a one-method interface, so you can swap the backend without touching anything else. OllamaLLM calls Ollama's /api/chat. StubLLM echoes the top source and needs no model at all, which is useful for testing the plumbing on a machine without a GPU. A hosted API goes in the same slot: write a class whose generate sends the prompt to the provider and returns the text.
# 6. Answer: any object with .generate(prompt) -> str works here.
class OllamaLLM:
def generate(self, prompt):
r = post("/api/chat", {"model": CHAT_MODEL, "stream": False,
"messages": [{"role": "user", "content": prompt}],
"options": {"temperature": 0, "num_ctx": 4096}})
return r["message"]["content"]
class StubLLM:
"""No model at all: returns the top source so you can test the plumbing."""
def generate(self, prompt):
first = prompt.split("[1] ", 1)[1].split("\n\n", 1)[0]
return f"(stub) {first} [1]"
def check_citations(answer, n_sources):
cited = {int(n) for n in re.findall(r"\[(\d+)\]", answer)}
return sorted(cited), sorted(c for c in cited if not 1 <= c <= n_sources)
def ask(question, llm, records, k=3):
hits = retrieve(records, question, k)
answer = llm.generate(build_prompt(question, hits))
cited, bad = check_citations(answer, len(hits))
return answer, hits, cited, bad
check_citations is a cheap guard. With three sources, a [4] in the answer means the model invented a reference, and you should not show that answer as cited. It can't tell you whether [2] supports the sentence it follows; grading that needs a judge, covered in LLM-as-a-judge in Python. num_ctx is set explicitly because Ollama's default context size depends on your VRAM (context length docs); three 80-word chunks plus the template come to well under 1,000 tokens, so 4,096 leaves plenty of room.
Run it#
Real output from three questions, each printing the top three chunks with their scores, the answer, and the citation check:
$ python3 rag.py ask "When do I get my deposit back?"
0.680 rentals#4 Pedalwise Cycle Rentals: rental terms. Late returns. A bike ...
0.669 rentals#2 Pedalwise Cycle Rentals: rental terms. Deposit. Every rental...
0.653 care#4 Pedalwise Cycle Rentals: care and safety. Cancellations. Onl...
You get your deposit back within three working days after the bike comes back undamaged [2].
cited [2], invalid []
$ python3 rag.py ask "My tyre went flat 10 km from the shop, what do I do?"
0.755 care#2 Pedalwise Cycle Rentals: care and safety. Punctures. If you ...
0.582 care#3 Pedalwise Cycle Rentals: care and safety. Damage. Minor scra...
0.571 care#4 Pedalwise Cycle Rentals: care and safety. Cancellations. Onl...
If your tyre went flat 10 km from the shop, you can bring the bike back by auto and the shop will refund up to 200 rupees of the fare [1].
cited [1], invalid []
$ python3 rag.py ask "Can my 17 year old son rent an electric bike?"
0.721 rentals#3 Pedalwise Cycle Rentals: rental terms. Identity. Renters mus...
0.681 care#0 Pedalwise Cycle Rentals: care and safety. Helmets. Every ren...
0.639 care#1 Pedalwise Cycle Rentals: care and safety. Batteries. An elec...
No, a 17-year-old son cannot rent an electric bike [1].
cited [1], invalid []
All three answers are correct and cite the right chunk.
The deposit question did not retrieve the deposit chunk first. The late-returns chunk won by 0.011, because it ends with "the full deposit is kept". Retrieval got it wrong at rank 1 and the answer was still right, because k=3 passed the correct chunk along as source [2] and the model picked it. That is the argument for retrieving more than one chunk.
The tyre answer applied the "further than 5 km" rule to a 10 km distance correctly, but it dropped the helpline number that the same chunk gives as the first step. The model answered the literal question. Citations tell you where an answer came from, not whether it is complete.
Measure retrieval before you tune anything#
Everything downstream depends on retrieval. If the right chunk never reaches the prompt, no prompt wording will fix the answer. The cheapest useful metric is hit@k: for each test question, is the chunk that holds the answer among the top k results?
Ten questions, phrased the way a customer would ask rather than copied from the documents. Each case names a phrase that only the correct chunk contains, so the test keeps working when chunk ids change:
CASES = [ # (question, a phrase that only the right chunk contains)
("Is the Indiranagar branch open on Tuesdays?", "closed for servicing"),
("How much is an e-bike for a whole day?", "1,100 rupees per day"),
("When do I get my deposit back?", "three working days"),
("Can my 17 year old son rent an electric bike?", "18 years old"),
("What happens if I keep the bike for three extra days?", "48 hours"),
("Do I have to wear a helmet?", "Helmets are mandatory"),
("How far can I ride the e-bike before the battery dies?", "45 km"),
("My tyre went flat 10 km from the shop, what do I do?", "refunds up to 200 rupees"),
("How much will I pay if I bend the wheel?", "bent wheel"),
("I booked online but can't make it, do I get money back?", "full refund up to 2 hours"),
]
def evaluate(records, ks=(1, 3), verbose=True):
hits = {k: 0 for k in ks}
for question, phrase in CASES:
ranked = rag.retrieve(records, question, k=max(ks))
rank = next((i for i, (_, r) in enumerate(ranked, 1) if phrase in r["text"]), None)
for k in ks:
hits[k] += rank is not None and rank <= k
if verbose:
print(f" rank {rank or '-'} top={ranked[0][0]:.3f} {question}")
return {k: hits[k] / len(CASES) for k in ks}
The script rebuilds the index at three chunk sizes and scores each one:
max_words=80: 10 chunks
rank 1 top=0.753 Is the Indiranagar branch open on Tuesdays?
rank 1 top=0.767 How much is an e-bike for a whole day?
rank 2 top=0.680 When do I get my deposit back?
rank 1 top=0.721 Can my 17 year old son rent an electric bike?
rank 1 top=0.727 What happens if I keep the bike for three extra days?
rank 1 top=0.678 Do I have to wear a helmet?
rank 1 top=0.826 How far can I ride the e-bike before the battery dies?
rank 1 top=0.755 My tyre went flat 10 km from the shop, what do I do?
rank 1 top=0.710 How much will I pay if I bend the wheel?
rank 1 top=0.718 I booked online but can't make it, do I get money back?
hit@1 90% hit@3 100%
max_words=30: 21 chunks
hit@1 80% hit@3 100%
max_words=15: 32 chunks
hit@1 80% hit@3 100%
Smaller chunks did worse here, and the verbose run shows why. At 30 words the puncture paragraph splits into "call the helpline, a mechanic comes within 5 km" and "further away, take an auto and get up to 200 rupees back". The question mentions a flat tyre, which matches the first window, but the answer lives in the second, so the right chunk drops to rank 2 (rank 3 at 15 words). One paragraph per chunk kept the fact and its condition together.
Ten questions over ten chunks is a smoke test: one question moving changes hit@1 by ten points, and with only ten chunks, hit@3 covers 30% of the whole corpus, so 100% there is easy. The test is useful because it is fast (under four seconds for all three runs) and it catches regressions. Before trusting the system on real documents, grow it to 50 or more questions collected from the people who will use the tool, include questions the documents can't answer, and re-run it after every change to chunking, the embedding model or k. Evaluating a RAG app in Python extends this to recall@k, MRR and answer grading, scored separately.
Where this breaks#
- Questions with no answer. Retrieval always returns k chunks, even for "Do you rent tandem bikes?", which the documents never mention. The prompt's "I don't know" rule is the only defence in this build. Adding a similarity threshold below which the app refuses without calling the model is covered in the local RAG post.
- Exact strings. Embeddings capture meaning and are weak on codes, part numbers and phone numbers. Asking for "080-4000-1234" may not retrieve the chunk containing it. Keyword search fixes that, which is the next step below.
- Facts spread across chunks. "What's the cheapest way to rent an e-bike for a week with theft protection?" needs the price chunk and the damage chunk together. With k=3 both might arrive; with a bigger corpus they often won't.
- Stale index.
build_indexre-embeds everything on every run. For ten chunks that costs nothing. For a real corpus, hash each chunk and embed only what changed.
Where to go next#
Each of these posts picks up where this one stops:
- The RAG cheat sheet: chunking strategies, hybrid search, reranking and metrics on one page.
- Local RAG with Ollama and sqlite-vec: a persistent index in one SQLite file, refusal thresholds, RAM sizing and
num_ctxtraps. - Vector databases explained: the brute-force search from step 4 in numpy, then HNSW and IVF measured.
- Hybrid search and reranking: BM25 plus vectors plus a cross-encoder, for the exact-string failures above.
- Evaluate a RAG app in Python: a fuller version of the hit@k test, with answer grading.
- RAG architectures compared: when naive RAG stops being enough, and what hybrid, agentic and graph variants change.
Start by adding your own ten questions to CASES and running the eval before you add a single new document.
Sources#
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (arXiv 2005.11401)
- Ollama API: embed
- Ollama API: chat
- Ollama: embeddings guide
- Ollama: context length
- Ollama download
- nomic-embed-text v1.5 model card
- nomic-embed-text in the Ollama library
- qwen3 in the Ollama library
- Sentence Transformers documentation
- all-MiniLM-L6-v2 model card
- Python docs: urllib.request
- Python docs: re