0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09Three ways RAG goes wrong
Brightcart's assistant now searches its policies before answering, but Dev has found three kinds of failure. In the first, the policy was cut in half when the documents were split into chunks, so the crucial condition, "within 30 days", ended up in a different chunk that wasn't retrieved. In the second, the right passage was found, but ranked fifth, and only the top three were sent to the model. In the third, the customer asked a follow-up, "and what about the kettle?", and searching for those words alone found nothing useful.
Retrieval quality is usually the biggest lever in a RAG system. Today: chunking well, reranking, rewriting questions, and measuring retrieval properly. Season Five, Module Eighteen, stop two: better retrieval.
1:01Chunking: where you cut matters
Chunking means splitting documents into passages small enough to retrieve precisely. Brightcart's policy handbook is about twelve thousand tokens. Cut into two-hundred-token chunks, it becomes sixty chunks. Five-hundred-token chunks with fifty tokens of overlap: twenty-seven. Thousand-token chunks with a hundred tokens of overlap: fourteen. There's a trade-off. Small chunks match questions precisely, but rules can get separated from their exceptions. Large chunks keep more context together, but each one covers several topics, which blurs its embedding, and they add irrelevant text and cost to the prompt.
Two simple improvements help a lot. Overlap repeats a little text at the edges, so a sentence near a boundary appears in both neighbouring chunks. And structure-aware chunking cuts along the document's natural seams: headings, sections and list items, keeping each rule together with its exceptions, and never splitting a sentence.
2:08Context and metadata for chunks
A chunk on its own can lose its meaning. "Report within thirty days": report what? Under which policy? So we enrich each chunk with its context: the document title, the section heading, perhaps a one-sentence description of where it fits, generated automatically. Now both keyword and vector search have more to go on. And we attach metadata: product category, region, date and policy version. Then we can filter, searching only the current version of the policy, for the customer's region. That also prevents a common and embarrassing failure: confidently quoting an outdated policy.
2:49Reranking: retrieve many, keep a few
To fix the second failure, the right passage ranked fifth, we split retrieval into two stages. First, fast retrieval fetches a generous shortlist, say thirty candidates, focused on not missing anything. Then a reranker carefully reorders them, and only the top three to five are sent to the model. Why is the reranker more accurate? Embedding search turns the question and each passage into vectors separately, which is fast because passage vectors can be prepared in advance, but the two never really "read" each other.
A reranker, called a cross-encoder, reads the question and a passage together, with attention flowing between them, and outputs a relevance score. It's far too slow to run on millions of chunks, but perfect for re-checking thirty. In Dev's example, the passage ranked fifth moves up to first.
3:46Query rewriting
The third failure: the customer's follow-up, "And what about the kettle?" On its own, that question makes no sense to a search engine. So before retrieving, a small model rewrites it into a standalone question, using the conversation so far: "What is Brightcart's policy for a kettle that arrived damaged?" Now retrieval works. Query rewriting can also fix typos, expand abbreviations, split a question with several parts into separate searches, or generate a few different phrasings and merge their results. Another trick for vague questions: have the model write a short hypothetical answer, and search with that, since answers often look more like the documents than questions do.
4:33Retrieval metrics: precision, recall, MRR, nDCG
To improve retrieval, measure it. Build an evaluation set of questions, each labelled with the passages that should be found. Suppose for one question the relevant passages are P-one and P-two, and the retriever returns P-four, P-one, P-three, P-two. Precision at one is zero: the top result wasn't relevant. Precision at two is a half. Recall at two is a half: only one of the two relevant passages made the top two. Recall at four is one. The mean reciprocal rank is a half, since the first relevant passage appears at position two.
And n-D-C-G, a score that rewards relevant passages near the top, comes out at about zero point six five, where one would be a perfect order. For RAG, the most important of these is usually recall at k, for the number of passages you actually send. If the right passage isn't retrieved, the model never sees it.
5:36Evaluating the whole RAG system
For the whole RAG system, evaluate each link in the chain. Context relevance: did retrieval bring back the right passages? Groundedness: is every claim in the answer supported by those passages? And answer quality: is it correct and helpful? Each combination points to a different fix. Bad retrieval means improving chunking, search or reranking. Good retrieval but ungrounded answers means improving the prompt or the model. Good retrieval and grounded answers that are still wrong usually means the knowledge simply isn't in the documents, and someone needs to write it.
6:15Beyond plain text: SQL, images, tools
Not all knowledge is in paragraphs. For questions about numbers in a database, like how many orders shipped late last week, it's better to have the model write a database query, run it safely, read-only, and put the result into the context. For images, multimodal embeddings, like the CLIP model from episode forty-eight, can find product photos from a text description. And for a specific customer's order, it's best not to search at all, but to fetch the record directly through the order system. That's a tool call, and tools are where we're heading next.
6:55Try it yourself: count the chunks
Let's chunk the twelve-thousand-token handbook again, this time into three-hundred-token pieces with thirty tokens of overlap. How many chunks? Pause. Each new chunk moves forward two hundred and seventy tokens, three hundred minus the thirty of overlap. So it takes forty-five chunks to cover the handbook. Smaller chunks match questions more precisely, but each carries less surrounding context; larger chunks carry more context, but also more irrelevant text. The right size is something you measure, not guess.
7:36What reranking did to the metrics
Before reranking, the ranking was P4, P1, P3, P2, and the first relevant passage sat at rank two. After a reranker, it's P1, P4, P2, P3. What happens to the metrics? Pause. Precision at one jumps from zero to one: the top result is now relevant. The reciprocal rank doubles to one, and the ranking score rises from zero point six five to zero point nine two. Both relevant passages now appear in the top three. Since the model tends to lean on the first passages it sees, putting the right one at the top matters a lot.
8:22The reranking budget
Reranking costs time, so it needs a budget. Brightcart retrieves thirty candidates cheaply, then a cross-encoder reads each question-passage pair together and keeps the best four. If each pair takes about five milliseconds, that's fifteen hundredths of a second before the model even starts writing. The team tunes it: fewer candidates means faster, but risks missing the right passage; pairs can be processed in batches on a GPU; and simple lookups, like an order number, skip reranking entirely.
8:59Contextual chunks, by example
Here's why context matters for chunks. On its own, a chunk saying "this applies within thirty days, except for items in clause four" is almost useless: what applies? Before indexing, Brightcart adds the document title, the section heading and a one-line summary: "Returns policy, damaged items: customers may claim for damaged items." Now the chunk is easier to find for questions about damage, and the model can understand it when it arrives.
9:31Rewrite the follow-up question
A customer says their kettle arrived with a cracked lid. After the assistant replies, they ask: "How long do I have?" What should the system search for? Pause. Searching for "how long do I have" on its own finds nothing useful: it could mean anything. A query-rewriting step uses the conversation to turn it into a standalone question: "How long do I have to report a damaged kettle?" Now retrieval finds the damaged-items policy straight away. Follow-up questions are where many retrieval systems quietly fail.
10:11Metadata filters
Metadata can make retrieval much sharper. Each Brightcart chunk is tagged with its product category, delivery zone, document type and effective date. When a customer asks about kettle warranties, the search is filtered to kettle policies that are currently in force, and delivery questions are filtered to the customer's delivery zone. Fewer candidates, and better ones. But be careful: a wrong filter silently hides the right answer, so filters need logging and testing just like everything else.
10:46Building a retrieval test set
To improve retrieval, measure it on its own. Brightcart's agents take a hundred and fifty real customer questions and mark which chunks contain each answer. Now every change, a different chunk size, a new embedding model, a filter or a reranker, can be scored with recall at five, reciprocal rank and ranking quality. Retrieval experiments are quick and cheap, because no text needs to be generated, so the team can try many configurations in an afternoon.
11:18Tables and images in documents
Real documents aren't just paragraphs. Brightcart's manuals contain warranty tables, and naive text extraction can scramble their columns into nonsense. A better pipeline extracts each table as structured rows, then turns each row into a readable sentence: "Steel kettle: two-year warranty, faults covered, accidental damage excluded." Diagrams can be described by a vision-language model, and the description indexed. If the retriever can't read it, the assistant can't use it.
11:51Retrieval or generation failure?
The assistant tells a customer they have fourteen days to report damage. The policy says thirty. Is that a retrieval failure or a generation failure? Pause and think about how you'd find out. Look at what was retrieved. If the thirty-day passage wasn't among the chunks, retrieval failed, and the fixes are in chunking, query rewriting or filters. If it was there and the model still said fourteen, generation failed, and the fixes are in the prompt, citations or a verification step. Logging the retrieved chunks with every answer turns this from guesswork into a two-minute check.
12:36Myth vs Fact
Myth: if a RAG system gives wrong answers, use a bigger model. Fact: very often the problem is retrieval: the right passage was never found. Measure retrieval first, and fix chunking, metadata, search, reranking and query rewriting before blaming the model.
12:55Recap
Let's recap. Chunk documents along their natural structure, with some overlap, keeping rules with their exceptions. Enrich each chunk with its context, and filter by metadata like version and region. Retrieve generously, then rerank with a cross-encoder and send only the best few passages. Rewrite follow-up questions into standalone ones. And measure retrieval with precision, recall, M-R-R and n-D-C-G, then evaluate groundedness and correctness for the whole system. One sentence to remember: if it isn't retrieved, it can't be used, so measure the search first.
13:37Next: AI agents
Mission complete. Brightcart's retrieval now keeps rules and exceptions together, filters out old policy versions, reranks the shortlist, understands follow-up questions, and is measured on every change. Next, a big step: from an assistant that only answers, to one that does things. Checking an order's status, starting a return, booking a courier. Agents: giving models tools, and the ability to plan. See you on the map.