Embeddings & Production RAG — Grounding Models in Your Truth
"Foundation models know the internet. RAG makes them answer from your documents — and prove it with citations."
01 · The hookThe $45K Hallucination at PolicyPal
A model only knows what it was trained on. Retrieval-augmented generation turns a closed-book exam into an open-book one, by finding the right passages first and putting them in the prompt.
"Our insurance claim adjusters spend 3 hours per claim hunting through 4,000 pages of regional policy PDFs. When we tried a standard ChatGPT wrapper, it hallucinated a non-existent coverage clause and authorized a $45,000 invalid payout. Build an enterprise AI assistant that answers queries STRICTLY from our policy manuals, cites exact page numbers, and never bluffs."
Here's the incident report. An adjuster asked the pilot chatbot: "Is flood damage covered for commercial warehouses in Florida under Tier-2 plans?" The model answered, with total confidence: "Yes, Tier-2 covers flood damage up to $50,000 per policy section 4.B." Section 4.B says the opposite — it excludes flood damage in Florida. The model never read the policy. It pattern-matched against insurance text it saw during pretraining and produced an authoritative-sounding guess. The payout was approved and never recovered.
The fix is not a bigger model or a sterner prompt. The fix is retrieval-augmented generation (RAG): before the model answers, you retrieve the actual policy paragraphs relevant to the question, inject them into the prompt as context, and instruct the model to answer only from that context — with citations an auditor can check.
This module is the single most job-critical build in the course. RAG architecture — chunking, retrieval, reranking, knowledge grounding — appears in roughly 65% of applied-LLM job postings (per our August 2026 market research), named explicitly at Goldman Sachs, Salesforce, Amazon, and Infosys. Walmart's Staff SWE "AI-RAG Expert" posting asks you to "design, fine-tune, and deploy Generative AI models with a focus on RAG frameworks" and to build agents for "knowledge grounding, multi-step reasoning, and decision-making." When you finish this module you'll have the flagship portfolio project the research says wins interviews: a production RAG system with a defended eval report.
RAG is a search engine bolted to a text generator. You've built the
search half your whole career: WHERE description LIKE '%flood%', then a
real inverted index with Elasticsearch, with ranking and filters. The generator is the
LLM you met in Module 06.
The only genuinely new part is searching by meaning instead of by keyword — and an embedding index is exactly a database index for semantics. Same mental model as a B-tree: pay an indexing cost at write time so lookups are cheap at read time.
The pipeline as a whole behaves like a read-through cache in front of a brilliant but unreliable service: never let the service answer from its own stale memory; always hand it fresh, authoritative data and make it show its sources.
02 · The intuitionClosed Book, Open Book, and Meaning-Space
Victoria Vance's memo hands us one number to kill: $45,000 paid out on a clause the model never read, on top of the 3 hours per claim adjusters still spend hunting through 4,000 pages. Before anyone builds anything, we have to know what the pilot chatbot actually did wrong, because "the model lied" is not a fix you can ship. The answer is that nobody ever showed it the policy. This section draws the difference between answering from memory and answering from a document, then shows the one trick that lets a machine find the right paragraph when the question and the paragraph share no words at all.
An LLM answering from its training weights is a brilliant student taking a closed-book exam. Ask it for PolicyPal's exact Florida flood rules and it has two options: admit ignorance, or improvise from every insurance document it ever read on the public internet. Models are trained to be helpful, so they improvise — fluently. That's a hallucination: not a bug in the model, but the model doing exactly what it was built to do, with the wrong information source.
RAG turns it into an open-book exam. Three steps, every request: retrieve the handful of paragraphs most relevant to the question, augment the prompt by pasting those paragraphs in as context, and generate an answer grounded in — and cited against — that context. The model's job shrinks from "know everything" to "read these five paragraphs and synthesize an answer," which is a task LLMs are genuinely excellent at.
Here is the incident and its repair, drawn as one picture. The top half is what happened to Victoria's $45,000. The bottom half is the same question through RAG. Every claim in this section points at a marker in it.
- Closed book. The pilot chatbot got the question and nothing else. It answered out of its own weights, which are the average of every insurance document on the public internet, and it produced a page reference, "section 4.B", that it had never read. Fluent, specific, and wrong.
- The file nobody opened. PolicyPal's real answer sat in DOC-FL-2026 page 14 the whole time, and it says the opposite: Florida warehouse flood damage is excluded. No step in the closed-book path touches that file, so nothing in it can correct the model. That gap is the $45,000.
- Open book. RAG puts one step in front of the model: find the three passages closest in meaning to the question, and paste them into the prompt as numbered blocks. The model's job shrinks from "know PolicyPal's rules" to "read these three and answer".
- The citation closes the loop. Each block keeps its document id and page, so the [1] the model writes is not decoration. It maps back to DOC-FL-2026 page 14, and the adjuster can open that page and check. Trust stops being a property of the model and becomes a property of the link.
The magic ingredient is how retrieval finds "relevant" paragraphs when the question shares no words with the answer. An embedding model maps every chunk of text to a point in a high-dimensional space — 384 to 3,072 coordinates — where distance encodes meaning. Texts about the same thing land near each other, even when their vocabulary is completely different. Your query becomes a point in the same space; retrieval is nearest-neighbor search.
- One cluster per topic, marker 1. Every chunk of PolicyPal's policies becomes one point. The embedding model was trained so that texts about the same subject point in the same direction, so all four insurance passages land inside one loose blob without anyone sorting them. Nothing here is a keyword index; the position of a point is the whole record of what it means.
- The score is an angle, marker 2. The dashed line beside marker 2 joins the query to "water damage claim", and it is labelled cos 0.78. Cosine 1.0 would mean the two point in exactly the same direction; 0 would mean unrelated. The two texts share no word at all, and keyword search would score them zero.
- Far means unrelated, marker 3. The finance blob below marker 3 holds perfectly good English about earnings and dividends, and the same query scores it 0.06. That number is what stops the retriever handing the adjuster a paragraph about stock buybacks. Retrieval is nearest-neighbour search: sort every point by this one number and keep the top few.
Notice what Fig. 8.1 claims: the query and its best match share no words. Keyword search would score them zero. Meaning-space search scores them 0.78. That single property — retrieval by paraphrase — is why every serious document Q&A system since 2023 is built on embeddings.
"Isn't this just Elasticsearch with extra steps? I have run search in production for years."
— a nine-year engineer, right about now
Half of it is exactly Elasticsearch, and you should feel at home. The index, the top-k query, the metadata filters, the ranking function: all of that is search engineering you already know. In section 05 the keyword half of the pipeline literally is BM25, the scoring algorithm inside Elasticsearch.
The other half is new in two ways. First, the index key is a vector of meaning rather than a list of words. That is marker 2 in Fig. 8.1: the query and its best match score 0.78 while sharing no word at all, and Elasticsearch would score that pair zero. Second, the consumer of the results is not a person scanning ten blue links. It is a language model that will write a confident paragraph from whatever you hand it. That changes what "good retrieval" means: a person forgives a wrong result at rank 3, a model may quote it as fact.
The honest downside: vector search is worse than Elasticsearch at exact identifiers, part numbers and names. Nothing in Fig. 8.1 has an address, only a direction, and an identifier like PP-FL-4B barely moves the query's point at all. You will watch that failure in section 04, and the fix is to run both.
Chunk the documents.
Embed the chunks.
Retrieve by meaning.
Answer only from what you retrieved.
Cite what you used.
Chunk the documents: cut the 4,000 pages into passages small enough that one passage is about one thing. Embed the chunks: turn each passage into a point, the way every dot in Fig. 8.1 was made. Retrieve by meaning: score every point against the question's point and keep the nearest few, which is marker 2 in Fig. 8.1. Answer only from what you retrieved: the numbered blocks at marker 3 in Fig. 8.0b are the model's whole world for that request. Cite what you used: the [1] at marker 4 in Fig. 8.0b, which resolves to DOC-FL-2026 page 14.
The math: cosine similarity — optional depth
How do we score "closeness" of two embedding vectors A and B with d dimensions each? We measure the angle between them:
cos θ = (A · B) / (‖A‖ ‖B‖) = Σᵢ AᵢBᵢ / (√(Σᵢ Aᵢ²) × √(Σᵢ Bᵢ²))
Symbol by symbol: A · B is the dot product — multiply the vectors coordinate-by-coordinate and sum (Σᵢ AᵢBᵢ). ‖A‖ is the vector's length (its Euclidean norm, √ of the sum of squared coordinates). Dividing by both lengths strips magnitude out of the score, leaving only direction. Result: cos θ = 1.0 means "pointing the same way" (same meaning), 0.0 means perpendicular (unrelated), and for typical text embeddings you'll see practical matches in the 0.4–0.9 band.
Why cosine and not Euclidean distance? A 40-word chunk and a 400-word chunk about the same topic can have very different vector magnitudes; Euclidean distance would punish the length difference. Cosine only cares about direction — meaning — not size.
The production shortcut: if you normalize every vector to length 1
(‖A‖ = ‖B‖ = 1), the denominator vanishes and cosine similarity is the dot
product. That's why the code below passes normalize_embeddings=True and
then just does matrix multiplication — one fused, SIMD-friendly operation.
Questions you might be asking now
The picture, the bubble and the math box above use three ideas at speed: a cosine score, a keyword score, and normalising a vector. The questions below slow each one down. Every answer uses the same query and three short sentences, with vectors small enough to multiply by hand.
| Name | Text | What it is | Water & flooding | Buildings & property | Money & finance |
|---|---|---|---|---|---|
| query | "warehouse flooding?" | The query from Fig. 8.1 | 4 | 3 | 0 |
| water sentence | "Water damage to storage buildings is excluded." | Section 4.B's exclusion, reworded; shares no word with the query | 3 | 4 | 0 |
| fire sentence | "Warehouse fire damage carries a separate deductible." | A different rule that happens to share the word "warehouse" | 0 | 3 | 4 |
| earnings sentence | "Quarterly earnings rose after the stock buyback." | Finance-speak, like the far cluster in Fig. 8.1 | 0 | 0 | 5 |
What is cosine similarity, and how do I work it out by hand?
Cosine similarity scores whether two lists of numbers point the same way. Multiply matching positions and add, then divide by both lengths. The query and the water sentence score 24 ÷ (5 × 5) = 0.96, an angle of 16.3 degrees between them.
Think of each list of numbers as an arrow from a shared starting point. Each number says how far it travels along one dial. The query, (4, 3, 0), goes 4 steps along water, 3 along buildings and none along money.
Two texts about the same thing are arrows that point in nearly the same direction. Cosine similarity is a score for that direction. It is 1 when two arrows point exactly the same way and 0 when they meet at a right angle. Here are the three steps for the query and the water sentence.
- Multiply matching positions, then add. Water: 4 × 3 = 12. Buildings: 3 × 4 = 12. Money: 0 × 0 = 0. The total, 24, is called the dot product.
- Measure each arrow's length. Square each number, add the squares, take the square root. Query: √(4² + 3² + 0²) = √25 = 5. Water sentence: √(3² + 4² + 0²) = √25 = 5. This is Pythagoras' rule with one more side.
- Divide the dot product by both lengths. 24 ÷ (5 × 5) = 0.96. The division removes how long the arrows are and keeps only where they point. The third question below shows why that matters.
| Sentence | A · dot product | B · lengths | C · cosine | Angle to the query |
|---|---|---|---|---|
| water | 4 × 3 + 3 × 4 + 0 × 0 = 24 | 5 and 5 | 24 ÷ 25 = 0.96 | 16.3° |
| fire | 4 × 0 + 3 × 3 + 0 × 4 = 9 | 5 and 5 | 9 ÷ 25 = 0.36 | 68.9° |
| earnings | 4 × 0 + 3 × 0 + 0 × 5 = 0 | 5 and 5 | 0 ÷ 25 = 0.00 | 90.0° |
The formula in the math box is the same three steps in symbols. In cos θ = (A · B) ÷ (‖A‖ ‖B‖), θ (theta) is the angle between the arrows. A · B (read "A dot B") is step A. ‖A‖ and ‖B‖ (read "the length of A" and "the length of B") are step B, and the fraction is step C.
- Multiply matching positions. The query's water number meets the sentence's water number, buildings meets buildings, money meets money. The three products, 12, 12 and 0, add to 24. A dial where either text scores 0 adds nothing, which is why the money column is empty.
- Divide by the lengths. Each length is the square root of that arrow's own squares, and both come out at 5 here. Dividing 24 by 5 × 5 gives 0.96. The fire and earnings sentences also have length 5, so their scores are simply 9 ÷ 25 and 0 ÷ 25.
- The angle. The water sentence leans 16.3 degrees from the query, the fire sentence 68.9 and the earnings sentence 90. Only the angles to the query are true: the fire and water arrows are really 61.3 degrees apart, not the gap drawn here.
Two honest limits. A real embedding has 384 numbers, and no single number means "water"; the toy names its dials only so you can check each product. And real cosines rarely fall to 0 for unrelated text, so read the order of the scores, never the size of one. A cosine of 0.96 is not a 96% chance of anything.
Cosine similarity = (multiply matching positions and add) ÷ (length × length). It scores direction only: 1 for the same way, 0 for a right angle.
Is embedding search the same thing as keyword search? Score one query both ways.
No. Keyword search scores the words a chunk shares with the query; embedding search scores the direction of its meaning. On the three sentences, keyword scoring puts the fire sentence first with 0.98 and gives the water sentence 0. Cosine puts the water sentence first with 0.96.
Keyword search is what Elasticsearch runs, and its scoring formula is called BM25 (short for "Best Match 25"). It gives a chunk points for every query word the chunk contains. Rare words earn more points than common ones. A word the chunk does not contain earns nothing at all.
The query "warehouse flooding?" becomes two words: warehouse and flooding. None of the three sentences contains "flooding". Only the fire sentence contains "warehouse". So two of the three scores are exactly 0 before any arithmetic starts, and only one score needs working out.
Here it is for the fire sentence, with Elasticsearch's default settings, k1 = 1.2 and b = 0.75.
- Count the chunks that contain the word. "warehouse" appears in 1 of the 3 sentences.
- Turn rarity into a weight. This weight is the IDF (inverse document frequency): ln(1 + (3 − 1 + 0.5) ÷ (1 + 0.5)) = ln(1 + 1.667) = ln(2.667) = 0.981. Here ln is the natural logarithm. It grows slowly, so a very rare word gets a bigger weight but never an unlimited one.
- Adjust for the chunk's length. The factor is 1 − 0.75 + 0.75 × (7 words ÷ 7 words on average) = 1.00. All three sentences were written with seven words so that this step cancels. A longer-than-average chunk gets a factor above 1 and a lower score.
- Count repeats, with diminishing returns. The word appears once: 1 × (1.2 + 1) ÷ (1 + 1.2 × 1.00) = 2.2 ÷ 2.2 = 1.00. A second "warehouse" would add less than the first did.
- Multiply the two parts. 0.981 × 1.00 = 0.981, or 0.98 rounded.
Symbol key: k1 (read "k-one") sets how quickly repeats stop adding points. b sets how strongly a long chunk is marked down. The 0.5s in step B keep the fraction sensible when a word is in no chunk or in every chunk.
| Sentence | Words shared with the query | BM25 score | BM25 rank | Cosine | Cosine rank |
|---|---|---|---|---|---|
| water | none | 0 | tied last | 0.96 | 1st |
| fire | warehouse | 0.98 | 1st | 0.36 | 2nd |
| earnings | none | 0 | tied last | 0.00 | 3rd |
Read the two rank columns. BM25 put the wrong sentence first, because a fire rule happens to share one word with the query. It also cannot tell the right sentence from a stock buyback, because both score 0. Cosine separates all three, because it never compares words, only where the arrows point.
- The false leader. The fire sentence is about a different risk, but it contains "warehouse", and that one shared word is all BM25 can see. It scores 0.98 and takes rank 1.
- The paraphrase scores zero. "Water damage to storage buildings" means what the query means, but not one of its words is "warehouse" or "flooding". BM25 adds nothing for a word that is not there, so the right answer gets exactly 0.
- Meaning wins here. The water sentence's arrow is 16.3 degrees from the query's, so its cosine is 0.96 and it ranks first. The fire sentence shares only the buildings dial and scores 0.36. The earnings sentence shares no dial and scores 0.
- A tie versus an order. On the left, the right answer and the stock buyback tie at 0, so any tie-break is a coin toss. On the right, all three get different scores and a sensible order.
| Keyword search (BM25) | Embedding search (cosine) | |
|---|---|---|
| What it compares | The exact words of the query and the chunk | The direction of two vectors of numbers |
| A score of 0 means | Not one query word is in the chunk | The two arrows meet at a right angle |
| Needs a trained model | No; it counts words | Yes; the model makes the vectors |
| Good at | Rare exact strings: PP-FL-4B, names, form numbers | Paraphrase: "flooding" finds "water damage" |
| Bad at | Synonyms and rewording | Identifiers the model never learned |
| Where on this page | The sparse leg of Stage 4, section 05 | retrieve() in section 03 |
The honest limit: this toy flatters embedding search, because its vectors were written by hand to mean what the sentences mean. The reverse case is just as real. A form number like PP-FL-4B is a rare string that BM25 pins at once and an embedding blurs. That is failure 3 in section 04, and the Brain Power question just below asks you to predict it.
Neither method wins alone. That is why production systems run both, then merge the two ranked lists, which is the hybrid search of Fig. 8.4.
Keyword search asks "which words match?" and gives a paraphrase 0. Embedding search asks "which way does it point?" and blurs rare identifiers. Run both.
Why divide by the lengths at all? And what does normalize_embeddings=True actually do to the numbers?
Dividing by the lengths throws away how long an arrow is and keeps only where it points. Paste the water sentence in twice and its straight-line distance from the query jumps from 1.41 to 5.39, almost as far as the fire sentence at 5.66. Its cosine stays 0.96. normalize_embeddings=True does that division once, when the index is built.
The obvious way to say how close two points are is straight-line distance, also called Euclidean distance. Subtract the matching numbers, square the differences, add them, take the square root. It measures where an arrow points and how long it is, both at once.
That is a problem for text. In a vector built by counting, a longer chunk makes a longer arrow even when it means the same thing. The math box above makes this argument in words. Here it is with the water sentence pasted in twice, so every count doubles from (3, 4, 0) to (6, 8, 0).
- Distance to the water sentence as written. √((4 − 3)² + (3 − 4)² + (0 − 0)²) = √(1 + 1 + 0) = √2 = 1.41.
- Distance to the water sentence pasted twice. √((4 − 6)² + (3 − 8)² + (0 − 0)²) = √(4 + 25 + 0) = √29 = 5.39.
- Distance to the fire sentence, for comparison. √((4 − 0)² + (3 − 3)² + (0 − 4)²) = √(16 + 0 + 16) = √32 = 5.66.
- Cosine of the doubled sentence. (4 × 6 + 3 × 8 + 0 × 0) ÷ (5 × 10) = 48 ÷ 50 = 0.96. Doubling every number doubles the top of the fraction and the bottom together, so nothing changes.
By distance, repeating a sentence made it look almost as unrelated as a fire rule. Paste it three times, (9, 12, 0), and the distance is 10.30, further away than the stock buyback at 7.07. The cosine is 0.96 every time.
What normalize_embeddings=True does
Normalising means dividing every number in a vector by that vector's own length, so that its new length is exactly 1. It is step C of the cosine, done in advance, once per chunk. The table shows it for three of the arrows.
| Vector | Length | Working | Normalised vector |
|---|---|---|---|
| query (4, 3, 0) | 5 | 4 ÷ 5, 3 ÷ 5, 0 ÷ 5 | (0.8, 0.6, 0) |
| water (3, 4, 0) | 5 | 3 ÷ 5, 4 ÷ 5, 0 ÷ 5 | (0.6, 0.8, 0) |
| water twice (6, 8, 0) | 10 | 6 ÷ 10, 8 ÷ 10, 0 ÷ 10 | (0.6, 0.8, 0), the same point |
Now the cosine is a single multiply: 0.8 × 0.6 + 0.6 × 0.8 + 0 × 0 = 0.96. The bottom of the fraction is 1 × 1, so it can be dropped. That is why mini_rag.py searches with one line, doc_vecs @ q_vec, and why marker 1 of Fig. 8.1a says every row of the index has length 1.
- Distance grows with length. The water sentence sits 1.41 from the query. Pasted twice, it points the same way but reaches twice as far, and the dashed line to it is 5.39 long. By distance alone it would now rank level with a fire rule, which sits 5.66 away.
- The angle does not change. Both water arrows lie on one line, so the angle to the query is 16.3 degrees for both. Cosine reads only that angle, which is why it gives 0.96 to each. Length stopped mattering the moment the lengths were divided out.
- Normalised, they are one point. Divide (3, 4) by 5 and (6, 8) by 10, and both land on (0.6, 0.8), on the circle of length 1. Once every chunk is stored like this, a repeated or padded chunk cannot drift away from the query just by being longer.
- One multiply is the cosine. With both lengths equal to 1, the multiply 0.8 × 0.6 + 0.6 × 0.8 already is the cosine, 0.96. Distance between the tips is 0.28, and 0.28² = 2 − 2 × 0.96. So on normalised vectors, ranking by distance and ranking by cosine always agree.
The honest limit: the multiply is a cosine only if the stored chunk vectors were normalised too. If they were not, a longer chunk vector wins the multiply, and the ranking is quietly wrong. That is why mini_rag.py passes normalize_embeddings=True on both encode calls, for the chunks and for the question.
Cosine divides the lengths out; normalising divides them out once, in advance, so that a plain multiply is the cosine. Normalise the chunks and the query the same way.
Before reading on: the embedding model was trained on general web text. What happens when the adjuster searches for an internal identifier the model has never seen — "What does endorsement form PP-FL-4B cover?" Will meaning-space search find the one chunk that defines PP-FL-4B?
Reveal the answer
Probably not reliably. "PP-FL-4B" gets shredded by the tokenizer into subword fragments ("PP", "-", "FL", ...) that carry almost no meaning, so the identifier contributes nearly nothing to the query vector. The rest of the query — "endorsement form ... cover" — matches dozens of chunks about endorsements and coverage equally well. Semantic search is great at paraphrase and terrible at exact rare tokens.
Old-school keyword search (BM25) has the exact opposite profile: "PP-FL-4B" is a rare term, so any chunk containing it rockets to rank 1. This is why production systems run both and fuse the results — hybrid search, coming in section 05.
03 · Build it yourselfA Real RAG System in ~70 Lines
We now know what retrieval has to do for Victoria: find PolicyPal's flood clause from a question that never uses the word "exclusion". Knowing it and having it are different things, and the pilot has to face real adjuster questions again. So we build the smallest honest version of Fig. 8.0b's bottom half: five real policy passages, a real embedding model, one strict system prompt, and the $45,000 question run straight through it. Everything in the production pipeline later is a repair to this 70-line program, so it is worth being able to write it from memory.
The original version of this course demoed RAG with a TF-IDF term-overlap "vector
store." We're replacing that on principle: TF-IDF counts word matches, so it is
keyword search wearing a vector costume — it scores "flooding in warehouse" vs
"water damage in commercial store" at zero, the exact paraphrase failure you watched
sink bag-of-words models in Module 05. If your retrieval can't do paraphrase, it isn't
semantic search, and your RAG system inherits every blind spot of LIKE '%flood%'.
So we build the real thing, minimally: a genuine neural embedding model
(all-MiniLM-L6-v2 — 384 dimensions, ~80 MB, runs offline on your CPU),
numpy cosine search, and grounded generation via claude-haiku-4-5
($1/$5 per million tokens in/out — the economical tier for high-volume Q&A, as of
Aug 2026). No frameworks, no database, no magic. If you have no API key, the script still
runs end-to-end and shows you the retrieval half.
You have not been taught any of the library calls below yet. That is on purpose. Guess first, then check. Every line in this table is explained in full over the next two sections, and the step-by-step list above the code walks each one.
Build it in chunks
We build mini_rag.py in five chunks. Each one runs on its own. Lines marked # check are only for looking; the whole file below leaves them out. Files are in code/08-rag/ladder/.
-
Chunk 1 — the corpus: five policy passages with citable ids
Everything in RAG starts with text you can point at. Before any model appears, we need the five passages, each carrying the document and page it came from, because that id is what a citation will be made of later.
Step-by-step: what mini_rag.py does, in plain English
- Import
os,numpyandSentenceTransformer. Only the import of the encoder is used from chunk 2 on. - Build
CHUNKS, a list of five dictionaries. Each has anid(document and page) and thetextof the passage. - Print how many chunks there are and the first id, as a check.
mini_rag.py — chunk 1runs offline# pip install "sentence-transformers>=3.0,<6" "numpy>=1.26" "anthropic>=0.40" # First run downloads all-MiniLM-L6-v2 (~80 MB). After that: fully offline, CPU-only. import os import numpy as np from sentence_transformers import SentenceTransformer # --- 1. The corpus: policy chunks, each with metadata we can cite ------------ CHUNKS = [ {"id": "DOC-FL-2026 p.14", "text": "Section 4.B: Commercial warehouse properties located in Florida " "high-risk hurricane zones EXCLUDE water and flood damage. Flood " "coverage requires a separate Tier-1 Supplemental Endorsement."}, {"id": "DOC-FL-2026 p.15", "text": "Section 4.C: The Tier-1 Supplemental Endorsement (form PP-FL-4B) " "adds flood coverage up to $250,000 per location for an added " "premium of 12 percent of the base policy."}, {"id": "DOC-TX-2025 p.8", "text": "Section 2.A: Standard fire damage deductible for commercial " "retail buildings in Texas is $2,500 per occurrence, provided " "fire suppression systems were inspected within 12 months."}, {"id": "DOC-GEN-2026 p.3", "text": "Section 1.C: All claims exceeding $25,000 require dual approval " "from a Senior Adjuster plus an onsite photographic inspection " "report verified by forensic engineering."}, {"id": "DOC-CA-2025 p.11", "text": "Section 3.F: Wildfire damage in California brush zones carries a " "deductible of 5 percent of insured value, with defensible-space " "certification renewed every 24 months."}, ] # check print(len(CHUNKS), "chunks;", CHUNKS[0]["id"])listofdict— each passage keeps its source next to its text. This is the metadata habit that makes citations possible.Run
python3 chunk1_corpus.py. It prints5 chunks; DOC-FL-2026 p.14. - Import
-
Chunk 2 — the index: turn every passage into 384 numbers, once
A computer cannot compare meanings, but it can compare lists of numbers. So we load a small embedding model and run each passage through it one time. That table of numbers is the index.
Step-by-step: what mini_rag.py does, in plain English
- Load
all-MiniLM-L6-v2, a model that turns any text into a list of 384 numbers. The first run downloads about 80 MB. - Encode all five texts at once.
normalize_embeddings=Truescales each list to length 1, so comparing two lists later is a plain multiply. - Print the shape of the result: five rows, 384 columns.
mini_rag.py — chunk 2 (adds to chunk 1)runs offline# --- 2. Index: embed every chunk once (the "write-time" cost) ---------------- # normalize_embeddings=True gives unit vectors, so cosine similarity == dot product. model = SentenceTransformer("all-MiniLM-L6-v2") # 384-D, CPU-friendly doc_vecs = model.encode([c["text"] for c in CHUNKS], normalize_embeddings=True) # check print("index shape:", doc_vecs.shape)SentenceTransformer.encode— text in, a numpy table of numbers out.Run
python3 chunk2_index.py. It printsindex shape: (5, 384). Five passages, 384 numbers each. - Load
-
Chunk 3 — retrieve: find the passages closest in meaning to a question
An index is no use until you can ask it something. Now we embed the question the same way and score every passage against it.
Step-by-step: what mini_rag.py does, in plain English
- Define
retrieve(query, k). Encode the question with the same model, so it lands in the same number space. - Multiply the table by the question's numbers. Each result is one similarity score per passage (cosine similarity, because every row has length 1).
- Sort the scores from high to low and keep the first
k. - Return pairs of (score, chunk), best first. Print them for the Florida question as a check.
mini_rag.py — chunk 3 (adds to chunk 2)runs offlinedef retrieve(query: str, k: int = 3) -> list[tuple[float, dict]]: q_vec = model.encode([query], normalize_embeddings=True)[0] scores = doc_vecs @ q_vec # one dot product per chunk top = np.argsort(scores)[::-1][:k] return [(float(scores[i]), CHUNKS[i]) for i in top] # check for s, c in retrieve("Is flood damage covered for commercial warehouses in Florida?"): print(f"{s:.3f} {c['id']}")@— numpy's matrix multiply.np.argsort(scores)[::-1]— positions from the highest score down.Run
python3 chunk3_retrieve.py. It prints0.740 DOC-FL-2026 p.14, then0.499 DOC-FL-2026 p.15, then0.432 DOC-CA-2025 p.11. The flood-exclusion page wins, though the question never says "exclude". - Define
-
Chunk 4 — the grounding contract and the offline answer path
Retrieval alone returns passages, not answers. Here we write the strict instruction the model will get, and the code that numbers the retrieved passages as [1], [2], [3]. With no API key, the function stops after showing retrieval, so you can run this chunk today.
Step-by-step: what mini_rag.py does, in plain English
- Write
SYSTEM: answer only from the numbered chunks, cite each claim like [1], and sayINSUFFICIENT_CONTEXTwhen the answer is missing. - In
answer(), callretrieveand buildcontext: each hit as[n] (id) text. - If there is no
ANTHROPIC_API_KEY, return the scores and ids with a template answer. This is the offline path.
mini_rag.py — chunk 4 (adds to chunk 3)runs offline# --- 3. Generation with citation discipline ---------------------------------- SYSTEM = ( "You are PolicyPal's claims assistant. Answer ONLY from the numbered " "context chunks. Cite every factual claim with its chunk number, like [1]. " "If the context does not contain the answer, reply exactly: INSUFFICIENT_CONTEXT." ) def answer(query: str) -> str: hits = retrieve(query) context = "\n\n".join(f"[{n}] ({c['id']}) {c['text']}" for n, (_, c) in enumerate(hits, 1)) if not os.environ.get("ANTHROPIC_API_KEY"): # offline fallback path shown = "\n".join(f" [{n}] cos={s:.3f} {c['id']}" for n, (s, c) in enumerate(hits, 1)) return (f"(no API key — retrieval only)\n{shown}\n" f"Template answer: quote chunk [1] verbatim and cite it.") # check print(answer("Is flood damage covered for commercial warehouses in Florida?"))os.environ.get— reads a setting from the environment, returnsNoneif missing. An f-string with:.3fprints three decimals.Run
python3 chunk4_prompt_offline.pywith no key set. It prints(no API key — retrieval only), the same three scores and ids as chunk 3 numbered [1] to [3], andTemplate answer: quote chunk [1] verbatim and cite it.If a key is set, this chunk returns nothing yet; chunk 5 adds the model call. - Write
-
Chunk 5 — call Claude with the context, and run two questions
Last, we hand the numbered passages and the question to the model. This is the only chunk that spends money, so it comes last.
Step-by-step: what mini_rag.py does, in plain English
- Import
anthropicand create a client; it reads the key from the environment. - Call
messages.createonce with the strictSYSTEM, and a user message that holds the context then the question.max_tokens=500caps the reply. - Return the text of the first text block in the reply.
- Under
__main__, ask two questions and print each answer.
mini_rag.py — chunk 5 (the finished file)needs API keyimport anthropic client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY resp = client.messages.create( model="claude-haiku-4-5", max_tokens=500, system=SYSTEM, messages=[{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {query}"}], ) return next(b.text for b in resp.content if b.type == "text") if __name__ == "__main__": for q in ["Is flood damage covered for commercial warehouses in Florida?", "What is the fire deductible for a shop in Texas?"]: print(f"\nQ: {q}\n{answer(q)}")client.messages.create— the Anthropic Messages API.next(... for b in resp.content if b.type == "text")— picks the first text block.Run
python3 chunk5_claude.py. With no key (what we measured) it prints both questions with the offline retrieval lists: Florida top hit0.740 DOC-FL-2026 p.14, Texas top hit0.787 DOC-TX-2025 p.8. With a key, the Florida answer is the model's cited reply. Not run here with a key. - Import
The whole program
Lines 1–31 are chunk 1 (the pip comment, imports and the corpus), 32–37 chunk 2, 38–44 chunk 3, 45–61 chunk 4, and 62–75 chunk 5 with the two demo questions. Every chunk starts with a # ── chunk n ── comment.
Step-by-step: what mini_rag.py does, in plain English
- Bring in three libraries:
osto read the API key from the environment,numpyfor the arithmetic, andSentenceTransformer, the wrapper around the embedding model. - Define
CHUNKS: five hand-written policy passages, each a dictionary holding an id (document and page) and the text. In a real system a parser produces these; here they are typed in so you can read them. - Load the embedding model
all-MiniLM-L6-v2. The first run downloads about 80 MB; after that it runs on your CPU with no network. - Encode all five chunk texts at once into
doc_vecs, a table with five rows of 384 numbers each.normalize_embeddings=Truescales every row to length 1, which is what makes step 6 a plain multiply. This is the index, and it is built once. - Define
retrieve(query, k): encode the question the same way, so it lands in the same 384-number space as the chunks. - Multiply the table by the question's vector. Because every row has length 1, each product is a cosine similarity: 1.0 means "same direction", which means same meaning; 0 means unrelated.
- Sort the scores, reverse so the highest comes first, keep the top
kpositions, and return (score, chunk) pairs, best first. - Define
SYSTEM, the grounding contract: answer only from the numbered chunks, cite each claim with [n], and if the answer is not there sayINSUFFICIENT_CONTEXT. - Define
answer(query): retrieve the top chunks and format them as numbered context blocks, each carrying its document id. - If there is no
ANTHROPIC_API_KEYin the environment, stop here and print the retrieval results with their scores. The retrieval half of RAG never needs a key. - Otherwise create an Anthropic client (it reads the key itself) and call the model once, with the system prompt and a user message holding the context and then the question.
- Pull the text out of the first text block of the reply and return it.
- When run as a script, ask two questions and print each answer.
# pip install "sentence-transformers>=3.0,<6" "numpy>=1.26" "anthropic>=0.40"
# First run downloads all-MiniLM-L6-v2 (~80 MB). After that: fully offline, CPU-only.
import os
import numpy as np
from sentence_transformers import SentenceTransformer
# ── chunk 1: the corpus ──
# --- 1. The corpus: policy chunks, each with metadata we can cite ------------
CHUNKS = [
{"id": "DOC-FL-2026 p.14",
"text": "Section 4.B: Commercial warehouse properties located in Florida "
"high-risk hurricane zones EXCLUDE water and flood damage. Flood "
"coverage requires a separate Tier-1 Supplemental Endorsement."},
{"id": "DOC-FL-2026 p.15",
"text": "Section 4.C: The Tier-1 Supplemental Endorsement (form PP-FL-4B) "
"adds flood coverage up to $250,000 per location for an added "
"premium of 12 percent of the base policy."},
{"id": "DOC-TX-2025 p.8",
"text": "Section 2.A: Standard fire damage deductible for commercial "
"retail buildings in Texas is $2,500 per occurrence, provided "
"fire suppression systems were inspected within 12 months."},
{"id": "DOC-GEN-2026 p.3",
"text": "Section 1.C: All claims exceeding $25,000 require dual approval "
"from a Senior Adjuster plus an onsite photographic inspection "
"report verified by forensic engineering."},
{"id": "DOC-CA-2025 p.11",
"text": "Section 3.F: Wildfire damage in California brush zones carries a "
"deductible of 5 percent of insured value, with defensible-space "
"certification renewed every 24 months."},
]
# ── chunk 2: the index ──
# --- 2. Index: embed every chunk once (the "write-time" cost) ----------------
# normalize_embeddings=True gives unit vectors, so cosine similarity == dot product.
model = SentenceTransformer("all-MiniLM-L6-v2") # 384-D, CPU-friendly
doc_vecs = model.encode([c["text"] for c in CHUNKS], normalize_embeddings=True)
# ── chunk 3: retrieve ──
def retrieve(query: str, k: int = 3) -> list[tuple[float, dict]]:
q_vec = model.encode([query], normalize_embeddings=True)[0]
scores = doc_vecs @ q_vec # one dot product per chunk
top = np.argsort(scores)[::-1][:k]
return [(float(scores[i]), CHUNKS[i]) for i in top]
# ── chunk 4: grounding contract and offline path ──
# --- 3. Generation with citation discipline ----------------------------------
SYSTEM = (
"You are PolicyPal's claims assistant. Answer ONLY from the numbered "
"context chunks. Cite every factual claim with its chunk number, like [1]. "
"If the context does not contain the answer, reply exactly: INSUFFICIENT_CONTEXT."
)
def answer(query: str) -> str:
hits = retrieve(query)
context = "\n\n".join(f"[{n}] ({c['id']}) {c['text']}"
for n, (_, c) in enumerate(hits, 1))
if not os.environ.get("ANTHROPIC_API_KEY"): # offline fallback path
shown = "\n".join(f" [{n}] cos={s:.3f} {c['id']}"
for n, (s, c) in enumerate(hits, 1))
return (f"(no API key — retrieval only)\n{shown}\n"
f"Template answer: quote chunk [1] verbatim and cite it.")
# ── chunk 5: call Claude ──
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
resp = client.messages.create(
model="claude-haiku-4-5", max_tokens=500, system=SYSTEM,
messages=[{"role": "user",
"content": f"Context:\n{context}\n\nQuestion: {query}"}],
)
return next(b.text for b in resp.content if b.type == "text")
if __name__ == "__main__":
for q in ["Is flood damage covered for commercial warehouses in Florida?",
"What is the fire deductible for a shop in Texas?"]:
print(f"\nQ: {q}\n{answer(q)}")
Run it with a key set and the Florida question comes back something like: "No. Flood damage is excluded for commercial warehouses in Florida high-risk hurricane zones [1]. Coverage is available only via the Tier-1 Supplemental Endorsement, which adds up to $250,000 of flood coverage for a 12 percent premium [2]." That is the $45K bug, fixed, with receipts. Three things to internalize before we break it:
- The index is built once, searched many times. Embedding the corpus is the expensive write-time step; each query costs one embedding call plus one matrix multiply. Database-index thinking, exactly.
- Citations are a prompt contract, not an afterthought. The system
prompt demands numbered cites and a refusal token (
INSUFFICIENT_CONTEXT). You'll eval that contract in section 07. - Metadata rides along with the text. Every chunk carries its doc ID and page. Whatever store you graduate to, this discipline is what makes "verify in one click" possible.
- Built once, marker 1.
model.encoderuns over all five chunk texts and returns a table with one row per chunk and 384 numbers per row.normalize_embeddings=Truescales every row to length 1, which is the trick that turns cosine similarity into a plain multiply later. In production this step runs on a schedule, not per request. - One multiply per question, marker 2. The question goes through the same encoder and comes back as one row of 384 numbers. Multiplying the table by that row gives five numbers, one per chunk, each of which is the cosine similarity because both sides have length 1. This is database-index thinking: pay at write time, read cheaply.
- Sort and number, marker 3. Sorting five scores and keeping the best three is the whole of "retrieval" in this version. Those three become the blocks [1], [2] and [3] in the prompt, each carrying its document id and page, which is what makes the model's citations resolvable.
04 · Watch it breakThe Four Classic RAG Failures
The 70-liner answered the Florida question correctly, with a page citation. That is exactly the demo that gets a project funded, and it is also where most teams stop. But PolicyPal's real corpus is not five hand-typed passages: it is 4,000 pages, three years of near identical revisions, and form numbers like PP-FL-4B. Each of those differences breaks the toy in a specific, repeatable way. We run all four breakages on purpose here, because section 05 is not a list of best practices — it is one component per failure, and the components only make sense once you have seen the damage each one repairs.
The 70-liner works beautifully on a 5-chunk toy corpus. Every production RAG system that has ever paged an on-call engineer failed in one of the four ways below. Learn to recognize them now, because section 05's entire architecture — recursive chunking, hybrid search, rerankers, faithfulness evals — exists as a response to these four failures, one component per failure.
All four, on one screen, before we take them one at a time. Each panel shows what the retriever actually returned and why the sentence the adjuster read was wrong.
- The clause cut in half, marker 1. A fixed-size chunker slices every 120 characters and does not know what a sentence is. The exclusion ends up in chunk 1 and the remedy in chunk 2, so retrieval returns a true half-answer. Nothing downstream can detect this, because the model was told the truth; it was just told half of it.
- Near-duplicates, marker 2. The 2024, 2025 and 2026 editions of the Florida policy are almost the same words, so they score almost the same cosine: 0.71, 0.70, 0.69. Three slots, one fact. The dual-approval rule that actually gates a $30,000 payout sits just under the cut line and never reaches the prompt.
- The identifier, marker 3. Two bars, near enough the same length. The chunk that defines PP-FL-4B and a chunk of generic endorsement prose score almost identically against a question about PP-FL-4B, because the tokenizer turns that form number into meaningless fragments. The rest of the question matches both equally well.
- Answering from memory, marker 4. Retrieval worked. The context block says EXCLUDE in capitals, and the model still wrote "likely covered". This is the one failure that happens in front of the user, and it is the one that cost $45,000.
Failure 1 — Bad chunking splits the answer in half
The adjuster's question now reaches a corpus that the pipeline has already damaged, before anyone typed anything. Nobody slices 4,000 pages by hand, so the first thing a naive pipeline does is cut every document every N characters. Watch what that knife does to the one clause the $45,000 payout turned on.
Real corpora don't arrive pre-chunked. Naive pipelines slice documents every N characters. Watch what a fixed-size chunker does to the exact clause that matters most:
# stdlib only — no installs
CLAUSE = ("Section 4.B: Commercial warehouse properties located in Florida "
"high-risk hurricane zones EXCLUDE water and flood damage. Flood "
"coverage requires a separate Tier-1 Supplemental Endorsement, "
"described in Section 4.C, at a 12 percent added premium.")
def fixed_chunks(text: str, size: int = 120) -> list[str]:
return [text[i:i + size] for i in range(0, len(text), size)]
for n, chunk in enumerate(fixed_chunks(CLAUSE), 1):
print(f"chunk {n}: {chunk!r}")
chunk 1: 'Section 4.B: Commercial warehouse properties located in Florida high-risk hurricane zones EXCLUDE water and flood damage'
chunk 2: '. Flood coverage requires a separate Tier-1 Supplemental Endorsement, described in Section 4.C, at a 12 percent added pr'
chunk 3: 'emium.'
- The arithmetic of the cut, marker 1. The clause is 246 characters. Dividing by 120 gives chunks at 0-120, 120-240 and 240-246. Those boundaries are decided by counting characters, so the first cut falls one character before the full stop, separating "EXCLUDE water and flood damage" from "Flood coverage requires a separate Tier-1 Supplemental Endorsement".
- The orphan, marker 2. What is left over is 'emium.', six characters. The embedding model will happily turn it into 384 numbers, and those numbers mean nothing. Every corpus chunked this way carries thousands of these, quietly taking up index space and occasionally winning a slot.
- The sentence-aware cut, marker 3. Splitting on the full stop gives 121 and 124 characters — near enough the same sizes, but each half is a complete statement. Retrieval can now return the exclusion, the remedy, or both, and any one of them is a true and complete answer to something.
The exclusion landed in chunk 1; the remedy (the endorsement) landed in chunk 2; chunk 3
is the orphaned string 'emium.', which will embed as pure noise. Retrieval
now returns chunk 1 alone, and the model truthfully answers "flood damage is excluded" —
without mentioning that coverage can be bought. Technically grounded, materially
wrong, and no hallucination detector will ever flag it, because the failure happened at
index time.
Failure 2 — Top-k returns near-duplicates and crowds out the doc you need
Chunking fixed, the same question meets PolicyPal's second reality. The Florida policy exists as a 2024, a 2025 and a 2026 edition, and they differ by a few sentences. The question an adjuster actually asks is "can I approve this myself", which needs two different documents at once: the one about flood cover and the one about who may sign. Here is what top-3 retrieval hands the model instead.
Enterprise corpora are full of near-identical revisions: the 2024, 2025, and 2026 editions of the Florida policy differ by a few sentences. Add them all to the index and ask a question that needs two distinct documents — "Can I approve a $30,000 Florida flood claim myself?" — and top-3 retrieval returns:
[1] cos=0.71 DOC-FL-2026 p.14 (flood exclusion, current)
[2] cos=0.70 DOC-FL-2025 p.14 (flood exclusion, last year — 97% identical)
[3] cos=0.69 DOC-FL-2024 p.13 (flood exclusion, two years ago)
missed: DOC-GEN-2026 p.3 (dual-approval rule for claims > $25,000)
- The ranking, marker 1. Cosine similarity asks one question of every chunk: how close is your meaning to the question's meaning? Three revisions of the same paragraph are, by construction, almost equally close, which is why the scores sit within 0.02 of each other. The ranking is not wrong. It is answering a question nobody wanted answered.
- The chunk just under the line, marker 2. DOC-GEN-2026 p.3 says claims over $25,000 need a Senior Adjuster plus an inspection report. It mentions neither Florida nor flooding, so it scores lower than three paragraphs that do. Being the only relevant chunk earns it nothing, because nothing in the scoring function knows what the adjuster is allowed to do.
- What the model sees, marker 3. The prompt now contains one fact, repeated. The model will answer correctly about coverage and say nothing about approval, which reads as a complete answer and is not one. The fixes are index hygiene (drop superseded revisions), metadata filters (current revisions only), and a reranker that reads the question against each candidate.
All three slots got spent on the same fact, and the dual-approval rule — the one that makes this claim require a senior adjuster — never reached the model. Similarity search optimizes for closeness, not for coverage. Fixes you'll meet shortly: dedupe/version-filter at index time, retrieve more candidates and let a reranker promote diversity, and metadata filters ("only current revisions").
Failure 3 — Semantic search whiffs on exact identifiers
Adjusters do not only ask about topics; they ask about form numbers. PP-FL-4B is the endorsement that would have let the Florida warehouse buy flood cover for 12 percent more premium, and it appears on exactly one page of the 4,000. If the retriever cannot find that one page, the assistant's answer to "what does PP-FL-4B cover" is a guess. This is the failure the Brain Power question predicted, now drawn and then measured.
The Brain Power question, now as a measurement. Embed the PP-FL-4B question against the chunk that defines the form and a generic chunk that merely talks about endorsements:
# pip install "sentence-transformers>=3.0,<6"
from sentence_transformers import SentenceTransformer
m = SentenceTransformer("all-MiniLM-L6-v2")
docs = [
"The Tier-1 Supplemental Endorsement (form PP-FL-4B) adds flood coverage "
"up to $250,000 per location.", # the actual answer
"Supplemental endorsements extend coverage beyond the base commercial "
"policy for an additional premium.", # generic filler
]
q = "What does endorsement form PP-FL-4B cover?"
vecs = m.encode([q] + docs, normalize_embeddings=True)
print("chunk naming PP-FL-4B :", round(float(vecs[0] @ vecs[1]), 3))
print("generic endorsement :", round(float(vecs[0] @ vecs[2]), 3))
id_probe.py below and your own two numbers will land within a few hundredths of each other.- The tiles, marker 1. "What does endorsement form ... cover?" is six ordinary words that any paragraph about endorsements matches well. The seventh tile, PP-FL-4B, is the only one that distinguishes the right chunk from the wrong one, and it is the one the embedding model handles worst.
- The two distances, marker 2. This is the picture from Fig. 8.1 again, zoomed into the region around the query. Both candidates land at almost the same distance, so the ranking between them is decided by wording noise rather than by the identifier. In a corpus with hundreds of chunks mentioning "endorsement", the right chunk routinely loses.
- The opposite profile, marker 3. BM25 scores a chunk by which query words it contains, weighting rare words far above common ones. PP-FL-4B is as rare as a term gets, so the one chunk that contains it is pinned at rank 1 while "endorsement" and "cover" barely move anything. Neither method wins alone, which is the whole argument for running both.
Run it: the two cosines land nearly on top of each other. The identifier — the entire point of the query — contributes almost nothing, because it tokenizes into meaningless subword fragments. In a real corpus with hundreds of chunks mentioning "endorsement" and "coverage," the chunk that actually defines PP-FL-4B routinely loses the ranking. A BM25 keyword engine gets this query right in one shot: the rare term is a laser pointer. Neither method wins alone — this failure is the argument for hybrid search.
Failure 4 — Retrieval succeeds, but the model answers from its own memory anyway
Three failures have now happened before the model saw a single token, and all three are invisible until someone reads a bad answer. The fourth is the one that actually cost Victoria $45,000, and it is the strangest of the four, because it happens when retrieval has already done its job perfectly.
The sneakiest one. Retrieval returns the correct exclusion clause, and the model replies:
Q: Is flood damage covered for commercial warehouses in Florida?
"Commercial property policies typically include flood coverage up to
policy limits, though some regional exclusions may apply. Your Florida
warehouse is likely covered for flood events subject to the standard
deductible."
The context said EXCLUDE; the model said "likely covered." It leaned on its parametric memory — the average of every insurance document on the internet — instead of the retrieved truth sitting right in its prompt. This happens more when the grounding instruction is soft, when context is long and the key clause is buried mid-prompt, and when the model's prior is strong. You cannot fix what you don't measure: this failure is exactly what the faithfulness metric from Module 07's eval toolkit detects, and we'll wire it up in section 07. Grounding is a contract, and contracts need tests.
Before the two of them argue, look at what each one actually breaks. The left column is everything the retriever can get wrong, with the numbers from the four failures above. The right column is the generator's single failure. Every line in the chat below points at a marker in this picture.
- The retriever's column, marker 1. Cutting, scoring and finding are all its job, and all three of its failures are committed weeks before a question arrives. Nothing in the generated answer looks wrong when the retriever fails; the answer is fluent, cited, and built from the wrong evidence.
- The generator's column, marker 2. One failure, and it is the expensive one. The context block says EXCLUDE and the reply says "likely covered", which means the model preferred its own memory of the internet to the document in its prompt. This is the only one of the four that a user can see happening.
- Two different clocks, marker 3. The timeline is why the two roles are argued about separately. An index-time failure is silent and old; a query-time failure is loud and new. A team that cannot tell which clock a bad answer came from will keep fixing the wrong half.
- Two report cards, marker 4. Context recall asks whether the needed chunk was retrieved at all, context precision asks whether the top-ranked chunks were relevant, and faithfulness asks whether the answer stayed inside what was retrieved. The first two grade the left column, the third grades the right, and section 07 wires all three up.
Tonight's talk: The Retriever and The Generator argue over the question, "Who's more important?"
Let's be clear about who does the work here. Look at the left column, marker 1. I read four thousand pages so nobody else has to, and I find the five paragraphs that matter in under a hundred milliseconds. You get handed the answer on a plate, and then you write a paragraph. A paragraph. My cousin the search engine has been doing my job since 1998. You are the new hire.
the retriever's job is to turn 4,000 pages into a handful of passages, fast. Everything in marker 1's column is work that happens before the model is even called.
A plate of five paragraphs is not an answer. The adjuster asked a question. Marker 1, second line: 0.71, 0.70, 0.69 — three copies of the same flood exclusion, and the dual-approval rule left out entirely. I am the one who reads what you hand me, notices what is missing, writes a sentence a human can act on, and puts a [1] after it so someone can check. Without me, you are a list of links.
a ranked list is not an answer. The generator turns passages into one sentence a person can act on, and attaches the citation that makes it checkable.
Without me, you are an improviser. Marker 2, bottom line: forty-five thousand dollars. Nobody retrieved anything that day, you were asked about Florida flood cover, and you invented a coverage clause. Every fact you have ever stated correctly about PolicyPal, I put in front of you first.
with no retrieval step at all, the model answers from training data. That is the closed-book path, and it is what produced the $45,000 payout.
And three of the four failures are in your column, marker 1, not mine. Failure 1: you cut a clause in half at character 120. Failure 2: you spent all three slots on duplicates. Failure 3: you could not tell PP-FL-4B from a generic paragraph about endorsements. Nobody paged me for any of those.
marker 1 lists the three index-time failures. All of them are decided by chunking and scoring, long before any prompt is built.
Failure 4 is yours, and it is the worst one. Marker 2, top box: I handed you the exclusion clause and it said EXCLUDE, in capitals. The box under it is what you wrote. "Likely covered." You had the truth in your prompt and answered from your memory of the internet anyway.
the two stacked boxes at marker 2 are the same request: correct evidence in, invented answer out. Retrieval cannot prevent this one.
Which is why the prompt now says answer only from the context and cite every claim, and why faithfulness watches me on every request. I accept the contract. I would just point out, marker 4, that I am not the only one being graded. Context recall and context precision are your report cards, and they are kept separate from mine for a reason.
marker 4 splits the grading. Faithfulness scores the generator; context recall and context precision score the retriever.
The reason being that when you fail, they page one engineer, and when I fail, they page a different one.
separate scores exist so that a bad answer names a team. One number for the search half, one for the writing half.
The reason being that we fail differently, and marker 3 is the proof. You fail at the left tick, index time, weeks before anyone asks a question, and silently. I fail at the right tick, query time, in front of the user. A team that cannot tell which tick a bad answer came from cannot fix either of us.
the timeline at marker 3 has two ticks. Retrieval failures are old and invisible; generation failures are immediate and visible.
Then let's agree on one thing. Nobody should trust either of us. They should trust the citation.
the only thing a human can verify is the link back to the page. Neither component asks to be believed.
The citation I write and you make checkable. Fine. We'll revisit who's more important when the eval results come in.
the citation needs both of them: the retriever carries the page number, the generator writes the [1] that points at it.
Oh, you can count on it.
unresolved on purpose. The eval numbers in section 07 are what settle it, per question, per corpus.
Before the industry section: each failure above is fixed by one component of the production pipeline. Can you name the component for each of the four before you see the diagram?
Reveal the answer
(1) Bad chunking → smarter chunking strategies (recursive/semantic/parent-document). (2) Near-duplicate crowding → reranking plus metadata filtering and index hygiene. (3) Exact-identifier misses → hybrid dense+BM25 retrieval with rank fusion. (4) Ignoring context → citation-forcing prompts verified by faithfulness evals in CI. If you got 3 of 4, you already understand why the industry pipeline looks the way it does.
05 · The industry pipelineHow Professionals Build RAG in 2026
Four failures, four holes in the 70-liner, and Victoria wants a system her auditors will sign off on. This section is the repair kit, assembled in the order the damage happens: parse and chunk so the flood clause is never cut at character 120, embed and index so 4,000 pages answer in milliseconds, hybrid search so PP-FL-4B is findable, rerank so the dual-approval rule is not crowded out by three near-duplicates, and citations so every sentence carries a page an auditor can open. Read what follows as seven stages of one machine, not seven topics.
Here is the whole production architecture at a glance. Everything below the diagram walks it stage by stage. Note the shape: an offline index path (run on every document change) and an online query path (run per request, under a second), meeting at the index — plus an eval loop feeding error analysis back into the pipeline, because in 2026 a RAG system without evals is a demo, not a product.
Now the same picture a second time, with this module's actual files in the boxes. If a stage in Fig. 8.2 feels abstract, find its row here: every stage is a script you can run or a line you have already read.
| Stage | In the 70-line version (section 03) | In the production build (this section) | What flows out |
|---|---|---|---|
| Ingest + parse | Five chunks typed by hand in CHUNKS | LlamaParse or a layout-aware parser over 50+ PDFs | Clean text with document and page metadata |
| Chunk | Skipped: each passage is already one chunk | RecursiveCharacterTextSplitter, about 500 tokens, 10–15% overlap | Chunks that do not cut a sentence in half |
| Embed | model.encode(...) in mini_rag.py | The same call, batched, on a schedule; model name pinned in the schema | One 384-number vector per chunk |
| Index | A numpy array in memory, doc_vecs | The chunks table in schema.sql with an HNSW index | Something you can search in milliseconds |
| Embed the query | model.encode([query]) inside retrieve() | Identical: same model, same version, forever | One vector for the question |
| Hybrid search | doc_vecs @ q_vec, cosine only | Dense + BM25, fused by rrf() in hybrid_rrf.py | A ranked shortlist of candidates |
| Rerank | None | CrossEncoder in rerank.py over the top 50 | The five chunks that really answer the question |
| Pack context | The "\n\n".join(...) line in answer() | The same, plus a token budget and parent-chunk expansion | Numbered blocks [1] to [5] |
| Generate + cite | client.messages.create(...) with the strict SYSTEM | The same contract, streamed, citations rendered as links | An answer an auditor can check |
| Eval | None | Ragas in eval_rag.py: faithfulness, context precision, context recall | Numbers that say which stage to fix |
Stage 1 — Parse & chunk: where most quality is won or lost
PolicyPal's 4,000 pages arrive as PDFs with two-column layouts, tables and scanned amendments. Failure 1 showed what cutting them every 120 characters does to the one clause that mattered. This stage is where that is repaired, and it has the largest effect of any stage on the three numbers you will measure in section 07, because nothing downstream can recover a fact that was split in half at index time.
Parsing is unglamorous and decisive: a policy PDF with two-column layouts, tables, and scanned amendments will destroy a naive text extractor. The 2026 default for messy PDFs is LlamaParse (LlamaIndex's parsing service) or an OSS layout-aware parser; for clean HTML/Markdown, plain extraction is fine. Then chunking — you watched failure 1; here are the four strategies that fix it, on the same document:
Here are those four strategies again, applied to the actual Section 4.B clause you just broke. Same 246 characters, four different knives.
- Counting characters, marker 1. The knife falls at 120 and 240 because 246 divided by 120 says so, and for no other reason. One character earlier than the full stop is enough to put "EXCLUDE water and flood damage" and "Flood coverage requires a separate Tier-1 Supplemental Endorsement" in different chunks.
- Trying the big boundaries first, marker 2. A recursive splitter looks for a paragraph break; failing that, a sentence break; failing that, a word break. On this clause it finds the full stop at 121 and stops there, producing 121 and 124 characters. This is the default for prose, policies and documentation, and it is the whole of the fix for failure 1.
- Measuring meaning instead, marker 3. A semantic splitter embeds each sentence and cuts where consecutive sentences stop pointing the same way. Here it finds the same boundary, because the clause genuinely changes subject there: what is excluded, then how to buy cover. You pay for it in index-time compute and one more threshold to tune.
- Two sizes at once, marker 4. Parent-document indexes the small halves, because small chunks retrieve precisely, and returns the dashed parent, because the model answers better with the surrounding sentences. The retrieval unit and the reading unit stop being the same thing.
| Strategy | How it splits | Choose when | Watch out for |
|---|---|---|---|
| Fixed-size + overlap | Every ~N tokens, 10–15% overlap | First baseline; uniform log-like text | Splits sentences and ideas (failure 1) |
| Recursive | Paragraphs → sentences → words, targeting ~300–800 tokens | The default for prose, Markdown, policies, docs | Still blind to meaning; tune size per corpus |
| Semantic | Breaks where inter-sentence embedding distance jumps | Dense technical docs; index-time budget to spend | Slow indexing; a threshold to tune |
| Parent-document | Embed small children; return the larger parent on hit | Precise retrieval and the LLM needs surrounding context | Index bookkeeping; larger prompts per query |
Stage 2 — Choose an embedding model
The chunks are now clean and whole. Something has to turn each one into the 384 numbers that make Fig. 8.1's meaning-space possible. This looks like a shopping decision and is really a schema decision: change the model later and every vector PolicyPal has stored becomes garbage until the whole corpus is re-embedded.
| Model | Dims | Runs where | Choose when |
|---|---|---|---|
all-MiniLM-L6-v2 | 384 | Local, CPU | Prototypes, labs, laptops — what we used above |
text-embedding-3-large (OpenAI) | 3072 (truncatable) | API | Best-in-class managed quality; fine paying per token and shipping data out |
BGE-M3 (BAAI, open) | 1024 | Local, GPU-friendly | Self-hosted production; multilingual; emits dense and sparse signals from one model |
voyage-3-large | 1024 (default) | API | Retrieval-benchmark leader when you want a second managed option to A/B |
One rule matters more than the choice itself: the query and the corpus must be embedded by the same model, same version, forever. Swap models and every stored vector is garbage until you re-embed the corpus. Treat the embedding model name as part of your index schema, and budget for one full re-embedding per model upgrade.
Stage 3 — The vector store: prototype on Chroma, ship on pgvector
Chunks and vectors exist; they now have to live somewhere that survives a restart and answers in milliseconds. PolicyPal already runs Postgres for claims, users and permissions, and that fact decides most of this stage. Prototype on the thing with no server, ship on the thing your ops team already carries, and keep every chunk's document id and page next to its vector, because that metadata is what makes Victoria's citations possible.
Chroma is the fastest way to get a persistent, metadata-filterable vector store with zero servers — it even embeds for you (its default embedding function is the same MiniLM family you just used):
# pip install "chromadb>=0.5,<2" — needs mini_rag.py from section 03 alongside
import chromadb
from mini_rag import CHUNKS
client = chromadb.PersistentClient(path="./policypal_db") # on-disk, no server
col = client.get_or_create_collection(
"policies", metadata={"hnsw:space": "cosine"})
col.add(
ids=[c["id"] for c in CHUNKS],
documents=[c["text"] for c in CHUNKS],
metadatas=[{"doc": c["id"].split(" p.")[0],
"page": int(c["id"].split(" p.")[1])} for c in CHUNKS],
)
res = col.query(
query_texts=["florida flood exclusions"], # Chroma embeds this for you
n_results=3,
where={"doc": "DOC-FL-2026"}, # metadata filtering, for free
)
for cid, dist in zip(res["ids"][0], res["distances"][0]):
print(f"{1 - dist:.3f} {cid}")
For production, the boring default under ~10 million vectors is pgvector — because you already run Postgres. Your chunks live next to your users, permissions, and billing tables; retrieval joins against access control in one SQL statement; backups, replication, and monitoring are problems you already solved. Amazon's own Solutions Architect postings name "Aurora pgvector" as a standard RAG substrate. Schema first:
-- Postgres 16+ with the pgvector extension installed
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
doc_id text NOT NULL,
page int,
content text NOT NULL,
embedding vector(384) -- must match your embedding model's dims
);
-- HNSW approximate-nearest-neighbor index on cosine distance
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
# pip install "psycopg[binary]>=3.2" "pgvector>=0.3" "sentence-transformers>=3.0,<6"
import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer
from mini_rag import CHUNKS
model = SentenceTransformer("all-MiniLM-L6-v2")
conn = psycopg.connect("dbname=policypal", autocommit=True)
register_vector(conn) # teaches psycopg the vector type
# --- index time: insert chunks with embeddings -------------------------------
vecs = model.encode([c["text"] for c in CHUNKS], normalize_embeddings=True)
with conn.cursor() as cur:
for c, v in zip(CHUNKS, vecs):
doc, page = c["id"].split(" p.")
cur.execute(
"INSERT INTO chunks (doc_id, page, content, embedding) "
"VALUES (%s, %s, %s, %s)", (doc, int(page), c["text"], v))
# --- query time: <=> is pgvector's cosine-distance operator ------------------
def search(query: str, k: int = 5):
q = model.encode([query], normalize_embeddings=True)[0]
return conn.execute(
"SELECT doc_id, page, content, 1 - (embedding <=> %s) AS cosine "
"FROM chunks ORDER BY embedding <=> %s LIMIT %s",
(q, q, k)).fetchall()
for doc_id, page, content, cosine in search("florida flood exclusions"):
print(f"{cosine:.3f} {doc_id} p.{page}")
SELECT doc_id, page, content,
1 -1 (embedding <=>2 %s) AS cosine
FROM chunks
ORDER BY embedding <=> %s3
LIMIT %s4
- One minus the distance. pgvector's operators return a distance, where 0 means identical. Subtracting from 1 turns cosine distance back into the similarity you have used all module, where 1 means identical. Printing the raw distance and reading it as a similarity is the most common first-week confusion.
- The operator.
<=>is cosine distance. Its siblings are<->for straight-line (Euclidean) distance and<#>for negative inner product. Use the one your index was built for (vector_cosine_opsinschema.sql), or the index is silently ignored and every query scans the whole table. - ORDER BY the same operator, bare. This is the clause the HNSW index actually serves. The planner uses the index only when the ORDER BY expression is the distance operator itself. Order by the computed
cosinecolumn instead and you get a full table scan that looks correct and is a hundred times slower. - LIMIT is k. Approximate nearest-neighbour search is cheap because it stops early. Ask for 5 and it finds 5; ask for 5,000 and the index loses its advantage. Retrieve a modest shortlist here and let the reranker do the precise work.
| Store | Choose when | Avoid when | Ops burden |
|---|---|---|---|
| Chroma | Prototyping, labs, single-process apps, <~1M vectors | Multi-writer production, HA requirements | None |
| pgvector | Default under ~10M vectors; you already run Postgres; retrieval must join ACLs/metadata | Very high QPS with heavy filtered ANN at 100M+ scale | The Postgres you already carry |
| Qdrant | Performance-critical OSS self-hosting; rich payload filtering at scale | Team can't own another stateful service | One more service |
| Pinecone | Managed/serverless; no infra team; elastic scale | Strict data-residency; cost-sensitive at large scale | None (you rent it) |
Stage 4 — Hybrid retrieval: dense + BM25, fused by RRF
Storage is solved and failure 3 is still open: PP-FL-4B is unfindable by meaning alone, and it is the endorsement that decides whether a Florida warehouse can buy flood cover at all. The fix is not a better embedding model. It is a second retriever with exactly the opposite blind spot, plus a merge rule that does not require the two to agree on units.
Failure 3 showed that dense retrieval misses exact identifiers and keyword search misses paraphrase. Production systems run both per query and merge the two ranked lists with Reciprocal Rank Fusion (RRF) — a beautifully dumb algorithm that ignores the incomparable raw scores and combines positions instead:
Step-by-step: what hybrid_rrf.py does, in plain English
- Bring in numpy, Python's regular-expression module, the BM25 implementation from
rank_bm25, the embedding model, and the fiveCHUNKSfrommini_rag.py. - Pull the chunk texts into a plain list, because both legs index the same texts.
- Dense leg: load the same embedding model and encode every chunk, exactly as in section 03.
- Sparse leg: define
tokenize(), which lowercases the text and pulls out runs of letters, digits and hyphens, so punctuation never sticks to a token. Build a BM25 index over the tokenised chunks. BM25 scores a chunk by which query words it contains, weighted so that rare words count for more than common ones. dense_ranking(query): embed the question, score every chunk by dot product, and return the chunk positions from best to worst.sparse_ranking(query): score every chunk with BM25 for the question's tokens, cut by the sametokenize(), and return positions from best to worst. Note that both functions return positions, not scores. The fusion step never sees a score.rrf(rankings, k=60): start an empty score sheet. Walk down each ranked list; the chunk at positionposearns 1 divided by (k + pos + 1), added to its running total. Return the chunks sorted by total, highest first. A chunk near the top of both lists beats a chunk that is first in only one.- Ask the PP-FL-4B question, fuse the two rankings, and print the ids of the top three.
# pip install "rank-bm25>=0.2" "sentence-transformers>=3.0,<6" "numpy>=1.26"
import re
import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
from mini_rag import CHUNKS
texts = [c["text"] for c in CHUNKS]
# Dense leg — identical to section 03
model = SentenceTransformer("all-MiniLM-L6-v2")
doc_vecs = model.encode(texts, normalize_embeddings=True)
# Sparse leg — BM25 over lowercase tokens (production: a real analyzer).
# Punctuation must not stick to a token. A bare .split() stores the chunk text
# "(form PP-FL-4B)" as "(form" and "pp-fl-4b)", so the query token "pp-fl-4b"
# never matches and the rare term this leg exists for is silently lost.
def tokenize(text: str) -> list[str]:
return re.findall(r"[a-z0-9][a-z0-9-]*", text.lower())
bm25 = BM25Okapi([tokenize(t) for t in texts])
def dense_ranking(query: str) -> list[int]:
q = model.encode([query], normalize_embeddings=True)[0]
return list(np.argsort(doc_vecs @ q)[::-1])
def sparse_ranking(query: str) -> list[int]:
return list(np.argsort(bm25.get_scores(tokenize(query)))[::-1])
def rrf(rankings: list[list[int]], k: int = 60) -> list[int]:
"""Reciprocal Rank Fusion. Positions, not raw scores — so a cosine in
[0, 1] and a BM25 score in [0, 30] never need to be calibrated."""
fused: dict[int, float] = {}
for ranking in rankings:
for pos, idx in enumerate(ranking):
fused[idx] = fused.get(idx, 0.0) + 1.0 / (k + pos + 1)
return sorted(fused, key=lambda i: fused[i], reverse=True)
query = "What does endorsement form PP-FL-4B cover?"
for idx in rrf([dense_ranking(query), sparse_ranking(query)])[:3]:
print(CHUNKS[idx]["id"]) # the chunk defining PP-FL-4B now tops the
# sparse list on the rare token itself —
# before the fix it matched only "endorsement"
One line in that script earns a second look: the tokeniser. A bare
t.lower().split() leaves punctuation attached, so the chunk text
"(form PP-FL-4B)" is stored as (form and pp-fl-4b). The
query asks for pp-fl-4b and never matches it.
The damage hides itself. With the plain split the right chunk still wins the BM25 list, but it wins on the single word "endorsement": it scores 1.05, and every other chunk scores 0.
With the tokeniser above it matches "endorsement", "form" and "pp-fl-4b" and scores 2.42; the flood-exclusion chunk picks up 0.34. Same rank 1, a different reason. In a real corpus the wrong reason loses.
Why k = 60? It dampens the reward for rank 1 versus rank 3 so that one
leg's opinion can't steamroll the other — a value the original RRF paper found robust
and nobody has meaningfully improved on since. If you're on pgvector, the sparse leg is
Postgres full-text search (tsvector/ts_rank), and the fusion
is ten lines of SQL or Python — no new infrastructure.
- The dense list, marker 1. Meaning-space is fooled by wording: B, the flood exclusion, talks about coverage and endorsements in general terms and wins rank 1. A, the chunk that actually defines PP-FL-4B, comes second. C, generic filler, comes third.
- The sparse list, marker 2. BM25 asks a different question: which chunk contains rare query words? Only A contains "PP-FL-4B", so A takes rank 1 outright, and the ordering of the other two is decided by ordinary words.
- The arithmetic, marker 3. Each chunk earns one over sixty plus its rank, once per list it appears in. A is 2nd and 1st, so 1/62 + 1/61 = 0.0325. B is 1st and 3rd, so 1/61 + 1/63 = 0.0323. C is 3rd and 2nd, so 1/63 + 1/62 = 0.0320. No cosine and no BM25 score is added to anything; only positions.
- The margin, marker 4. The gap between first and second place is 0.0002. That is deliberate: the curve 1/(60 + rank) is almost flat, so being first rather than second in one list is worth very little. A chunk near the top of both lists beats a chunk that is first in one and missing from the other.
Stage 5 — Rerank: spend expensive compute on the shortlist only
Hybrid search finds PP-FL-4B now, but failure 2 is still live: three near-identical Florida revisions at 0.71, 0.70 and 0.69 can still take every slot and bury the dual-approval rule. Separating them needs a model that reads the question and a candidate together, so that "approve it myself" can be noticed to contradict "requires dual approval". That model is far too slow to run over 4,000 pages, which is why it runs last, over a shortlist.
Your bi-encoder (the embedding model) compresses each text into one vector independently — that's what makes indexing possible, and it's also why nuance gets lost. A cross-encoder reranker reads the query and a candidate together, token by token, and outputs a much sharper relevance score. Too slow to run on a million chunks; perfect for re-scoring the top 50:
Before the code, the arithmetic that makes the funnel a design rather than a compromise. Every number below comes from the two facts already on this page: a cross-encoder reads about 50 pairs in 100 milliseconds, and generation costs $1 per million input tokens.
- Cheap on the left, marker 1. Embedding 10 million chunks happened once, weeks ago. At query time an approximate-nearest-neighbour index visits a few hundred nodes rather than 10 million rows, so the count in the second column has almost no effect on the number in the fourth. That is what makes the wide end of the funnel affordable.
- Expensive on the right, marker 2. The cross-encoder costs one full model pass per candidate: 50 pairs at about 2 milliseconds each is the 100 milliseconds quoted on Fig. 8.5. This is the only stage whose cost grows directly with how many documents you let in, which is why the shortlist width is the number you tune.
- The counterfactual, marker 3. Ten million pairs at the same 2 milliseconds is 20 million milliseconds, which is 5.6 hours for one question. Widen the shortlist from 50 to 500 and you pay ten times more for a gain the evals usually cannot see. The funnel is not a shortcut around quality; it is the only shape that finishes.
Step-by-step: what rerank.py does, in plain English
- Bring in the
CrossEncoderclass and, frommini_rag.py, both the chunks and theretrieve()function from section 03. - Load the reranker model
BAAI/bge-reranker-v2-m3. The first run downloads about 1.1 GB; after that it is local. It runs on a CPU; a GPU makes it fast. - Set the question about approving a $30,000 claim, the one you traced by hand in section 03.
- Recall stage: call
retrieve()for the top five by cosine. This is the cheap step, and it may rank the answer-bearing chunk low. - Score every (question, chunk text) pair with the cross-encoder. Unlike the embedding model, it reads both texts together, token by token, so it can notice that "approve myself" conflicts with "requires dual approval".
- Print the order the bi-encoder produced, then sort the candidates by the new scores and print that order. The dual-approval chunk should move up.
# pip install "sentence-transformers>=3.0,<6"
from sentence_transformers import CrossEncoder
from mini_rag import CHUNKS, retrieve
# BGE-reranker-v2-m3: ~1.1 GB download once, then local. CPU works; GPU flies.
reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")
query = "Can I approve a $30,000 Florida flood claim myself?"
candidates = [c for _, c in retrieve(query, k=5)] # recall stage: cheap
scores = reranker.predict([(query, c["text"]) for c in candidates])
print("bi-encoder order :", [c["id"] for c in candidates])
reranked = sorted(zip(scores, candidates), key=lambda p: -p[0])
print("reranked order :", [c["id"] for _, c in reranked])
# The dual-approval chunk (DOC-GEN-2026 p.3) — buried by cosine similarity
# behind three flood chunks — jumps into the top slots: the cross-encoder
# actually reads "approve ... myself" against "require dual approval".
This is the fix for failure 2: near-duplicates that all look equally "similar" to a bi-encoder get separated decisively by a model that reads the query against each candidate. Typical production numbers: reranking the top 50 lifts answer-bearing chunks into the top 5 in the large majority of hard queries — the cheapest precision win in the entire pipeline. Managed alternative: Cohere rerank-v3 if you'd rather call an API than host the model.
"If the cross-encoder is that much better, why not skip the vector index and rerank everything?"
— the question every team asks in week two
Because of arithmetic, and it is drawn at marker 3 of Fig. 8.5b. A cross-encoder reads the question and one candidate together, so it costs one full model pass per document. Fifty candidates take about a hundred milliseconds on a CPU, which is 2 ms each. Ten million documents at 2 ms is 20,000,000 ms, or 5.6 hours, per query. The bi-encoder is the only reason a query finishes at all: it did its expensive work once, at index time, and at query time it does one multiply per document.
So the funnel is not a compromise, it is the design. Cheap and approximate over everything, expensive and precise over a shortlist. The number to tune is the width of the shortlist. Rerank fifty and you catch most of what recall missed; rerank five hundred and you pay ten times more for a gain the evals usually cannot see.
The downside of the reranker itself: it is a second model to operate and version, and a hundred milliseconds you must find inside your latency budget.
Questions you might be asking now
The funnel of Fig. 8.5, its price list in Fig. 8.5b and the bubble above take three things for granted. They assume you know what "recall" means, what flows from one stage to the next, and why chunk size matters. The questions below slow each one down. Every answer uses the same adjuster question and the same five chunks, and every number comes from rerunning retrieval_trace.py or chunk_size_two_ways.py.
| Chunk | What it says | Current revision? | Needed for this question? | Vector: flood, Florida, approval, extra cover | Size |
|---|---|---|---|---|---|
| FL-2026 p.14 | Section 4.B: Florida warehouses in high-risk hurricane zones EXCLUDE flood damage; cover needs the Tier-1 endorsement | yes | yes: is it covered? | (4, 5, 0, 2.5) | 189 characters |
| FL-2025 p.14 | The same clause, last year, without "high-risk" | no | no | (4, 4.5, 0, 2.5) | 179 characters |
| FL-2024 p.13 | The same clause, 2024, without "hurricane zones" | no | no | (4, 4, 0, 2.5) | 163 characters |
| GEN-2026 p.3 | Section 1.C: claims over $25,000 need dual approval from a Senior Adjuster plus an inspection report | yes | yes: who may approve? | (0, 0, 5, 0) | 166 characters |
| FL-2026 p.15 | Section 4.C: endorsement PP-FL-4B adds flood cover up to $250,000 for a 12 percent premium | yes | no | (3, 0, 0, 5) | 167 characters |
Fig. 8.5 says the wide end of the funnel is "tuned for recall". What is recall, and how do I work out recall@k by hand?
Recall@k is the share of the chunks you needed that made it into the top k. The $30,000 question needs two chunks, and the dense top 3 holds one of them, so recall@3 = 1 ÷ 2 = 0.50. Its partner, precision@k, is the share of the top k that were needed: 1 ÷ 3 = 0.33.
Both measures start from a label that only a person can write: for this question, which chunks are needed? An adjuster needs two facts. Is Florida flood damage covered (FL-2026 p.14)? And may one adjuster approve $30,000 alone (GEN-2026 p.3)? The other three chunks are not wrong, but they do not answer the question.
Here is the dense ranking from the hand-made vectors: FL-2026 p.14 at 0.71, FL-2025 p.14 at 0.70, FL-2024 p.13 at 0.69, GEN-2026 p.3 at 0.64 and FL-2026 p.15 at 0.22. Now the arithmetic for a top 3.
- Count the needed chunks. Two: FL-2026 p.14 and GEN-2026 p.3.
- Keep the top k of the ranking. With k = 3 that is FL-2026 p.14, FL-2025 p.14 and FL-2024 p.13.
- Count the needed chunks inside that top k. One: FL-2026 p.14. The dual-approval rule is fourth, just under the cut.
- Recall@3 = needed found ÷ needed in total. 1 ÷ 2 = 0.50. Half of what the answer needs never reaches the model.
- Precision@3 = needed found ÷ slots used. 1 ÷ 3 = 0.33. Two of the three slots hold superseded copies.
| k | Chunk added at this rank | Needed found | Recall@k | Precision@k |
|---|---|---|---|---|
| 1 | FL-2026 p.14 (needed) | 1 | 1 ÷ 2 = 0.50 | 1 ÷ 1 = 1.00 |
| 2 | FL-2025 p.14 | 1 | 1 ÷ 2 = 0.50 | 1 ÷ 2 = 0.50 |
| 3 | FL-2024 p.13 | 1 | 1 ÷ 2 = 0.50 | 1 ÷ 3 = 0.33 |
| 4 | GEN-2026 p.3 (needed) | 2 | 2 ÷ 2 = 1.00 | 2 ÷ 4 = 0.50 |
| 5 | FL-2026 p.15 | 2 | 2 ÷ 2 = 1.00 | 2 ÷ 5 = 0.40 |
Recall can only rise as k grows, because keeping more chunks never loses one. Precision usually falls, because each extra slot can add noise. Widening k from 3 to 4 buys the missing rule at the price of a fourth block.
- Found. The current flood exclusion ranks first, so the "is it covered?" half of the answer is inside the top 3.
- Cut. The dual-approval rule scores 0.64 and ranks fourth, under two superseded copies of the flood clause. It is the only chunk that answers "may I approve this myself?", and at k = 3 the model never sees it. This is failure 2 in section 04, written as a number.
- The two counts. Recall divides by what was needed (2). Precision divides by what was kept (3). Neither looks at the scores 0.71 or 0.64, only at which side of the cut a needed chunk landed.
- The price of a wider cut. At k = 4 the approval rule gets in and recall jumps to 1.00. Precision only climbs back to 0.50, because two of the four blocks are still old copies. Widening k buys recall; it does not buy a clean prompt.
This is exactly the split in Fig. 8.5. The wide end is judged by recall at a large k: is the needed chunk anywhere in the 1,000 candidates? The reranker can only promote what recall delivered, so a miss there is final. The narrow end is judged by precision at a small k: are the 5 blocks in the prompt the right ones?
A better ranking raises both numbers at once. Keep only current revisions and the dense top 2 is FL-2026 p.14 then GEN-2026 p.3: recall@2 = 1.00 and precision@2 = 1.00. The next answer traces that fix.
| Recall@k (this answer) | Context recall (Ragas, section 07) | |
|---|---|---|
| What it counts | Needed chunks found in the top k | Facts in the reference answer that the retrieved text supports |
| Who decides "needed" | A person, who labels chunk ids for each question | A judge model, which reads the reference answer against the retrieved text |
| How far to trust it | Exact, as far as the labels are right | As far as the judge is right, which is why Module 07 spot-checks it |
The honest limits. Recall@k is only as good as the labels, and someone must write them for every test question. It ignores order inside the top k, so a needed chunk at rank 3 counts the same as one at rank 1. And a large enough k always gives 1.00: here k = 5 is the whole corpus, which proves nothing.
Recall@k: of the chunks you needed, how many made the top k. Precision@k: of the top k, how many you needed. The funnel buys recall wide and precision narrow.
Walk one adjuster question through the whole pipeline, station by station, with the real numbers.
Both search legs rank the three Florida revisions on top, so fusion hands the model one fact three times and recall@3 is 0.50. Filter to current revisions first, and the same code puts the dual-approval rule in block [2]. The prompt stays the same size, about 222 tokens, or $0.0002 of input.
The question is "Can I approve a $30,000 Florida flood claim myself?", the one you ranked by hand in section 03. Fig. 8.5f lays out all seven stations twice: as built, and with one fix.
Station 1 · the chunks are already in the index
This work was done weeks ago, at index time. The five chunks sit in the index with an id, a current-revision flag and a vector. By Module 06's rule of thumb, 4 characters ≈ 1 token, each chunk is 41 to 47 tokens long.
Station 2 · the dense leg
The question is embedded on the same four dials, as (2, 3, 3, 0). Each chunk then gets a cosine, worked exactly as in Fig. 8.1g. Here are two of the five.
- FL-2026 p.14. Dot product 2 × 4 + 3 × 5 + 3 × 0 + 0 × 2.5 = 23. Lengths √22 = 4.690 and √47.25 = 6.874. Cosine 23 ÷ (4.690 × 6.874) = 23 ÷ 32.24 = 0.71.
- GEN-2026 p.3. Dot product 2 × 0 + 3 × 0 + 3 × 5 + 0 × 0 = 15. Lengths 4.690 and 5. Cosine 15 ÷ 23.45 = 0.64.
The dense order is 0.71, 0.70 and 0.69 for the three revisions, then the approval rule at 0.64 and the endorsement at 0.22. The approval rule is fourth.
Station 3 · the keyword leg
The question becomes nine words: can, i, approve, a, 30,000, florida, flood, claim, myself. Each Florida revision contains three of them: a, florida and flood. The dual-approval chunk contains only "a". It says "approval" and "claims", and BM25 counts exact words only.
| Chunk | Question words it contains | Length in words | BM25 | Rank |
|---|---|---|---|---|
| FL-2024 p.13 | a, florida, flood | 21 | 1.27 | 1 |
| FL-2025 p.14 | a, florida, flood | 23 | 1.23 | 2 |
| FL-2026 p.14 | a, florida, flood | 24 | 1.21 | 3 |
| GEN-2026 p.3 | a | 23 | 0.29 | 4 |
| FL-2026 p.15 | flood | 27 | 0.27 | 5 |
The oldest revision wins the keyword leg, only because it is the shortest, and BM25 marks longer chunks down. An English analyzer that cuts words to their stems would match "approve" with "approval". Elasticsearch's standard analyzer does not stem, and neither does this toy or the tokenize() in hybrid_rrf.py. Both strip punctuation; neither touches word endings.
Station 4 · fusion
RRF adds 1 ÷ (60 + rank) from each list, as in Fig. 8.4b. The scores are shown to five decimal places, because the top three differ only in the fifth.
| Chunk | Dense rank | Keyword rank | Working | Fused |
|---|---|---|---|---|
| FL-2026 p.14 | 1 | 3 | 1/61 + 1/63 = 0.01639 + 0.01587 | 0.03227 |
| FL-2024 p.13 | 3 | 1 | 1/63 + 1/61 = 0.01587 + 0.01639 | 0.03227 |
| FL-2025 p.14 | 2 | 2 | 1/62 + 1/62 = 0.01613 + 0.01613 | 0.03226 |
| GEN-2026 p.3 | 4 | 4 | 1/64 + 1/64 = 0.01562 + 0.01562 | 0.03125 |
| FL-2026 p.15 | 5 | 5 | 1/65 + 1/65 = 0.01538 + 0.01538 | 0.03077 |
Fusion rewards two lists that agree, and here both lists agree on the wrong thing. The top 3 are three copies of one clause, so recall@3 is 0.50, exactly as in the recall answer above. Hybrid search fixes failure 3, the missing identifier. It does nothing for failure 2, the crowd of copies.
Station 5 · the fix: filter, then search again
The index already stores a current-revision flag, so filter on it before either leg runs. The two old copies never enter a list. The dense leg now gives 0.71, 0.64 and 0.22; BM25, recomputed over three chunks, gives 2.12, 0.48 and 0.45, in the same order. Fused, FL-2026 p.14 scores 2/61 = 0.0328, GEN-2026 p.3 scores 2/62 = 0.0323 and FL-2026 p.15 scores 2/63 = 0.0317. Recall@3 is now 1.00.
Station 6 · the reranker
This station has no scores here: they need the 1.1 GB model that rerank.py downloads. Its cost is 3 pairs × 2 ms = 6 ms after the filter, using Fig. 8.5b's 2 ms per pair. With three candidates for three slots, it changes the order, not which blocks go in. Without the filter, it is the only stage that could lift the approval rule above the copies.
Station 7 · the prompt the model reads
The filtered top 3 are packed exactly as answer() in mini_rag.py packs them. This is the user message, printed by the script:
Context:
[1] (DOC-FL-2026 p.14) Section 4.B: Commercial warehouse properties located in Florida high-risk hurricane zones EXCLUDE water and flood damage. Flood coverage requires a separate Tier-1 Supplemental Endorsement.
[2] (DOC-GEN-2026 p.3) Section 1.C: All claims exceeding $25,000 require dual approval from a Senior Adjuster plus an onsite photographic inspection report verified by forensic engineering.
[3] (DOC-FL-2026 p.15) Section 4.C: The Tier-1 Supplemental Endorsement (form PP-FL-4B) adds flood coverage up to $250,000 per location for an added premium of 12 percent of the base policy.
Question: Can I approve a $30,000 Florida flood claim myself?
Read the output. Block [1] answers "is it covered?" and block [2] answers "may I approve it alone?": no, above $25,000 a Senior Adjuster must co-approve. Block [3] is the least relevant of the three. It is in the prompt only because k is 3, and the grounding contract tells the model to use only what it needs.
The system prompt (222 characters) plus this message (667) is 889 characters, about 222 tokens: $0.000222 at claude-haiku-4-5's $1 per million input tokens. The unfiltered prompt is about 224 tokens. The fix changes what fills the slots, not how many there are: 68% of the chunk text is now needed, against 36%.
The reply needs an API key, so it is not shown. The contract guarantees only the mapping: any [2] in it resolves to DOC-GEN-2026 page 3, as in Fig. 8.5c.
- Cut by the copies. The approval rule scores 0.64, under three near-identical flood clauses at 0.71, 0.70 and 0.69, so at k = 3 it is already out. Fig. 8.1d shows the same shape from the real model.
- Exact words only. The approval rule says "approval" and "claims"; the question says "approve" and "claim". The only shared word is "a", while the shortest flood copy wins on length.
- Agreement on the wrong thing. RRF rewards chunks that rank high in both lists, and both lists put the copies on top. Fusion cannot promote a chunk that neither leg ranked.
- The filter. Dropping superseded revisions before search leaves three candidates, with the approval rule second in every list. Recall@3 goes from 0.50 to 1.00 with no change to the scoring code.
- Same size, better contents. Both prompts are about 222 tokens, about $0.0002 each. What changed is that 68% of the chunk text now matters to the question, against 36% before.
The honest limits. The dense scores come from hand-made vectors, so only the shape matches section 04's real run, and nothing here predicts your corpus. The reranker's order and the model's reply need models this page cannot run offline.
Trace a failing question station by station and write down the top 3 at each one. The first station where a needed chunk drops out is the stage to fix.
Why does chunk size matter? Show me one document chunked two ways.
Because a chunk is both the unit the search scores and the unit the model reads. Store Sections 4.B and 4.C as one 357-character chunk, and the flood question gets the exclusion and the remedy together: recall@3 rises from 0.50 to 1.00. The PP-FL-4B question pays for it: its best cosine falls from 0.96 to 0.77, and its lead over the runner-up almost halves.
The document is DOC-FL-2026, pages 14 and 15: Section 4.B, the flood exclusion, and Section 4.C, the PP-FL-4B endorsement. They are the first and last rows of the table above. Way 1 stores them as two chunks of 189 and 167 characters. Way 2 stores one chunk of 357.
Two questions test the two ways. The flood question, "Is flood damage covered for commercial warehouses in Florida?", needs both sections: the exclusion, and the way to buy cover back. The form question, "What does endorsement form PP-FL-4B cover?", needs only 4.C. Their hand-made vectors are (3, 3, 0, 1) and (1, 0, 0, 4).
The big chunk needs a vector of its own. A model such as all-MiniLM-L6-v2 builds one by averaging the vectors of every token in its input. The toy imitates that by averaging the two halves' vectors, weighted by their length.
- Weight each half by its length. 189 × (4, 5, 0, 2.5) = (756, 945, 0, 472.5). 167 × (3, 0, 0, 5) = (501, 0, 0, 835).
- Add the two. (1,257, 945, 0, 1,307.5).
- Divide by the total length. 189 + 167 = 356, so the big chunk's vector is (3.53, 2.65, 0, 3.67). The space that joins the two texts carries no vector, so it is not counted.
- Score it as usual. Against the flood question its cosine is 0.89. Against the form question it is 0.77.
| Way 1: two chunks | Way 2: one chunk | |
|---|---|---|
| Flood question: top 3 | FL-2025 p.14 at 0.99, FL-2026 p.14 at 0.98, FL-2024 p.13 at 0.98 | FL-2025 p.14 at 0.99, FL-2024 p.13 at 0.98, the big chunk at 0.89 |
| Flood question: recall@3 (needs 4.B and 4.C) | 1 ÷ 2 = 0.50; 4.C is fourth at 0.55 | 2 ÷ 2 = 1.00; both are inside one block |
| Form question: best chunk | FL-2026 p.15 at 0.96 | The big chunk at 0.77 |
| Form question: lead over the runner-up, FL-2024 p.13 at 0.55 | 0.96 − 0.55 = 0.41 | 0.77 − 0.55 = 0.22 |
| Form question: text in the top 3 | 509 characters ≈ 127 tokens | 699 characters ≈ 175 tokens |
Read the table as the two ways a size goes wrong. Too small, and an answer is split across chunks that must then compete for slots. Here the remedy, 4.C, lost its slot to two old copies of 4.B. That is failure 1 in section 04 again, with a different cause.
Too big, and a chunk's vector drifts towards the average of its topics. The form question still finds the big chunk first, but with a lead of 0.22 instead of 0.41. And 189 of the big chunk's 357 characters are the exclusion, which the form question never asked about.
- Two knives. Both ways hold the same policy text. Way 1 cuts at the page break, between the exclusion and the remedy. Way 2's single vector blends both topics: flood and Florida from 4.B, extra cover from 4.C.
- Too small splits the answer. The flood question needs both sections. With two chunks, the three copies of 4.B score 0.98 to 0.99 and fill the top 3, and 4.C is cut at 0.55. With one chunk, 4.C rides into the prompt inside the big chunk, and recall@3 becomes 1.00.
- Too big blurs the vector. The form question needs only 4.C. The small 4.C chunk points almost straight at it, 0.96. The big chunk is half exclusion, so it points partly elsewhere, 0.77. It still ranks first in this five-chunk toy.
- The lead is what shrinks. Against the runner-up at 0.55, the lead falls from 0.41 to 0.22. In a corpus with hundreds of endorsement paragraphs, a smaller lead is how a blurred chunk loses its slot; the toy shows only the shrinking margin.
The honest limit: no chunk size is right for every corpus, and this toy shows the trade, not the answer. Real models let the two halves influence each other, so real cosines will differ. The advice in the interview radar stands. Sweep two or three sizes, such as 300, 500 and 800 tokens, on labelled questions. Keep the size with the best recall@k at a k you can afford.
Parent-document retrieval, marker 4 of Fig. 8.3b, avoids choosing. It searches with the small chunks, which keeps the vectors sharp, and hands the model the big one, which keeps the answer whole.
A chunk is what gets scored and what gets read. Too small splits an answer across slots; too big blurs the vector and fills the prompt. Measure recall@k at two or three sizes.
Stage 6 — The same pipeline in LangChain 1.0 and LlamaIndex
You can now build PolicyPal's pipeline by hand, which is the only safe moment to meet a framework. Both of the ones below do the same stages in about a dozen lines. Read them for shape, not syntax: if you can point at parse, chunk, embed, index, retrieve and generate in each file, the framework is saving you typing rather than hiding the machine from you.
You now understand every stage, which means frameworks can save you typing without
owning your brain. Same corpus, both frameworks, complete and current as of Aug 2026.
First LangChain 1.0 — note there is no RetrievalQA, no
LLMChain, no chain ceremony; in 1.0 you compose plain functions:
Read these two files for their shape, not their syntax. Every stage you just learned appears as one call. You are not expected to memorise either framework's API; the point is to recognise the pipeline underneath, so that a framework can never hide it from you.
# pip install "langchain>=1.0,<2" "langchain-anthropic>=1.0" \
# "langchain-huggingface" "langchain-chroma" "langchain-text-splitters"
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_chroma import Chroma
from langchain_anthropic import ChatAnthropic
from mini_rag import CHUNKS, SYSTEM
docs = [Document(page_content=c["text"], metadata={"source": c["id"]})
for c in CHUNKS]
splits = RecursiveCharacterTextSplitter(
chunk_size=500, chunk_overlap=80).split_documents(docs)
vs = Chroma.from_documents(
splits,
HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2"),
collection_name="policypal_lc")
retriever = vs.as_retriever(search_kwargs={"k": 4})
llm = ChatAnthropic(model="claude-haiku-4-5", max_tokens=600)
def ask(query: str) -> str:
hits = retriever.invoke(query)
context = "\n\n".join(f"[{n}] ({d.metadata['source']}) {d.page_content}"
for n, d in enumerate(hits, 1))
msg = llm.invoke([("system", SYSTEM),
("user", f"Context:\n{context}\n\nQuestion: {query}")])
return msg.content
print(ask("Is flood damage covered for commercial warehouses in Florida?"))
Now LlamaIndex — the framework that treats "index documents, query them, cite sources" as its whole reason for existing, so the same system is barely a dozen lines:
# pip install "llama-index>=0.12" "llama-index-llms-anthropic" \
# "llama-index-embeddings-huggingface"
from llama_index.core import VectorStoreIndex, Document, Settings
from llama_index.core.node_parser import SentenceSplitter
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.anthropic import Anthropic
from mini_rag import CHUNKS
Settings.embed_model = HuggingFaceEmbedding(
model_name="sentence-transformers/all-MiniLM-L6-v2")
Settings.llm = Anthropic(model="claude-haiku-4-5", max_tokens=600)
Settings.node_parser = SentenceSplitter(chunk_size=500, chunk_overlap=80)
docs = [Document(text=c["text"], metadata={"source": c["id"]}) for c in CHUNKS]
index = VectorStoreIndex.from_documents(docs)
engine = index.as_query_engine(similarity_top_k=4)
resp = engine.query("Is flood damage covered for commercial warehouses in Florida?")
print(resp)
for node in resp.source_nodes: # citations ride on node metadata
print(f" {node.score:.3f} {node.metadata['source']}")
| Approach | Choose when | Avoid when | What you trade |
|---|---|---|---|
| Your own code (section 03 grown up) | You need full control: custom fusion, ACL joins, unusual stores; RAG is the product | Prototyping speed matters most | You write more; you understand everything |
| LlamaIndex | Document Q&A is the whole job; messy PDFs (LlamaParse); fastest path to cited answers | RAG is one part of a complex agent app | Its abstractions fit retrieval, less so everything else |
| LangChain 1.0 | RAG is one component in a larger LLM app (agents in Module 09, middleware, tool use) | You only need document Q&A | Bigger surface area; more churn to track |
Stage 7 — Citations done properly
Every stage so far makes the answer right. This one makes it checkable, which is the thing Victoria actually asked for: "cites exact page numbers, and never bluffs". It costs three small disciplines, one at index time, one at prompt time, one in the interface, and the page number has to survive all three or the citation is decoration.
The pattern you have seen in every code block deserves its own paragraph, because it is what separates deployable systems from demos. Do it in three parts.
- At index time, store
doc_id,pageand a stablechunk_idas metadata on every chunk. - At prompt time, number the context blocks
[1],[2], and so on, and instruct the model to tag every factual claim with the number of the chunk supporting it. - At render time, map each
[n]back through the metadata to a link that opens the source document at the right page.
- Store it or lose it, marker 1. The document id and page live on the chunk record, next to the text and the vector. If they were dropped during parsing, no later stage can invent them, and the whole citation contract dies here, silently.
- Number the blocks, marker 2. The context is built as [1], [2], [3], each carrying its source in brackets. The numbers are local to this one request; they are the only handle the model is given, which is exactly why they are easy for it to use correctly.
- The model writes only the number, marker 3. Notice what the model does not have to do: it never writes a page number, a file name or a URL, so it cannot get one wrong. It writes "[1]", and being able to hallucinate a citation is designed out.
- Resolve it in the interface, marker 4. Your code maps [1] back through the block it built to chunk c-0147, and from there to DOC-FL-2026 page 14, rendered as a link. Trust stops being a property of the model and becomes a property of the interface.
resp = client.messages.create(
model="claude-haiku-4-5",1
max_tokens=500,2
system=SYSTEM,3
messages=[{"role": "user",
"content": f"Context:\n{context}4\n\nQuestion: {query}5"}],
)
answer = next(b.text for b in resp.content if b.type == "text")6
- The generator. An economical model, because the hard part, finding the facts, already happened. As of August 2026, $1 per million input tokens. Upgrade the model when faithfulness scores say so, not before.
- The length cap. A grounded answer with citations is short. A cap of 500 tokens also caps the damage when a model starts to ramble past its evidence.
- The contract. The system prompt from
mini_rag.py: answer only from the numbered chunks, cite every claim with [n], and sayINSUFFICIENT_CONTEXTwhen the answer is not there. The faithfulness eval in section 07 tests this one line. - The evidence. The retrieved chunks, numbered [1], [2], [3], each carrying its document id and page. These numbers are what the model's citations point back to.
- The question, last. Context first, question after it, so the model has read the evidence before it decides what to say. Put the question first and the model starts composing an answer before it has seen the facts.
- The answer, unwrapped. The reply is a list of content blocks: text here, tool-use blocks in Module 09. Take the first text block. Everything an auditor needs, the [n] markers, is inside it.
The adjuster reads "flood excluded [1]", clicks [1], and lands on DOC-FL-2026 page 14.
Trust is no longer a property of the model. It is a property of the UI.
ada-002 embeddings: OpenAI's text-embedding-ada-002 is
two generations obsolete — worse and pricier than text-embedding-3-*; any
tutorial using it predates 2024.
Naive fixed-chunk + cosine-only as the "final architecture": that's the section 03 baseline, and you just watched it fail four ways — in 2026 hybrid + rerank + evals is the standard, and interviewers know it.
FAISS-only tutorials: FAISS is a fine ANN library, but it's an in-process index with no persistence story, no metadata filtering, and no ops model — it teaches you to skip exactly the production concerns this module exists to teach.
When you see these three markers together, you're reading a 2023 blog post; smile and close the tab.
Before Victoria signs off, here is every tool this module leans on, and what you would pick instead.
The stack, and why
The stack, and why
How many passages, and do they live next to your business data? That one question picks the store; the rest follow from privacy, cost and languages. As of October 2026.
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Embeddings | all-MiniLM-L6-v2 via sentence-transformers (384 numbers, runs on CPU) | text-embedding-3-large, BGE-M3, voyage-3-large | Free, offline, 80 MB, and every lab can run it. Honest weakness: short input window and lower quality than the big models. | Recall@5 on your own labelled questions stays below ~90%, or documents are not English, or chunks run past ~256 tokens. |
| Vector store | pgvector (Chroma while prototyping) | Qdrant, Pinecone, Milvus, Weaviate | PolicyPal already runs Postgres, so vectors sit next to claims and permissions with one backup. Weakness: slower than a dedicated engine at very large size. | More than ~10M vectors, or filtered search is too slow after you have tuned the HNSW index. |
| Keyword half of hybrid | rank-bm25 in the lab, Postgres full-text search in the build | Elasticsearch, OpenSearch | Exact codes like PP-FL-4B are found by keyword, not meaning. Weakness: no understanding of synonyms. | You already run Elasticsearch/OpenSearch, or need per-field boosts and fuzzy matching across millions of documents. |
| Reranker | BAAI/bge-reranker-v2-m3 as a local CrossEncoder | Cohere Rerank, ColBERT-style models | Open, free per call, and no document leaves your machine. Weakness: slow on a CPU. | No GPU and the page must answer in under ~1 second: use a hosted reranker. |
| Generator | claude-haiku-4-5 ($1/$5 per million tokens) | claude-sonnet-5, OpenAI models, a local model through Ollama | Cheapest tier that follows the "answer only from the context" rule. Weakness: weaker on multi-clause questions. | Faithfulness (Ragas) stays under your target on hard questions: try Sonnet. Documents may not leave your network: use a local model. |
| Pipeline glue | Plain Python (LangChain 1.0 and LlamaIndex shown in Stage 6) | LangChain, LlamaIndex, Haystack | Every step stays visible, which is what you need while learning. Weakness: you write the loaders yourself. | You need more than ~10 file formats or connectors; take LlamaIndex loaders. |
| Evaluation | Ragas (faithfulness, context precision, context recall) | DeepEval, TruLens, Langfuse | Three numbers that point at the stage to fix. Weakness: the judge is itself a paid model call. | You want RAG tests to fail a pull request in CI: add DeepEval or promptfoo. |
Start boring (pgvector, hybrid search, a reranker, Ragas), and change a layer only when a measured number on your own questions says it is the weak one.
06 · Advanced patternsQuery Rewriting, Agentic RAG, GraphRAG
The seven stages now answer a well-formed question well. PolicyPal's adjusters do not write well-formed questions; they write "warehouse thing from last email??" at 4:40 on a Friday, and they are the people whose 3 hours per claim we are trying to win back. Three patterns sit on top of a working pipeline: rewriting the question before retrieval, letting a model decide whether to retrieve at all, and pulling answers out of relationships rather than passages. Reach for them after the basic pipeline is measured, never before.
Query rewriting. Users don't write good search queries — they write "warehouse thing from last email??".
Cheap fix: before retrieval, have a small model rewrite the question into one or several clean search queries (multi-query), retrieve for each, and RRF-fuse the results — the same fusion function you already wrote.
A related trick, HyDE, has the model draft a hypothetical answer and embeds that instead of the question, since answers live closer to answer-shaped chunks in meaning-space. Both cost one extra cheap LLM call and routinely lift recall on vague queries.
rrf() function merges three lists instead of two (marker 3) — a new list, not a new formula.- The question nobody can search, marker 1. "Warehouse thing from last email??" contains one usable word. A small model rewrites it into search queries using the vocabulary the corpus actually uses, which costs one cheap call and a few tens of milliseconds.
- Three shots instead of one, marker 2. Each rewritten query lands in a different part of meaning-space, so between them they cover exclusions, coverage and the form number. If any one of them finds the answer-bearing chunk, fusion will carry it up.
- The same fusion, marker 3. Nothing about
rrf()changes. It already takes a list of rankings, so a third ranking is one more argument. A chunk ranked first in two lists scores 2/61 = 0.0328 and beats a chunk ranked first in exactly one, 1/61 = 0.0164, which is again consensus beating confidence.
Agentic RAG. Instead of retrieving on every request, put a router in front: a model (or classifier) that decides per query whether to answer directly ("what does RAG stand for?" needs no retrieval), search the vector index, query SQL for structured facts, or say it can't help.
The retrieval pipeline becomes a tool that a reasoning loop chooses to call — which is precisely the mental model Module 09 builds into full agents. If you've ever written a request router with fallback handlers, you already know the shape.
GraphRAG, in one paragraph of awareness: instead of (or alongside) chunk embeddings, extract entities and relationships into a knowledge graph and retrieve by traversing it. It shines on questions that span many documents ("which policies were affected by the 2025 Florida amendment, and who approved them?") where no single chunk contains the answer. It costs an order of magnitude more at index time and is genuinely harder to operate — know it exists, name-drop it accurately (Goldman's VP posting pairs "RAG pipelines and knowledge graphs"), and reach for it only after plain RAG demonstrably fails on multi-hop questions.
07 · Eval the thingRagas on Your Pipeline — Module 07, Applied
PolicyPal's pipeline now has seven moving parts, and Victoria has one question left: how do we know it will not do the $45,000 thing again? Guessing is what got us here. This section puts a number on each half of the system — one for whether the right paragraph was found, one for whether the model stayed inside it — so that when quality drops, the score itself says which of the two engineers in Fig. 8.1f to page.
Module 07's discipline — error analysis, labeled examples, validated LLM-as-judge — plugs into RAG through Ragas, the standard RAG-evaluation library (and a resume keyword that lands in the top score quartile 2.6× as often, per our research). The crucial idea: score retrieval and generation separately, because they fail separately and are fixed by different components. Build a question set with reference answers written from the corpus, run the pipeline, and let a judge model grade each stage:
Step-by-step: what eval_rag.py does, in plain English
- Bring in Ragas's
evaluatefunction and its dataset class, the three metrics, the wrapper that lets Ragas use a LangChain chat model as its judge, and frommini_rag.pytheretrieve()andanswer()functions. - Write
QA: six questions with reference answers you produced by reading the corpus yourself. The last one has no answer in the corpus on purpose; the correct behaviour there isINSUFFICIENT_CONTEXT. - For each question: retrieve the top three chunks, generate an answer, and record four things in a row: the question, the retrieved texts, the model's answer, and your reference answer.
- Build the judge: a stronger model than the generator (Sonnet judging Haiku), wrapped so Ragas can call it.
- Run
evaluateover the rows with three metrics. Faithfulness asks the judge whether every claim in the answer is supported by the retrieved context. Context precision asks whether the top-ranked chunks were relevant. Context recall asks whether the facts in the reference answer appeared in the retrieved context at all. - Print the result: three numbers between 0 and 1. The table under the code tells you which stage each low number blames.
# pip install "ragas>=0.2,<0.4" "langchain-anthropic>=1.0" \
# "sentence-transformers>=3.0,<6"
from ragas import evaluate, EvaluationDataset
from ragas.metrics import Faithfulness, ContextPrecision, ContextRecall
from ragas.llms import LangchainLLMWrapper
from langchain_anthropic import ChatAnthropic
from mini_rag import retrieve, answer
QA = [ # (question, reference answer written by reading the corpus yourself)
("Is flood damage covered for commercial warehouses in Florida?",
"No — excluded under Section 4.B unless a Tier-1 Supplemental "
"Endorsement (form PP-FL-4B) is purchased."),
("What does the Tier-1 Supplemental Endorsement cost and cover?",
"A 12 percent added premium for flood coverage up to $250,000 per location."),
("What is the fire deductible for a Texas retail building?",
"$2,500 per occurrence, if suppression systems were inspected within 12 months."),
("Which claims need dual approval?",
"Claims exceeding $25,000 need a Senior Adjuster plus a verified "
"onsite photographic inspection report."),
("What is the wildfire deductible in California brush zones?",
"5 percent of insured value, with defensible-space certification "
"renewed every 24 months."),
("Does the policy cover earthquake damage in Oregon?",
"The corpus does not address this; the correct behavior is to answer "
"INSUFFICIENT_CONTEXT."),
] # seed set — grow to 20+ before trusting the numbers, 100+ for the lab
rows = []
for question, reference in QA:
hits = retrieve(question, k=3)
rows.append({
"user_input": question,
"retrieved_contexts": [c["text"] for _, c in hits],
"response": answer(question),
"reference": reference,
})
# Judge with a stronger model than the generator (Module 07 rule of thumb).
judge = LangchainLLMWrapper(ChatAnthropic(model="claude-sonnet-5", max_tokens=2048))
result = evaluate(
EvaluationDataset.from_list(rows),
metrics=[Faithfulness(), ContextPrecision(), ContextRecall()],
llm=judge,
)
print(result) # e.g. {'faithfulness': 0.86, 'context_precision': 0.78,
# 'context_recall': 0.91}
Three numbers came back. Here is what each one accuses, drawn with the run above.
- Three questions, three suspects, marker 1. Faithfulness asks whether every claim in the answer is supported by the retrieved context, so only the prompt, the contract and the model can move it. Context precision asks whether the top-ranked chunks were relevant, so it is the reranker's and the filters' score. Context recall asks whether the needed facts were retrieved at all, so it belongs to chunking, hybrid search and k.
- Why one number is not enough, marker 2. A faithfulness of 0.86 could mean a well-behaved model, or a model that is faithfully repeating three copies of the wrong chunk. Nothing in that single score distinguishes the two, which is exactly how teams end up tuning prompts to fix a chunking bug.
- The square, marker 3. Read faithfulness against context recall. High faithfulness with low recall means the model is honest and starved, so the fix is upstream, in chunking and retrieval. Low faithfulness with high recall means you delivered the evidence and the model wrote something else, so the fix is the grounding contract. That is the answer to the interview question "how do you tell a retrieval problem from a generation problem?".
| Metric | Question it answers | Low score means | Fix lives in |
|---|---|---|---|
| Faithfulness | Is every claim in the answer supported by the retrieved context? | Generation is inventing (failure 4) | Grounding prompt, citation contract, model choice |
| Context precision | Are the top-ranked chunks actually relevant? | Retrieval ranks junk first (failure 2) | Reranker, dedupe, metadata filters |
| Context recall | Did the needed facts get retrieved at all? | The answer never reached the model (failure 1 & 3) | Chunking, hybrid search, k, index hygiene |
This table is the answer to a question interviewers love: "How do you tell a retrieval problem from a generation problem?" High faithfulness + low context recall → your generator is honest but starved: fix chunking or retrieval. Low faithfulness + high recall → retrieval delivered and the model freelanced anyway: fix the prompt contract, and consider a model that follows instructions harder. Two numbers, two different engineers get paged. And per Module 07: spot-check the judge against your own labels on ~20 rows before you trust it in CI.
08 · Under the hoodThe Math, If You Want It
You can now build, measure and defend PolicyPal's whole pipeline. Two of its pieces were handed to you as rules rather than reasons: why fusion adds positions instead of scores, and why retrieval needs two differently shaped models. Neither is needed to ship Victoria's assistant. Both come up in the system-design round, and both are short.
Reciprocal Rank Fusion — why ranks beat scores
Given R ranked lists (dense, sparse, one per rewritten query...), the fused score of document d is:
RRF(d) = Σᵣ 1 / (k + rankᵣ(d))
where rankᵣ(d) is d's 1-based position in list r (absent = contributes 0) and k ≈ 60, the value from stage 4. Why not combine the raw scores?
Because a cosine in [0, 1] and a BM25 score in [0, ~30] live on incomparable scales; any weighted sum needs per-corpus calibration that drifts as the corpus changes. Ranks are scale-free.
The 1/(k + rank) curve means rank 1 earns ≈ 0.0164 and rank 10 earns ≈ 0.0143. That is the same gentle slope you measured by hand at marker 4 of Fig. 8.4b, where first place beat second by 0.0002. A document that is merely present near the top of both lists therefore beats one that is #1 in a single list. That's the behavior you want: consensus over confidence.
Bi-encoder vs cross-encoder — why retrieval needs two model shapes
A bi-encoder computes score(q, d) = cos(f(q), f(d)) — each text passes through the encoder f alone, so all document vectors are precomputable and searching N docs costs N dot products (microseconds with an HNSW index). The price: q and d never see each other inside the model; the interaction is squeezed through two fixed vectors.
A cross-encoder computes score(q, d) = g(q ⊕ d) — query and document are concatenated and attend to each other in every layer, so the model can notice that "approve ... myself" contradicts "requires dual approval." Nothing is precomputable: each candidate costs a full forward pass, which is why it only ever sees the shortlist. The funnel in Fig. 8.5 is simply this cost/precision trade drawn as a picture. (Why do embeddings encode meaning at all? Contrastive training: the model is optimized so paraphrase pairs score high cosine and unrelated pairs score low — millions of times, until direction-in-space is similarity. The attention machinery underneath is exactly Module 05's.)
There are no dumb questions
- Context windows are 1M tokens now. Why not paste all 4,000 pages into every prompt and skip RAG entirely?
- Arithmetic first: 4,000 pages ≈ 2M tokens, which doesn't fit — and even a corpus that did fit would cost real money per query (1M input tokens on claude-haiku-4-5 is $1.00; on frontier models several times that) at seconds of added latency. Quality second: models demonstrably attend less reliably to facts buried in the middle of huge contexts, and you get page-level citations only if you control which pages went in. Operationally: retrieval is also your access-control layer — the model can't leak a document that was never retrieved for that user. Long contexts and prompt caching raised the threshold where RAG pays off; they did not remove it.
- Do I need a GPU for any of this?
- No. MiniLM and BGE-small embed thousands of chunks per minute on a laptop CPU; pgvector and Chroma are CPU services; the BGE reranker is the slowest local piece but handles top-50 reranking in a few hundred milliseconds on CPU. A GPU becomes interesting when you're embedding millions of chunks on a schedule — rent one for the batch job.
- My retrieval scores look great — cosine 0.8+ on everything. Are we done?
- Careful: raw cosine values are not calibrated. Some embedding models score almost everything above 0.6; what matters is the ranking and whether the answer-bearing chunk lands in the context, which is exactly what context recall measures against labeled data. Never read absolute cosine values as confidence — this is the retrieval version of Module 02's lesson about probabilities that aren't probabilities.
- Should I fine-tune the model on our policy documents instead?
- For knowledge, almost never — fine-tuning bakes facts into weights, where they can't be updated per document, can't be cited, can't be access-controlled, and still get hallucinated. RAG keeps knowledge in a database you can edit at 5 p.m. and audit at 6. Fine-tuning earns its keep for behavior — style, format, domain vocabulary — and Module 11 gives you the full decision framework. The interview-grade answer is in the radar below.
The elevator version: "RAG with citations turns 'trust the AI' into 'verify in one click' — the difference between a demo and a deployable system in a regulated industry." Every answer carries document and page references an auditor, regulator, or judge can check; that's what gets Legal and Compliance to sign off.
The ROI frame, with PolicyPal's numbers: adjusters spend 3 hours per claim on document lookup; grounded Q&A cuts that to roughly 20 minutes.
At 12,000 claims a year and a $85/hour loaded cost, that's ≈ 2.7 hours × 12,000 × $85 ≈ $2.7M/year in recovered adjuster capacity, against roughly $40–60K of annual run cost (embedding, storage, and pennies-per-query generation on an economical model) plus one engineering quarter to build.
The same pitch generalizes to support: grounded self-serve answers deflecting 30% of a 100K-ticket/year queue at $8 a ticket is $240K/year, with citation links doubling as agent-assist. And the $45K hallucinated payout? The faithfulness eval that catches it costs fractions of a cent per answer.
09 · The labBuild the Flagship: Production RAG With a Defended Eval Report
Victoria asked for an assistant over 4,000 pages of policy PDFs that cites exact page numbers and never bluffs, and every stage of that now exists on this page as a script you have read and a picture you can point at. The lab is the assembly: your own messy corpus, the same seven stages, and an eval report that shows the three numbers in Fig. 8.6 moving as you turn each stage on. Build it as though a hiring manager will read the README, because our market research says one will.
Mission: build a production RAG service over a real, messy corpus of 50+ PDFs — ideally documents you own (your employer's public docs, a hobby domain's manuals); otherwise script the download of public insurance policy documents (FEMA's National Flood Insurance Program manuals plus a state insurance department's published policy filings make a gloriously messy, on-theme corpus). This is the #1 portfolio project in our market research: "production RAG with a defended eval report." You have ~80% of the code from this module; the 20% you write is the integration, the API, and the eval-driven iteration.
- Ingestion pipeline parses all 50+ PDFs (LlamaParse or equivalent for the ugly ones), chunks recursively with metadata (doc, page, section), and indexes into pgvector — re-runnable idempotently when documents change
- Retrieval is hybrid (dense + Postgres full-text BM25, RRF fusion) with a local BGE-reranker-v2 stage — each stage toggleable by config so you can measure its contribution
- FastAPI endpoint
POST /askstreams the answer token-by-token and returns structured citations (doc, page, chunk id, score) — plus aGET /healthand request logging - Ragas eval on 100 curated Q-A pairs you wrote from the corpus — reporting faithfulness, context precision, and context recall per configuration (naive → hybrid → hybrid+rerank), so the README can show the numbers moving
- README documents the architecture, the retrieval metrics table, three failure modes found via error analysis (Module 07 style: read the worst 20 traces, categorize, hypothesize), and the fix iteration for each — with before/after scores
- Answers include numbered citations that resolve to page-level source links; questions the corpus can't answer return an explicit refusal, verified by at least 5 adversarial eval questions
Stretch goal: add an agentic router (vector search vs direct answer vs "not in corpus") and eval it against plain RAG on the same 100 questions — this is exactly portfolio project #10 from the research, and a preview of Module 09.
10 · Interview radarHow This Shows Up in Interviews
"Design a document Q&A system for 10 million documents."
The real test The GenAI system-design round, verbatim — graded on the retrieval funnel and on evals as a system component, not on how many vendors you can name.
Strong answer Separate the two paths. The write path is event-driven ingestion: parse → chunk → embed in batches → index, with a re-embedding strategy planned for embedding-model upgrades. The read path is a narrowing funnel: embed the query, hybrid recall of ~1,000 candidates, rerank to 50, pack the top 5 into the prompt, and generate with citations — p95 under ~2s with streaming.
Then name the scale decisions explicitly:
- pgvector to ~10M vectors, then Qdrant or a managed store
- Metadata-filtered ANN for tenant isolation
- Semantic caching for repeated queries
- An eval harness with online faithfulness sampling as the monitoring layer
Land it Interviewers are listening for the narrowing funnel of Fig. 8.5 and for evals-as-a-component — not for a vendor list.
"You chose 500-token recursive chunks. Defend that."
The real test Whether your numbers are measured or inherited — "it's the default" is the weak answer that fails here.
Strong answer Chunk size trades recall against precision. Too big, and one chunk's embedding averages several topics together, which shows up as retrieval noise; too small, and answers get split across chunks (failure 1). Recursive splitting respects document structure so sentences survive the cut, and an overlap of 10–15% insures against splits landing on a boundary. The honest final move: "I swept 300/500/800 on our eval set and context recall peaked at 500 for this corpus."
Land it Tune with evals, not folklore — the number is defensible because you measured it on this corpus, not because a tutorial shipped it.
"When does RAG beat fine-tuning, and vice versa?"
The real test The vendor-agnostic judgment question — can you split knowledge from behavior instead of picking a favorite technique?
Strong answer RAG wins for knowledge: it's updatable per-document in minutes, citable, access-controllable, and auditable — a policy that changed yesterday gets answered from the new document, not from weights trained last quarter. Fine-tuning wins for behavior: style, output format, domain jargon, and latency-critical instruction-following — and it does not reliably teach new facts. Production systems often use both: RAG for truth, a light fine-tune for tone.
Land it Bonus points for the failure modes of each: RAG inherits retrieval failures, while fine-tuning inherits staleness and re-training cost.
"How do you measure retrieval quality separately from generation quality?"
Strong answer This is the module's eval section said out loud. Label a Q-A set with known source chunks. Measure retrieval alone with context recall and context precision — did the answer-bearing chunk make top-k, and how high did it rank?
Measure generation alone with faithfulness against the retrieved context — given correct context, did the model stay inside it?
Then apply the diagnosis matrix: high faithfulness plus low recall means fix retrieval; low faithfulness plus high recall means fix the grounding prompt or the model.
Land it Mention judge validation against human labels and you have cleared a standard most candidates miss.
Quick reference — Retrieval-augmented generation
- The one-line case
- A model alone sits a closed-book exam. RAG makes it an open-book one.
- parametric memory
- What the model knows from training: fixed, undated, and unable to cite anything.
- The pipeline
- Parse → chunk → embed → store → retrieve → rerank → generate with citations. Most quality problems live in the first three.
- Hybrid search
- Dense vectors for meaning plus BM25 keyword for exact terms, fused with Reciprocal Rank Fusion. This is the default, not an optimisation — pure vector search misses product codes and names.
- reranker
- A cross-encoder that re-scores the top candidates by reading query and passage together. Slower per item, much more accurate, so it runs on a shortlist.
- faithfulness
- Is every claim in the answer supported by the retrieved context? This is the metric that catches confident invention.
- Store choice (Aug 2026)
- Chroma to prototype · pgvector as the boring default under ~10M vectors · Qdrant for performance. Not ada-002, not FAISS-only tutorials.
- Stack rule
- Start with pgvector, hybrid search, a reranker and Ragas. Swap a layer only when a number on your own questions names it as the weak one (Qdrant above ~10M vectors).
- cosine similarity
- Multiply two vectors position by position and add, then divide by both lengths. 1 means the same direction, 0 a right angle. Read the order of the scores, not the size of one.
- BM25
- The keyword score inside Elasticsearch: points for each query word a chunk contains, more for rare words, fewer for long chunks. A word that is not there scores exactly 0.
- recall@k · precision@k
- Of the chunks a question needs, the share that made the top k · of the top k, the share that were needed. Both need a person's labels.
11 · RecapWhat You Can Do Now
- You can explain hallucination as closed-book answering and fix it with retrieve → augment → generate, grounded by a citation contract
- You can build a working semantic-search RAG system in ~70 lines with a real embedding model, cosine search, and grounded generation — no frameworks
- You can recognize the four classic RAG failures on sight and name the pipeline component that fixes each one
- You can design a chunking strategy (fixed/recursive/semantic/parent-document) and defend the choice with eval numbers
- You can stand up Chroma for prototypes and pgvector for production, with metadata and citations modeled from day one
- You can implement hybrid dense+BM25 retrieval with RRF fusion and a local cross-encoder reranker — and explain why each exists
- You can build the same pipeline in LangChain 1.0 or LlamaIndex and argue when each (or neither) is the right layer
- You can eval a RAG system with Ragas, separate retrieval failures from generation failures, and iterate from error analysis
- You can work a cosine similarity, a BM25 score and a recall@k by hand, and trace one question station by station to find where a needed chunk dropped out
- You can explain what chunk size trades: answers split across slots when chunks are too small, blurred vectors and fuller prompts when they are too big
From this module: close the page and sketch Fig. 8.2 from memory — both paths, all stages, and the eval feedback loop. Then annotate each of the four failures from section 04 onto the stage that fixes it. Reaching back to Module 05: explain why attention lets the word "bank" embed differently in "river bank" versus "bank deposit" — and why that same mechanism is the reason your chunk embeddings can match paraphrases that share no words with the query.