Skip to content
LLM application engineering Core 26 min read

Retrieval-augmented generation

Retrieval-augmented generation (RAG) answers a question by first fetching the passages most likely to contain the answer, then asking a language model to answer from those passages, with citations. The one idea: separate knowing where to look (retrieval, which you can measure and fix) from reading and explaining (generation), and make the second depend on the first.

10,000 ft

A language model's knowledge is frozen into its weights at training time: it is compressed, sometimes wrong, out of date the day it ships, and blind to your private data. RAG gives the model an external, editable memory. The idea came from research on open-domain question answering (REALM and the 2020 RAG paper by Lewis et al.), and became the default architecture for enterprise assistants, support bots, documentation search and research tools once instruction-tuned models could read a few pages of context reliably. It sits on embeddings and vector search for retrieval and on prompt engineering for grounded generation; it is extended by advanced RAG (hybrid search, re-ranking, graphs), by agents that decide when and what to retrieve, and it competes with long context and fine-tuning. Its central lesson generalises to all LLM engineering: put facts in the context, not in the weights, and you can cite, update and audit them.

2,000 ft

Offline you build an index; online you run retrieve-then-read.

  1. Ingest: parse sources (HTML, PDF, tickets, tables) into clean text with metadata.
  2. Chunk and enrich: split into passages small enough to be specific and large enough to be self-contained; attach titles, dates, permissions, and optionally a short context summary.
  3. Index: embed chunks for semantic search and index their words for keyword search.
  4. Retrieve: (optionally rewrite the question, then) fetch the top-\(k\) chunks, fusing dense and keyword results and re-ranking the shortlist.
  5. Assemble: order, deduplicate and label the chunks within a token budget.
  6. Generate: instruct the model to answer only from the provided passages, cite them, and say when they do not contain the answer.
  7. Evaluate both halves: retrieval (did the right passage arrive?) and generation (was the answer faithful to it, and did it answer the question?).

RAG: an index built offline, a retrieve-then-read loop online
RAG: an index built offline, a retrieve-then-read loop online. ingest parse, clean, chunk + enrich metadata, context, index vectors + keywords, question, rewrite query (optional), retrieve top-k (+ re-rank), assemble context ordered, cited, budgeted, generate grounded, with citations, check faithful? abstain?RAG: an index built offline, a retrieve-then-read loop online. ingest parse, clean, chunk + enrich metadata, context, index vectors + keywords, question, rewrite query (optional), retrieve top-k (+ re-rank), assemble context ordered, cited, budgeted, generate grounded, with citations, check faithful? abstain?

Ground level

Why retrieve at all

Three properties of a model's parametric memory (its weights) make it a poor database:

  • It is stale. Training data has a cutoff; your price list changed yesterday.
  • It is incomplete and private-blind. It never saw your contracts, tickets or wiki.
  • It is unattributable. A fact recalled from weights has no source to show the user, and no way to tell recall from fabrication.

A non-parametric memory (an index of documents) fixes all three: update a document and the next answer changes; add a private corpus without training; show the passage behind every claim. The 2020 paper that named the technique, Lewis et al., combined a pre-trained seq2seq generator with a dense vector index of Wikipedia searched by a neural retriever, set the state of the art on three open-domain QA tasks, and found generations "more specific, diverse and factual" than a parametric-only baseline.

RAG is not the only lever, and choosing the wrong one is the most expensive mistake in this area.

