▚ The AI Engineer's Field Manual
Module 08 · Act III — The GenAI Core

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."

~9 hours Builds on: Module 07 (evals) · Module 05 (embeddings) Tools: sentence-transformers · Chroma · pgvector · LangChain 1.0 · LlamaIndex · Ragas Job-spec line it unlocks: "RAG frameworks, vector search, knowledge grounding" — Walmart Staff SWE

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.

Field report · Client memo

"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."

— Victoria Vance, Chief Risk & Operating Officer at "PolicyPal"

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.

You already know this

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.

1 CLOSED BOOK — what the pilot chatbot did the question FL warehouse flood? the model's memory pretraining, undated "Yes — Tier-2 covers flood up to $50,000, section 4.B" no source. no page. no check. $45,000 paid never recovered 2 the file nobody opened DOC-FL-2026 p.14 · Section 4.B Florida warehouses EXCLUDE water and flood damage never read 3 OPEN BOOK — the same question, through RAG same question unchanged retrieve top 3 by meaning [1] p.14 EXCLUDE flood [2] p.15 endorsement PP-FL-4B [3] p.3 dual approval "No — excluded [1]. Cover is available via the Tier-1 endorsement: $250,000, +12% [2]" 4 the citation closes the loop click [1] → DOC-FL-2026 page 14
Fig. 8.0b — The $45,000 incident and its repair. Closed book (marker 1): the question reaches only the model's memory, and the page that says EXCLUDE is never opened (marker 2). Open book (marker 3): three real policy passages are pasted into the prompt first, and the [1] in the answer resolves back to the page an auditor can read (marker 4).
  1. 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.
  2. 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.
  3. 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".
  4. 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.

meaning dimension 1 (2-D projection of 384-D space) meaning dim 2 1 2 3 insurance-speak flood damage water damage claim hurricane exclusion storm surge finance-speak quarterly earnings stock buyback dividend yield query: "warehouse flooding?" cos ≈ 0.78 cos ≈ 0.06
Fig. 8.1 — Embeddings place texts in a meaning-space: the query "warehouse flooding?" lands inside the insurance cluster, close to "water damage claim" (which shares zero keywords with it) and far from everything about finance.
  1. 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.
  2. 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.
  3. 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.

The query and three sentences every answer below uses. The vectors are hand-made: three numbers on three named dials, chosen so the arithmetic fits on a pencil. A real model gives 384 numbers, and none of them has a name.
NameTextWhat it isWater & floodingBuildings & propertyMoney & finance
query"warehouse flooding?"The query from Fig. 8.1430
water sentence"Water damage to storage buildings is excluded."Section 4.B's exclusion, reworded; shares no word with the query340
fire sentence"Warehouse fire damage carries a separate deductible."A different rule that happens to share the word "warehouse"034
earnings sentence"Quarterly earnings rose after the stock buyback."Finance-speak, like the far cluster in Fig. 8.1005
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.

  1. 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.
  2. 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.
  3. 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.
The same three steps for all three sentences. Values from rerunning cosine_by_hand.py.
SentenceA · dot productB · lengthsC · cosineAngle to the query
water4 × 3 + 3 × 4 + 0 × 0 = 245 and 524 ÷ 25 = 0.9616.3°
fire4 × 0 + 3 × 3 + 0 × 4 = 95 and 59 ÷ 25 = 0.3668.9°
earnings4 × 0 + 3 × 0 + 0 × 5 = 05 and 50 ÷ 25 = 0.0090.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.

1 STEPS A TO C, WATER SENTENCE water buildings money query 4 3 0 water sentence 3 4 0 multiplied 12 12 0 add the column results: 12 + 12 + 0 = 24 2 lengths: √(4² + 3² + 0²) = 5 and √(3² + 4² + 0²) = 5 cosine = 24 ÷ (5 × 5) = 0.96 fire: 9 ÷ 25 = 0.36 · earnings: 0 ÷ 25 = 0.00 3 THE SCORE IS THE ANGLE FROM THE QUERY query (4, 3, 0) water sentence cos 0.96 · 16.3° fire sentence cos 0.36 · 68.9° earnings cos 0.00 angles from the query are exact; the flat layout is not
Fig. 8.1g — Cosine similarity worked by hand on hand-made vectors. Left: the three steps for the water sentence. Right: the three scores drawn as angles from the query's arrow. Values from rerunning cosine_by_hand.py.
  1. 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.
  2. 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.
  3. 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.

  1. Count the chunks that contain the word. "warehouse" appears in 1 of the 3 sentences.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

One query, scored both ways. Values from rerunning cosine_by_hand.py.
SentenceWords shared with the queryBM25 scoreBM25 rankCosineCosine rank
waternone0tied last0.961st
firewarehouse0.981st0.362nd
earningsnone0tied last0.003rd

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.

KEYWORDS · BM25 SCORE water sentence 0 · shares no word 2 fire sentence 0.98 shares one word: warehouse 1 earnings sentence 0 · shares no word order: fire first; water and earnings tie at 0 MEANING · COSINE, HAND-MADE VECTORS water sentence 0.96 3 fire sentence 0.36 earnings sentence 0.00 order: water, then fire, then earnings 4 same query, same three sentences: the left method reads words, the right one reads direction
Fig. 8.1h — The query "warehouse flooding?" scored against the same three sentences by BM25 (left) and by cosine on hand-made vectors (right). Both bar scales run from 0 to 1. Values from rerunning cosine_by_hand.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
The two methods side by side
Keyword search (BM25)Embedding search (cosine)
What it comparesThe exact words of the query and the chunkThe direction of two vectors of numbers
A score of 0 meansNot one query word is in the chunkThe two arrows meet at a right angle
Needs a trained modelNo; it counts wordsYes; the model makes the vectors
Good atRare exact strings: PP-FL-4B, names, form numbersParaphrase: "flooding" finds "water damage"
Bad atSynonyms and rewordingIdentifiers the model never learned
Where on this pageThe sparse leg of Stage 4, section 05retrieve() 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).

  1. Distance to the water sentence as written. √((4 − 3)² + (3 − 4)² + (0 − 0)²) = √(1 + 1 + 0) = √2 = 1.41.
  2. Distance to the water sentence pasted twice. √((4 − 6)² + (3 − 8)² + (0 − 0)²) = √(4 + 25 + 0) = √29 = 5.39.
  3. Distance to the fire sentence, for comparison. √((4 − 0)² + (3 − 3)² + (0 − 4)²) = √(16 + 0 + 16) = √32 = 5.66.
  4. 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.

