AI Engineering · Build lab 6 of 14

RAG from scratch in Python: chunking, embeddings, pgvector and answers with citations

Build retrieval augmented generation by hand: chunk a Markdown handbook by headings, embed it with nomic-embed-text, search a NumPy store, then Postgres with pgvector and an HNSW index, behind one VectorStore interface. Answer with numbered citations, refuse when retrieval is weak, and debug what was retrieved.

⏱ 80 minIntermediate💸 Free (local models)10 stepsPython + Java

Python 3.12uvOllamallama3.2:3bnomic-embed-textNumPyPostgres + pgvector (Docker)psycopg 3Spring AI 1.0 (optional)

Overview video

1 / 7

0 of 10 steps done

What you will build

A question answering tool for a company handbook. You ask "How much can I spend on a hotel in London?" and it answers from the handbook, with a citation like [1] that points to the exact file and section. When the handbook does not cover the question, it says so instead of making something up.

You build every part yourself, so nothing is magic: load eight Markdown files, chunk them by heading with overlap, embed every chunk, store the vectors, retrieve the closest chunks for a question, build a prompt with numbered sources, and check the answer's citations.

The vectors live first in a NumPy matrix (in memory, saved to a folder), then in Postgres with pgvector started by Docker. Both sit behind one small VectorStore interface, so the RAG code does not change when the database does. The tests use the in-memory store and fakes, so they need no model and no Docker.

Before you start

Setup

S1Install uv (the Python project tool)

Skip this if you did lab 1. uv installs Python for you, creates the virtual environment and manages packages. One tool instead of pyenv + venv + pip.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
everything's installed!

S2Check uv works

The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.

Run
uv --version
You should see
uv 0.x.y

S3Install Ollama (runs models on your machine)

Skip this if you did lab 1. Download it from ollama.com/download and open it once. It runs a small server on port 11434 that speaks the same API as the hosted providers, for chat and for embeddings.

Run
ollama --version
You should see
ollama version is 0.x.y

S4Pull the chat model and the embedding model

llama3.2:3b (about 2 GB) writes the answers. nomic-embed-text (about 270 MB) turns text into 768 numbers; it is the same embedding model as lab 5. ollama list should show both afterwards.

Run
ollama pull llama3.2:3b
ollama pull nomic-embed-text
ollama list
You should seeyour text will differ: the model writes it
NAME                       ID              SIZE      MODIFIED
nomic-embed-text:latest    0a109f422b47    274 MB    2 seconds ago
llama3.2:3b                a80c4f17acd5    2.0 GB    3 days ago

S5Docker Desktop (for steps 8 and 9 only)

Steps 8 and 9 run Postgres with the pgvector extension in a container. Install Docker Desktop from docker.com/products/docker-desktop (macOS and Windows; on Windows it uses WSL 2) and open it once, so the Docker engine is running. On Linux, install Docker Engine and the Compose plugin from your distribution or docs.docker.com.

No Docker? Skip steps 8 and 9. Everything else, including the tests, uses the in-memory store and works without it.

Run
docker compose version
You should see
Docker Compose version v2.x.y

S6Java only (optional): JDK 21 and Maven

Only for the Spring AI version of step 9 (switch to Java at the top of the steps). Same tools as lab 1. It also needs Docker, for Postgres.

Run
brew install openjdk@21 maven
1

Create the project

A fresh project with NumPy, the SDK and pytest, plus the settings from lab 1 and three new ones.

uv init creates the project folder and pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them, so anyone can recreate it with uv sync. The Postgres packages come later, in step 8.

The settings grow by three: the embedding model, the minimum score a chunk needs to count as relevant (used in step 7), and the database URL (used in step 9). Copy .gitignore and llm.py from lab 1 or from below.

.env
# Local models through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
EMBED_MODEL=nomic-embed-text

# Retrieval: below this cosine similarity a chunk does not count as relevant.
MIN_SCORE=0.65

# Postgres with pgvector, started by docker compose in step 8.
DATABASE_URL=postgresql://rag:rag@localhost:5433/rag
  1. Ollama's OpenAI-compatible API. Chat and embeddings both live under this URL.line 2
  2. The embedding model. Documents and questions must be embedded by the **same** model, or their vectors cannot be compared.line 5
  3. A cosine similarity between 0 and 1. Step 7 explains how to pick it from real scores.line 8
  4. User rag, password rag, port 5433, database rag: the values docker-compose.yml sets up in step 8. Port 5433 so it does not clash with a Postgres you may already run on 5432.line 11
config.py 6 new or changed lines
import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()  # read .env into environment variables (real env vars win)


@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str
    embed_model: str
    min_score: float
    database_url: str