Which lever? Match the fix to what is missing
Which lever? Match the fix to what is missing. What is the model missing?, knowledge facts it never saw, private or fresh data, fits in context? (< ~200k tokens, stable), long context + prompt caching, RAG retrieve per question, behaviour format, tone, a skill, prompt + examples, fine-tune (SFT / LoRA), computation exact numbers, live state, tools / code model routes and explains, yes, no, first, Which lever? Match the fix to what is missing. What is the model missing?, knowledge facts it never saw, private or fresh data, fits in context? (< ~200k tokens, stable), long context + prompt caching, RAG retrieve per question, behaviour format, tone, a skill, prompt + examples, fine-tune (SFT / LoRA), computation exact numbers, live state, tools / code model routes and explains, yes, no, first,
  • Long context instead of retrieval. If the whole corpus fits in the context window and does not change often, put all of it in the prompt and cache it. Anthropic's contextual retrieval write-up suggests exactly this for knowledge bases under about 200,000 tokens. Li et al. (2024) compared the two directly: when resourced sufficiently, long-context models "consistently" outperformed RAG on average, but RAG's "significantly lower cost remains a distinct advantage"; their Self-Route method sends each query to RAG or long context based on the model's own judgement. Long inputs also degrade unevenly (prompt engineering), so retrieval still helps quality, not only cost, as contexts grow.
  • Fine-tuning instead of retrieval. Fine-tuning reliably changes behaviour (format, style, a narrow skill). It is a poor way to add facts: they are absorbed unreliably, cannot be cited, and every update means retraining.
  • Tools instead of retrieval. If the answer is a computation over live, structured data (a balance, an order status, a projection), do not retrieve text about it; call code that computes it (structured outputs and tools).

Ingestion: garbage in, confident garbage out

Most production RAG failures start before any model runs. PDFs lose reading order and turn tables into soup; HTML brings navigation menus and cookie banners; scanned documents need OCR; the same policy exists in three versions. Practical rules: extract structure (headings, lists, tables) and keep it as Markdown; drop boilerplate; keep one current version and record its date; attach metadata you will filter on (product, region, audience, permission group); and keep a stable id per source so citations survive re-indexing.

Chunking

The retriever returns chunks, so chunks are the unit of both recall and context cost. A chunk must be specific enough that its embedding is about one thing (a 20-page document embedded as one vector is about everything and matches nothing well) and self-contained enough that it still makes sense when read alone ("It takes 5–7 days" is useless without "Card refunds…").

Common strategies, from simplest to most deliberate:

Strategy How Good for Weakness
Fixed tokens + overlap Every \(n\) tokens, overlapping by \(o\) Quick baselines Cuts mid-sentence, duplicates text
Recursive / structural Split on headings, then paragraphs, then sentences, up to a size limit Docs with structure Uneven sizes
Semantic Split where consecutive sentence embeddings change most Unstructured prose More compute, tuning
Parent–child Retrieve small chunks, send their larger parent section to the model Precise retrieval, full context Two-level index
Contextual Prepend a generated 1–2 sentence summary of where the chunk sits in its document Ambiguous chunks One LLM call per chunk at index time

Measured evidence beats rules of thumb. Chroma's 2024 chunking evaluation compared strategies on the same corpora and found choices moved recall by up to 9%. A plain recursive splitter at 200 tokens with no overlap was consistently strong, while 800-token chunks with 400 tokens of overlap (the setting the authors assumed was OpenAI's default) had slightly below-average recall and the poorest precision, because large overlapping chunks fill the context with redundant text. Treat chunk size as a hyperparameter and tune it on your own eval set.

fixed size + overlap## Refunds · Refunds go to the original method. Card refunds take 5–7 days. ## Limits · New accounts…← chunk 2 straddles two topicsstructure-aware (split on headings, then sentences)## Refunds · Refunds go to the original method. Card refunds take 5–7 days. ## Limits · New accounts…Each chunk is about one thing and carries its heading, so its embedding and its citation are both clean.
Chunk boundaries decide what a vector is "about". Overlap protects against cutting an answer in half, at the cost of duplicate tokens; boundaries that follow the document's own structure usually do better.

Contextual enrichment attacks the self-containment problem directly. Anthropic's 2024 contextual retrieval prepends to each chunk 50–100 tokens of model-written context ("This chunk is from the refunds section of the help centre; it concerns card payments…") before embedding and keyword-indexing it. On their evaluation, the top-20 retrieval failure rate fell from 5.7% to 3.7% with contextual embeddings (a 35% reduction), to 2.9% when contextual BM25 was added (49%), and to 1.9% with re-ranking on top (67%). With prompt caching, they estimated the one-off cost at about USD 1.02 per million document tokens.

