Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
The brief for pydocs-rag: a FastAPI service that answers how-do-I questions from 461 Python standard library docstrings, cites the exact record, and refuses what isn't there. Five stages, a 34-question golden set, a BM25 baseline of hit@5 0.794 and MRR 0.615 to beat, seven tests as the done check and a 20-point portfolio rubric.
What you will learn
- Plan a RAG portfolio project in five testable stages: ingest, retrieve, rerank, answer and serve
- Use a real corpus (461 stdlib docstrings) and a 34-question golden set instead of a toy file
- Set a baseline (BM25 hit@5 0.794, MRR 0.615) and keep a stage only when the eval improves
- Define done as passing tests and score the result on a 20-point rubric
Before you start
- The RAG Pipeline Explained
- Hybrid Search: BM25 Plus Dense Embeddings
- Retrieval Evals: Recall@K, MRR and nDCG
A RAG demo over three sentences in a text file proves nothing to a hiring manager. A RAG service over a real corpus, with an eval they can rerun themselves, proves a lot. This article is the brief for that project: what you build, what you start with, how you measure it and how a reviewer would score it. It sets the job and the done check, not the answers; the fun part is yours.
The project runs without an API key, using a stand-in test model. Put a key in .env and the same code calls a real model.
The job: a librarian who shows the page
Think of a really good librarian. You ask a question, they answer from the books, they point at the exact page, and if the books don't cover it, they say so. They don't make something up. The service, pydocs-rag, is that librarian as an API:
- People ask in plain words, like "How do I shuffle a list in place?", not the function name.
- The service answers with a citation: the exact record the answer came from, in square brackets, like
[json.loads], plus the evidence it looked at. - When the question isn't in the documents, like "What is the capital of France?", it refuses honestly.
Every response has four fields: answer, citations, refused and evidence.
A real corpus: the standard library
The corpus is the Python standard library itself: every public function, class and method that has a docstring, from 20 modules (json, pathlib, itertools, re, csv and more). That's 461 records: 133 functions, 97 classes and 231 methods, from CPython 3.13.7. One record looks like this (text shortened):
{"id": "json.loads", "kind": "function",
"signature": "loads(s, *, cls=None, object_hook=None, parse_float=None, pa...",
"text": "Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python obje..."}
The id is exactly what shows up later as the citation. One detail reviewers do notice: the licence. The docstrings ship with CPython under the PSF License, and the project keeps a licence note right next to the data.
The pipeline you build
Five stages, each in its own file, so each can be tested on its own:
- Ingest. Embed every record once (all-MiniLM-L6-v2, normalised) and save the vectors with a small manifest that records the model name and a hash of the corpus. Refuse to load an index that's out of date.
- Retrieve. BM25 matches words. Add dense search, which matches meaning, then fuse the two with reciprocal rank fusion into a hybrid. (Background: hybrid search with RRF.)
- Rerank. The first pass has to be fast over all 461 records, so the reranker takes a closer look at just the hybrid top 20. (See reranking with a cross-encoder for when this helps.)
- Answer. Refuse when the best evidence is weak, and remove any citation that isn't in the evidence. (See citations and abstention.)
- Serve. FastAPI, Docker, one command.
What you start with
The starter folder gives you the plumbing: the corpus loader, the 34-question golden set, a BM25 keyword retriever, the eval harness, and the FastAPI app with the prompt and the stand-in test model. The parts that decide quality are TODOs. In ingest.py they look like this:
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
INDEX_DIR = Path(__file__).resolve().parents[1] / "index"
@dataclass
class Index:
docs: list[Doc]
vectors: np.ndarray # one normalised 384-number row per doc
model: object # the SentenceTransformer, also used for questions and reranking
def corpus_hash(path: Path = CORPUS) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()[:16]
def build_index(index_dir: Path = INDEX_DIR) -> dict:
raise NotImplementedError("TODO: embed every doc.search_text with embedder() (normalised), save index_dir/vectors.npy and a manifest.json with model, corpus_hash, docs, dims; return the manifest")
def load_index(index_dir: Path = INDEX_DIR) -> Index:
raise NotImplementedError("TODO: read the manifest, raise RuntimeError('... stale ...') if corpus_hash or model changed, return Index(docs, vectors, embedder())")
The other TODOs are dense_scores, rrf and the hybrid branch in retrieve.py, rerank in rerank.py, and clean_citations and answer in answer.py. The corpus hash is the quiet hero: change one docstring and the manifest no longer matches, so a stale index can't sneak into production.
The eval: proof, not vibes
The golden set has 34 questions written in plain words, each with the record that answers it:
{"question": "How do I parse a JSON string into a Python dict?", "expected": ["json.loads"]}
{"question": "Write a Python object to a file as JSON", "expected": ["json.dump"]}
{"question": "Turn a Python object into a JSON formatted string", "expected": ["json.dumps"]}
Another one is "Middle value of a list of numbers", which should come from statistics.median. Three numbers are measured:
| Metric | Question it answers |
|---|---|
| hit@1 | Is the right record first? |
| hit@5 | Is it anywhere in the top five? |
| MRR | One over its rank, averaged: second place scores one half |
The starting point is BM25 alone, the retriever the starter already has: hit@5 = 0.794, MRR = 0.615. Your pipeline has to beat those numbers, and the rule for every stage is the same: keep it only when the eval says it helps. Run it with python -m pydocs_rag.evaluate and write down hit@1, hit@5 and MRR for each pipeline. More on these metrics in retrieval evals.
Done means the tests pass
There's one test file, tests/test_done.py, and it's the same in the starter and the solution. Run it on the starter today:
python -m pytest -q
1 failed, 6 errors
The TODOs raise NotImplementedError, so that red line is your to-do list. The target is 7 passed, and the tests check three things:
- Quality. Hybrid plus rerank reaches hit@5 of at least 0.85, and MRR(hybrid + rerank) ≥ MRR(hybrid) ≥ MRR(BM25).
- Safety. Citations come only from the evidence, and the France question is refused.
- Shape. A manifest exists, a stale index is refused, and bad input gets a 422.
How a reviewer will score it
Since this is a portfolio piece, here's the rubric: 20 points, 0, 2 or 4 per area.
| Area | 0 | 2 | 4 |
|---|---|---|---|
| Ingest | none | index built every start | separate step, manifest, stale index refused |
| Retrieval | one method | hybrid | hybrid + rerank kept only because the eval says so |
| Eval | none | one number | table for every pipeline, misses listed, rerunnable |
| Answer safety | free text | citations | citations checked against evidence + refusal threshold |
| Shipping | notebook | runs locally | README with design decision + one-command Docker run |
The README is part of the work: the design choice, the eval table and how to run it. Presenting your portfolio has a six-section template for it.
Stretch goals
- Swap the reranker for a cross-encoder and report the eval and the latency change.
- Add 10 harder golden questions (two-step ones, "difference between X and Y") and report the new numbers.
- Add a
/searchendpoint and a small page that shows the evidence beside the answer. - Put an answer cache in front of the model and report the hit rate on a replayed question list.
Common mistakes
- Embedding at every start. Ingest is a separate step; the API only loads.
- Keeping a reranker because it sounds better. If MRR doesn't go up, change it or drop it.
- Trusting the model's citations. Check every cited id against the evidence you actually passed in.
- Reporting one number. A table for every pipeline, with the misses listed, is what makes the eval believable.
Try it yourself
Go into the starter folder, run python -m pytest -q and watch it fail. Fill in the TODOs in order: ingest, retrieve, rerank, answer. Then ship it: green tests, a README with your eval table, and docker compose up. Open solution\ only after you're done.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.