Skip to content

Learn RAG

A short guide to read before (or alongside) the labs. The README has setup, the file list and rules of thumb. This page explains how the pieces fit, which decisions matter, and where to go deeper.

1. What RAG is, and why it exists

RAG (retrieval-augmented generation) means: before the model answers, find the few passages in your documents that answer the question and put them in the prompt. The model then answers from your content, not from memory.

The problem it solves: an LLM only knows its training data, frozen at a date. It has never seen your return policy, your credit terms or your datasheets. There are three ways to fix that:

Approach Good for The catch
Paste all documents into every prompt A handful of short documents Slow and costly per question, and answers get worse as the prompt grows
Fine-tune the model on your documents Teaching style or format Expensive, stale after every edit, no citations, can't "un-learn" a deleted policy
RAG Knowledge that changes and must be cited Answers are only as good as retrieval

Analogy: RAG is an open-book exam. The model doesn't memorise your textbook; for each question it gets the right pages open in front of it, and it can point to the page it used.

When you need it: for text that explains (policies, manuals, specs, FAQs). For live data that changes by the minute (stock, prices, order status), use tool calling from ../llm-api. For questions that count or add up rows (revenue, who owes what), ask the database (labs 12 and 13). Real assistants use all three.

2. The mental model

RAG has two phases: ingest docs into a vector store offline, then per question search the store and put the top chunks in the prompt

RAG has two phases that share one vector store.

  • Ingest runs offline whenever documents change: cut each document into chunks, turn each chunk into a vector, store it.
  • Query runs per question: turn the question into a vector with the same model, find the closest chunks, paste them into the prompt, and ask the LLM to answer only from them.

Analogy: ingest is building a library's catalog once. Query is looking up the right shelf for each visitor's question. You'd never rebuild the catalog for every visitor, and you'd never hand a visitor the whole library.

The one idea to hold on to: the model only sees what search hands it. If the right chunk is not retrieved, no prompt, model or temperature fixes the answer. That is why most of the labs, and most real RAG work, are about retrieval, not generation.

In code: ingest, retrieve, generate.

import chromadb
import door

col = chromadb.PersistentClient("store").get_or_create_collection("b2b_docs")
chunks = ["Bulk orders have a 15-day return window and a 10% restocking fee.",
          "Standard delivery takes 5 to 7 business days."]
col.add(ids=["r1", "s1"], documents=chunks,
        embeddings=door.embed(chunks).vectors)                                    # ingest

q = "Can I return 600 bolts?"
hits = col.query(query_embeddings=door.embed([q]).vectors, n_results=1)
context = hits["documents"][0][0]                                                 # retrieve
prompt = f"Answer only from this context:\n{context}\n\nQuestion: {q}"
print(door.chat([{"role": "user", "content": prompt}]).text)                     # generate

That is the whole idea. rag.py is the same flow, split into small functions, with the details that matter in practice: chunking by headings, metadata, re-ingest without duplicates, hybrid search and citations.

3. The labs in four stages

Stage 1: the core loop (01–04)

Build the pipeline above by hand, one step per script.

Script What you see Key takeaway
01_embeddings.py Similar meaning gives similar vectors; product codes give flat scores Vectors understand paraphrase, not SKUs
02_chunking.py Fixed-size cuts vs heading-aware chunks Chunk by the document's structure, keep "Title > Section" on top
03_ingest_and_search.py Chroma store, re-ingest only changed docs Indexing is a pipeline you re-run, not a one-time job
04_basic_rag.py The exact prompt, answers with citations, "I don't know" RAG is "just" a prompt; tell the model what to do when the answer is missing

Stage 2: better retrieval (05–08)

The retrieval funnel: rewrite the follow-up, run vector and keyword search inside a metadata filter, fuse with RRF, rerank to the top 3, then build the prompt

Each script improves one step of the query path. Read the diagram left to right:

  • 07 Rewrite. "And for bulk?" retrieves nothing. One LLM call turns it into a full question using the chat history.
  • 05 Hybrid search. Vectors for meaning, BM25 for exact codes (HARNESS-6P, IS 2925). Merge by rank with RRF, because the two scores are on different scales.
  • 06 Filters. Restrict by tier or doc type inside the database query. A chunk that is never retrieved cannot leak to the wrong customer.
  • 08 Rerank. Search is fast but rough. Fetch 10, let a smarter judge read each one with the question, and keep the best 3.

Purple boxes are extra LLM calls. Each one adds latency, so add them only when the evaluation says they help.

Stage 3: measure, then let the model drive (09–10)

Agentic RAG: the model calls search_docs, get_stock and get_price in a loop, then answers with sources that are validated in code

  • 09 Evaluation. A golden set of real questions, each with the section that holds the answer. hit@k and MRR tell you if a change helped. In our run, hybrid search scored lower than vector-only on this small set. That is the lesson: measure, don't assume.
  • 10 Agentic RAG. Retrieval becomes a tool next to live stock and price tools. The model decides what to call and can search again with a better query. In our run it chose the right tools every time, but invented file citations for tool results. Validate citations in code.

Stage 4: real files and real tables (11–13)

  • 11 Messy documents. A PDF datasheet whose table breaks across pages, an Excel sheet with merged cells, a scan. Read naively, a table row loses its column names and the model guesses which number is the shear load. Read by structure, each row is one chunk that answers on its own. Scans are flagged, not silently skipped.
  • 12 Talk to your data. "Revenue in September" is a SUM, not a passage. The model writes SQL, code runs it, the model explains the rows. Score it by running it against gold queries. Writing the business rules down ("revenue leaves out cancelled orders") matters more than the model.
  • 13 SQL guardrails (Before you ship). A read-only connection, the SQL parsed and allow-listed, every customer table rewritten to that customer's rows in code, time and row caps. Then the safer option: a semantic layer, where the model picks a metric and code writes the SQL.