Retrieval: dense, sparse and hybrid

Dense retrieval (embeddings) matches meaning: "get my money back" finds "refunds". Sparse retrieval, classically BM25, matches words, weighting rare words more and saturating repeated ones. They fail differently. Dense retrieval blurs exact identifiers, numbers, rare names and negation; BM25 misses paraphrase and synonyms entirely. BEIR found BM25 a "robust baseline" that many dense models failed to beat out of domain (embeddings and vector search). Production systems therefore run both and fuse the ranked lists (reciprocal rank fusion is the usual, parameter-light method), then re-rank the top 50–100 with a cross-encoder. These steps are the subject of advanced RAG; the Build it section shows the keyword half failing and being repaired.

Query transformation often matters as much as the index. Users write fragments, follow-ups ("and for UPI?") and questions in the vocabulary of their problem, not of your documents. Rewriting the question into a standalone, explicit query, or generating a hypothetical answer and searching with its embedding (HyDE, Gao et al., 2022), closes much of that gap at the cost of one extra model call.

Assembling the context and generating

The generator sees exactly what you assemble, so assembly is prompt engineering:

  1. Budget tokens. \(k\) chunks of \(c\) tokens cost \(kc\) input tokens per call (8 × 400 = 3,200). More chunks raise recall and also add distractors; Chroma's context rot study found that "even a single distractor reduces performance relative to the baseline".
  2. Order deliberately. Put the strongest evidence first (or first and last, given the lost-in-the-middle effect), group chunks from the same source, and drop near-duplicates.
  3. Label every chunk with an id and source so the model can cite it and you can verify the citation.
  4. Instruct grounding and abstention. "Answer only from the documents. Cite like [2]. If the documents do not contain the answer, say so." A system that cannot say "I don't know" will answer from its weights when retrieval fails, which is the failure RAG was meant to prevent.
  5. Verify citations in code where you can: does the cited chunk exist, and does it contain the quoted figure or name?

A grounded prompt in the shape the Build it code produces:

Answer using only the documents. Cite like [1]. If they do not contain the answer, say you don't know.
<documents>
<doc id="1" source="refunds">Refunds are issued to the original payment method. Card refunds take 5 to 7 working days.</doc>
<doc id="2" source="kyc">To verify your account, upload a PAN card and complete a video check. Verification usually takes one working day.</doc>
</documents>
Question: how long does a card refund take

Document 2 is a distractor that scored well on "card" and "take". The instruction and the labels are what let the model ignore it.

How RAG fails

Barnett et al. (2024) catalogued seven failure points from three production case studies. They map onto the pipeline, which tells you where to look:

Where a RAG answer goes wrong (Barnett et al. 2024)
Where a RAG answer goes wrong (Barnett et al. 2024). corpus, retriever, context window, generator, answer, FP1 missing content, FP2 missed top-ranked FP3 not in context, FP4 not extracted, FP5 wrong format FP6 wrong specificity FP7 incompleteWhere a RAG answer goes wrong (Barnett et al. 2024). corpus, retriever, context window, generator, answer, FP1 missing content, FP2 missed top-ranked FP3 not in context, FP4 not extracted, FP5 wrong format FP6 wrong specificity FP7 incomplete
  1. Missing content: the answer is not in the corpus, and the system answers anyway.
  2. Missed the top-ranked documents: the answer exists but ranked below \(k\).
  3. Not in context: retrieved, but dropped when results were consolidated to fit the budget.
  4. Not extracted: in the context, but the model failed to use it (noise or contradictions).
  5. Wrong format: ignored the requested table or list.
  6. Incorrect specificity: too general or too specific for the need.
  7. Incomplete: right but missing parts that were available.

