Platform Engineering · Lesson 256

Building RAG in Python, Step by Step

Retrieval-augmented generation (RAG) answers questions from your own documents: split them into chunks, turn chunks into embeddings, store them in an index, find the chunks closest to a question, and ask a model to answer from those chunks with citations. Each step is a few lines of Python, and each has a setting that decides whether answers are right. This lesson builds a documentation assistant end to end and evaluates it, and shows the two mistakes that make RAG confidently wrong: chunks that bury the answer, and documents and queries embedded with different models.

Difficulty: Advanced · Know this first: Lesson 244, Lesson 255

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes per question, including what bad settings cost to find. It is a worked example, not a measurement. The chunk and query hops decide whether retrieval finds the right text at all.

Try it: chunk size, overlap, and an answer near a boundary

The answer to a question is a 120-token passage somewhere in a page. Set the chunk size and overlap, and see how often the whole passage lands inside one chunk, and how much unrelated text comes with it.

96%answers kept whole in one chunk
96%of the chunk is other text

Diluted: the answer is a small part of a large chunk, so its embedding is mostly about other things

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

RAG in Python grows in four levels: a first pipeline, good retrieval, trustworthy answers, and RAG as a product.

Basic — A first pipeline

At the basic level you can answer questions from documents.

  • Load text, split into chunks, embed, store vectors in a NumPy array or pgvector.
  • Embed the question, take the top k by cosine similarity, put them in the prompt.
  • Ask the model to answer only from the context.

Where it breaks: never looking at what was retrieved, only at the final answer.

Try it: Basic

An answer is wrong. What should you look at first?

Now do it: Print the retrieved chunks for five wrong answers.

Intermediate — Good retrieval

At the intermediate level retrieval finds the right text.

  • Chunking at headings, 200 to 500 tokens, overlap, title prefixes.
  • Hybrid search with BM25 and reciprocal rank fusion; metadata filters.
  • A cross-encoder reranker on the top candidates.

Try it: Intermediate

Users search for error code E1043 and get unrelated results. What helps most?

Now do it: Add BM25 to a toy retriever and compare results for an exact term.

Advanced — Trustworthy answers

At the advanced level answers can be checked and are safe.

  • Citations to sources; "not found" when nothing clears the reranker threshold.
  • Access control enforced at retrieval; retrieved text treated as untrusted data.
  • An evaluation set with recall@k, groundedness, and refusal accuracy.

Try it: Advanced

Where must document permissions be enforced in RAG?

Now do it: Add an access-group filter to a retrieval query.

Master — RAG as a product

At the master level the system improves under measurement.

  • Incremental indexing on document change; re-embedding as a planned migration with dual indexes.
  • Feedback from users linked to the query, chunks, and answer.
  • Cost and latency budgets per stage; caching of embeddings and frequent answers.

Trade-off: more retrieved chunks and larger rerankers raise recall and cost and latency; measure where the gains stop.

Try it: Master

How do you change the embedding model without breaking retrieval?

Now do it: Write down the steps for an embedding migration for one index you know.

Go deeper

A complete, small RAG retriever in Python with chunking, a recorded embedding model, a model check at query time, and recall@k. It uses sentence-transformers (pip install sentence-transformers numpy).

import re, numpy as np
from sentence_transformers import SentenceTransformer

MODEL = "sentence-transformers/all-MiniLM-L6-v2"     # pin a revision in production
enc = SentenceTransformer(MODEL)

def chunk(title, text, size=120, overlap=24):
    words = text.split()
    step = size - overlap
    return [f"{title}: " + " ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]

docs = {
    "Timeouts": "The API gateway closes idle connections after 60 seconds. Upstream timeouts default to 30 seconds and can be raised to 120 with the upstream_timeout setting.",
    "Retries": "Clients should retry 429 and 503 responses with exponential backoff. Do not retry 400 responses.",
    "Billing": "Invoices are issued on the first day of each month and can be downloaded from the billing page.",
}
chunks = [c for t, body in docs.items() for c in chunk(t, body)]
index = {"model": MODEL, "vectors": enc.encode(chunks, normalize_embeddings=True), "chunks": chunks}

def search(q, k=2, model=MODEL):
    assert model == index["model"], "query and index use different embedding models"
    v = enc.encode([q], normalize_embeddings=True)[0]
    scores = index["vectors"] @ v
    return [(round(float(scores[i]), 3), index["chunks"][i][:60]) for i in np.argsort(-scores)[:k]]

evalset = [("How long until idle connections are closed?", "Timeouts"),
           ("Should I retry a 400 error?", "Retries"),
           ("When are invoices sent?", "Billing")]
hits = sum(any(c.startswith(want) for _, c in search(q)) for q, want in evalset)
print(f"recall@2 = {hits}/{len(evalset)}")
print(search("What is the maximum upstream timeout?"))

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. An assistant started answering nonsense after an upgrade that "only touched the query service".

Timeline

  • Tuesday 10:00The query service is redeployed with a newer embedding model of the same dimension, to improve quality. The document index, embedded with the old model, is left as it was.
  • Tuesday 10:00 to 12:00Answers become unrelated to questions; support tickets about the assistant spike. Every component reports healthy.
  • Tuesday 12:00Running the evaluation set shows recall@5 of 0.03. The query model is rolled back; a new index is built with the new model and switched over two days later.

What changed after

The index stores its model and revision, the query service refuses to search on a mismatch, model upgrades are migrations with a second index, and the evaluation set runs on every deploy.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install sentence-transformers for the commands.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Embeddings put similar meaning close together.

    python3 -c "from sentence_transformers import SentenceTransformer; m = SentenceTransformer('all-MiniLM-L6-v2'); v = m.encode(['reset my password', 'I forgot my login', 'invoice for March'], normalize_embeddings=True); print((v @ v.T).round(2))"
  2. Count tokens per chunk to choose a chunk size.

    python3 -c "text = open('/usr/share/common-licenses/GPL-3').read().split(); size, step = 400, 340; chunks = [text[i:i + size] for i in range(0, len(text), step)]; print(len(text), 'words ->', len(chunks), 'chunks of', size, 'with overlap', size - step)" 2>/dev/null || echo "use any long text file"
  3. Record the model with the index; refuse to mix models.

    python3 -c "import json; json.dump({'model': 'all-MiniLM-L6-v2', 'revision': 'pinned-sha', 'dim': 384}, open('index-meta.json', 'w')); print(open('index-meta.json').read())"; rm -f index-meta.json

2. Python: retrieval_eval.py

This program builds a tiny bag-of-words retriever, measures recall@2 on an evaluation set with small and large chunks, and shows what happens when queries are embedded with a different "model" than the documents. Save it as retrieval_eval.py, then run it.

# retrieval_eval.py
import math, re
from collections import Counter

doc = ("Timeouts. The gateway closes idle connections after 60 seconds. Upstream timeout defaults to 30 seconds. "
       "Retries. Clients retry 429 and 503 with exponential backoff. Never retry 400 errors. "
       "Billing. Invoices are issued on the first day of the month. Refunds take five days. "
       "Login. Reset your password from the account page. Accounts lock after five failed attempts.")
words = doc.split()
evalset = [("how long until idle connections close", "60 seconds"), ("should I retry a 400", "Never retry 400"),
           ("when are invoices issued", "first day"), ("how many failed attempts lock an account", "lock after five")]
tok = lambda s: Counter(w for w in re.findall(r"[a-z0-9]+", s.lower()) if len(w) > 2)
def cos(a, b):
    dot = sum(a[w] * b[w] for w in a)
    return dot / (math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values())) or 1)