4. Decisions your team will face

Decision Start with Change when
Chunking By heading, with "Title > Section" on each chunk Sections are very long (split by sentence), or content is tabular (one row per chunk)
Search Hybrid (vector + BM25, RRF) Your golden set shows vector-only is as good and queries never contain codes
Chunks in the prompt (k) 3 to 5 Rarely more. Long contexts bury the answer ("lost in the middle"). Rerank instead
Reranking Off The right chunk is in the top 20 but not the top 3. Use a cross-encoder, not the chat LLM
Access control Metadata filter in the DB query, bound from the session Never relax this. Never filter in the prompt
Embedding model nomic-embed-text Queries in Hindi or mixed language, or eval scores plateau. Changing it means re-embedding everything
Pipeline vs agent Fixed pipeline (04) Questions mix documents with live data, or need several lookups (10)
PDF and Excel parsing pdfplumber and openpyxl, one chunk per table row (11) Scans, multi-column layouts or many formats: a layout parser (Docling, Unstructured) or a vision model
Questions over tables Text-to-SQL behind the guards for internal analysts (12, 13); a semantic layer for customers Dozens of tables: retrieve the relevant tables first (schema linking) instead of sending the whole schema

5. What the labs don't cover

The labs use ten markdown files and one laptop. Production adds:

  • Ingestion at scale. OCR for scans, complex layouts and images (lab 11 only flags scans); scheduled sync from Confluence or SharePoint; stable chunk IDs so an edit doesn't renumber everything.
  • Permissions from the source. Real ACLs per document, carried into chunk metadata, and deletes that propagate (DPDP Act requests).
  • Search infrastructure. Millions of chunks need an ANN index in a real engine (pgvector, OpenSearch, Vertex AI Vector Search), with the keyword side handled by a proper analyzer.
  • Prompt injection in documents. A retrieved chunk can contain instructions. Treat retrieved text as data.
  • Evaluation in production. Log questions, retrieved chunks and answers; grow the golden set from real failures; add answer-level checks (LLM-as-judge).
  • Cost and latency. Embedding cost at ingest, rerank latency per query, caching of frequent questions.

Check yourself

Answer each in a sentence or two, without looking. If one is hard, reread the section in brackets.

  1. A RAG answer is wrong. Why should you check retrieval before you change the prompt or the model? (section 2)
  2. Why does vector search alone struggle with a question that names a product code like HARNESS-6P? (section 3, labs 01 and 05)
  3. Why must the customer-tier filter run inside the database query and not as a rule in the prompt? (section 3, lab 06)
  4. A teammate adds query rewriting and reranking because "more steps must help". What would you ask for before you accept the change, and why? (section 3, lab 09)
  5. A buyer asks "What was our revenue in September?" Why is that a poor fit for searching documents, and what would you use? (sections 1 and 3, lab 12)

Same pattern, other industries

The labs use a B2B catalog, but the pattern carries across domains. What changes is the data and the rules around it.

Industry Use case What changes
E-commerce (B2C) Product Q&A on the product page, from manuals, specs and reviews Reviews are opinions, not facts: tag the source type and keep them apart from specs
Banking Relationship-manager assistant over RBI circulars and internal credit policy Documents have effective dates: retrieve the version in force, and cite the exact clause
Insurance Claims assessor checks a claim against the policy wording and endorsements Each policyholder has their own documents: filter by policy number, and exclusions matter more than cover
Manufacturing Shop-floor troubleshooting from SOPs, maintenance logs and machine manuals Scanned PDFs, tables and part numbers: needs OCR and hybrid search; queries may be in Hindi

Going deeper: advanced RAG topics

Once the labs make sense, these are the topics worth searching for. Each one fixes a specific weakness of the basic pipeline.

Topic What it solves Search for
Contextual retrieval Chunks lose meaning when cut from their document "contextual retrieval", "contextual chunk headers"
Parent-child (small-to-big) retrieval Small chunks match well but give the model too little context "parent document retriever", "small-to-big retrieval"
Query expansion and HyDE Short or vague questions retrieve poorly "HyDE hypothetical document embeddings", "multi-query retrieval"
Cross-encoder reranking LLM reranking (08) is slow and costly "cross-encoder reranker", "bge-reranker"
Late interaction (ColBERT) One vector per chunk is too coarse "ColBERT late interaction", "multi-vector retrieval"
Multimodal and document RAG PDFs with tables, drawings and scans "ColPali", "document layout parsing for RAG"
GraphRAG Questions that connect many documents ("which suppliers affect these SKUs?") "GraphRAG", "knowledge graph RAG"
Self-correcting RAG The model can't tell when retrieval failed "corrective RAG CRAG", "Self-RAG"
Fine-tuned embeddings Domain terms (steel grades, IS standards) embed poorly "fine-tune embedding model sentence-transformers"
Semantic caching The same questions cost the same every time "semantic cache LLM"
Answer-level evaluation hit@k says nothing about answer quality "RAG faithfulness evaluation", "LLM as judge"
Text-to-SQL at scale Many tables, vague column names, joins the model gets wrong "schema linking text-to-SQL", "BIRD benchmark", "semantic layer dbt Cube"

Before moving on, try these: the exercises in PRACTICE.md: weighted fusion in hybrid search, checking citations in code, a golden set measured before and after one change, then build a seller agreement assistant yourself.

Next topic: MCP servers. Example 10 already has search_docs as a tool; an MCP server exposes it to any client (Claude Desktop, IDEs) without changing the RAG code.