Their two takeaways are worth memorising: validation of a RAG system "is only feasible during operation", and robustness "evolves rather than designed in at the start". Log every query, its retrieved chunks and the answer, and review failures weekly.

Evaluating RAG

Evaluate the two halves separately, then together.

Question Metric Needs
Did the right passage arrive? recall@k, MRR, nDCG on labelled query → chunk pairs Gold relevant chunks
Is the answer supported by the context? Faithfulness / groundedness: share of claims entailed by retrieved text Judge (LLM or human)
Does it answer the question? Answer relevance, correctness against a reference Reference answers or a judge
Was retrieval precise? Context precision: share of retrieved chunks that were relevant Judge or labels
Does it abstain when it should? Abstention rate on unanswerable questions Unanswerable test cases

RAGAS (Es et al., 2023) popularised reference-free versions of these (faithfulness, answer relevance, context precision and recall) computed with LLM judges; ARES (Saad-Falcon et al., 2023) fine-tunes small judges and uses a few hundred human labels to correct their errors statistically. Judges need calibrating against human labels before you trust them (evals in practice). Benchmarks show how much headroom remains: on CRAG (Yang et al., 2024), most advanced LLMs alone reached at most 34% accuracy, straightforward RAG lifted that only to 44%, and state-of-the-art industry solutions answered 63% of questions without hallucination.

RAG over structured data: retrieve named facts, not text

Finny's Jarvis answers questions about a member's own FIRE plan, and it does retrieve, but not by vector search over text. A routing call picks named slices of the plan (such as the FIRE age or the year-by-year projection) and one deterministic operation to run over them; code fetches those slices from the backend and computes the result; the model is then given a labelled fact table and only phrases the answer. A deterministic gate checks every number in the reply against the computed facts and repairs, trims or refuses an answer whose figures it cannot trace. It is the RAG pattern (retrieve, then generate from what was retrieved, then verify grounding) with the retrieval made exact because the data is structured, and with faithfulness checked by code rather than by a judge. The team's own record is honest about the limit: the gate guarantees faithful, not correct, so correctness is measured separately by graders. See the Jarvis case study.

History

Retrieval and generation met through open-domain question answering. Classic QA systems retrieved with TF-IDF or BM25 and then extracted a span. In 2020, three papers made retrieval neural and end-to-end. REALM (Guu et al.) pre-trained a language model together with a latent retriever over Wikipedia, back-propagating through the retrieval step, and beat previous open-QA systems by 4–16 points. DPR (Karpukhin et al.) showed a simple dual encoder beat BM25 for passage retrieval. RAG (Lewis et al.) coupled DPR with a BART generator and gave the technique its name. Fusion-in-Decoder (Izacard and Grave) encoded each passage separately and let the decoder attend over all of them, and found accuracy kept improving as more passages were retrieved: generators are good at aggregating evidence.

Scale followed. RETRO (Borgeaud et al., 2021) retrieved from a 2-trillion-token database during language modelling and matched GPT-3 and Jurassic-1 on the Pile with 25× fewer parameters. Atlas (Izacard et al., 2022) reached over 42% on Natural Questions from only 64 examples, beating a 540B-parameter model by 3 points with 50× fewer parameters. These results made the case that knowledge can live outside the weights. From 2023, with instruction-tuned chat models able to read retrieved passages without any joint training, RAG became an application pattern rather than a model architecture: an off-the-shelf retriever plus an off-the-shelf LLM and a prompt. Later work such as Self-RAG (Asai et al., 2023) trained models to decide when to retrieve and to critique their own use of passages, and agentic systems now treat retrieval as one tool among many (agents).

First principles

Why should retrieve-then-read beat a bigger model? Because of what each component is good at. Retrieval is a recall problem over a huge, changing corpus, solved cheaply by indexes. Reading is a comprehension problem over a small context, which is exactly what language models are trained on. Asking the weights to do both forces a model to store every fact (capacity grows with the corpus) and to recall it without a pointer (no provenance). Splitting the problem lets each part scale and be fixed independently.