Normalising three vectors. Values from rerunning cosine_by_hand.py.
VectorLengthWorkingNormalised vector
query (4, 3, 0)54 ÷ 5, 3 ÷ 5, 0 ÷ 5(0.8, 0.6, 0)
water (3, 4, 0)53 ÷ 5, 4 ÷ 5, 0 ÷ 5(0.6, 0.8, 0)
water twice (6, 8, 0)106 ÷ 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.

1 RAW ARROWS: DISTANCE CHANGES, ANGLE DOES NOT water & flooding buildings & property query (4, 3) water (3, 4) water twice (6, 8) 1.41 5.39 16.3° 2 straight-line distance to the query: water 1.41 · water twice 5.39 · fire 5.66 cosine to the query: 0.96 · 0.96 · 0.36 3 NORMALISED: EVERY ARROW HAS LENGTH 1 circle of length 1 query (0.8, 0.6) water and water twice (0.6, 0.8) 3 4 one multiply: 0.8 × 0.6 + 0.6 × 0.8 = 0.96, the cosine distance now 0.28, and 0.28² = 0.08 = 2 − 2 × 0.96 so distance and cosine now give the same order
Fig. 8.1i — The same arrows before and after normalising. Left: the water and buildings dials only; the fire sentence also has a money number, so it leaves this flat picture and appears only in the text. Right: every arrow divided by its own length. Values from rerunning cosine_by_hand.py.
  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.
  2. 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.
  3. 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.
  4. 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.

🧠 Brain power

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.

Sharpen your pencil

Below are twelve lines lifted from mini_rag.py, the file you are about to read. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. Wrong guesses are welcome; they are the point of the exercise.

model = SentenceTransformer("all-MiniLM-L6-v2")load a small neural network that turns any piece of text into a list of 384 numbers
doc_vecs = model.encode([c["text"] for c in CHUNKS], normalize_embeddings=True)
q_vec = model.encode([query], normalize_embeddings=True)[0]
scores = doc_vecs @ q_vecmultiply every chunk's numbers by the question's numbers: one similarity score per chunk
top = np.argsort(scores)[::-1][:k]
return [(float(scores[i]), CHUNKS[i]) for i in top]
"Answer ONLY from the numbered context chunks."
"If the context does not contain the answer, reply exactly: INSUFFICIENT_CONTEXT."give the model a way to say "I don't know" instead of inventing something
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"):
client.messages.create(model="claude-haiku-4-5", max_tokens=500, system=SYSTEM, messages=[...])
next(b.text for b in resp.content if b.type == "text")
Check your answers
model = SentenceTransformer("all-MiniLM-L6-v2")load a small neural network that turns any piece of text into a list of 384 numbers
doc_vecs = model.encode([c["text"] for c in CHUNKS], normalize_embeddings=True)run every policy chunk through that network once, and scale each list of numbers to length 1 so that comparing two lists is a single multiply. This is the index. It is built once.
q_vec = model.encode([query], normalize_embeddings=True)[0]do the same for the question, and take the first (and only) result out of the list the encoder returns
scores = doc_vecs @ q_vecmultiply every chunk's numbers by the question's numbers: one similarity score per chunk. Because every list has length 1, each score is the cosine similarity
top = np.argsort(scores)[::-1][:k]sort the scores lowest to highest, reverse so the highest comes first, keep the first k. The result is chunk positions, not scores
return [(float(scores[i]), CHUNKS[i]) for i in top]hand back a list of pairs, best first: the score as a plain Python number, and the chunk it belongs to
"Answer ONLY from the numbered context chunks."the sentence in the system prompt that forbids the model from using anything it remembers from training. This is the grounding contract
"If the context does not contain the answer, reply exactly: INSUFFICIENT_CONTEXT."give the model a way to say "I don't know" instead of inventing something
context = "\n\n".join(f"[{n}] ({c['id']}) {c['text']}" for n, (_, c) in enumerate(hits, 1))build the text the model will read: each retrieved chunk numbered [1], [2], [3] with its document id, separated by blank lines. Those numbers are what the model will cite
if not os.environ.get("ANTHROPIC_API_KEY"):check whether an API key exists in the environment. If not, take the offline path: print the retrieval results and a template answer instead of calling the model
client.messages.create(model="claude-haiku-4-5", max_tokens=500, system=SYSTEM, messages=[...])call the model once, with the strict system prompt and a user message holding the numbered context followed by the question. max_tokens caps the length of the reply
next(b.text for b in resp.content if b.type == "text")the reply comes back as a list of content blocks; take the text of the first block that is text. That is the answer, with its [n] citations inside it