def settings() -> Settings:
    return Settings(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
        api_key=os.environ.get("LLM_API_KEY", "ollama"),
        model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
        embed_model=os.environ.get("EMBED_MODEL", "nomic-embed-text"),
        min_score=float(os.environ.get("MIN_SCORE", "0.65")),
        database_url=os.environ.get("DATABASE_URL", "postgresql://rag:rag@localhost:5433/rag"),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell or on the server take priority.line 6
  2. frozen=True makes the settings read-only, so nothing changes them by accident.line 9
  3. Environment variables are always strings. float(...) turns "0.65" into the number 0.65, like Double.parseDouble or parseFloat.line 25
.gitignore
.venv/
__pycache__/
.env
index/
  1. Never commit .env: one day it holds a real key.line 3
  2. index/ is the saved in-memory store (step 5). It is rebuilt from the handbook, so it does not belong in git.line 4
llm.py
from openai import OpenAI

from config import settings


def make_client() -> OpenAI:
    s = settings()
    return OpenAI(base_url=s.base_url, api_key=s.api_key, timeout=120, max_retries=2)
  1. A function, not a global: the RAG code receives the client as a parameter, so tests can hand it a fake (step 10).line 6
  2. Generous timeout for a local model on a laptop CPU. max_retries=2 retries network errors, 429 and 5xx for you.line 8
Run
uv init rag-handbook
cd rag-handbook
uv add numpy openai python-dotenv
uv add --dev pytest
You should seeyour text will differ: the model writes it
Initialized project `rag-handbook` at `.../rag-handbook`
Resolved 18 packages in 450ms
Installed 16 packages in 40ms
 + numpy==2.5.5
 + openai==3.60.0
 + python-dotenv==1.2.4
 ...
Stuck on this step?
uv: command not found
Run export PATH="$HOME/.local/bin:$PATH" (macOS and Linux), or open a new terminal so the installer's PATH change applies.
uv also created main.py
Newer uv versions write a hello-world main.py. This lab does not use it: delete it or leave it.
2

The handbook: eight Markdown files

A small, realistic knowledge base: the employee handbook of Larkspur, a made-up software company.

Make a folder called handbook and save the eight files below in it. Every file has one # title and a few ## sections, the way most internal docs, wikis and READMEs are written. The company, its tools (Peoplebase, TravelDesk) and its rules are invented, which is the point: the model cannot know them from training, so a correct answer must come from retrieval.

Look at expenses.md: its Hotels section is longer than the others. Step 3 splits it in two, and you will see the overlap at work.

handbook/expenses.md
# Travel and expenses

## Booking travel
Book all work travel in TravelDesk, at least 14 days ahead when you can. Fly economy class. For trips under four hours, take the train instead of flying.

Your manager approves each trip in TravelDesk before you book. Trips to a customer also need the account owner's approval.

## Hotels
Hotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night.

Book a hotel within walking distance or a short public transport ride of where you work. Breakfast is included in the limit when the hotel sells it with the room.

If a conference hotel costs more than the limit, ask your manager before booking. Approved exceptions are noted on the trip in TravelDesk, so finance can see them when you submit the bill.

## Meals
On a work trip, meals are covered up to 60 euros a day. Alcohol is not covered.

## Submitting expenses
Submit expenses in Peoplebase within 30 days, with a photo of every receipt. They are paid with your next salary.
  1. Approval rules like this are why RAG exists: the facts live in your documents, not in the model.line 6
  2. The longest section (three paragraphs), so it becomes two chunks in step 3.line 8
  3. The answer to the question you ask in step 6: 250 euros a night in London.line 9
handbook/time-off.md
# Time off

## Vacation
Everyone gets 25 vacation days a year, plus the public holidays of the country you work from. The year runs from January to December.

You can carry up to 5 unused days into the next year. Carried days expire on 31 March.

## Sick leave
There is no fixed number of sick days. Tell your manager before 10:00 on the first day. From the fourth day in a row, send a doctor's note to the People team.

## Parental leave
Every parent gets 16 weeks of fully paid leave, to take within the first year after a birth or adoption. You can split it into up to three blocks.

## How to request time off
Request time off in Peoplebase. For more than three days in a row, ask at least two weeks ahead.
handbook/remote-work.md
# Remote work

## Where you can work
You can work from any country where Larkspur has a company: Portugal, Spain, Germany or the United Kingdom.

Working from another country is allowed for up to 30 days a year. Tell the People team before you go, because of tax and insurance rules.

## Core hours
Be available from 11:00 to 15:00 Lisbon time. Outside core hours, plan your day as you like.

## Home office budget
New joiners get a one-time budget of 1,000 euros for a desk, a chair and a screen. Internet at home is paid with 40 euros a month on top of your salary.
handbook/security.md
# Security

## Your laptop
Laptops use full-disk encryption and lock after 5 minutes. Never leave your laptop in a car, not even in the trunk.

## Passwords and two-factor login
Use the company password manager for every work account. Turn on two-factor login with the hardware key you get on your first day.

## Lost or stolen devices
If a laptop, phone or hardware key is lost or stolen, report it in the #security-help channel within one hour, or email security@larkspur.example. The security team locks the device remotely.

## Phishing
Forward suspicious emails to phishing@larkspur.example and delete them. The finance team never asks for payments by email or chat.
handbook/onboarding.md
# Your first week

## Before day one
Your laptop and hardware key arrive at your home address a few days before you start. Do not set them up yet.

## Day one
The welcome call starts at 10:00 Lisbon time. You meet your onboarding buddy, who sets up the laptop with you and answers questions for your first month.

## First week checklist
Read this handbook, set up the password manager, book a coffee chat with each person on your team, and ship one small change to production.
handbook/on-call.md
# On-call

## The rotation
Engineers join the on-call rotation after three months at Larkspur. A shift lasts one week, from Monday 10:00 to the next Monday 10:00.

## On-call pay
You get 300 euros for each week on call, plus 50 euros for each incident you handle outside working hours.

## Responding to a page
Acknowledge a page within 15 minutes. If you cannot fix it within 30 minutes, escalate to the secondary on-call engineer.

## After an incident
Write a blameless postmortem within five working days and share it in the #incidents channel.
handbook/benefits.md
# Benefits

## Health insurance
Private health insurance covers you, your partner and your children from your first day.

## Learning budget
Each person has 1,500 euros a year for books, courses and conferences. Spending over 500 euros at once needs your manager's approval.

## Equipment
You get a new laptop every three years. A broken laptop is replaced straight away.

## Wellbeing
Larkspur pays up to 50 euros a month towards a gym, a sports club or a meditation app.
handbook/offices.md
# Offices

## The Lisbon office
The Lisbon office is open from 08:00 to 20:00 on working days. Guests sign in at reception and wear a visitor badge.

## Meeting rooms
Book meeting rooms in the office calendar. Free a room you no longer need, so others can use it.

## Team weeks
Each team meets in Lisbon for one week, twice a year. Larkspur pays the travel and the hotel for team weeks.
Why this way? Use documents the model has never seen when you build and test RAG. With public facts (the capital of France) a wrong retrieval still gives a right answer, and you never notice retrieval is broken.
3

Chunk by headings, with overlap

Turn eight files into small, self-contained chunks that each know where they came from.

You do not embed whole files. A file mixes many topics, so its vector is a blurry average of all of them, and a long file would fill the prompt. You split it into chunks: pieces small enough to be about one thing.

Where to cut matters. Cutting every 400 characters splits sentences in half. Cutting at headings follows the author's own structure: one section, one topic. Each chunk keeps metadata: the file name (source) and the heading path (Travel and expenses > Hotels), which you need later for citations.

A section longer than max_chars is split between paragraphs, and each new piece repeats the last paragraph of the one before (the overlap). A fact that sits on the border, or a sentence that refers back to the previous paragraph, then still has its context in at least one chunk.

chunking.py
import re
from dataclasses import dataclass
from pathlib import Path

HEADING = re.compile(r"^(#{1,6})\s+(.+)$")


@dataclass(frozen=True)
class Chunk:
    id: str  # "expenses.md#3": the file name and the chunk's position, unique
    source: str  # "expenses.md"
    heading: str  # "Travel and expenses > Hotels"
    text: str

    def for_embedding(self) -> str:
        """What the embedding model sees: the heading path gives a short chunk its context."""
        return f"{self.heading}\n\n{self.text}"


def split_sections(markdown: str) -> list[tuple[str, list[str]]]:
    """Cut a Markdown file at its headings. Returns [(heading path, [paragraph, ...]), ...]."""
    sections = []
    path: list[str] = []  # the headings above the current line, one per level
    paragraphs: list[str] = []
    lines: list[str] = []

    def end_paragraph():
        if lines:
            paragraphs.append("\n".join(lines))
            lines.clear()

    def end_section():
        end_paragraph()
        if paragraphs:
            sections.append((" > ".join(path), paragraphs.copy()))
            paragraphs.clear()

    for line in markdown.splitlines():
        match = HEADING.match(line)
        if match:
            end_section()
            level = len(match.group(1))
            path[level - 1:] = [match.group(2).strip()]
        elif line.strip():
            lines.append(line.strip())
        else:
            end_paragraph()
    end_section()
    return sections


def pack(paragraphs: list[str], max_chars: int, overlap: int) -> list[str]:
    """Group paragraphs into pieces of about max_chars. Each new piece repeats the last
    "overlap" paragraphs of the piece before, so a fact on the border is in both."""
    pieces = []
    current: list[str] = []
    for paragraph in paragraphs:
        if current and len("\n\n".join(current + [paragraph])) > max_chars:
            pieces.append(current)
            current = current[-overlap:] if overlap > 0 else []
        current.append(paragraph)
    if current:
        pieces.append(current)
    return ["\n\n".join(piece) for piece in pieces]


def chunk_markdown(markdown: str, source: str, max_chars: int = 400, overlap: int = 1) -> list[Chunk]:
    chunks = []
    for heading, paragraphs in split_sections(markdown):
        for text in pack(paragraphs, max_chars, overlap):
            chunks.append(Chunk(id=f"{source}#{len(chunks)}", source=source, heading=heading, text=text))
    return chunks


def load_handbook(folder: str = "handbook") -> list[Chunk]:
    chunks = []
    for path in sorted(Path(folder).glob("*.md")):
        chunks.extend(chunk_markdown(path.read_text(encoding="utf-8"), path.name))
    return chunks
  1. A regular expression for a Markdown heading: one to six #, a space, then the title. Group 1 is the hashes (its length is the level), group 2 the title. r"..." is a raw string, so \s reaches the regex engine unchanged.line 5
  2. @dataclass(frozen=True) writes the constructor, equals, hashCode and toString for you, and makes the object immutable. Like a Java record.line 8
  3. The text that gets **embedded** includes the heading path. "Up to 180 euros a night" alone does not say "hotel"; with the heading in front, the vector does.line 15
  4. path holds one heading per level: ["Travel and expenses", "Hotels"]. Joined with " > ", it becomes the heading path.line 23
  5. A function inside a function. It can read and change the lists of the outer function (lines.clear(), paragraphs.append(...)), like a Java lambda capturing an object. It cannot rebind their names, and it does not need to.line 27
  6. splitlines() splits on line breaks. A blank line ends a paragraph; a heading ends a section.line 38
  7. Slice assignment: replace everything from index level - 1 to the end with the new title. A ## heading (level 2) keeps the # title and drops the previous ## and anything deeper.line 43
  8. Would this paragraph make the piece too long? Then close the current piece first. current and ... skips the check for the first paragraph, so a single huge paragraph still becomes a chunk.line 58
  9. The overlap: start the next piece with the last overlap paragraphs. The if is needed because current[-0:] is the **whole** list in Python, not an empty one.line 60
  10. The id is the file name plus the chunk's position: unique, readable and stable while the file does not change.line 71
  11. sorted(...) so the order (and so the ids) is the same on every machine. glob("*.md") lists the Markdown files.line 77
show_chunks.py
from chunking import load_handbook

chunks = load_handbook("handbook")
for c in chunks:
    print(f"{c.id:<16} {c.heading:<42} {len(c.text):>3} chars")
print(f"\n{len(chunks)} chunks from {len({c.source for c in chunks})} files")

print("\nThe Hotels section is too long for one chunk. The overlap repeats a paragraph:")
for c in chunks:
    if c.heading.endswith("Hotels"):
        print(f"\n[{c.id}]\n{c.text}")
  1. Format specs: :<16 pads to 16 characters, left-aligned; :>3 right-aligns. Like String.format("%-16s") in Java.line 5
  2. {c.source for c in chunks} is a **set comprehension**: the distinct file names. Its length is the number of files.line 6
Run
uv run show_chunks.py
You should see
benefits.md#0    Benefits > Health insurance                 88 chars
benefits.md#1    Benefits > Learning budget                 133 chars
benefits.md#2    Benefits > Equipment                        82 chars
benefits.md#3    Benefits > Wellbeing                        86 chars
expenses.md#0    Travel and expenses > Booking travel       277 chars
expenses.md#1    Travel and expenses > Hotels               269 chars
expenses.md#2    Travel and expenses > Hotels               352 chars
expenses.md#3    Travel and expenses > Meals                 79 chars
expenses.md#4    Travel and expenses > Submitting expenses  113 chars
offices.md#0     Offices > The Lisbon office                116 chars
offices.md#1     Offices > Meeting rooms                     96 chars
offices.md#2     Offices > Team weeks                       108 chars
on-call.md#0     On-call > The rotation                     135 chars
on-call.md#1     On-call > On-call pay                      106 chars
on-call.md#2     On-call > Responding to a page             121 chars
on-call.md#3     On-call > After an incident                 93 chars
onboarding.md#0  Your first week > Before day one           109 chars
onboarding.md#1  Your first week > Day one                  153 chars
onboarding.md#2  Your first week > First week checklist     139 chars
remote-work.md#0 Remote work > Where you can work           246 chars
remote-work.md#1 Remote work > Core hours                    92 chars
remote-work.md#2 Remote work > Home office budget           152 chars
security.md#0    Security > Your laptop                     115 chars
security.md#1    Security > Passwords and two-factor login  130 chars
security.md#2    Security > Lost or stolen devices          191 chars
security.md#3    Security > Phishing                        130 chars
time-off.md#0    Time off > Vacation                        221 chars
time-off.md#1    Time off > Sick leave                      158 chars
time-off.md#2    Time off > Parental leave                  146 chars
time-off.md#3    Time off > How to request time off          96 chars

30 chunks from 8 files

The Hotels section is too long for one chunk. The overlap repeats a paragraph:

[expenses.md#1]
Hotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night.

Book a hotel within walking distance or a short public transport ride of where you work. Breakfast is included in the limit when the hotel sells it with the room.

[expenses.md#2]
Book a hotel within walking distance or a short public transport ride of where you work. Breakfast is included in the limit when the hotel sells it with the room.

If a conference hotel costs more than the limit, ask your manager before booking. Approved exceptions are noted on the trip in TravelDesk, so finance can see them when you submit the bill.
Why this way? Chunking is the biggest quality lever in RAG and the easiest to get wrong. If the answer is split across two chunks and only one is retrieved, no prompt can fix it. Structure-aware chunks with a little overlap are the solid default; for the trade-offs (size, overlap, token limits) see Chunking documents.
Stuck on this step?
Only 0 chunks from 0 files
The handbook folder is not next to show_chunks.py, or the files do not end in .md. Run the command from the project folder.
4

A VectorStore interface and an in-memory store

One small interface for "store vectors, find the closest", and the simplest implementation: a NumPy matrix.

embedder.py is lab 5's embedder without the cache. Two things to remember from lab 5: every vector is normalized to length 1, so the dot product of two vectors is their cosine similarity (1.0 = same direction, near 0 = unrelated). And nomic-embed-text expects a task prefix: search_document: before every chunk and search_query: before every question. Leave them out and the scores get noticeably worse.

store.py defines what a vector store is, with a Protocol: Python's version of an interface. Any class with these four methods counts as a VectorStore; it does not have to say implements. That is checked by type checkers like mypy, not at runtime.

The in-memory store keeps one matrix with a row per chunk. Search is one matrix-vector product (every row times the query) and a sort. For a few thousand chunks this is fast enough; a database is for when you have more data, several processes, or need filtering and updates.

embedder.py
import numpy as np

# nomic-embed-text was trained with a task prefix on every text: one for documents, one for questions.
DOC_PREFIX = "search_document: "
QUERY_PREFIX = "search_query: "


def normalize(v: np.ndarray) -> np.ndarray:
    """Scale every row to length 1, so a dot product is the cosine similarity."""
    norms = np.linalg.norm(v, axis=-1, keepdims=True)
    return v / np.where(norms == 0, 1, norms)


class Embedder:
    def __init__(self, client, model: str, batch_size: int = 16):
        self.client = client
        self.model = model
        self.batch_size = batch_size

    def embed(self, texts: list[str]) -> np.ndarray:
        """One row per text, in the same order, each of length 1."""
        rows = []
        for start in range(0, len(texts), self.batch_size):
            batch = texts[start:start + self.batch_size]
            resp = self.client.embeddings.create(model=self.model, input=batch)
            rows.extend(item.embedding for item in sorted(resp.data, key=lambda d: d.index))
        return normalize(np.array(rows, dtype=np.float32))

    def embed_documents(self, texts: list[str]) -> np.ndarray:
        return self.embed([DOC_PREFIX + t for t in texts])

    def embed_query(self, text: str) -> np.ndarray:
        return self.embed([QUERY_PREFIX + text])[0]
  1. nomic-embed-text was trained with these prefixes. Other models use other prefixes, or none: read the model card.line 4
  2. axis=-1, keepdims=True: one length per row, kept as a column so the division below works row by row (NumPy broadcasting).line 10
  3. np.where(norms == 0, 1, norms): never divide by zero; an all-zero vector stays zero.line 11
  4. One request per batch of 16 texts instead of one per text. The OpenAI SDK's embeddings.create works with Ollama, and with hosted providers.line 25
  5. Sort by index so the vectors line up with the texts, whatever order the server sends them in.line 26
store.py
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Protocol

import numpy as np

from chunking import Chunk


@dataclass(frozen=True)
class Hit:
    chunk: Chunk
    score: float  # cosine similarity: 1.0 means the same direction, near 0 means unrelated


class VectorStore(Protocol):
    """What every store can do. The RAG code only ever talks to these four methods."""

    def clear(self) -> None: ...

    def add(self, chunks: list[Chunk], vectors: np.ndarray) -> None: ...

    def search(self, vector: np.ndarray, k: int) -> list[Hit]: ...

    def count(self) -> int: ...


class InMemoryStore:
    """All vectors in one NumPy matrix, one row per chunk. With a folder, it is saved there after
    every change and loaded again on the next run."""

    def __init__(self, folder: str | None = None):
        self.folder = Path(folder) if folder else None
        self.chunks: list[Chunk] = []
        self.vectors = np.zeros((0, 0), dtype=np.float32)
        if self.folder and (self.folder / "vectors.npy").exists():
            self.vectors = np.load(self.folder / "vectors.npy")
            rows = json.loads((self.folder / "chunks.json").read_text(encoding="utf-8"))
            self.chunks = [Chunk(**row) for row in rows]

    def clear(self) -> None:
        self.chunks = []
        self.vectors = np.zeros((0, 0), dtype=np.float32)
        self._save()

    def add(self, chunks: list[Chunk], vectors: np.ndarray) -> None:
        self.vectors = np.vstack([self.vectors, vectors]) if self.chunks else vectors
        self.chunks = self.chunks + list(chunks)
        self._save()

    def search(self, vector: np.ndarray, k: int) -> list[Hit]:
        if not self.chunks:
            return []
        scores = self.vectors @ vector
        best = np.argsort(-scores, kind="stable")[:k]
        return [Hit(self.chunks[i], float(scores[i])) for i in best]

    def count(self) -> int:
        return len(self.chunks)

    def _save(self) -> None:
        if self.folder is None:
            return
        self.folder.mkdir(exist_ok=True)
        np.save(self.folder / "vectors.npy", self.vectors)
        rows = [asdict(c) for c in self.chunks]
        (self.folder / "chunks.json").write_text(json.dumps(rows, indent=1), encoding="utf-8")


STORES = ("memory",)


def make_store(kind: str) -> VectorStore:
    if kind == "memory":
        return InMemoryStore("index")
    raise ValueError(f"unknown store {kind!r}, choose one of {STORES}")
  1. A search result: the chunk and how close it is. The RAG code only ever sees Hits, never the store's internals.line 12
  2. Protocol = structural interface. Java's interface VectorStore { ... }, but any class with matching methods fits, without declaring it.line 17
  3. ... (Ellipsis) as a body means "no implementation here", like an abstract method.line 20
  4. str | None = None: the folder is optional. Without one (in tests), nothing touches the disk.line 33
  5. A saved store exists: load the matrix (np.load) and the chunks (JSON) back.line 37
  6. Chunk(**row): ** spreads a dict into keyword arguments, so {"id": ..., "source": ...} becomes Chunk(id=..., source=...).line 40
  7. np.vstack stacks matrices on top of each other. An empty store just takes the new matrix.line 48
  8. @ is matrix multiplication: a (30 × 768) matrix times a 768 vector gives 30 scores, one per chunk, in one fast call.line 55
  9. np.argsort(-scores) gives the row numbers from highest to lowest score (minus flips the order). [:k] keeps the first k. kind="stable" keeps ties in insertion order, so results are repeatable.line 56
  10. float(...) turns a NumPy number into a plain Python float, so it prints and compares like any other number.line 57
  11. asdict turns each Chunk into a dict, so json.dumps can write it.line 68
  12. The store names --store accepts. Step 9 adds "pg" here.line 71
  13. A factory: callers ask for a store by name and get a VectorStore. Only this function knows the concrete classes.line 74
Why this way? With an interface between the RAG code and the database, you can start with the simplest store, test with it, and move to Postgres (or a managed vector database) later by writing one new class. Nothing else changes, and step 9 proves it.
5

Ingest the handbook and search it

Embed all chunks once, save them, then find the closest chunks for a question.

RAG has two phases. Ingest (offline, when documents change): chunk, embed, store. Query (online, per question): embed the question, search, answer. ingest.py is the first phase. It throws away what the store held and rebuilds it, so running it twice is safe.

search.py is retrieval on its own, without any chat model. Always look at this first: if the right chunk is not in the top results, the answer cannot be right either.

argparse reads command-line options, like picocli in Java or commander in Node. --store will choose between memory and (after step 9) pg. uv run ingest.py --help lists the options.

ingest.py
import argparse
import time

from chunking import load_handbook
from config import settings
from embedder import Embedder
from llm import make_client
from store import STORES, make_store

parser = argparse.ArgumentParser(description="Chunk, embed and store the handbook.")
parser.add_argument("--store", choices=STORES, default="memory")
args = parser.parse_args()

chunks = load_handbook("handbook")
start = time.perf_counter()
embedder = Embedder(make_client(), settings().embed_model)
vectors = embedder.embed_documents([c.for_embedding() for c in chunks])
seconds = time.perf_counter() - start
print(f"Embedded {len(chunks)} chunks in {seconds:.1f}s ({vectors.shape[1]} numbers each)")

store = make_store(args.store)
store.clear()
store.add(chunks, vectors)
print(f"The {args.store} store now holds {store.count()} chunks")
  1. choices=STORES makes argparse reject unknown names with a clear message, and default="memory" is used when you leave the option out.line 11
  2. time.perf_counter() is a precise clock for measuring durations, like System.nanoTime().line 15
  3. Embed what for_embedding() returns: the heading path plus the text. embed_documents adds the search_document: prefix.line 17
  4. vectors.shape is (rows, columns): 30 chunks, 768 numbers each.line 19
  5. Clear first, so a chunk you deleted from the handbook does not stay in the store.line 22
search.py
import sys

from config import settings
from embedder import Embedder
from llm import make_client
from store import make_store

question = " ".join(sys.argv[1:]) or "How much can I spend on a hotel?"
store = make_store("memory")
query = Embedder(make_client(), settings().embed_model).embed_query(question)
for hit in store.search(query, k=4):
    print(f"{hit.score:.3f}  {hit.chunk.id:<16} {hit.chunk.heading}")
  1. The words after the script name, joined into one question. With none, a default question.line 8
  2. embed_query adds the search_query: prefix. The question and the chunks get different prefixes on purpose.line 10
Run
uv run ingest.py
uv run search.py "How much can I spend on a hotel in London?"
You should seeyour text will differ: the model writes it
Embedded 30 chunks in 1.9s (768 numbers each)
The memory store now holds 30 chunks
0.785  expenses.md#1    Travel and expenses > Hotels
0.679  expenses.md#2    Travel and expenses > Hotels
0.594  expenses.md#3    Travel and expenses > Meals
0.582  benefits.md#1    Benefits > Learning budget
Why this way? Both Hotels chunks come first, well ahead of the rest, and the first one has the answer (250 euros in London). Notice how close the unrelated chunks still score (about 0.58): with this model, cosine scores of unrelated text rarely go near 0. That is why a "minimum score" needs real numbers, which step 7 uses.
Stuck on this step?
openai.NotFoundError: ... model "nomic-embed-text" not found
You have not pulled the embedding model: run ollama pull nomic-embed-text.
APIConnectionError: Connection error.
Ollama is not running. Open the Ollama app or run ollama serve.
Your scores differ a little from the ones shown
Normal: they depend on the exact model build and your hardware. The order should be the same, with the two Hotels chunks on top.
6

The prompt: numbered sources and citations

Give the model the retrieved chunks as numbered sources, ask it to cite them, and check which ones it cited.

Now the G of RAG. The prompt has two parts. The system message sets the rules: answer only from the sources, cite them as [1], and say a fixed sentence when the sources do not have the answer. The user message carries the numbered sources and the question.

The sources go in the user message, not the system message, on purpose. They are data copied from documents, and a document can contain text like "ignore your rules" (prompt injection). Keeping your instructions in the system message and the documents clearly labelled as sources makes that harder.

After the answer comes back, cited_numbers reads the [n] markers with a regular expression and keeps only numbers that really were sources. ask.py prints the file and heading of each one, so a reader can check the claim.

prompt.py
from store import Hit

NOT_FOUND = "I don't know. The handbook does not say."

SYSTEM = f"""You answer questions about the Larkspur employee handbook.
Rules:
- Use only the numbered sources in the user message. Do not use outside knowledge.
- After each fact, cite the number of its source in square brackets, like [1] or [2].
- If the sources do not answer the question, reply exactly: {NOT_FOUND}
- Keep the answer short: one to three sentences."""


def format_sources(hits: list[Hit]) -> str:
    """[1] file > heading path, then the chunk text. Numbered from 1, in ranking order."""
    blocks = []
    for n, hit in enumerate(hits, start=1):
        c = hit.chunk
        blocks.append(f"[{n}] {c.source} > {c.heading}\n{c.text}")
    return "\n\n".join(blocks)


def build_messages(question: str, hits: list[Hit]) -> list[dict]:
    user = f"Sources:\n\n{format_sources(hits)}\n\nQuestion: {question}"
    return [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": user},
    ]
  1. One fixed sentence for "not in the handbook". Your code (and your tests) can recognise it, which is much harder with free-form apologies.line 3
  2. An f-string with triple quotes: a multi-line string with {NOT_FOUND} filled in, like a Java text block plus formatted().line 5
  3. Tell the model what to do when it does not know. Without this rule, small models fill the gap with a plausible guess.line 9
  4. enumerate(hits, start=1) gives (1, hit), (2, hit), ...: numbers that match what a person reads, starting at 1.line 16
  5. Each source shows its file and heading path, then the text. The model sees where every fact comes from.line 18
  6. Sources first, question last. Models pay most attention to the end of the prompt, so the question goes there.line 23
rag.py
import re
from dataclasses import dataclass

from prompt import build_messages
from store import Hit, VectorStore

CITATION = re.compile(r"\[(\d+)\]")


@dataclass
class Answer:
    text: str
    sources: list[Hit]  # what the model was given, numbered from 1
    cited: list[int]  # the source numbers the answer really cites


def cited_numbers(text: str, n_sources: int) -> list[int]:
    """The source numbers cited in the text, in order, without repeats or made-up numbers."""
    found = []
    for match in CITATION.finditer(text):
        n = int(match.group(1))
        if 1 <= n <= n_sources and n not in found:
            found.append(n)
    return found


def answer(question: str, store: VectorStore, embedder, client, model: str, k: int = 4) -> Answer:
    hits = store.search(embedder.embed_query(question), k)
    resp = client.chat.completions.create(
        model=model,
        messages=build_messages(question, hits),
        temperature=0,
    )
    text = resp.choices[0].message.content
    return Answer(text, hits, cited_numbers(text, len(hits)))
  1. Matches [1], [12]: a literal [, one or more digits (captured), a literal ]. Compiled once, used many times.line 7
  2. A plain (mutable) dataclass for the result: the text, the sources the model saw, and the numbers it cited.line 10
  3. finditer walks over every match in the text, like Matcher.find() in a Java loop.line 20
  4. A chained comparison: 1 <= n <= n_sources means 1 <= n and n <= n_sources. It drops made-up numbers like [7] when there were four sources.line 22
  5. embedder and client have no type: anything with embed_query and chat.completions.create works. Tests pass fakes here (duck typing).line 27
  6. Retrieval: embed the question, take the k closest chunks.line 28
  7. Temperature 0: the most likely words. For answering from documents you want faithful, repeatable answers.line 32
ask.py
import argparse
import sys

import openai

from config import settings
from embedder import Embedder
from llm import make_client
from rag import answer
from store import STORES, make_store

parser = argparse.ArgumentParser(description="Ask the Larkspur handbook a question.")
parser.add_argument("question")
parser.add_argument("--store", choices=STORES, default="memory")
args = parser.parse_args()

s = settings()
store = make_store(args.store)
if store.count() == 0:
    sys.exit(f"The {args.store} store is empty. Run: uv run ingest.py --store {args.store}")

client = make_client()
try:
    result = answer(args.question, store, Embedder(client, s.embed_model), client, s.model)
except openai.APITimeoutError:
    sys.exit("The model took too long. Try again, or use a smaller model.")
except openai.APIConnectionError:
    sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
    sys.exit(f"A model is missing. Run: ollama pull {s.model} and ollama pull {s.embed_model}")

print(result.text)
if result.cited:
    print("\nSources:")
    for n in result.cited:
        c = result.sources[n - 1].chunk
        print(f"  [{n}] {c.source} > {c.heading}")
else:
    print("\n(the answer cites no sources: check it before trusting it)")
  1. A positional argument: the question, in quotes on the command line.line 13
  2. Asking an empty store gives empty answers that look like a broken model. Fail early with the fix instead.line 19
  3. Timeout before connection error, on purpose: APITimeoutError is a subclass of APIConnectionError, and Python uses the first except that matches.line 25
  4. Ollama answers 404 for a model it does not have: chat or embedding.line 29
  5. Citation [n] is result.sources[n - 1]: the list starts at 0, the numbers at 1.line 36
  6. No citation is a warning sign: the model may have answered from its own memory.line 39
Run
uv run ask.py "How much can I spend on a hotel in London?"
You should seeyour text will differ: the model writes it
You can spend up to 250 euros per night on a hotel in London [1].

Sources:
  [1] expenses.md > Travel and expenses > Hotels
Why this way? Citations turn "trust me" into "check me". They also give you a cheap automatic test: an answer that cites nothing, or cites a source number that does not exist, is suspicious and can be flagged or logged.
Stuck on this step?
The answer has no [1] markers
Small models sometimes forget. Run it again, or try a larger model (ollama pull llama3.1:8b and set LLM_MODEL). The rule is in the system prompt; you can also add "Every sentence must end with a citation."
It cites [1, 2] and the Sources list is empty
The regex only matches one number per bracket. The first exercise below upgrades it to read lists like [1, 2].
7

Refuse when retrieval is weak, and a --debug flag

Do not even ask the model when nothing relevant was found, and see exactly what was retrieved and why.

Vector search always returns k results, even for "What is the capital of Australia?". Without a check, those four unrelated chunks go to the model, which then either says it does not know (good) or answers from its own memory (bad: an answer your handbook never gave).

So answer() now drops every hit below min_score, and if nothing is left it refuses without calling the model: cheaper, faster and safe. When some hits pass, only those are sent.

How do you pick the number? Run real questions with --debug and look at the scores. With nomic-embed-text and this handbook, the right chunk for a covered question scores about 0.78 to 0.87; for questions the handbook does not cover, the best chunk scores about 0.50 to 0.66. 0.65 sits between them. No number is perfect: "Can I expense a gym membership?" is answered by the Wellbeing section, yet its best score is 0.626, so it is refused. That is the trade-off: a higher minimum refuses more good questions, a lower one lets more noise through. Measure on a set of real questions, log refusals, and re-measure whenever you change the embedding model.

rag.py 11 new or changed lines
import re
from dataclasses import dataclass, field

from prompt import NOT_FOUND, build_messages
from store import Hit, VectorStore

CITATION = re.compile(r"\[(\d+)\]")


@dataclass
class Answer:
    text: str
    sources: list[Hit]  # what the model was given, numbered from 1
    cited: list[int]  # the source numbers the answer really cites
    retrieved: list[Hit] = field(default_factory=list)  # everything the search returned
    refused: bool = False  # True when retrieval found nothing relevant and the model was not called


def cited_numbers(text: str, n_sources: int) -> list[int]:
    """The source numbers cited in the text, in order, without repeats or made-up numbers."""
    found = []
    for match in CITATION.finditer(text):
        n = int(match.group(1))
        if 1 <= n <= n_sources and n not in found:
            found.append(n)
    return found


def answer(question: str, store: VectorStore, embedder, client, model: str,
           k: int = 4, min_score: float = 0.65) -> Answer:
    retrieved = store.search(embedder.embed_query(question), k)
    relevant = [hit for hit in retrieved if hit.score >= min_score]
    if not relevant:
        return Answer(NOT_FOUND, [], [], retrieved, refused=True)

    resp = client.chat.completions.create(
        model=model,
        messages=build_messages(question, relevant),
        temperature=0,
    )
    text = resp.choices[0].message.content
    return Answer(text, relevant, cited_numbers(text, len(relevant)), retrieved)
  1. field(default_factory=list): every Answer gets its **own** new list. A plain = [] default would be shared by all objects (Python refuses it in dataclasses for that reason).line 15
  2. Lets the caller tell "the code refused" from "the model said it does not know".line 16
  3. Retrieve as before. retrieved keeps everything, so --debug can show what was dropped too.line 31
  4. A list comprehension with a condition, like hits.stream().filter(h -> h.score() >= minScore).toList().line 32
  5. The refusal: the fixed sentence, no sources, and the model is never called.line 34
  6. Only the relevant hits are numbered and sent, so [1] is always a chunk that passed the check.line 38
ask.py 13 new or changed lines
import argparse
import sys
import textwrap

import openai

from config import settings
from embedder import Embedder
from llm import make_client
from rag import answer
from store import STORES, make_store

parser = argparse.ArgumentParser(description="Ask the Larkspur handbook a question.")
parser.add_argument("question")
parser.add_argument("--store", choices=STORES, default="memory")
parser.add_argument("--debug", action="store_true", help="show the retrieved chunks and their scores")
args = parser.parse_args()

s = settings()
store = make_store(args.store)
if store.count() == 0:
    sys.exit(f"The {args.store} store is empty. Run: uv run ingest.py --store {args.store}")

client = make_client()
try:
    result = answer(args.question, store, Embedder(client, s.embed_model), client, s.model, min_score=s.min_score)
except openai.APITimeoutError:
    sys.exit("The model took too long. Try again, or use a smaller model.")
except openai.APIConnectionError:
    sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
    sys.exit(f"A model is missing. Run: ollama pull {s.model} and ollama pull {s.embed_model}")

if args.debug:
    print(f"--- retrieved {len(result.retrieved)} chunks, min score {s.min_score} ---")
    for hit in result.retrieved:
        status = "used" if hit in result.sources else "dropped"
        print(f"{hit.score:.3f} {status:<7} {hit.chunk.id:<16} {hit.chunk.heading}")
        print("      " + textwrap.shorten(hit.chunk.text, width=70, placeholder=" ..."))
    print("---")

print(result.text)
if result.refused:
    print("(no chunk reached the minimum score, so the model was not asked)")
elif result.cited:
    print("\nSources:")
    for n in result.cited:
        c = result.sources[n - 1].chunk
        print(f"  [{n}] {c.source} > {c.heading}")
else:
    print("\n(the answer cites no sources: check it before trusting it)")
  1. action="store_true": a flag with no value. --debug present means args.debug is True.line 16
  2. The minimum score comes from .env, so you can tune it without touching code.line 26
  3. hit in result.sources compares Hits by value (dataclasses write equals for you), so it finds the same hit in the other list.line 37
  4. {status:<7} pads to 7 characters, so the columns line up.line 38
  5. textwrap.shorten squeezes the text onto one line of at most 70 characters, cutting at a word and adding " ...".line 39
  6. Say clearly that the code refused. In a real app you would log the question: unanswered questions show what the docs are missing.line 43
Run
uv run ask.py --debug "What is the capital of Australia?"
uv run ask.py --debug "Who is the CEO of Larkspur?"
You should seeyour text will differ: the model writes it
--- retrieved 4 chunks, min score 0.65 ---
0.570 dropped remote-work.md#0 Remote work > Where you can work
      You can work from any country where Larkspur has a company: ...
0.537 dropped offices.md#0     Offices > The Lisbon office
      The Lisbon office is open from 08:00 to 20:00 on working days. ...
0.528 dropped on-call.md#3     On-call > After an incident
      Write a blameless postmortem within five working days and share it ...
0.522 dropped expenses.md#2    Travel and expenses > Hotels
      Book a hotel within walking distance or a short public transport ...
---
I don't know. The handbook does not say.
(no chunk reached the minimum score, so the model was not asked)
--- retrieved 4 chunks, min score 0.65 ---
0.662 used    remote-work.md#0 Remote work > Where you can work
      You can work from any country where Larkspur has a company: ...
0.642 dropped on-call.md#0     On-call > The rotation
      Engineers join the on-call rotation after three months at ...
0.635 dropped benefits.md#3    Benefits > Wellbeing
      Larkspur pays up to 50 euros a month towards a gym, a sports club ...
0.632 dropped offices.md#2     Offices > Team weeks
      Each team meets in Lisbon for one week, twice a year. Larkspur ...
---
I don't know. The handbook does not say.

(the answer cites no sources: check it before trusting it)
Why this way? The two questions show both safety nets. Australia: nothing reaches 0.65, so the code refuses and the model is never asked. The CEO question mentions Larkspur, so one chunk just passes (0.662) even though it says nothing about a CEO; the prompt rule then makes the model say it does not know. A threshold alone is never enough, and neither is a prompt rule alone.
Stuck on this step?
Everything is refused, even good questions
Your scores are lower (another embedding model, or no search_query: / search_document: prefixes). Look at --debug, then lower MIN_SCORE in .env, or re-run uv run ingest.py if you changed the embedder.
Off-topic questions still get answers
Raise MIN_SCORE a little, and check the answer cites a source. A model that answers from memory usually cites nothing.
8

Start Postgres with pgvector (Docker)

A real database for vectors, running in one container, with the vector extension switched on.

pgvector is a Postgres extension that adds a vector column type, distance operators and vector indexes. Your chunks, their metadata and their vectors then live in one ordinary table, next to the rest of your data, with transactions, backups and SQL filters for free.

The official pgvector/pgvector image is Postgres with the extension already installed. docker-compose.yml describes the container: the image, the user and password, the port, and a named volume so the data survives restarts. docker compose up -d --wait starts it in the background (-d) and waits until the health check says Postgres accepts connections (--wait).

Then add the two Python packages: psycopg (version 3, the standard Postgres driver; [binary] brings a precompiled client library, so you need nothing else installed) and pgvector (teaches psycopg to send and receive NumPy arrays as vector values).

schema.sql is the table. PgVectorStore (next step) runs it on every start; each statement says IF NOT EXISTS, so running it again changes nothing. You can also switch the extension on by hand, as the last command shows.

docker-compose.yml
services:
  db:
    image: pgvector/pgvector:pg17
    environment:
      POSTGRES_USER: rag
      POSTGRES_PASSWORD: rag
      POSTGRES_DB: rag
    ports:
      - "5433:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U rag -d rag"]
      interval: 2s
      timeout: 5s
      retries: 15

volumes:
  pgdata:
  1. Postgres 17 with pgvector. Pin the major version: a future latest could be a new Postgres major with a different data layout.line 3
  2. The image creates this user, password and database on the first start. Local development only: use real secrets anywhere else.line 5
  3. host:container. Postgres listens on 5432 inside the container; you reach it on 5433 on your machine.line 9
  4. A named volume keeps the database files when the container is removed. docker compose down -v deletes it too.line 11
  5. pg_isready is how Docker knows Postgres is up. --wait waits for this check to pass.line 13
schema.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS chunks (
    id        text PRIMARY KEY,
    source    text NOT NULL,
    heading   text NOT NULL,
    content   text NOT NULL,
    embedding vector(768) NOT NULL
);

CREATE INDEX IF NOT EXISTS chunks_embedding_idx
    ON chunks USING hnsw (embedding vector_cosine_ops);
  1. Switches pgvector on in this database. Installed in the image is not enough: each database needs CREATE EXTENSION once.line 1
  2. The chunk id from step 3 (expenses.md#1) is the primary key.line 4
  3. vector(768): exactly 768 numbers, the size nomic-embed-text produces. Postgres rejects any other size, which catches "embedded with the wrong model" early. A model with another size needs a new table (or column).line 8
  4. An **HNSW** index: a graph that finds near neighbours without comparing against every row. vector_cosine_ops builds it for cosine distance, the <=> operator used in the search.line 11
Run
uv add "psycopg[binary]" pgvector
docker compose up -d --wait
docker compose exec db psql -U rag -d rag -c "CREATE EXTENSION IF NOT EXISTS vector;" -c "SELECT extversion FROM pg_extension WHERE extname = 'vector';"
You should seeyour text will differ: the model writes it
Resolved 28 packages in 380ms
Installed 3 packages in 20ms
 + pgvector==0.5.1
 + psycopg==3.3.9
 + psycopg-binary==3.3.9
[+] Running 3/3
 ✔ Network rag-handbook_default   Created
 ✔ Volume "rag-handbook_pgdata"   Created
 ✔ Container rag-handbook-db-1    Healthy
CREATE EXTENSION
 extversion
------------
 0.8.0
(1 row)
Stuck on this step?
Cannot connect to the Docker daemon / docker: command not found
Docker Desktop is not installed or not running. Open it and wait until it says the engine is running, then try again. No Docker at all? Skip to step 10: the tests and the in-memory store need none of this.
Bind for 0.0.0.0:5433 failed: port is already allocated
Something already uses port 5433. Change the left number in ports (for example "5434:5432") and the port in DATABASE_URL in .env.
The first start takes a minute
Docker is downloading the image (about 150 MB compressed). Later starts take a second or two.
9

A pgvector store behind the same interface

Write PgVectorStore with the same four methods, switch the factory, and run the same commands against Postgres.

PgVectorStore has exactly the methods of InMemoryStore, so it is a VectorStore. ingest.py, ask.py and rag.py do not change: only store.py learns the name "pg". That is the payoff of step 4.

The search is one SQL query. <=> is pgvector's cosine distance (0 = same direction, 2 = opposite), so 1 - distance is the cosine similarity your in-memory store computes. ORDER BY embedding <=> query LIMIT k is the exact shape the HNSW index speeds up; keep it like that.

HNSW is approximate: on big tables it can, rarely, miss a true neighbour, in exchange for speed. On a table this small the index still finds every true neighbour (by default it looks at 40 candidates, the hnsw.ef_search setting), so the order and the scores match the in-memory store.

pg_store.py
import sys
from pathlib import Path

import numpy as np
import psycopg
from pgvector.psycopg import register_vector

from chunking import Chunk
from store import Hit

SCHEMA = Path(__file__).with_name("schema.sql")

SEARCH = """
SELECT id, source, heading, content, 1 - (embedding <=> %(query)s) AS score
FROM chunks
ORDER BY embedding <=> %(query)s
LIMIT %(k)s
"""


class PgVectorStore:
    """The same four methods as InMemoryStore, backed by a Postgres table with a vector column."""

    def __init__(self, url: str):
        try:
            self.conn = psycopg.connect(url, autocommit=True, connect_timeout=5)
        except psycopg.OperationalError as e:
            sys.exit(f"Cannot reach Postgres. Is it running? (docker compose up -d --wait)\n{e}")
        self.conn.execute(SCHEMA.read_text(encoding="utf-8"))
        register_vector(self.conn)

    def clear(self) -> None:
        self.conn.execute("TRUNCATE chunks")

    def add(self, chunks: list[Chunk], vectors: np.ndarray) -> None:
        rows = [(c.id, c.source, c.heading, c.text, v) for c, v in zip(chunks, vectors)]
        with self.conn.transaction(), self.conn.cursor() as cur:
            cur.executemany(
                "INSERT INTO chunks (id, source, heading, content, embedding) VALUES (%s, %s, %s, %s, %s)",
                rows,
            )

    def search(self, vector: np.ndarray, k: int) -> list[Hit]:
        rows = self.conn.execute(SEARCH, {"query": vector, "k": k}).fetchall()
        return [Hit(Chunk(id=r[0], source=r[1], heading=r[2], text=r[3]), float(r[4])) for r in rows]

    def count(self) -> int:
        return self.conn.execute("SELECT count(*) FROM chunks").fetchone()[0]
  1. From the pgvector package: registers the vector type with psycopg, so NumPy arrays go in and come out without any string formatting.line 6
  2. Path(__file__) is this file. .with_name("schema.sql") is the file next to it, wherever you start the program from.line 11
  3. 1 - (embedding <=> query): cosine distance turned back into similarity, the same number as the dot product in the in-memory store.line 14
  4. %(query)s is a named parameter: psycopg sends the value separately from the SQL text (server-side binding), so there is no SQL injection and no quoting. Like ? in JDBC, but by name, so one value can be used twice.line 16
  5. autocommit=True: each statement is committed at once, like JDBC's default. connect_timeout=5 fails fast if Postgres is not running.line 26
  6. A clear message instead of a stack trace when Docker is not running.line 28
  7. Runs the whole schema.sql. psycopg accepts several statements in one execute when there are no parameters.line 29
  8. Order matters: register_vector looks up the vector type, which only exists after CREATE EXTENSION. The other way round fails with "vector type not found in the database".line 30
  9. with opens a transaction and a cursor; at the end it commits the transaction (or rolls it back on an exception) and closes the cursor, like Java's try-with-resources. Either every row is inserted or none.line 37
  10. executemany runs the same INSERT once per row. v is a NumPy array; the pgvector adapter turns it into a vector.line 38
  11. A query with a dict of named parameters. fetchall() returns a list of tuples, one per row.line 44
  12. r[0] to r[4] are the columns in the order of the SELECT. The table's content column becomes the chunk's text.line 45
store.py 5 new or changed lines
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Protocol

import numpy as np

from chunking import Chunk
from config import settings


@dataclass(frozen=True)
class Hit:
    chunk: Chunk
    score: float  # cosine similarity: 1.0 means the same direction, near 0 means unrelated


class VectorStore(Protocol):
    """What every store can do. The RAG code only ever talks to these four methods."""

    def clear(self) -> None: ...

    def add(self, chunks: list[Chunk], vectors: np.ndarray) -> None: ...

    def search(self, vector: np.ndarray, k: int) -> list[Hit]: ...

    def count(self) -> int: ...


class InMemoryStore:
    """All vectors in one NumPy matrix, one row per chunk. With a folder, it is saved there after
    every change and loaded again on the next run."""

    def __init__(self, folder: str | None = None):
        self.folder = Path(folder) if folder else None
        self.chunks: list[Chunk] = []
        self.vectors = np.zeros((0, 0), dtype=np.float32)
        if self.folder and (self.folder / "vectors.npy").exists():
            self.vectors = np.load(self.folder / "vectors.npy")
            rows = json.loads((self.folder / "chunks.json").read_text(encoding="utf-8"))
            self.chunks = [Chunk(**row) for row in rows]

    def clear(self) -> None:
        self.chunks = []
        self.vectors = np.zeros((0, 0), dtype=np.float32)
        self._save()

    def add(self, chunks: list[Chunk], vectors: np.ndarray) -> None:
        self.vectors = np.vstack([self.vectors, vectors]) if self.chunks else vectors
        self.chunks = self.chunks + list(chunks)
        self._save()

    def search(self, vector: np.ndarray, k: int) -> list[Hit]:
        if not self.chunks:
            return []
        scores = self.vectors @ vector
        best = np.argsort(-scores, kind="stable")[:k]
        return [Hit(self.chunks[i], float(scores[i])) for i in best]

    def count(self) -> int:
        return len(self.chunks)

    def _save(self) -> None:
        if self.folder is None:
            return
        self.folder.mkdir(exist_ok=True)
        np.save(self.folder / "vectors.npy", self.vectors)
        rows = [asdict(c) for c in self.chunks]
        (self.folder / "chunks.json").write_text(json.dumps(rows, indent=1), encoding="utf-8")


STORES = ("memory", "pg")


def make_store(kind: str) -> VectorStore:
    if kind == "memory":
        return InMemoryStore("index")
    if kind == "pg":
        from pg_store import PgVectorStore  # imported only when needed

        return PgVectorStore(settings().database_url)
    raise ValueError(f"unknown store {kind!r}, choose one of {STORES}")
  1. Now --store pg is accepted by argparse in ingest.py and ask.py, without touching them.line 72
  2. An import inside the function: psycopg is only loaded when you ask for Postgres, so the memory store and the tests never need it.line 79
Run
uv run ingest.py --store pg
uv run ask.py --store pg --debug "How many weeks of parental leave do I get?"
docker compose exec db psql -U rag -d rag -c "\d chunks"
You should seeyour text will differ: the model writes it
Embedded 30 chunks in 1.9s (768 numbers each)
The pg store now holds 30 chunks
--- retrieved 4 chunks, min score 0.65 ---
0.837 used    time-off.md#2    Time off > Parental leave
      Every parent gets 16 weeks of fully paid leave, to take within the ...
0.680 used    time-off.md#0    Time off > Vacation
      Everyone gets 25 vacation days a year, plus the public holidays of ...
0.653 used    offices.md#2     Offices > Team weeks
      Each team meets in Lisbon for one week, twice a year. Larkspur ...
0.643 dropped remote-work.md#0 Remote work > Where you can work
      You can work from any country where Larkspur has a company: ...
---
You get 16 weeks of fully paid leave, which you can split into up to three blocks [1].

Sources:
  [1] time-off.md > Time off > Parental leave
                  Table "public.chunks"
  Column   |    Type     | Collation | Nullable | Default 
-----------+-------------+-----------+----------+---------
 id        | text        |           | not null | 
 source    | text        |           | not null | 
 heading   | text        |           | not null | 
 content   | text        |           | not null | 
 embedding | vector(768) |           | not null | 
Indexes:
    "chunks_pkey" PRIMARY KEY, btree (id)
    "chunks_embedding_idx" hnsw (embedding vector_cosine_ops)
Why this way? Look at the scores first: the parental leave chunk wins clearly (0.837), but "Team weeks" (0.653) just passes the 0.65 threshold and is sent to the model too, though it has nothing to do with leave. That is harmless here, because the model cited only [1], and it is a reminder that a threshold is a rough filter, not a relevance judge. A reranker (the hybrid search lab) is the better tool for that. Now the database itself. Postgres with pgvector is often the right first vector database: you already know how to run, back up and secure it, and you can filter with normal SQL (WHERE source = 'expenses.md') in the same query. Move to a dedicated vector database when you have tens of millions of vectors or need features Postgres lacks, and thanks to the interface that is one new class.
Stuck on this step?
Cannot reach Postgres. Is it running?
Start it with docker compose up -d --wait in the project folder, and check docker compose ps shows it healthy.
psycopg.errors.DataException: expected 768 dimensions, not 1024
You changed EMBED_MODEL to a model with another size. Change vector(768) in schema.sql, then drop the old table: docker compose exec db psql -U rag -d rag -c "DROP TABLE chunks;" and ingest again.
vector type not found in the database
register_vector ran before CREATE EXTENSION. Keep the order in __init__: run schema.sql first.
Windows: \d chunks prints an error
PowerShell can mangle the quotes. Open a psql shell with docker compose exec db psql -U rag -d rag, type \d chunks, and leave with \q.
10

Test it without a model or a database

Tests for chunking, retrieval, the prompt, citations and refusals that run in milliseconds.

The RAG code only needs three things from outside: something with embed_query (the embedder), something with chat.completions.create (the client) and a VectorStore. Tests hand it a fake embedder that counts a few keywords, a fake client that returns a fixed reply and records every request, and the in-memory store. No Ollama, no Docker.

The store fixture runs every store test twice: once with a store in memory and once with a store that was saved to disk and loaded again into a fresh object. When you later run Postgres in CI, you can add a third case and every test checks PgVectorStore too: that is how you keep two implementations of one interface honest.

test_chunking.py
from chunking import chunk_markdown, load_handbook, pack

DOC = """# Expenses

Intro paragraph.

## Hotels

Up to 180 euros a night.

## Meals

Up to 60 euros a day.
"""


def test_one_chunk_per_section_with_heading_path():
    chunks = chunk_markdown(DOC, "expenses.md")
    assert [c.heading for c in chunks] == ["Expenses", "Expenses > Hotels", "Expenses > Meals"]
    assert [c.id for c in chunks] == ["expenses.md#0", "expenses.md#1", "expenses.md#2"]
    assert chunks[1].source == "expenses.md"
    assert chunks[1].text == "Up to 180 euros a night."


def test_heading_goes_into_the_embedded_text():
    hotels = chunk_markdown(DOC, "expenses.md")[1]
    assert hotels.for_embedding() == "Expenses > Hotels\n\nUp to 180 euros a night."


def test_long_section_is_split_with_one_paragraph_of_overlap():
    a, b, c = "a" * 30, "b" * 30, "c" * 30
    assert pack([a, b, c], max_chars=70, overlap=1) == [f"{a}\n\n{b}", f"{b}\n\n{c}"]


def test_no_overlap_when_overlap_is_zero():
    a, b, c = "a" * 30, "b" * 30, "c" * 30
    assert pack([a, b, c], max_chars=70, overlap=0) == [f"{a}\n\n{b}", c]


def test_a_paragraph_longer_than_max_chars_stays_whole():
    assert pack(["x" * 100], max_chars=40, overlap=1) == ["x" * 100]


def test_the_handbook():
    chunks = load_handbook("handbook")
    assert len({c.source for c in chunks}) == 8
    assert len({c.id for c in chunks}) == len(chunks)  # ids are unique
    hotels = [c for c in chunks if c.heading == "Travel and expenses > Hotels"]
    assert len(hotels) == 2
  1. A tiny Markdown document inside the test: you can see the input and the expected output on one screen.line 3
  2. The heading path and the metadata are what citations depend on, so they get a test of their own.line 19
  3. Three 30-character paragraphs, at most 70 characters per piece: a + b fits, c does not. The second piece starts with b: the overlap.line 32
  4. With overlap=0, nothing repeats. This test catches the current[-0:] trap from step 3.line 37
  5. One test on the real handbook: eight files, unique ids, and the long Hotels section really split in two.line 44
test_rag.py
from types import SimpleNamespace

import numpy as np
import pytest

from chunking import Chunk
from embedder import normalize
from prompt import NOT_FOUND, build_messages
from rag import answer, cited_numbers
from store import Hit, InMemoryStore

VOCAB = ["hotel", "night", "laptop", "stolen", "vacation", "days"]


class FakeEmbedder:
    """Counts a few known words: texts that share words get similar vectors."""

    def vector(self, text: str) -> np.ndarray:
        words = text.lower().replace("?", " ").replace(".", " ").split()
        counts = [sum(w.startswith(v) for w in words) for v in VOCAB]
        return normalize(np.array(counts, dtype=np.float32))

    def embed_documents(self, texts):
        return np.vstack([self.vector(t) for t in texts])

    def embed_query(self, text):
        return self.vector(text)


class FakeClient:
    """Stands in for OpenAI(): returns one fixed reply and records every request."""

    def __init__(self, reply: str):
        self.reply = reply
        self.requests = []
        self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))

    def create(self, **kwargs):
        self.requests.append(kwargs)
        message = SimpleNamespace(content=self.reply)
        return SimpleNamespace(choices=[SimpleNamespace(message=message)])


CHUNKS = [
    Chunk("expenses.md#1", "expenses.md", "Travel and expenses > Hotels", "Hotels are covered up to 180 euros a night."),
    Chunk("security.md#2", "security.md", "Security > Lost or stolen devices", "Report a stolen laptop within one hour."),
    Chunk("time-off.md#0", "time-off.md", "Time off > Vacation", "Everyone gets 25 vacation days a year."),
]


@pytest.fixture(params=["memory", "saved-and-loaded"])
def store(request, tmp_path):
    """Every test below runs once per store: the same contract for every VectorStore."""
    embedder = FakeEmbedder()
    s = InMemoryStore(str(tmp_path / "index") if request.param == "saved-and-loaded" else None)
    s.add(CHUNKS, embedder.embed_documents([c.for_embedding() for c in CHUNKS]))
    if request.param == "saved-and-loaded":
        s = InMemoryStore(str(tmp_path / "index"))  # a fresh object that reads the saved files
    return s


def test_search_ranks_the_closest_chunk_first(store):
    hits = store.search(FakeEmbedder().embed_query("my laptop was stolen"), k=2)
    assert hits[0].chunk.id == "security.md#2"
    assert hits[0].score > hits[1].score
    assert len(hits) == 2


def test_answer_sends_numbered_sources_and_reads_citations(store):
    client = FakeClient("Hotels are covered up to 180 euros a night [1].")
    result = answer("hotel price per night?", store, FakeEmbedder(), client, "fake-model", min_score=0.5)
    assert result.cited == [1]
    assert result.sources[0].chunk.id == "expenses.md#1"
    user_message = client.requests[0]["messages"][1]["content"]
    assert "[1] expenses.md > Travel and expenses > Hotels\nHotels are covered" in user_message
    assert client.requests[0]["temperature"] == 0


def test_low_scores_refuse_without_calling_the_model(store):
    client = FakeClient("this reply must never be used")
    result = answer("What is the capital of Australia?", store, FakeEmbedder(), client, "fake-model")
    assert result.refused
    assert result.text == NOT_FOUND
    assert client.requests == []
    assert len(result.retrieved) == 3  # still there for --debug


def test_the_prompt_tells_the_model_to_stay_in_the_sources():
    hit = Hit(CHUNKS[0], 0.9)
    system, user = build_messages("Hotel limit?", [hit])
    assert "Use only the numbered sources" in system["content"]
    assert NOT_FOUND in system["content"]
    assert user["content"].endswith("Question: Hotel limit?")


def test_cited_numbers_ignores_repeats_and_made_up_sources():
    assert cited_numbers("A [2]. B [1][2]. C [7].", n_sources=3) == [2, 1]
    assert cited_numbers("No citations here.", n_sources=3) == []
  1. The fake "model" knows six words. Each one is one dimension of the vector: a text's vector counts how often it uses each word.line 12
  2. w.startswith(v) so "hotels" counts as "hotel". sum(...) over booleans counts the Trues.line 20
  3. Normalized like the real embedder, so dot products are cosine similarities. A text with none of the words stays all zeros and scores 0 against everything.line 21
  4. Builds client.chat.completions.create out of simple objects (SimpleNamespace is like a JS object literal), ending at our method. The same trick as lab 3.line 36
  5. A **parametrized fixture**: pytest runs each test that asks for store once per param. request.param says which one; tmp_path is a fresh temporary folder per test.line 51
  6. A new InMemoryStore object on the same folder: it must load what the first one saved.line 58
  7. The fake gives "hotel price per night" a high score with the Hotels chunk, so it passes min_score=0.5.line 71
  8. Checks the exact prompt format: number, file, heading path, then the text.line 75
  9. The most important refusal check: the fake client recorded **no** request, so the model was never called.line 84
  10. [7] is not a source (there are three) and [2] repeats: both are dropped.line 97
Run
uv run pytest -q
You should see
..............                                                           [100%]
14 passed in 0.09s
Why this way? Unit tests check your code: the chunk borders, the numbering, the refusal, the citation parsing. Whether the system retrieves the right chunk and answers correctly for real questions is a different test, an evaluation set of questions with known answers, run against the real models (see Evaluating RAG and the evals lab).
Stuck on this step?
ModuleNotFoundError: No module named 'chunking'
Run pytest from the project folder (where chunking.py is) with uv run pytest -q.
test_the_handbook fails
It reads the real handbook folder: check all eight files are there, and that the Hotels section in expenses.md has its three paragraphs.

Check it works

Three checks: the tests pass with no model and no database, a covered question gets an answer with a citation, and an off-topic question is refused without calling the model.

If you did steps 8 and 9, run the same two questions with --store pg added: the answers and sources should be the same.

Test
uv run pytest -q
uv run ingest.py
uv run ask.py "What should I do if my laptop is stolen?"
uv run ask.py "What is the dress code?"
You should see
14 passed in 0.09s
Embedded 30 chunks in 1.9s (768 numbers each)
The memory store now holds 30 chunks
Report it in the #security-help channel within one hour, or email security@larkspur.example [1]. The security team then locks the device remotely [1].

Sources:
  [1] security.md > Security > Lost or stolen devices
I don't know. The handbook does not say.
(no chunk reached the minimum score, so the model was not asked)

Troubleshooting

The right chunk is retrieved, but the answer is wrong or mixes facts

Run with --debug and read the sources the model got. If the answer is there, it is a generation problem: keep the temperature at 0, make the rules stricter, or use a larger model (llama3.1:8b). Small models sometimes mix two sources (180 and 250 euros, for example).

The right chunk is not in the top 4

A retrieval problem: no prompt fixes it. Check the task prefixes are in embedder.py, re-run uv run ingest.py after any change to chunking or the embedder, try k=6, or add keyword search next to vectors (Hybrid search and reranking, the next lab).

Answers ignore a change you made to the handbook

The store still holds the old chunks. Run uv run ingest.py (and --store pg) again after every change to the documents.

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0 ... (size 768 is different from 8)

The saved index was built with another embedding model than the one answering now. Run uv run ingest.py again: documents and questions must use the same model.

psycopg.OperationalError: ... password authentication failed for user "rag"

The volume holds a database created with other settings. Reset it (this deletes its data): docker compose down -v, then docker compose up -d --wait and ingest again.

Everything is slow on the first question

Ollama loads each model into memory on first use (the embedding model, then the chat model). Later questions are faster. Keep questions short and k small: every source makes the prompt longer.

What changes in production

  • Re-index incrementally. Rebuilding everything is fine for 30 chunks, not for a million. Store a content hash per document, and only re-chunk and re-embed documents whose hash changed; delete the chunks of deleted documents. Write new rows in a transaction so readers never see a half-empty table.
  • Filter by permission before retrieval, not after the answer. Put the access rules (team, region, document owner) in columns next to the vector and add them to the WHERE clause. A chunk the user may not read must never reach the prompt.
  • Log every question with its retrieved ids and scores. Refused questions show what the documents are missing; low-scoring correct answers show where chunking or the model is weak. Build an evaluation set from real questions and run it on every change to chunking, the embedding model, k or MIN_SCORE.
  • Treat retrieved text as untrusted. Documents can contain instructions aimed at the model. Keep them in the user message labelled as sources, never give the RAG prompt tools that can act on their own, and show citations so people can check.
  • Version the embedding model with the index. Vectors from different models (or the same model with and without prefixes) cannot be compared. Changing the model means re-embedding everything, ideally into a new table that you switch to when it is complete.

Interview angle

“Walk me through how you would build RAG over company documents, and how you keep it from making things up.”

Ingest offline: load the documents, chunk them along their structure (headings) at a few hundred tokens with a little overlap, keep metadata like source and section, embed each chunk with the heading in front, and store vectors and metadata together; I would start with Postgres and pgvector with an HNSW index on cosine distance, behind a small vector store interface. At query time I embed the question with the same model, take the top k by cosine similarity, and drop anything under a calibrated threshold; if nothing is left I refuse without calling the model. Otherwise the prompt has strict rules, answer only from the numbered sources, cite them, and use a fixed sentence when the answer is missing, with the sources in the user message as data. I parse the citations and flag answers that cite nothing. Then I measure: unit tests with fakes for the logic, and an evaluation set of real questions for retrieval recall and answer faithfulness, run on every change.

Clean up

Stop Postgres when you are done. docker compose down keeps the data volume for next time; add -v to delete it too. The index/ folder can be deleted any time: uv run ingest.py recreates it. Keep the project: the next labs (hybrid search, LangChain) use the same handbook.

Run
docker compose down -v
rm -rf index

Practice

No model needed: these run in your browser and check your answer.

Read citations like [1, 2], and catch made-up ones

Small models often cite several sources in one bracket: [1, 2]. Write check_citations(answer, n_sources) that returns a dict with two lists: "cited", the valid source numbers in order of first appearance, without repeats; and "unknown", numbers that are not between 1 and n_sources (the model made them up), also in order and without repeats. Brackets can hold one number or several separated by commas and spaces.

Exercise
import re


def check_citations(answer, n_sources):
    cited, unknown = [], []
    for match in re.finditer(r"\[(\d+)\]", answer):
        cited.append(int(match.group(1)))
    return {"cited": cited, "unknown": unknown}


print(check_citations("Up to 250 euros [1, 2]. Ask your manager [1]. See also [9].", 3))
Hint

Match the whole bracket with `re.finditer(r"\[([\d,\s]+)\]", answer)`, then split `match.group(1)` on commas and `int()` each part (`int(" 2")` is fine: int ignores surrounding spaces).

Fixed-size windows with overlap

Headings are not always there (plain text, transcripts). The fallback is a sliding window. Write windows(words, size, overlap): split a list of words into windows of size words, where each window starts size - overlap words after the previous one, so neighbours share overlap words. Stop after the first window that reaches the end of the list. Raise ValueError unless 0 <= overlap < size.

Exercise
def windows(words, size, overlap):
    out = []
    for start in range(0, len(words), size):
        out.append(words[start:start + size])
    return out


print(windows("the hotel limit is 250 euros a night in London".split(), 4, 1))
Hint

Use `range(0, len(words), size - overlap)` for the start positions, slice `words[start:start + size]`, and `break` once `start + size >= len(words)`.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip) Download Java project (.zip)