That split also creates the system's central dependency, which you can write as an identity. Let \(R\) be the event "a passage containing the answer is in the context" and \(C\) the event "the answer is correct". Then

\[ P(C) = P(R)\,P(C\mid R) + \big(1-P(R)\big)\,P(C\mid \neg R). \]

With retrieval recall \(P(R)=0.85\), a generator that uses good context well, \(P(C\mid R)=0.90\), and a model that occasionally guesses right from its weights, \(P(C\mid\neg R)=0.20\): \(P(C)=0.765+0.030=0.795\). Raising the generator to 0.95 gives 0.838. Raising retrieval recall to 0.95 instead gives \(0.855+0.010=0.865\). Retrieval improvements often pay more than generator improvements, and the \(\neg R\) branch is where hallucinations live: a well-built system turns that branch into "I don't know" rather than a guess, trading a little \(P(C)\) for much lower \(P(\text{confidently wrong})\).

Why not retrieve more and let the model sort it out? Because \(P(C\mid R)\) is not constant in \(k\): recall rises with \(k\), but each extra passage is a potential distractor and costs tokens, so \(P(C\mid R)\) falls. The best \(k\) balances the two, and it moves when you change the retriever, the re-ranker or the model, so it has to be measured, not assumed.

The maths

The probabilistic RAG model. Lewis et al. treat the retrieved passage \(z\) as a latent variable. A retriever with query encoder \(\mathbf q(x)\) and passage encoder \(\mathbf d(z)\) defines

\[ p_\eta(z\mid x)\ \propto\ \exp\big(\mathbf d(z)^\top\mathbf q(x)\big), \]

truncated to the top-\(k\) passages. RAG-sequence uses one passage for the whole output and marginalises:

\[ p(y\mid x)\ \approx \sum_{z\in\text{top-}k} p_\eta(z\mid x)\prod_{t} p_\theta(y_t\mid x,z,y_{<t}). \]

RAG-token may draw on a different passage for each token:

\[ p(y\mid x)\ \approx\ \prod_{t}\ \sum_{z\in\text{top-}k} p_\eta(z\mid x)\,p_\theta(y_t\mid x,z,y_{<t}). \]

Training maximises \(\log p(y\mid x)\) over question–answer pairs, which updates the generator \(\theta\) and the query encoder \(\eta\) jointly; the passage encoder (and so the index) was kept fixed to avoid re-indexing. A worked example of RAG-sequence: two passages with retrieval probabilities 0.7 and 0.3, and generator probabilities for the correct answer of 0.9 and 0.2 given each, give \(p(y\mid x)=0.7\cdot0.9+0.3\cdot0.2=0.69\). The model hedges across evidence in proportion to how much it trusts each passage. Prompt-based RAG with a chat model does something cruder: it puts all \(k\) passages in one context and lets attention do the weighting.

BM25. For a query \(Q\) with terms \(q_1..q_n\) and a chunk \(D\) of length \(|D|\) in a collection of \(N\) chunks with average length \(\overline{|D|}\):

\[ \text{BM25}(D,Q)=\sum_{i=1}^{n}\text{IDF}(q_i)\cdot\frac{f(q_i,D)\,(k_1+1)}{f(q_i,D)+k_1\big(1-b+b\,\frac{|D|}{\overline{|D|}}\big)},\qquad \text{IDF}(q)=\ln\Big(1+\frac{N-n(q)+0.5}{n(q)+0.5}\Big), \]

where \(f(q,D)\) is the term's count in \(D\) and \(n(q)\) the number of chunks containing it. Three design choices are visible: rare terms weigh more (IDF); repeated terms saturate, approaching \(k_1+1\) (typically \(k_1\in[1.2,2]\)); and long chunks are penalised in proportion to \(b\) (typically 0.75), so a short chunk that matches one common word can outrank a relevant long one. The Build it output shows exactly that.