Do not worry if you got half of these. If you guessed that @ multiplies and that argsort sorts, you already have the retrieval half. The generation half is one API call and a strict system prompt, which is the part most tutorials get wrong.

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/.

  1. 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
    1. Import os, numpy and SentenceTransformer. Only the import of the encoder is used from chunk 2 on.
    2. Build CHUNKS, a list of five dictionaries. Each has an id (document and page) and the text of the passage.
    3. 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"])
    

    list of dict — each passage keeps its source next to its text. This is the metadata habit that makes citations possible.

    Run python3 chunk1_corpus.py. It prints 5 chunks; DOC-FL-2026 p.14.

  2. 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
    1. Load all-MiniLM-L6-v2, a model that turns any text into a list of 384 numbers. The first run downloads about 80 MB.
    2. Encode all five texts at once. normalize_embeddings=True scales each list to length 1, so comparing two lists later is a plain multiply.
    3. 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 prints index shape: (5, 384). Five passages, 384 numbers each.

  3. 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
    1. Define retrieve(query, k). Encode the question with the same model, so it lands in the same number space.
    2. Multiply the table by the question's numbers. Each result is one similarity score per passage (cosine similarity, because every row has length 1).
    3. Sort the scores from high to low and keep the first k.
    4. 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 offline
    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]
    
    # 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 prints 0.740 DOC-FL-2026 p.14, then 0.499 DOC-FL-2026 p.15, then 0.432 DOC-CA-2025 p.11. The flood-exclusion page wins, though the question never says "exclude".

  4. 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
    1. Write SYSTEM: answer only from the numbered chunks, cite each claim like [1], and say INSUFFICIENT_CONTEXT when the answer is missing.
    2. In answer(), call retrieve and build context: each hit as [n] (id) text.
    3. 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, returns None if missing. An f-string with :.3f prints three decimals.

    Run python3 chunk4_prompt_offline.py with no key set. It prints (no API key — retrieval only), the same three scores and ids as chunk 3 numbered [1] to [3], and Template answer: quote chunk [1] verbatim and cite it. If a key is set, this chunk returns nothing yet; chunk 5 adds the model call.

  5. 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
    1. Import anthropic and create a client; it reads the key from the environment.
    2. Call messages.create once with the strict SYSTEM, and a user message that holds the context then the question. max_tokens=500 caps the reply.
    3. Return the text of the first text block in the reply.
    4. Under __main__, ask two questions and print each answer.
    mini_rag.py — chunk 5 (the finished file)needs API key
        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)}")
    

    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 hit 0.740 DOC-FL-2026 p.14, Texas top hit 0.787 DOC-TX-2025 p.8. With a key, the Florida answer is the model's cited reply. Not run here with a key.

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
  1. Bring in three libraries: os to read the API key from the environment, numpy for the arithmetic, and SentenceTransformer, the wrapper around the embedding model.
  2. 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.
  3. 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.
  4. Encode all five chunk texts at once into doc_vecs, a table with five rows of 384 numbers each. normalize_embeddings=True scales every row to length 1, which is what makes step 6 a plain multiply. This is the index, and it is built once.
  5. Define retrieve(query, k): encode the question the same way, so it lands in the same 384-number space as the chunks.
  6. 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.
  7. Sort the scores, reverse so the highest comes first, keep the top k positions, and return (score, chunk) pairs, best first.
  8. Define SYSTEM, the grounding contract: answer only from the numbered chunks, cite each claim with [n], and if the answer is not there say INSUFFICIENT_CONTEXT.
  9. Define answer(query): retrieve the top chunks and format them as numbered context blocks, each carrying its document id.
  10. If there is no ANTHROPIC_API_KEY in the environment, stop here and print the retrieval results with their scores. The retrieval half of RAG never needs a key.
  11. 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.
  12. Pull the text out of the first text block of the reply and return it.
  13. When run as a script, ask two questions and print each answer.
mini_rag.pyruns offline · Claude key optional
# 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:

1 INDEX TIME · done once, before any question arrives CHUNKS 5 policy passages encode doc_vecs 5 rows × 384 numbers normalized the index every row has length 1 the write-time cost 2 QUERY TIME · every request, in milliseconds the question one string encode q_vec 384 numbers 5 scores one per chunk doc_vecs multiplied by q_vec 3 sort, keep three, number them one multiply per chunk, no model call, so search is one matrix multiply highest 3 scores, best first [1] DOC-FL-2026 p.14 [2] p.15 [3] p.3
Fig. 8.1a — The 70-liner as two paths. Everything expensive happens once, at index time (marker 1); a question costs one encode and one multiply (marker 2), and the three highest scores become the numbered blocks the model reads (marker 3).
  1. Built once, marker 1. model.encode runs over all five chunk texts and returns a table with one row per chunk and 384 numbers per row. normalize_embeddings=True scales 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.
  2. 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.
  3. 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.
BE the retriever

Your turn to play the machine. Here are the five chunks in CHUNKS, shortened, and a new question. Meaning-space search has no idea what an adjuster is allowed to do. It only measures how close each chunk's meaning is to the question's meaning. With a pencil, rank the five chunks the way you think retrieve() would, top three first. Then answer the second question.

The question: "Can I approve a $30,000 Florida flood claim myself?"

  1. DOC-FL-2026 p.14 — Florida warehouses in hurricane zones: flood damage excluded
  2. DOC-FL-2026 p.15 — the Tier-1 endorsement adds flood coverage up to $250,000
  3. DOC-TX-2025 p.8 — Texas fire deductible, $2,500
  4. DOC-GEN-2026 p.3 — claims over $25,000 need dual approval and an inspection
  5. DOC-CA-2025 p.11 — California wildfire deductible

Which three does the retriever return? Which single chunk does the adjuster actually need to answer "can I approve this myself"? Are they the same?

Check your answer

On this five-chunk corpus the ranking is close. The two Florida flood chunks and the dual-approval chunk fight for the top three, and which one wins depends on wording the retriever cannot reason about: it sees "Florida", "flood" and "claim" in the question and scores the flood clauses highly, and it sees "$30,000" and "approve" and scores the dual-approval rule highly too. Run it and see where they land for you.

Now add two older revisions of the Florida policy, which is exactly what section 04 does. The fight is over: three near-identical flood exclusions take all three slots and the dual-approval rule is gone. Yet chunk 4 is the only one that answers "can I do this myself". Everything else tells the adjuster whether the claim is covered, which is a different question.

So: the retriever returns what is closest in meaning; the adjuster needs what answers the question; and those are not the same thing. That gap is the entire reason the production pipeline has a reranker, a model that reads the question and each candidate together and notices that "approve it myself" conflicts with "requires dual approval". Keep this example in mind. It returns as failure 2, and the fix is stage 5.

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.

Failure mode

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.

1 FAILURE 1 · the clause is cut in half chunk 1 chunk 2 3 EXCLUDE flood unless endorsed 'emium.' returned: chunk 1, alone answer: "flood damage is excluded" wrong because the remedy — buy the endorsement — was sitting in chunk 2 2 FAILURE 2 · near-duplicates take every slot [1] cos 0.71 DOC-FL-2026 p.14 flood exclusion [2] cos 0.70 DOC-FL-2025 p.14 same, last year [3] cos 0.69 DOC-FL-2024 p.13 same, 2024 missed: DOC-GEN-2026 p.3 — dual approval over $25,000 wrong because the question needed two different documents and got one fact, three times 3 FAILURE 3 · the identifier does not score the chunk that defines PP-FL-4B a generic paragraph about endorsements the same, near enough wrong because PP-FL-4B is shredded into PP / - / FL / - / 4 / B and carries no meaning 4 FAILURE 4 · the model answers from memory [1] ...zones EXCLUDE water and flood damage. "likely covered for flood events" wrong because the truth was already in the prompt and nothing about retrieval was broken
Fig. 8.1b — The four classic RAG failures, each drawn as what the retriever returned and why the answer was wrong. Three of them (markers 1, 2, 3) happen at index time, before anyone asks a question; only marker 4 happens while the adjuster waits.
  1. 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.
  2. 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.
  3. 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.
  4. 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:

bad_chunking.pyruns offline
# 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}")
output
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.'
1 the clause is 246 characters long; the knife falls every 120 cut at character 120 cut at 240 chunk 1 · 120 chars chunk 2 · 120 chars 3 "...zones EXCLUDE water and flood damage" ". Flood coverage requires a separate ... added pr" 2 chunk 3 is the 6-character string 'emium.' — it will embed as pure noise 3 the same clause, cut where the sentence ends one cut, at character 121, after the full stop sentence 1 · 121 chars sentence 2 · 124 chars the whole exclusion, ending in a full stop the whole remedy: endorsement, 12 percent, premium
Fig. 8.1c — Where the knife lands. The clause is 246 characters; a 120-character chunker cuts at 120 and 240 and leaves a 6-character orphan (markers 1 and 2). A sentence-aware splitter cuts once, at 121, and both halves are readable on their own (marker 3).
  1. 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".
  2. 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.
  3. 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:

observed retrieval (corpus + 2 old revisions)
[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)
"Can I approve a $30,000 Florida flood claim myself?" 1 what cosine ranked [1] cos 0.71 DOC-FL-2026 p.14 flood exclusion, current [2] cos 0.70 DOC-FL-2025 p.14 the same clause, last year [3] cos 0.69 DOC-FL-2024 p.13 the same clause, two years ago top-3 cut [4] just under DOC-GEN-2026 p.3 dual approval over $25,000 2 the only chunk that answers the question asked 3 three slots, one fact The model reads "flood is excluded" three times and never learns that a $30,000 claim needs a Senior Adjuster's second signature and a photographic inspection.
Fig. 8.1d — Similarity is not coverage. The three near-identical Florida revisions score 0.71, 0.70 and 0.69 and take every slot (marker 1); the dual-approval rule, the only chunk that answers "can I approve this myself", sits just under the cut (marker 2), so the model is handed one fact three times (marker 3).
  1. 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.
  2. 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.
  3. 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:

id_probe.pyruns offline
# 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))
1 the query, word by word What does endorsement form PP-FL-4B cover? Six of the seven tiles also appear in the generic paragraph about endorsements. PP-FL-4B becomes PP / - / FL / - / 4 / B subword fragments with no meaning attached 2 Fig. 8.1's meaning-space, zoomed in the query the chunk defining PP-FL-4B generic endorsement filler same same 3 what BM25 does with the same query PP-FL-4B occurs in exactly one chunk, so it is a rare term, and keyword search pins that chunk at rank 1 in one shot.
Fig. 8.1e — Why the identifier does not help. Six of the query's seven tiles match the generic chunk too (marker 1), so in meaning-space both candidates sit at almost the same distance from the query (marker 2). Keyword search has the opposite profile (marker 3). Drawn from the shape of the result, not from measured cosines: run id_probe.py below and your own two numbers will land within a few hundredths of each other.
  1. 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.
  2. 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.
  3. 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:

observed generation (weak grounding prompt)
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.

1 THE RETRIEVER — fails silently, at index time failure 1 · the clause cut at character 120 the remedy ended up in a different chunk failure 2 · 0.71 / 0.70 / 0.69, three copies the dual-approval rule never reached the prompt failure 3 · PP-FL-4B scores like generic filler the one page that defines the form is unfindable 2 THE GENERATOR — fails loudly, at query time failure 4 · retrieval worked perfectly [1] ...zones EXCLUDE water and flood damage. "likely covered for flood events" $45,000 paid. The truth was already in the prompt. one request, one wrong sentence, in front of a user 3 when each one fails index time weeks before anyone asks failures 1 to 3 land here query time while the adjuster waits failure 4 lands here 4 the two report cards context recall + context precision grade the left column · faithfulness grades the right
Fig. 8.1f — The two halves of RAG, and the failures each one owns. Three failures are the retriever's and happen at index time, silently (markers 1 and 3); one is the generator's and happens in front of the user (marker 2). They are graded by different metrics on purpose (marker 4).
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Fireside chat

Tonight's talk: The Retriever and The Generator argue over the question, "Who's more important?"

The Retriever
The Generator

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.

🧠 Brain power

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.

INDEX TIME — offline batch, re-run on document change Ingest Parse Chunk Embed Index (pgvector) ANN lookup QUERY TIME — every request Query Embed Hybrid search dense + BM25 → RRF Rerank Pack context Generate + cite Eval error analysis → fix chunking, retrieval, prompts
Fig. 8.2 — The production RAG pipeline. Offline: ingest → parse → chunk → embed → index. Online: embed the query, hybrid-search the index, rerank the candidates, pack context, generate with citations — and continuously eval, feeding failures back into the pipeline.

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.

Fig. 8.2 again, concretely: each stage as it exists in this module's code
StageIn the 70-line version (section 03)In the production build (this section)What flows out
Ingest + parseFive chunks typed by hand in CHUNKSLlamaParse or a layout-aware parser over 50+ PDFsClean text with document and page metadata
ChunkSkipped: each passage is already one chunkRecursiveCharacterTextSplitter, about 500 tokens, 10–15% overlapChunks that do not cut a sentence in half
Embedmodel.encode(...) in mini_rag.pyThe same call, batched, on a schedule; model name pinned in the schemaOne 384-number vector per chunk
IndexA numpy array in memory, doc_vecsThe chunks table in schema.sql with an HNSW indexSomething you can search in milliseconds
Embed the querymodel.encode([query]) inside retrieve()Identical: same model, same version, foreverOne vector for the question
Hybrid searchdoc_vecs @ q_vec, cosine onlyDense + BM25, fused by rrf() in hybrid_rrf.pyA ranked shortlist of candidates
RerankNoneCrossEncoder in rerank.py over the top 50The five chunks that really answer the question
Pack contextThe "\n\n".join(...) line in answer()The same, plus a token budget and parent-chunk expansionNumbered blocks [1] to [5]
Generate + citeclient.messages.create(...) with the strict SYSTEMThe same contract, streamed, citations rendered as linksAn answer an auditor can check
EvalNoneRagas in eval_rag.py: faithfulness, context precision, context recallNumbers 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:

Fixed-size cuts mid-sentence cheap; blind to meaning Recursive splits at paragraphs, then sentences — the default Semantic topic shift topic shift splits where embedding distance jumps — slower to build Parent-document parent searched returned to LLM search small, hand back big
Fig. 8.3 — Four chunking strategies on the same document. Fixed slices cut sentences; recursive respects structural boundaries; semantic splits where meaning shifts; parent-document searches precise small chunks but hands the LLM the surrounding parent for full context.

Here are those four strategies again, applied to the actual Section 4.B clause you just broke. Same 246 characters, four different knives.

1 Fixed-size 120 chars 120 chars 6 cuts one character before the full stop: exclusion and remedy split, plus a 6-character orphan 2 Recursive 121 chars · whole sentence 124 chars · whole sentence tries paragraphs, then sentences, then words: the cut lands after the full stop, at 121 3 Semantic topic: what is excluded topic: how to buy cover same cut, found by measuring where meaning jumps — one embedding pass per sentence, at index time 4 Parent-document parent handed to the model: all 246 characters child 121 · searched child 124 · searched search the precise 121-character child, then hand the model the whole clause around it costs index bookkeeping and a longer prompt per query
Fig. 8.3b — The same 246-character Section 4.B clause under four knives. Only the fixed-size knife (marker 1) separates the exclusion from its remedy; recursive and semantic (markers 2 and 3) land the single cut at character 121, after the full stop; parent-document (marker 4) searches the small halves and returns the whole clause.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Decision table — choosing a chunking strategy (start recursive; graduate deliberately)
StrategyHow it splitsChoose whenWatch out for
Fixed-size + overlapEvery ~N tokens, 10–15% overlapFirst baseline; uniform log-like textSplits sentences and ideas (failure 1)
RecursiveParagraphs → sentences → words, targeting ~300–800 tokensThe default for prose, Markdown, policies, docsStill blind to meaning; tune size per corpus
SemanticBreaks where inter-sentence embedding distance jumpsDense technical docs; index-time budget to spendSlow indexing; a threshold to tune
Parent-documentEmbed small children; return the larger parent on hitPrecise retrieval and the LLM needs surrounding contextIndex 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.

Embedding models worth knowing, as of Aug 2026
ModelDimsRuns whereChoose when
all-MiniLM-L6-v2384Local, CPUPrototypes, labs, laptops — what we used above
text-embedding-3-large (OpenAI)3072 (truncatable)APIBest-in-class managed quality; fine paying per token and shipping data out
BGE-M3 (BAAI, open)1024Local, GPU-friendlySelf-hosted production; multilingual; emits dense and sparse signals from one model
voyage-3-large1024 (default)APIRetrieval-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):

chroma_quickstart.pyruns offline
# 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:

schema.sqlruns offline
-- 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);
pgvector_rag.pyruns offline (needs local Postgres)
# 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}")
Anatomy of a vector query — the one SQL statement to know by heart
SELECT doc_id, page, content,
       1 -1 (embedding <=>2 %s) AS cosine
FROM   chunks
ORDER  BY embedding <=> %s3
LIMIT  %s4
  1. 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.
  2. 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_ops in schema.sql), or the index is silently ignored and every query scans the whole table.
  3. 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 cosine column instead and you get a full table scan that looks correct and is a hundred times slower.
  4. 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.
