Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

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.

Chaand Sheikh

·27 November 2026Retrieval and RAG

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:

The five stages of pydocs-rag 1 ingestembed once+ a manifest 2 retrieveBM25 + densefused: hybrid 3 reranka closer lookat the top 20 4 answercite evidenceor refuse 5 serveFastAPIDocker a separate step, run once the API loads a ready index and starts in seconds
Ingest sits on the other side of the line: the service never re-embeds 461 records on every start.
  1. 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.
  2. 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.)
  3. 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.)
  4. Answer. Refuse when the best evidence is weak, and remove any citation that isn't in the evidence. (See citations and abstention.)
  5. 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:

MetricQuestion it answers
hit@1Is the right record first?
hit@5Is it anywhere in the top five?
MRROne 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.

Area024
Ingestnoneindex built every startseparate step, manifest, stale index refused
Retrievalone methodhybridhybrid + rerank kept only because the eval says so
Evalnoneone numbertable for every pipeline, misses listed, rerunnable
Answer safetyfree textcitationscitations checked against evidence + refusal threshold
Shippingnotebookruns locallyREADME 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 /search endpoint 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 35 of 89

Previous
RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
Next post
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

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.

On this page

  • The job: a librarian who shows the page
  • A real corpus: the standard library
  • The pipeline you build
  • What you start with
  • The eval: proof, not vibes
  • Done means the tests pass
  • How a reviewer will score it
  • Stretch goals
  • Common mistakes
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.