Reciprocal rank fusion. To merge ranked lists \(L_1..L_m\) (dense, sparse), score each chunk by

\[ \text{RRF}(d)=\sum_{j=1}^{m}\frac{1}{\kappa+\text{rank}_j(d)},\qquad \kappa\approx 60, \]

which needs no score calibration between retrievers, only ranks.

Retrieval metrics are those of the previous page: recall@k, MRR and nDCG, computed on labelled (query, relevant chunk) pairs.

Build it

A complete, if tiny, RAG retrieval stack in plain Python and NumPy: a fictional help-centre corpus, sentence-based chunking, BM25 from scratch, a labelled eval set, and the grounded prompt. Generation is left to whichever model you use; the point is to see retrieval succeed and fail measurably.

import re, numpy as np
DOCS = {  # a fictional payments app's help centre
 "refunds":  "Refunds are issued to the original payment method. Card refunds take 5 to 7 working days. "
             "UPI refunds usually arrive within 48 hours. You can track a refund under Activity.",
 "limits":   "New accounts can send up to 10,000 per day. Verified accounts can send up to 1,00,000 per day. "
             "Limits reset at midnight.",
 "kyc":      "To verify your account, upload a PAN card and complete a video check. "
             "Verification usually takes one working day. Verified accounts get higher limits.",
 "disputes": "If a merchant did not deliver, raise a dispute within 30 days of the payment. "
             "We contact the merchant and decide within 10 working days. Disputed money is held, not lost.",
 "fees":     "Sending money to friends is free. Card top-ups carry a 1.5 percent fee. "
             "There is no monthly fee.",
 "security": "We never ask for your PIN or OTP. If you shared an OTP, freeze your account from Settings "
             "and call support immediately.",
}
STOP = set("a an the to of and or is are be can do does i my you your we how what for there "
           "get under from not if within".split())
def stem(w):                      # a deliberately crude suffix stripper
    for suf in ("ing", "ily", "ed", "s"):
        if w.endswith(suf) and len(w) > len(suf) + 2:
            return w[: -len(suf)]
    return w
CLEAN = False
def tokens(t):
    ws = re.findall(r"[a-z0-9,.]+(?<![.,])", t.lower())
    return [stem(w) for w in ws if w not in STOP] if CLEAN else ws
def chunk(text, size=2):          # chunks of `size` sentences, no overlap
    s = re.split(r"(?<=\.)\s+", text)
    return [" ".join(s[i:i + size]) for i in range(0, len(s), size)]
chunks = [(doc, c) for doc, text in DOCS.items() for c in chunk(text)]
def index():
    global toks, N, avgdl, df
    toks = [tokens(c) for _, c in chunks]
    N, avgdl = len(toks), np.mean([len(t) for t in toks])
    df = {w: sum(w in t for t in toks) for w in {w for t in toks for w in t}}
def bm25(query, k1=1.2, b=0.75):
    q, scores = tokens(query), np.zeros(N)
    for i, t in enumerate(toks):
        for w in set(q) & set(t):
            idf = np.log(1 + (N - df[w] + 0.5) / (df[w] + 0.5))
            tf = t.count(w)
            scores[i] += idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * len(t) / avgdl))
    return scores
EVAL = [("how long does a card refund take", "refunds"), ("what is the daily sending limit", "limits"),
        ("is there a fee for card top-ups", "fees"), ("merchant never delivered my order", "disputes"),
        ("someone asked for my OTP", "security"), ("how do I get my money back", "refunds")]