Decision table — vector store selection, as of Aug 2026
StoreChoose whenAvoid whenOps burden
ChromaPrototyping, labs, single-process apps, <~1M vectorsMulti-writer production, HA requirementsNone
pgvectorDefault under ~10M vectors; you already run Postgres; retrieval must join ACLs/metadataVery high QPS with heavy filtered ANN at 100M+ scaleThe Postgres you already carry
QdrantPerformance-critical OSS self-hosting; rich payload filtering at scaleTeam can't own another stateful serviceOne more service
PineconeManaged/serverless; no infra team; elastic scaleStrict data-residency; cost-sensitive at large scaleNone (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:

user query catches meaning: "water damage" ≈ "flood" catches exact tokens: "PP-FL-4B" embed → 384-D vector vector index (HNSW) ranked list A (cosine) tokenize keywords BM25 index ranked list B (BM25 score) RRF fusion score(d) = Σ 1/(60 + rank) fused top-k → reranker
Fig. 8.4 — Hybrid retrieval: the same query runs down a dense (meaning) path and a sparse (keyword) path; RRF merges the two ranked lists by position, so their incomparable score scales never need calibrating.
Step-by-step: what hybrid_rrf.py does, in plain English
  1. Bring in numpy, Python's regular-expression module, the BM25 implementation from rank_bm25, the embedding model, and the five CHUNKS from mini_rag.py.
  2. Pull the chunk texts into a plain list, because both legs index the same texts.
  3. Dense leg: load the same embedding model and encode every chunk, exactly as in section 03.
  4. 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.
  5. dense_ranking(query): embed the question, score every chunk by dot product, and return the chunk positions from best to worst.
  6. sparse_ranking(query): score every chunk with BM25 for the question's tokens, cut by the same tokenize(), and return positions from best to worst. Note that both functions return positions, not scores. The fusion step never sees a score.
  7. rrf(rankings, k=60): start an empty score sheet. Walk down each ranked list; the chunk at position pos earns 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.
  8. Ask the PP-FL-4B question, fuse the two rankings, and print the ids of the top three.
hybrid_rrf.pyruns offline
# 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.

1 Dense (meaning) leg 1st B · the flood exclusion 2nd A · defines PP-FL-4B 3rd C · generic endorsement 2 Sparse (BM25) leg 1st A · the only chunk with "PP-FL-4B" 2nd C · generic endorsement 3rd B · the flood exclusion RRF · Σ 1/(60 + rank) 3 the arithmetic, to four decimal places A = 1/(60+2) + 1/(60+1) = 0.0161 + 0.0164 = 0.0325 B = 1/(60+1) + 1/(60+3) = 0.0164 + 0.0159 = 0.0323 C = 1/(60+3) + 1/(60+2) = 0.0159 + 0.0161 = 0.0320 fused order: A, then B, then C 4 the winning margin 0.0002 first beats second by 0.0002, so consensus wins and confidence does not
Fig. 8.4b — Reciprocal Rank Fusion done by hand on three chunks. The dense leg ranks B first (marker 1), the sparse leg ranks A first (marker 2), and adding one over sixty-plus-rank across both lists puts A on top with 0.0325 against B's 0.0323 (markers 3 and 4).
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Sharpen your pencil

Fuse two rankings by hand, once, and you will never again wonder what RRF does. Suppose the question is "What does endorsement form PP-FL-4B cover?" and the two legs return these rankings over three chunks: A defines PP-FL-4B, B is the flood exclusion, C is a generic paragraph about endorsements.

Dense (meaning) leg1st B, 2nd A, 3rd C — fooled by "coverage" and "endorsement" wording
Sparse (BM25) leg1st A, 2nd C, 3rd B — A alone contains the rare token PP-FL-4B
score(d) = Σ 1 / (60 + rank)one term per list the chunk appears in; rank is its 1-based position
score(A) = 1/(60+2) + 1/(60+1) =
score(B) =
score(C) =
Fused order:

Work to four decimal places. Then answer: how far apart are first and second place?

Check your answers
score(A) = 1/62 + 1/610.0161 + 0.0164 = 0.0325
score(B) = 1/61 + 1/630.0164 + 0.0159 = 0.0323
score(C) = 1/63 + 1/620.0159 + 0.0161 = 0.0320
Fused order:A, then B, then C. The chunk that defines PP-FL-4B wins: BM25 pinned it at the top on the rare token itself, and being second in the dense list was enough to carry it. That works only if the tokeniser keeps "PP-FL-4B" whole.

Notice two things. First, the margins are tiny: 0.0325 against 0.0323 — marker 4 in Fig. 8.4b. That is the gentle slope of 1/(60 + rank) at work. Being first instead of second in one list is worth about 0.0003, so RRF rewards consensus over confidence. A chunk near the top of both lists beats a chunk that is first in one and missing from the other. Second, no cosine score and no BM25 score was ever added to anything. Only positions. That is why the two legs never need to be calibrated against each other, and why adding a third leg (say, a rewritten query in section 06) is one more list, not a new formula.

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:

10 M 1,000 50 5 indexed chunks hybrid recall (ANN + BM25) RRF + exact cosine rank cross-encoder rerank LLM context cheap, approximate — tuned for recall expensive, precise — ~100 ms for 50 pairs
Fig. 8.5 — The retrieval funnel: each stage is more expensive per document and sees fewer documents. Recall problems are fixed on the left; precision problems on the right.

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.

1 what one query costs, stage by stage stage documents seen cost of each cost this query embed the question 1 one forward pass about 5 ms hybrid recall (HNSW + BM25) 10,000,000 → 1,000 index work, not per document about 10 ms 2 rerank the shortlist 50 → 5 2 ms per pair, on a CPU about 100 ms generate with citations 5 about 3,000 input tokens about $0.003 whole query 115 ms + $0.003 3 the same picture with no funnel at all rerank everything: 10,000,000 pairs × 2 ms = 20,000,000 ms = 5.6 hours, per query 200,000 times slower, to end up with the same five chunks
Fig. 8.5b — The funnel priced. Recall is cheap because the index does the work once (marker 1); the reranker is the expensive stage and is therefore the shortest list it can be (marker 2); running it over the whole corpus instead would take 5.6 hours per query (marker 3).
  1. 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.
  2. 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.
  3. 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
  1. Bring in the CrossEncoder class and, from mini_rag.py, both the chunks and the retrieve() function from section 03.
  2. 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.
  3. Set the question about approving a $30,000 claim, the one you traced by hand in section 03.
  4. Recall stage: call retrieve() for the top five by cosine. This is the cheap step, and it may rank the answer-bearing chunk low.
  5. 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".
  6. 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.
rerank.pyruns offline
# 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.

The five chunks every answer below uses, for the question "Can I approve a $30,000 Florida flood claim myself?" The 2026 texts are the CHUNKS of mini_rag.py; the 2025 and 2024 texts were written for this example. The four-number vectors are hand-made on named dials, picked so the three Florida revisions score the 0.71, 0.70 and 0.69 that section 04 reports from the real model.
ChunkWhat it saysCurrent revision?Needed for this question?Vector: flood, Florida, approval, extra coverSize
FL-2026 p.14Section 4.B: Florida warehouses in high-risk hurricane zones EXCLUDE flood damage; cover needs the Tier-1 endorsementyesyes: is it covered?(4, 5, 0, 2.5)189 characters
FL-2025 p.14The same clause, last year, without "high-risk"nono(4, 4.5, 0, 2.5)179 characters
FL-2024 p.13The same clause, 2024, without "hurricane zones"nono(4, 4, 0, 2.5)163 characters
GEN-2026 p.3Section 1.C: claims over $25,000 need dual approval from a Senior Adjuster plus an inspection reportyesyes: who may approve?(0, 0, 5, 0)166 characters
FL-2026 p.15Section 4.C: endorsement PP-FL-4B adds flood cover up to $250,000 for a 12 percent premiumyesno(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.

  1. Count the needed chunks. Two: FL-2026 p.14 and GEN-2026 p.3.
  2. 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.
  3. Count the needed chunks inside that top k. One: FL-2026 p.14. The dual-approval rule is fourth, just under the cut.
  4. Recall@3 = needed found ÷ needed in total. 1 ÷ 2 = 0.50. Half of what the answer needs never reaches the model.
  5. Precision@3 = needed found ÷ slots used. 1 ÷ 3 = 0.33. Two of the three slots hold superseded copies.
The same two counts for every k. Values from rerunning retrieval_trace.py.
kChunk added at this rankNeeded foundRecall@kPrecision@k
1FL-2026 p.14 (needed)11 ÷ 2 = 0.501 ÷ 1 = 1.00
2FL-2025 p.1411 ÷ 2 = 0.501 ÷ 2 = 0.50
3FL-2024 p.1311 ÷ 2 = 0.501 ÷ 3 = 0.33
4GEN-2026 p.3 (needed)22 ÷ 2 = 1.002 ÷ 4 = 0.50
5FL-2026 p.1522 ÷ 2 = 1.002 ÷ 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.

DENSE RANKING FOR THE $30,000 QUESTION 1 0.71 FL-2026 p.14 needed 1 2 0.70 FL-2025 p.14 old copy 3 0.69 FL-2024 p.13 old copy k = 3 4 0.64 GEN-2026 p.3 needed, cut 2 5 0.22 FL-2026 p.15 3 recall@3 = 1 needed found ÷ 2 needed = 0.50 precision@3 = 1 needed found ÷ 3 slots = 0.33 both counts ignore the scores: only the cut matters THE SAME TWO COUNTS FOR EVERY k 0 0.5 1 1 2 3 4 5 k, the number of chunks kept 1.00 0.33 0.40 0.50 1.00 recall@k precision@k 4
Fig. 8.5e — Recall@k and precision@k for the $30,000 question. Left: the dense ranking with the top-3 cut drawn in. Right: both counts for k from 1 to 5; at k = 2 the two lines meet at 0.50. Values from rerunning retrieval_trace.py on the hand-made vectors.
  1. Found. The current flood exclusion ranks first, so the "is it covered?" half of the answer is inside the top 3.
  2. 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.
  3. 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.
  4. 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 is not the same number as section 07's context recall
Recall@k (this answer)Context recall (Ragas, section 07)
What it countsNeeded chunks found in the top kFacts in the reference answer that the retrieved text supports
Who decides "needed"A person, who labels chunk ids for each questionA judge model, which reads the reference answer against the retrieved text
How far to trust itExact, as far as the labels are rightAs 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.

  1. 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.
  2. 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.

BM25 for the question, with the formula and settings from the keyword-versus-embedding answer. Values from rerunning retrieval_trace.py.
ChunkQuestion words it containsLength in wordsBM25Rank
FL-2024 p.13a, florida, flood211.271
FL-2025 p.14a, florida, flood231.232
FL-2026 p.14a, florida, flood241.213
GEN-2026 p.3a230.294
FL-2026 p.15flood270.275

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.

Reciprocal rank fusion of the two legs, k = 60. Values from rerunning retrieval_trace.py.
ChunkDense rankKeyword rankWorkingFused
FL-2026 p.14131/61 + 1/63 = 0.01639 + 0.015870.03227
FL-2024 p.13311/63 + 1/61 = 0.01587 + 0.016390.03227
FL-2025 p.14221/62 + 1/62 = 0.01613 + 0.016130.03226
GEN-2026 p.3441/64 + 1/64 = 0.01562 + 0.015620.03125
FL-2026 p.15551/65 + 1/65 = 0.01538 + 0.015380.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:

output · retrieval_trace.py, the user message after the filter
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.

AS BUILT: ALL FIVE CHUNKS FILTERED: CURRENT REVISIONS ONLY dense leg cosine 1 0.71 FL-2026 p.14 needed 2 0.70 FL-2025 p.14 3 0.69 FL-2024 p.13 4 0.64 GEN-2026 p.3 needed, cut 1 1 0.71 FL-2026 p.14 needed 2 0.64 GEN-2026 p.3 needed 3 0.22 FL-2026 p.15 keyword leg BM25 1 1.27 FL-2024 p.13 shortest copy 2 1.23 FL-2025 p.14 3 1.21 FL-2026 p.14 needed 4 0.29 GEN-2026 p.3 matches only "a" 2 1 2.12 FL-2026 p.14 needed 2 0.48 GEN-2026 p.3 needed 3 0.45 FL-2026 p.15 fusion RRF, k = 60 1 0.03227 FL-2026 p.14 needed 2 0.03227 FL-2024 p.13 3 0.03226 FL-2025 p.14 three copies 3 1 0.0328 FL-2026 p.14 needed 2 0.0323 GEN-2026 p.3 needed 3 0.0317 FL-2026 p.15 top 3 kept recall@3 0.50 · precision@3 0.33 recall@3 1.00 · precision@3 0.67 4 rerank 5 pairs × 2 ms = 10 ms · scores need the model 3 pairs × 2 ms = 6 ms · order only prompt system + 3 blocks [1] FL-2026 p.14 · [2] 2024 p.13 · [3] 2025 p.14 898 chars ≈ 224 tokens ≈ $0.000225 needed text: 189 of 531 chars, 36% [1] FL-2026 p.14 · [2] GEN p.3 · [3] FL p.15 889 chars ≈ 222 tokens ≈ $0.000222 needed text: 355 of 522 chars, 68% 5 citation every [n] resolves to a flood clause [2] resolves to DOC-GEN-2026 page 3
Fig. 8.5f — The $30,000 question through the same stations twice: as built over all five chunks (left) and with a current-revisions filter applied before search (right). The dense leg uses the hand-made vectors; everything else is computed. Values from rerunning retrieval_trace.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

  1. 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).
  2. Add the two. (1,257, 945, 0, 1,307.5).
  3. 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.
  4. Score it as usual. Against the flood question its cosine is 0.89. Against the form question it is 0.77.
Two questions, two ways. The other three chunks of the table stay in the index both times. Values from rerunning chunk_size_two_ways.py.
Way 1: two chunksWay 2: one chunk
Flood question: top 3FL-2025 p.14 at 0.99, FL-2026 p.14 at 0.98, FL-2024 p.13 at 0.98FL-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.552 ÷ 2 = 1.00; both are inside one block
Form question: best chunkFL-2026 p.15 at 0.96The big chunk at 0.77
Form question: lead over the runner-up, FL-2024 p.13 at 0.550.96 − 0.55 = 0.410.77 − 0.55 = 0.22
Form question: text in the top 3509 characters ≈ 127 tokens699 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.

1 ONE DOCUMENT, CUT TWO WAYS two chunks 4.B exclusion · 189 chars 4.C PP-FL-4B · 167 chars one chunk 4.B + 4.C · 357 chars · vector (3.53, 2.65, 0, 3.67) 2 THE FLOOD QUESTION NEEDS 4.B AND 4.C two chunks: top 3 0.99 FL-2025 p.14 (old 4.B) 0.98 FL-2026 p.14 (4.B) 0.98 FL-2024 p.13 (old 4.B) 0.55 FL-2026 p.15 (4.C), fourth, cut recall@3 = 1 ÷ 2 = 0.50 one chunk: top 3 0.99 FL-2025 p.14 (old 4.B) 0.98 FL-2024 p.13 (old 4.B) 0.89 big chunk (4.B + 4.C) recall@3 = 2 ÷ 2 = 1.00 3 THE FORM QUESTION NEEDS ONLY 4.C two chunks: 4.C 0.96 · lead 0.41 one chunk: 4.B + 4.C 0.77 · lead 0.22 4 runner-up FL-2024 p.13 at 0.55 0
Fig. 8.5g — DOC-FL-2026 pages 14–15 chunked two ways and searched with two questions. The big chunk's vector is the length-weighted average of its halves' hand-made vectors, a stand-in for the averaging an embedding model does. In the bottom row, each bar's length is proportional to its cosine. Values from rerunning chunk_size_two_ways.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

rag_langchain.pyneeds API key
# 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:

rag_llamaindex.pyneeds API key
# 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']}")
Honest comparison — which RAG layer when, as of Aug 2026
ApproachChoose whenAvoid whenWhat you trade
Your own code (section 03 grown up)You need full control: custom fusion, ACL joins, unusual stores; RAG is the productPrototyping speed matters mostYou write more; you understand everything
LlamaIndexDocument Q&A is the whole job; messy PDFs (LlamaParse); fastest path to cited answersRAG is one part of a complex agent appIts abstractions fit retrieval, less so everything else
LangChain 1.0RAG is one component in a larger LLM app (agents in Module 09, middleware, tool use)You only need document Q&ABigger 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.

1 index time · the chunk record chunk_id: c-0147 · doc_id: DOC-FL-2026 · page: 14 text: "Section 4.B: ... EXCLUDE water and flood damage." page 14 2 prompt time · the numbered block [1] (DOC-FL-2026 p.14) Section 4.B: Commercial warehouse properties ... EXCLUDE water and flood damage. page 14 3 model output · the tag "No. Flood damage is excluded for Florida warehouses [1]." just "[1]" 4 render time · the link [1] → opens DOC-FL-2026 at page 14 page 14
Fig. 8.5c — The citation path. The page number is written onto the chunk at index time (marker 1), travels into the numbered context block (marker 2), is referred to by the model as a bare [1] (marker 3), and is turned back into a page the adjuster can open at render time (marker 4).
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Anatomy of a grounded call — every part of the contract, on one screen
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
  1. 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.
  2. 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.
  3. The contract. The system prompt from mini_rag.py: answer only from the numbered chunks, cite every claim with [n], and say INSUFFICIENT_CONTEXT when the answer is not there. The faithfulness eval in section 07 tests this one line.
  4. 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.
  5. 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.
  6. 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.

Deprecation radar — spot the 2023 tutorial before it wastes your week

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.

What the RAG pipeline in this module uses, what else you could use, and when to switch
LayerWe useAlternativesWhy this oneSwitch when
Embeddingsall-MiniLM-L6-v2 via sentence-transformers (384 numbers, runs on CPU)text-embedding-3-large, BGE-M3, voyage-3-largeFree, 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 storepgvector (Chroma while prototyping)Qdrant, Pinecone, Milvus, WeaviatePolicyPal 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 hybridrank-bm25 in the lab, Postgres full-text search in the buildElasticsearch, OpenSearchExact 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.
RerankerBAAI/bge-reranker-v2-m3 as a local CrossEncoderCohere Rerank, ColBERT-style modelsOpen, 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.
Generatorclaude-haiku-4-5 ($1/$5 per million tokens)claude-sonnet-5, OpenAI models, a local model through OllamaCheapest 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 gluePlain Python (LangChain 1.0 and LlamaIndex shown in Stage 6)LangChain, LlamaIndex, HaystackEvery 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.
EvaluationRagas (faithfulness, context precision, context recall)DeepEval, TruLens, LangfuseThree 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.

1 what the adjuster typed "warehouse thing from last email??" rewriter: one cheap LLM call 2 one question becomes three query 1 florida warehouse flood coverage query 2 commercial flood exclusion clause query 3 endorsement form PP-FL-4B ranked list 1 ranked list 2 ranked list 3 RRF · Σ 1/(60 + rank) three terms now, not two 3 why it lifts recall a chunk ranked first in two of the three lists scores 2/61 = 0.0328, and beats a chunk ranked first in one list only, which scores 1/61 = 0.0164.
Fig. 8.5d — Query rewriting, drawn. One vague question becomes three clean ones (markers 1 and 2), each retrieves its own ranked list, and the same rrf() function merges three lists instead of two (marker 3) — a new list, not a new formula.
  1. 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.
  2. 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.
  3. 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
  1. Bring in Ragas's evaluate function and its dataset class, the three metrics, the wrapper that lets Ragas use a LangChain chat model as its judge, and from mini_rag.py the retrieve() and answer() functions.
  2. 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 is INSUFFICIENT_CONTEXT.
  3. 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.
  4. Build the judge: a stronger model than the generator (Sonnet judging Haiku), wrapped so Ragas can call it.
  5. Run evaluate over 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.
  6. Print the result: three numbers between 0 and 1. The table under the code tells you which stage each low number blames.
eval_rag.pyneeds API key
# 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.

1 three numbers from one run, and what each one blames faithfulness 0.86 grounding prompt · citation contract · model choice context precision 0.78 reranker · dedupe · metadata filters context recall 0.91 chunking · hybrid search · k · index hygiene 2 one number alone is not a diagnosis; two together are 3 reading two numbers together context recall LOW context recall HIGH faithfulness HIGH faithfulness LOW honest but starved: fix chunking or retrieval both halves working: ship it and keep sampling both broken: start with retrieval the model freelanced: fix the grounding contract
Fig. 8.6 — The three-way diagnosis. Each metric points at the components that can move it (marker 1), and no single number is a diagnosis on its own (marker 2); faithfulness read against context recall is what names the half of the system to fix (marker 3).
  1. 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.
  2. 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.
  3. 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?".
Reading the scores — which component each metric indicts
MetricQuestion it answersLow score meansFix lives in
FaithfulnessIs every claim in the answer supported by the retrieved context?Generation is inventing (failure 4)Grounding prompt, citation contract, model choice
Context precisionAre the top-ranked chunks actually relevant?Retrieval ranks junk first (failure 2)Reranker, dedupe, metadata filters
Context recallDid 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.
Boardroom translation

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.

LAB 08 — The portfolio project hiring screens actually ask about

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 /ask streams the answer token-by-token and returns structured citations (doc, page, chunk id, score) — plus a GET /health and 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

Interview radar

"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
🧠 Flex your memory

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.