def recall(size, overlap, query_model=tok):
    step = size - overlap
    chunks = [" ".join(words[i:i + size]) for i in range(0, len(words), step)]
    hits = 0
    for q, answer in evalset:
        top = sorted(chunks, key=lambda c: -cos(query_model(q), tok(c)))[:2]
        hits += any(answer in c for c in top)
    return hits, len(chunks)

for size, overlap in [(12, 3), (60, 0)]:
    hits, n = recall(size, overlap)
    print(f"chunks of {size:>2} words, overlap {overlap}: {n:>2} chunks, recall@2 {hits}/{len(evalset)}")
other_model = lambda s: Counter(w[::-1] for w in tok(s))          # a different "embedding space"
hits, _ = recall(12, 3, other_model)
print(f"queries embedded with a different model: recall@2 {hits}/{len(evalset)}")

Run it, and you should see this output:

$ python3 retrieval_eval.py
chunks of 12 words, overlap 3:  7 chunks, recall@2 4/4
chunks of 60 words, overlap 0:  1 chunks, recall@2 4/4
queries embedded with a different model: recall@2 1/4

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/building-rag-in-python && cd ~/labs/building-rag-in-python) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Building RAG in Python, Step by Step", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Embeddings put similar meaning close together.'
  'Count tokens per chunk to choose a chunk size.'
  'Record the model with the index; refuse to mix models.'
)

step_1() {
python3 -c "from sentence_transformers import SentenceTransformer; m = SentenceTransformer('all-MiniLM-L6-v2'); v = m.encode(['reset my password', 'I forgot my login', 'invoice for March'], normalize_embeddings=True); print((v @ v.T).round(2))"
}

step_2() {
python3 -c "text = open('/usr/share/common-licenses/GPL-3').read().split(); size, step = 400, 340; chunks = [text[i:i + size] for i in range(0, len(text), step)]; print(len(text), 'words ->', len(chunks), 'chunks of', size, 'with overlap', size - step)" 2>/dev/null || echo "use any long text file"
}

step_3() {
python3 -c "import json; json.dump({'model': 'all-MiniLM-L6-v2', 'revision': 'pinned-sha', 'dim': 384}, open('index-meta.json', 'w')); print(open('index-meta.json').read())"; rm -f index-meta.json
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Build an internal assistant over 40,000 Confluence pages and 10,000 runbooks, with per-team permissions and nightly updates.

Clarifying questions to ask

How do you chunk pages with tables and code? Which embedding model, and how is it recorded? How are permissions enforced? How do you measure quality and catch regressions? What happens when a page changes?

Rough sizing

Say 60 million tokens, about 200,000 chunks, 2,000 changed pages a night, 500 questions a day, and a 5-second answer budget.

Shape of the answer

Heading-aware chunking of 400 tokens with overlap, keeping tables whole; one pinned embedding model stored with each vector; pgvector with metadata (space, team, version) and HNSW; hybrid search with BM25 and rank fusion; access filters from the user's groups at query time; a cross-encoder reranker on the top 30; answers with citations and "not found"; incremental re-embedding of changed pages; a 300-question evaluation set run nightly and on every deploy.

Trade-offs to name

Smaller chunks raise precision and make more vectors; a reranker improves answers and adds latency. Strict permission filters can hide the only page that answers a question, so log "not found" answers to find gaps.

Saved on this device, in this browser.
Next in this series · Lesson 257
Serving Models from Python with FastAPI

Many models reach users through a small Python web service: FastAPI for the HTTP layer, Pydantic for request and response schemas, and a model loaded into memory.

Go to Lesson 257 →

Or browse the full course from the Lessons index.