REWRITE = {"how do I get my money back": "how do I get a refund"}   # what an LLM rewrite step might return
def evaluate(label, rewrite=False):
    index(); rr, hits = [], {1: 0, 3: 0}
    for q, gold in EVAL:
        q = REWRITE.get(q, q) if rewrite else q
        order = np.argsort(-bm25(q))
        rank = next(r for r, i in enumerate(order, 1) if chunks[i][0] == gold)
        rr.append(1 / rank); hits[1] += rank <= 1; hits[3] += rank <= 3
        if rank > 1: print(f"  miss: {q!r} -> top1 {chunks[order[0]][1]!r} (gold rank {rank})")
    print(f"{label:<34} recall@1 {hits[1]/len(EVAL):.2f}  recall@3 {hits[3]/len(EVAL):.2f}  MRR {np.mean(rr):.2f}")
evaluate("raw tokens")
CLEAN = True; evaluate("+ stop-words, stemming")
evaluate("+ query rewrite", rewrite=True)
def build_prompt(question, k=3):
    top = np.argsort(-bm25(question))[:k]
    ctx = "\n".join(f'<doc id="{j+1}" source="{chunks[i][0]}">{chunks[i][1]}</doc>' for j, i in enumerate(top))
    return (f"Answer using only the documents. Cite like [1]. If they do not contain the answer, "
            f"say you don't know.\n<documents>\n{ctx}\n</documents>\nQuestion: {question}")
print(build_prompt("how long does a card refund take", k=2))

Output:

  miss: 'what is the daily sending limit' -> top1 'Sending money to friends is free. Card top-ups carry a 1.5 percent fee.' (gold rank 7)
  miss: 'how do I get my money back' -> top1 'Verified accounts get higher limits.' (gold rank 4)
raw tokens                         recall@1 0.67  recall@3 0.67  MRR 0.73
  miss: 'how do I get my money back' -> top1 'Disputed money is held, not lost.' (gold rank 3)
+ stop-words, stemming             recall@1 0.83  recall@3 1.00  MRR 0.89
+ query rewrite                    recall@1 1.00  recall@3 1.00  MRR 1.00
Answer using only the documents. Cite like [1]. If they do not contain the answer, say you don't know.
<documents>
<doc id="1" source="refunds">Refunds are issued to the original payment method. Card refunds take 5 to 7 working days.</doc>
<doc id="2" source="kyc">To verify your account, upload a PAN card and complete a video check. Verification usually takes one working day.</doc>
</documents>
Question: how long does a card refund take

Three lessons in eleven chunks:

  • Surface form defeats keywords. "daily sending limit" shares no token with "send up to 10,000 per day … Limits" (sending ≠ send, limit ≠ limits) and matches "Sending money" in the fees chunk instead. Normalisation (stemming) fixes it.
  • Short chunks are over-rewarded. "Verified accounts get higher limits." is a one-sentence chunk left over by the splitter; it matches only the word "get", and BM25's length normalisation still ranks it first. Stop-word removal fixes this case; better chunking (no orphan sentences) fixes the cause.
  • Vocabulary mismatch needs meaning, not morphology. "money back" and "refund" share nothing. Stemming cannot help; a rewrite step (or dense retrieval, which would match them by meaning) does.

Things to try

  • Change chunk(text, size=2) to size=1 and size=4. Watch recall@1 and the size of the assembled prompt. Which failure from the list above does each setting cause?
  • Add dense retrieval with a real embedding model and fuse it with BM25 by reciprocal rank fusion. Does the "money back" query still need the rewrite?
  • Add an unanswerable question ("can I pay with crypto?") to EVAL, send the prompt to a model, and check that it abstains. Then remove the "say you don't know" sentence and try again.
  • Measure the end-to-end identity: for 30 questions, record whether the gold chunk was retrieved (\(R\)) and whether the answer was right (\(C\)). Estimate \(P(C\mid R)\) and \(P(C\mid\neg R)\) and decide which half to improve.

In practice

  • Build the eval set first: 50–200 real questions with the chunk(s) that answer them, plus 10–20 that the corpus cannot answer. Without it every change is a guess.
  • Measure retrieval before generation. If recall@k is 70%, no prompt will rescue the other 30%.
  • Start simple and add only what the evals justify: structural chunking, hybrid search, a re-ranker, query rewriting, contextual enrichment, in roughly that order of value for effort.
  • Enforce permissions at retrieval time, by filtering on the user's access before ranking. A chunk the user may not see must never reach the context; the model cannot be trusted to withhold it.
  • Treat retrieved text as untrusted input. Documents and web pages can contain instructions aimed at your model (guardrails and security).
  • Keep the index fresh and versioned: re-index on source change, record each chunk's source version, and make deletions propagate.
  • Log everything per query: the rewritten query, retrieved ids and scores, the prompt version and the answer. That log is your future eval set (evals in practice).

Common misconceptions

  • "RAG stops hallucination." It reduces it when retrieval succeeds and the model is told to abstain otherwise. With poor recall and no abstention, it gives hallucinations a citation.
  • "Bigger context windows make RAG obsolete." They make it optional for small, stable corpora. For large, changing or permissioned corpora, retrieval still wins on cost and auditability, and long inputs degrade with distractors.
  • "RAG means a vector database." RAG means generating from retrieved evidence. The retriever can be BM25, SQL, an API or a function over structured data.
  • "Fine-tuning on our documents is better than RAG." Fine-tuning teaches behaviour; it is an unreliable way to inject facts, and the facts cannot be cited or updated without retraining.

Check yourself

Name the three properties of parametric memory that RAG addresses.

Staleness (fixed at training time), incompleteness (no private or new data), and lack of provenance (no source to cite, no way to distinguish recall from fabrication).

Your RAG assistant answers confidently but wrongly when the corpus lacks the answer. Which failure point is this, and what are two fixes?

FP1, missing content. Fix it with an explicit abstention instruction plus unanswerable cases in the eval set, and with a relevance threshold or re-ranker score below which the system says it does not know (or routes to a human). Adding the missing content fixes the instance, not the class.

Using the identity P(C) = P(R)P(C|R) + (1 − P(R))P(C|¬R), when is improving the generator worth more than improving retrieval?

When retrieval recall is already high and \(P(C\mid R)\) is low: the marginal value of raising \(P(C\mid R)\) is \(P(R)\), and of raising \(P(R)\) is \(P(C\mid R)-P(C\mid\neg R)\). If \(P(R)=0.98\) and \(P(C\mid R)=0.6\), the generator (or context assembly) is the bottleneck.

Why can BM25 rank a one-sentence chunk above the relevant paragraph, and what does that teach about chunking?

BM25 normalises term frequency by chunk length relative to the average, so a very short chunk gets a large score from a single matching term. Orphan fragments from naive splitting are both hard to interpret and over-rewarded by keyword scoring; chunk on structure and merge fragments.

What does contextual retrieval change, and why does it help both dense and keyword search?

It prepends a short, model-written description of where a chunk sits in its document before indexing. Dense search benefits because the embedding now encodes the chunk's topic, not just its local wording; keyword search benefits because the added text contains the terms (product names, section titles) that the chunk itself omitted.

Hard: derive why RAG-token can produce answers RAG-sequence cannot, with an example.

RAG-sequence scores a whole answer under one passage at a time, so an answer that needs a fact from passage A for its first half and from passage B for its second half gets low probability under each passage alone. RAG-token marginalises per token, so each token can draw on the passage that supports it: "Card refunds take 5–7 days and UPI refunds 48 hours" can combine two chunks. Prompt-based RAG achieves the same by putting both passages in one context.

Hard: a team reports 92% faithfulness from an LLM judge and users still complain about wrong answers. Give three explanations.

(1) Faithful is not correct: the answer can be well supported by a retrieved passage that is outdated or about the wrong product (a retrieval or corpus problem). (2) The judge is miscalibrated or lenient; it has not been validated against human labels. (3) The eval set does not reflect real traffic (missing follow-ups, unanswerable questions, ambiguous phrasing), so the 92% measures a different distribution.

Go deeper

Papers

Videos and lectures

Articles

Books

Where this leads