Vector Databases & (Agentic) RAG

Agentic AI · L-RAG

Knowledge the model was not trained on: what retrieval repairs and what it breaks, the three stages of the pipeline, how the pipeline is measured, and the decision to let the agent retrieve for itself.

Prerequisite: the recap Linear Algebra.

Learning Objectives

  1. State which failures of a language model retrieval repairs — arbitrary fabrication, stale knowledge, the reversal curse, knowledge that was never in the weights — and which failure it creates.
  2. Describe the three stages of a retrieval pipeline — indexing, retrieval, generation — and name the decisions each stage fixes.
  3. Decide the ingestion questions: where a document is cut, what the indexed string contains, and which embedding model produces the vector.
  4. Explain approximate nearest-neighbour search, run HNSW by hand, and read the parameters a vector database exposes.
  5. Compare lexical, dense and hybrid retrieval, fuse two rankings, and derive why the most accurate scorer can only ever be a re-ranker.
  6. Choose a synthesis strategy over $k$ passages, and measure the pipeline: recall@$k$, precision@$k$, the three quality scores, and the difference between reference-based and reference-free evaluation.
  7. Decide from those measurements whether retrieval should become a tool the agent calls.
  8. Explain what changes when the corpus is source code — syntactic chunks, the draft as query, a map ranked by references, staged localization, search commands without an index — and choose among them.

Overview

Retrieval-augmented generation (RAG) supplies a language model with passages retrieved from an external document collection, so that an answer rests on knowledge that is not stored in the weights. Part I states which failures of a language model retrieval repairs and which failure it creates, Part II how documents are cut, embedded and indexed, Part III how a query is matched against a chunk, Part IV how $k$ retrieved passages become one answer, Part V how the pipeline is measured, Part VI whether the agent itself decides when to retrieve, and Part VII what changes when the corpus is source code. Ingestion, retrieval and synthesis are the three stages of the pipeline, in the order in which a document passes through them:

Part The question it answers Sections
I · Knowledge outside the Weights Which failures of a language model does a retrieved document repair, and which failure does retrieval create? The Limits of Parametric Knowledge · What Retrieval Repairs, and What It Creates · Retrieval-Augmented Generation · The Context Budget and the Retrieval Threshold · The Three Stages: Indexing, Retrieval, Generation · Standard Hybrid RAG
II · Ingestion What is put into the index, and which data structure searches it? Chunking · Metadata Extraction · Chunk Augmentation · Choosing the Embedding Model · Vector Indexing & Approximate Nearest Neighbors (ANN) · Inverted Index for Sparse Retrieval
III · Retrieval How is a query matched against a chunk? Semantic Retrieval / Dense Retrieval · Lexical Retrieval: TF-IDF and BM25 · Tokenization Mismatch · Lexical and Dense Retrieval: Cost and Quality · Hybrid Retrieval and Rank Fusion · Retrieval Variants · Re-ranking and the Cross-Encoder
IV · Synthesis How do $k$ retrieved passages become one answer? Chunk Order and Grounding · Response Synthesis over $k$ Passages
V · Evaluation How is the pipeline measured, stage by stage, so that the choices made in the three stages can be compared? Retrieval Metrics and the Three Quality Scores · Faithfulness · Answer Relevance · Context Relevance · Reference-Based and Reference-Free Evaluation
VI · Agentic RAG Should the agent itself decide whether, what and when to retrieve? Agentic RAG in Brief · Agentic Patterns in the Loop · Retrieval as a Tool · The Retriever Ceiling · Agentic RAG Architectures · Agentic versus Static RAG
VII · Retrieval for Code What changes when the corpus is source code? Syntactic Chunking · Iterative Retrieval · Repository Map · Hierarchical Localization · Command-Driven Retrieval · Design Space of Code Retrieval

Part I — Knowledge outside the Weights

The knowledge of a language model is parametric — stored in the weights and fixed when training ends; retrieval supplies, at inference time, knowledge that the weights do not hold. The largest part of it sits in the feed-forward layers, which hold two-thirds of a model's parameters and behave as a key-value memory: each key fires on a pattern in the text so far, and the value it selects adds a distribution over the next token (Geva et al., 2021). Four consequences follow from parametric storage. The model cannot hold what was private to an organisation. It cannot hold what happened after training stopped. It holds part of what it was taught in one direction only. And whatever it does hold, it holds without a source: no part of the weights records which document a fact came from.

Retrieval answers all four in the same way. The knowledge is moved out of the weights and into the context, where changing it costs an edit to a file rather than a training run, where the documents never leave the organisation that owns them, and where every sentence of the answer has a passage it can be attributed to. What that buys, what it does not buy, and what it breaks are the subject of this part.

The Limits of Parametric Knowledge

The weights are a store of finite capacity, and the training objective fills it in proportion to how often a fact appears. A fact met once contributes one term to the loss and competes for the same parameters as everything else, so the rare, the recent and the private are exactly what is held weakly or not at all.

Which of a model's mistakes can a document fix? Hallucination is one word for several different failures, and the answer differs for each, so the word has to be split before the question can be asked properly. The literature splits it along two independent axes, each of which is refined further in places.

Axis 1 — what the output conflicts with (Huang et al., 2025).

Factuality hallucination Faithfulness hallucination
Conflicts with the world the material supplied in the prompt
Example asked for the capital of Australia, the model answers Sydney; the capital is Canberra (Wang et al., 2025) given a report stating "the test was negative for diabetes", the model summarises it as "the patient was diagnosed with diabetes"
Cause the knowledge in the weights is wrong, outdated or absent the model departed from a source that was in front of it

Huang et al. refine the older split of Ji et al. (2023): an intrinsic hallucination contradicts the source it was given, an extrinsic one can be neither supported nor contradicted by that source and may still be true.

Axis 2 — whether the error is stable. Farquhar et al. (2024) reserve the term confabulation for a claim that is "both wrong and arbitrary — by which we mean that the answer is sensitive to irrelevant details such as random seed", and separate it from an error the model repeats.

Confabulation (arbitrary) Consistent error (stable)
Re-run the same prompt a different wrong answer each time the same wrong answer every time
What it indicates the model holds no belief about the question and is guessing the wrong belief is in the weights

Whether an error is stable is independent of what the output conflicts with, and stability decides whether a retrieved passage repairs a factuality hallucination. A factuality hallucination occurs both as a confabulation and as a consistent error. In a confabulation the weights favour no answer, and the retrieved passage supplies the answer they lack. In a consistent error the weights favour a wrong answer, and the passage contradicts it: the answer is correct only if the model follows the passage instead of the weights. Which of the two sources the model follows is contingent, and is measured, not assumed. Given one coherent passage that contradicts the weights, instruction-tuned models mostly follow the passage; given a second passage that agrees with the weights, they mostly return to the weights (Longpre et al., 2021; Chen, J. et al., 2024; Xie et al., 2024).

Which repair applies depends on both axes together — what the output conflicts with and whether the error is stable — and not on either axis alone.

confabulation (arbitrary) consistent error (stable)
factuality hallucination — conflicts with the world the weights favour no answer; the supplied passage provides one the weights favour a wrong answer; the supplied passage repairs it only if the model follows the passage instead of the weights
faithfulness hallucination — conflicts with the material supplied in the prompt the passage is in the prompt, and the model departs from it differently in each run the passage is in the prompt, and the model departs from it in the same way in each run

The faithfulness row is empty until a passage has been supplied: supplying a passage is the precondition of these errors, not their repair.

What Retrieval Repairs, and What It Creates

Retrieval repairs what the weights do not hold; it does not settle what they hold wrongly, and it creates one failure an ungrounded model cannot have.

Failure Repaired by retrieval? Why
nothing in the weights — never learned, or never available to training yes — the case the architecture was built for swapping the index swaps what the system knows (Lewis et al., 2020)
stale fact — true when training stopped yes, by the same mechanism the edit is to a file, not to a model
absent in one direction — the reversal curse yes, and no other repair here does a fact learned one way is barely answerable the other (Berglund et al., 2024)
a systematically wrong belief only if the passage overrules the weights the weights already favour a wrong answer; a contradicting passage wins when it is coherent and stands alone, and loses beside a passage that agrees with the weights (Xie et al., 2024)
context inconsistency — the answer contradicts the passage it cites no — retrieval creates this category support for each claim has to be asked for and graded (Asai et al., 2024)

Knowledge and reasoning are separated, and only one of them is expensive to change. A new document is indexed in minutes; the same fact written into the weights costs a training run. The model is then kept for what it is good at — reading and reasoning over text placed in front of it — and the facts are kept where facts can be edited.

Retrieval-Augmented Generation

RAG is two steps: retrieve, then generate. A retriever selects passages from a corpus of your choosing, those passages are placed into the prompt, and the model answers from them instead of from its training data alone. Embeddings (→ L-Embed) make the first step possible: they place meaning in $\mathbb{R}^d$, so relevance becomes nearest neighbour by cosine.

RAG was named and formalized by Lewis et al. (2020) through a core framing that continues to define modern architecture: a system operating with two distinct memory types, only one of which is cheap and fast to update.

Where it lives How it is changed Cost of a change
parametric memory the weights a training run GPU-months
non-parametric memory an index over documents editing a file minutes

"We can update RAG's world knowledge by simply replacing its non-parametric memory." — Lewis et al. (2020), §4.5

The Context Budget and the Retrieval Threshold

Retrieval is not the only way to supply knowledge the model lacks. Where the whole corpus fits into the context window, it is placed in every prompt as it stands: nothing is selected, so no search and no index are needed. The retrieval threshold, the point beyond which passages must be selected instead, is decided not by the size of the corpus but by the context budget, which has five terms:

  • Fit — a large corpus simply exceeds the window.
  • Cost and latency — the context is re-sent on every call, so a large stuffed context is paid turn after turn.
  • Attention — even where it fits, a long context buries the relevant part and accuracy falls (Liu et al., 2024).
  • Update cost — both routes take up an edited corpus without retraining, unlike knowledge held in the weights (Lewis et al., 2020); they differ in what an edit costs. An index re-embeds only the changed document. A corpus held in a cached prompt prefix is reused only up to the first changed token, because the cached key and value vectors of a position depend on all tokens before it, so everything after the edit is processed again (Kwon et al., 2023).
  • The generator's own capacity — a model with weak long-context ability gains from retrieval, a strong one often does better with the whole document, so the threshold moves when the model is swapped (Shim et al., 2026).

A concrete anchor. A forty-page product handbook is roughly 25,000 tokens and fits in a 128,000-token window with room to spare, so it is placed in the context and no index is built. Fifty thousand support tickets are roughly 25 million tokens and will never fit. Between those two extremes lies the interesting case, and it is decided by the five terms of the context budget rather than by the word large.

The consequence is a spectrum rather than a switch:

  • a small corpus is placed in the context;
  • a medium one keeps an index and summaries in the context and loads whole documents on demand;
  • a large one is served by retrieval over a vector index.

Evidence for the middle of the spectrum. Cochran (2026) compares the two designs on one corpus of 24 research papers with 13 questions. One model, Claude Opus 4.7, writes the answers of both systems.

Page-reading agent Single-round retrieval
Preparation a model compiles the papers into cross-linked markdown pages the papers are split into chunks and indexed
Answering a question an agent lists the pages and opens them with a tool, for up to 30 turns hybrid retrieval passes the five best chunks to the model, once
Tokens at query time, summed over the 13 questions 1,651,357 78,093 (about 21× fewer)
Time, summed over the 13 questions 22.0 min 3.3 min

Quality. Two language-model judges score every answer on four criteria, each from 1 to 10. The largest difference lies on inter-paper mapping, the criterion that asks whether an answer relates findings of two or more papers. For each system, the inter-paper-mapping scores of its answers to the four questions that require such synthesis are averaged over the four questions and over both judges. The average of the page-reading agent exceeds that of single-round retrieval by 6.6 on the 1–10 scale.

A stronger retrieval baseline removes most of that difference. In a variant added after the preregistered study, the model first splits each question into two to five sub-questions, and the retrieval pipeline runs once for each sub-question. On the same four questions, the difference to the page-reading agent falls from 6.6 to 0.4 — about 94 % of it disappears. The variant uses 491,000 tokens at query time, 6.3× as many as single-round retrieval and 30 % of the 1,651,357 tokens of the page-reading agent, and it takes 26.8 minutes, the longest of the three.

Why the page-reading agent is expensive. Every page that agent opens enters the context as a tool result and is sent again with every later model call for the same question, so the token count grows with the number of turns, and the cost term of the budget is incurred on every question.

Limits. One corpus, one model, and four questions behind the synthesis result. The quality scores come from language-model judges and are not checked against human ratings. The answers grow longer in the same order as the scores — on average 385 words (single-round retrieval), 604 (decomposition) and 740 (page-reading agent) — so answer length is not excluded as a cause.

Design rule. Loading documents on demand moves cost from indexing to every query. The design is chosen for questions that need synthesis across documents, and it is compared against a retrieval baseline that decomposes the question, not only against single-round retrieval.

A second boundary, independent of size. The context budget decides whether a corpus fits into the context window; it says nothing about a class of question that top-$k$ retrieval (returning, for a query, the $k$ passages with the highest relevance scores, $k$ fixed in advance; not the top-$k$ sampling rule of a language model) cannot serve at any $k$: "what are the main themes in this collection?". Similarity retrieval assumes the answer is localised — contained in a few records, with the rest irrelevant. Here every record contributes, so a retrieved subset is not a shorter answer but a different one, and enlarging $k$ does not repair it. Decomposing the question into sub-questions does not repair it either: decomposition helps where the answer lies in a few records that each sub-question can locate, as in the synthesis questions of Cochran (2026), but here the list of sub-questions would itself be the answer. Edge et al. (2025) classify such a question as query-focused summarization rather than retrieval, and answer it by summarising the corpus ahead of the query instead of ranking passages after it. A pipeline that does not detect the difference fails in a specific way: every sentence of the answer may be supported by a retrieved passage, and the answer still misrepresents the corpus.

The Three Stages: Indexing, Retrieval, Generation

A retrieval pipeline consists of three stages — indexing, retrieval and generation (Gao et al., 2024):

  1. Indexing (Ingestion)
  2. Retrieval
  3. Generation (Synthesis)
3 · Generation / synthesis (per query)2 · Retrieval (per query)1 · Indexing / ingestion (offline)documentschunkembedindexqueryembedsearchtop passagesprompt: question +passagesmodelgrounded answer

Stages 1 and 2 together are the retriever, which maps a query to relevant chunks; the model in stage 3 is the generator. Retriever + generator = RAG (Lewis et al., 2020). Retrievers are dense (embeddings and approximate search), sparse (term matching) or hybrid, and are often refined by a re-ranker.

The three stages run at different frequencies, and this difference governs every design choice in this lecture.

  • Stage 1 (indexing) runs offline, once per document, so an expensive chunker or a model that rewrites each chunk is affordable there.
  • Stages 2 and 3 (retrieval and generation) run once per query, so everything in them is measured in milliseconds and tokens. Work that can be moved from a per-query stage into indexing is usually worth moving.

Standard Hybrid RAG

A production pipeline rarely retrieves by embedding alone. The same chunk is written into two indexes — a vector index over its embedding and an inverted index over its words — both are searched with the query, and the two rankings are combined into one.

The inverted index serves the lexical retriever (also called sparse), which scores a passage with the tf-idf or BM25 weights of the words it shares with the query (→ L-Embed). Two properties matter for the diagram. The lexical side needs no model at all — an inverted index and a formula — and it fails on different queries than the dense side does: it matches a part number exactly and misses a paraphrase, where the embedding does the reverse.

3 · Generation (per query)2 · Retrieval (per query)1 · Indexing (offline, once per document)documentschunksembedvector indexterm weightingTF-IDF / BM25inverted indexqueryembedANN searchtokenizeinverted-index lookuprank fusiontop passagesprompt:question + passagesmodelgrounded answer

The rest of the lecture takes this diagram apart: what a chunk is and where it is cut, what is embedded, what the two indexes are as data structures, how one ranking is made from two, and what the generator does with the passages once it has them.

Part II — Indexing/Ingestion: From Documents to an Index

The index decides what retrieval can possibly return, and every choice that fixes it is made before a single query arrives. The stage decomposes into seven steps:

  1. load the documents
  2. transform them into text
  3. chunk them
  4. extract metadata
  5. embed each chunk
  6. build an index over the vectors
  7. store it.

Three of these seven steps involve permanent, unrecoverable decisions:

  • where the document is chunked (step 3)
  • what text goes into the embedded string (step 4)
  • which model generates the embedding (step 5)

A mistake in any of these three steps creates a silent failure downstream: the correct answer simply disappears from the search space rather than returning an incorrect result, making it far harder to detect. Steps 6 and 7 (indexing and storage) shift to a classic data-structures problem.

Chunking

A chunk is a smaller, self-contained snippet of text extracted from a larger document. Instead of feeding a 100-page PDF into a system all at once, the system breaks the document down into bite-sized pieces—typically ranging from a few sentences to a couple of paragraphs.

Why Chunking Matters

  • Precision Retrieval: When a user asks a question, the search system finds the exact chunk containing the answer rather than retrieving an entire document filled with irrelevant information.
  • Context Window Limits: AI models have limits on how much text they can read at one time. Chunks keep the context lean and focused.
  • Embedding Accuracy: Search in RAG relies on converting text into numerical vectors (embeddings). Short, single-topic chunks generate clear vector meanings, whereas a 50-page document converted to a single vector becomes blurry and hard to match against user queries.

A chunk is two things at once, and they want opposite sizes:

  • As the retrieval unit, it is what a single vector must summarize, where smaller is better because one vector can accurately represent one distinct idea.
  • As the reading unit, it is what the generator receives, where larger is better because an accurate answer requires surrounding context.

One example, both directions. A one-sentence chunk reading "It must be filed within that period." is a precise retrieval unit and a useless reading unit: retrieved on its own it tells the generator neither what must be filed nor which period. A whole-chapter chunk is the reverse — it certainly contains the answer, but its single vector is an average over thirty pages, so it sits near nothing in particular. Every named chunking policy is an answer to that tension, and most of them work by making the two units different.

Chunking Policies in RAG

Policy Retrieval unit (what is indexed and matched) Reading unit (what the generator receives) How it works, and what it is for Primary source
Fixed size (with overlap) Fixed token block The same block Baseline. Splits text by fixed token count with boundary overlap. Cheap and simple, but ignores document structure. —
Structure-aware Natural section / heading; for source code a syntax-tree node (function, class) The same unit Markup documents and source code. Splits along the document's own syntax — Markdown headings, HTML tags, JSON, or the abstract syntax tree of source code — so that a section or a function remains intact. for source code: Zhang et al. (2025) — syntax-tree chunks against fixed-size line chunks raise Pass@1 on RepoEval from 51.2 % to 57.9 %
Similarity-based (semantic) Topic segment The same segment Unstructured prose. Splits text where vector similarity between adjacent passages drops; often inaccurate in practice. Lu et al. (2025)
Sentence-window Single sentence / short span Target span + surrounding sentences Precise fact retrieval. Matches an exact, narrow sentence and passes neighboring context to the generator. —
Policy Retrieval unit (what is indexed and matched) Reading unit (what the generator receives) How it works, and what it is for Primary source
Parent–child (small-to-big) Small child chunk Enclosing parent section / page Granular matching with wide context. Matches small text snippets while retrieving their larger parent section. —
Summary tree (RAPTOR) Any tree node (leaf or summary) That specific node Thematic & multi-doc QA. Recursively clusters and summarizes chunks into a multi-layer tree, searching across all levels simultaneously. Sarthi et al. (2024)
Auto-merge Leaf chunks in a hierarchy An ancestor chosen per query Variable-depth queries. Dynamically replaces retrieved sibling chunks with their parent section if enough child nodes match. Lu et al. (2025)

Citability. In the table, only the similarity-based row, and the structure-aware row for source code, have a reachable primary source; summary tree (RAPTOR, Sarthi et al., 2024) and auto-merge (Lu et al., 2025) have one as well. Fixed size, structure-aware, sentence-window and parent–child are described in the practitioner literature without a citation, an experiment or a dataset, and the survey that names them is a pointer source rather than a citable one.

In the common case a chunk is a few hundred tokens of contiguous text with a small overlap into its neighbours, so that a sentence cut by a boundary still appears whole in one of the two pieces.

This section nevertheless recommends no chunk size, and the reason is measurable. In the standard document-question-answering collections the evidence for a question occupies only 1.7 to 10.5 sentences of a very long document, so any chunker that does not cut through that one sentence returns it and the end-to-end score barely moves: 64.50 for fixed-size chunking against 65.53 for the best method the same authors could build (Lu et al., 2025). A benchmark can only measure a component whose failure changes the answer.

Metadata Extraction

A chunk is stored together with the fields that say where it came from — title, author, date, source URL or file path, section heading, page number, and whatever the corpus itself carries: product, language, customer, access level. They are extracted once the document has been cut and before the chunk is embedded, and they are kept beside the vector rather than inside it. Two uses follow, and only one of them touches the score.

Filtering restricts the candidate set before anything is ranked. A question about the current price list is run only against the chunks whose validity range covers today; a question from a user without clearance is run only against the chunks that user may read. Passages that would mislead, or that must not be shown, are then not candidates at all — a guarantee no amount of ranking quality provides. Gao et al. (2024) count metadata among the pre-retrieval optimisations, beside index granularity and query rewriting.

Attribution returns the fields with the passage. The title, section heading, page number and source URL stored beside the vector are returned together with the chunk, so the answer can name the document it was produced from. These fields do not enter the score: they are read after ranking, by the generator and by the reader of the answer.

Chunk Augmentation

Chunk augmentation adds model-written context to a chunk before indexing, so that the text matched against a query differs from the text of the original chunk. A chunking policy fixes the unit that is matched and the unit that is returned; chunk augmentation changes the text by which a unit is matched. Before indexing, a model that has been shown the whole document writes fifty to a hundred tokens situating each chunk, and the augmented text — not the original — is what is embedded and what enters the inverted index (Contextual Retrieval = Contextual Embeddings + Contextual BM25; Ford, 2024). The indexed string is then no longer a substring of the document.

whole documentmodelchunk iverbatimsituating context50–100 tokensaugmented chunk:context + chunkembedvector indexterm weightingTF-IDF / BM25inverted index

The model is called once per chunk and is shown the whole document each time, so the cost falls entirely in the offline half of the pipeline, where it is paid once per document instead of once per query. Both indexes are then built over the augmented text — which is why one name covers two methods, contextual embeddings and contextual BM25.

Chunk augmentation repairs a chunk that is not retrieved because it does not name its subject; sentence-window, parent–child and auto-merge repair a chunk that is retrieved but holds too little text to answer from. An example shows the difference:

The string
the chunk The company's revenue grew by 3 % over the previous quarter.
what is indexed This chunk is from an SEC filing on ACME Corp's performance in Q2 2023; the previous quarter's revenue was $314 million. The company's revenue grew by 3 % over the previous quarter.

The italic half is what the model wrote; the rest is the chunk, unchanged. On its own the chunk names neither the company nor the quarter, so no inverted-index lookup matches a query about ACME in 2023 and no embedder places the chunk near such a query. Returning its parent would not help either: a parent is returned only if the child was retrieved, and it was not. The repair has to happen on the indexed string.

Reported on one corpus, the proportion of questions whose evidence is missing from the top twenty falls from 5.7 % to 2.9 % when both indexes are contextualised, and to 1.9 % with a re-ranker over 150 candidates. ⚠ Anthropic's own experiment (Ford, 2024), whose methodology is not published; the mechanism is established, the magnitudes are indicative.

An implementation of contextual retrieval is the Anthropic cookbook Enhancing RAG with contextual retrieval.

Choosing the Embedding Model

The embedding model decides which chunks a vector index can tell apart. The index ranks chunks by the similarity of their vectors, so chunks that the embedder maps to nearby vectors cannot be ranked apart, and the choice of embedder bounds retrieval quality before the index is built. What counts as similar is fixed by the pairs on which the embedder was trained (→ L-Embed); the vector store does not show them.

Two embedders trained on different pairs can order the same texts differently. For the query "How do I cancel my subscription?", one embedder may place "Steps to end your membership" (the same intent in different words) nearer, the other "How do I cancel my newspaper delivery?" (the same intent in the same words, for a particular service). Neither order is wrong in general: each follows from the training pairs of its embedder, and only one fits a given corpus.

The case in one table. Three embedders that score almost alike on short documents differ widely on long documents:

Model Parameters Input limit (tokens) BEIR (short documents) LoCoV1 (long documents)
E5-Mistral 7.11 B 4096 56.9 71.4
text-embedding-ada-002 (OpenAI) not published 8192; 2048 on LoCoV1 53.3 63.4
BGE-Large 335 M 512 54.3 54.8

BEIR comprises 17 retrieval tasks of the MTEB leaderboard, in most of which the longest documents are a few thousand tokens long; LoCoV1 comprises twelve retrieval tasks whose documents average 4,544 to 58,129 tokens. Both columns give nDCG@10 (a score from 0 to 100 for the ranking of the ten top-ranked documents, higher when the relevant documents stand at higher ranks), and every model truncates a document to its input limit (Saad-Falcon et al., 2024, Table 1). On BEIR the three models lie within 3.6 of each other, on LoCoV1 within 16.6, and text-embedding-ada-002 and BGE-Large change places. On LoCoV1 the order of the three models is the order of their input limits. text-embedding-ada-002 is truncated at 2048 tokens there because it scores higher at 2048 than at its limit of 8192.

Design rule. An embedder for a corpus of long documents is chosen on a long-document benchmark or on the corpus itself, not on a benchmark of short documents.

Asymmetric Retrieval and Task Prefixes

A retrieval query and its passage form an asymmetric pair: the two texts differ in length, form and intent, and the embedder must be told which side it encodes (→ L-Embed). For retrieval the marker changes the query vector, not the search. The prefix is ordinary text: it is tokenized together with the input, the self-attention layers compute the vector of every token from all tokens of the input, the prefix included, and the text vector is the mean of these token vectors (Günther et al., 2024, §4.1). The same words under a different prefix therefore give a different vector, and the unchanged nearest-neighbour search returns the neighbours of that vector. Where each prefix moves the vector is learned in training, from pairs that carry the prefix. Asked which text is closest to "What is the capital of France?", a similarity task answers "What is the name of the capital city of France?" — a rephrasal — and a question-answering task, with the query encoded as a query and both candidates stored as passages, answers "Paris is the capital of France." Both are right, and a single model trained on both kinds of pair therefore "receives conflicting reward signal" (Nussbaum et al., 2025, §4.2.2): one batch pushes questions toward questions, the next pushes questions toward answers. In nomic-embed-text the marker is a prefix: search_query: before the query, search_document: before every stored passage.

Omitting a prefix is a silent failure. It is ordinary text, so nothing raises an error: a vector comes back, the search returns its nearest neighbours, and they are the neighbours of a point placed under the wrong relation. The loss shows up only as recall the corpus never had. And because the prefix is part of every stored string, changing it means re-embedding the corpus rather than re-running the query — as does replacing the embedding model, since the stored vectors and the query vector must come from the same encoder to be comparable at all.

HyDE

Hypothetical document embeddings (HyDE) replace the query vector by the vector of a hypothetical answer: a language model writes a document that would answer the query, and retrieval is performed with the embedding of that document (Gao, L. et al., 2023). A task prefix tells the embedder which relation to encode; HyDE removes the need for a query-side representation instead. An instruction-following language model is asked to "write a passage to answer the question"; the same encoder $f$ that embedded the corpus embeds that hypothetical passage, and the mean over $N$ sampled passages $\hat d_1, \dots, \hat d_N$ becomes the query vector:

$$\hat{\mathbf{v}}_q = \frac{1}{N}\sum_{k=1}^{N} f(\hat d_k).$$

Retrieval has become passage-to-passage similarity — a symmetric task, which an encoder trained without relevance labels already performs.

The hypothetical passage may be factually wrong, and the design does not depend on it being right: it serves only as a search key and is discarded after the search. The fixed-size vector keeps the vocabulary and the shape of an answer and loses most of its details; the authors describe the encoder as "a lossy compressor" in exactly this role.

Measured on the TREC Deep Learning 2019 web-search queries with nDCG@10, a rank-weighted score over the top ten results: the unsupervised encoder alone reaches 44.5, with HyDE 61.3 — level with the same encoder fine-tuned on labelled pairs (62.1). The gain depends on the generator: 48.9 with an 11-billion-parameter model, 61.3 with InstructGPT. The cost is one generation call before every retrieval.

Practical Takeaway

  1. Ignore Generic Leaderboards: Standard benchmark ranks (like MTEB) do not guarantee performance on your real-world text.
  2. Test on Your Own Data: You must evaluate embedders empirically on your specific documents, chunk lengths, and user queries by measuring Recall@$k$ (how often the correct source text appears in the top $k$ results).
  3. The Hidden Failure: Getting embedding configuration wrong doesn't just produce bad answers—it prevents the search engine from finding the correct material entirely. The generator model can only answer using the documents it is actually given.

Vector Indexing & Approximate Nearest Neighbors (ANN)

Approximate nearest-neighbour (ANN) search returns vectors that are close to the query vector without a guarantee that they are the closest; in exchange it avoids the comparison with all $N$ vectors that exact search (FLAT) requires.

Exact search (FLAT) compares a query against all $N$ vectors ($O(Nd)$ cost), which only scales up to a few thousand items. To scale to millions of vectors, Approximate Nearest Neighbor (ANN) algorithms trade a small amount of recall for drastically reduced search latency.

Every ANN method works by searching only a target subset of the dataset:

  • IVF (Inverted File): Partitions space into Voronoi cells via $k$-means; checks only the nearest cells (nprobe: how many of those cells a single query actually searches).
  • HNSW (Graph): Navigates a multi-layer graph from upper layers that hold few vectors, joined by long edges, down to the bottom layer, which holds every vector (efSearch: the size of the candidate list HNSW keeps while it searches).
  • PQ (Product Quantization): Compresses high-dimensional vectors into short byte codes to speed up distance calculations and reduce RAM usage.
  • LSH (Locality-Sensitive Hashing): Hashes vectors so similar items collide in the same bucket.

Inverted Index for Sparse Retrieval

Dense retrieval searches the vector index; sparse retrieval searches an inverted index, built from the same chunks. The steps of this part up to here produce the vector index. A lexical (sparse) retriever scores a chunk by the terms it shares with the query, and for this it needs, for every term, the chunks in which the term occurs.

An inverted index stores, for every term of the collection, the list of chunks that contain it, so that a query reads only the lists of its own terms instead of scanning the collection. It is the second index of the hybrid pipeline, beside the vector index, and the structure against which lexical retrieval computes its tf-idf or BM25 scores. Manning et al. (2008, §1.2) call it "essentially without rivals as the most efficient structure for supporting ad hoc text search."

  • A term is the indexed unit after tokenization and normalization — usually a word, but also a string such as I-9 or Hong Kong (Manning et al., 2008, §1.1).
  • A document in the information-retrieval sense is "whatever units we have decided to build a retrieval system over" (Manning et al., 2008, §1.1); in a RAG pipeline it is the chunk.

Structure. The index has two parts (Manning et al., 2008, §1.2, §6.3.3):

  • the dictionary of all terms, held in memory, with each term's raw document frequency $\mathrm{df}_t$, the number of chunks that contain $t$. The index stores $\mathrm{df}_t$ and the number of chunks $N$. The idf is computed at query time;
  • one postings list per term: the identifiers of the chunks that contain the term, sorted by identifier. For ranked retrieval each entry also stores the raw count $\operatorname{count}(t,d)$ of occurrences of $t$ in chunk $d$, from which the weight $\mathrm{tf}_{t,d}$ is computed at query time.

Worked. Three chunks — $c_1$ "home sales rise", $c_2$ "new home sales", $c_3$ "July sales beat June sales" — give the following index, with each posting written as chunk : count:

Term $\mathrm{df}_t$ Postings list
beat 1 $c_3{:}1$
home 2 $c_1{:}1 \to c_2{:}1$
july 1 $c_3{:}1$
june 1 $c_3{:}1$
new 1 $c_2{:}1$
rise 1 $c_1{:}1$
sales 3 $c_1{:}1 \to c_2{:}1 \to c_3{:}2$

The term sales occurs twice in $c_3$, so its posting for $c_3$ stores the count 2, while $\mathrm{df}_{\text{sales}} = 3$ counts the chunks, not the occurrences.

Construction, offline and once per chunk (Manning et al., 2008, §1.2):

  1. tokenize each chunk;
  2. normalize the tokens to indexing terms (July → july; stemming maps sales and sale to one term where it is applied);
  3. sort the (term, chunk identifier) pairs by term and merge repeated occurrences into a count;
  4. group the pairs into the dictionary and the postings lists.

Query. The scorer reads the postings lists of the query terms only and adds each term's contribution to the score of every chunk listed there; the top $k$ scores are returned (term-at-a-time accumulation; Manning et al., 2008, §6.3.3). For the query "new home" the lists of new and home are read, $c_1$ and $c_2$ receive a score, and $c_3$ is never touched. Skipping $c_3$ is exact, not an approximation, because a term that does not occur in a chunk contributes zero to its tf-idf or BM25 score. An inverted index therefore returns the same ranking as scoring every chunk, whereas an ANN index trades recall for speed.

Update. A new chunk adds entries to the postings lists of its terms and changes $\mathrm{df}_t$ for each of them. Systems that must make new chunks searchable at once keep a small in-memory auxiliary index beside the main index, query both and merge the results, record deletions in an invalidation bit vector, and merge the auxiliary index into the main index when it is full; the alternative is to rebuild the index periodically (Manning et al., 2008, §4.5).

Part III — Retrieval: Matching a Query to a Chunk

Retrieval is the selection of a few passages from a large collection, given a query. Two components perform it.

  • A scorer is a function $s(q,p)$ mapping a query $q$ and a passage $p$ to a number meant to grow with relevance;
  • A ranking sorts the passages by that number and keeps the top $k$.

Three practical principles follow from how scoring and ranking work in practice:

  1. Query and document encoders are decoupled (Bi-encoders): To make search fast over millions of documents, passages are embedded into vectors in advance. At search time, the query is encoded independently, allowing the system to compare vectors using fast approximate nearest-neighbor search.
  2. Heavy cross-encoders only re-rank (Two-stage retrieval): The most accurate scoring models (cross-encoders that process query and document text together) are too slow to run over an entire database. They are only used as a second stage to re-order a small candidate pool fetched by a fast initial retriever.
  3. Hybrid search beats single-method search: Combining the rankings of two complementary retrieval methods — lexical search with BM25 over an inverted index and dense search over a vector index — performs better than relying on a single scoring function.

Semantic Retrieval / Dense Retrieval

Semantic retrieval uses dense embeddings at query time to fetch contextually relevant passages; it is nearest-neighbour search in the embedding space under cosine similarity (→ L-Embed). At query time the dense half of the pipeline performs three operations; the embedding of the passages is not among them, because it was done once at ingestion:

  1. Encode the query: The query encoder maps the incoming prompt to a vector $\mathbf{q} \in \mathbb{R}^d$ via a single forward pass of the embedding model (taking only a few milliseconds).
  2. Search the index: The vector index locates stored document vectors nearest to $\mathbf{q}$ based on cosine similarity $S_C(\mathbf{q}, \mathbf{d})$, typically using one of the approximate nearest neighbor (ANN) families described above.
  3. Map back to text: The $k$ nearest vectors are resolved back to their original text chunks, passing the raw passage text—not the vector representations—to the generator.

Notice what is absent at inference time: no passage computation happens on the fly. Passage embeddings are computed once during offline ingestion, imposing the core constraint of scalable semantic search: a dual-encoder architecture can only scale if the corpus is fully embedded before the query ever exists.

The bi-encoder, also called a dual encoder, was introduced with embeddings (→ L-Embed): query and passage pass through the same embedding model separately, a pooling step (by default the mean over the token vectors) reduces each to one vector in $\mathbb{R}^d$, and the two meet only in the cosine (Reimers & Gurevych, 2019). The passage branch is computed offline, once per chunk; only the query branch is computed when the query arrives. Karpukhin et al. (2020) call this property the decomposability of the similarity function: $s(q,p)$ is a function of two representations computed separately, so the passage side can be computed before the query is known.

per queryoffline, once per chunkpassage pembedding modelmean poolingpassage vectorvector indexquery qembedding model(same weights)mean poolingquery vectorcosine similarityscore s(q, p)

No query token ever attends to a passage token: everything the model knows about the pair is contained in two vectors computed without knowledge of each other.

Lexical Retrieval: TF-IDF and BM25

Where dense retrieval embeds text into continuous vector spaces, lexical (or sparse) retrieval scores passages purely by exact word overlap, requiring no neural models (Jurafsky & Martin, 2026, §11.1). Its two weightings are those of a sparse text vector: tf-idf weights a word by its frequency in the passage and its rarity across the corpus (→ L-Embed), and BM25 bounds the contribution of repeated occurrences and normalises in part by passage length (Robertson & Zaragoza, 2009; → L-Embed). In this lecture BM25 is the lexical arm of hybrid retrieval.

Tokenization Mismatch

Lexical retrievers tokenize text into words or stems (applying lowercasing, stop-word removal, and stemming/lemmatization), rather than using the generator's sub-word Byte-Pair Encoding (BPE) tokens. Meanwhile, dense retrievers rely on their own specific embedding model's vocabulary (→ L-Embed). Consequently, the term "token" carries entirely different structural definitions across different stages of the retrieval pipeline.

Lexical and Dense Retrieval: Cost and Quality

The two vectors behind the columns are compared in → L-Embed; the table compares the retrievers built on them.

Lexical (BM25 / TF-IDF over an inverted index) Dense (embedding-based)
Query cost tokenize + inverted-index lookup — cheap, no model call embed the query (a model forward pass) + ANN search
Index / memory inverted index; small; exact postings vector index (HNSW/IVF) + $d$-dimensional float vectors — more memory; ANN is approximate
Match type exact lexical (keyword overlap) semantic (meaning)
Strong on rare terms, identifiers, code, exact phrases; interpretable synonyms, paraphrase, cross-lingual
Weak on vocabulary mismatch — a query for "car" misses a document saying "automobile" exact and rare tokens — an error code ORA-01555 or a part number is mapped near every other code

Measured over the same 21 M Wikipedia passages (Karpukhin et al., 2020): top-20 retrieval accuracy 78.4 % (dense) against 59.1 % (BM25) on Natural Questions — real, anonymised Google queries paired with a Wikipedia page, annotated with a long answer, a short answer, or null where the page answers neither (Kwiatkowski et al., 2019) — at 995 against 23.7 queries per second — but 8.5 h to build the vector index against about 30 min for the inverted one. In this setup — an in-memory HNSW index against a Java Lucene index read from disk, the latter measured per CPU thread — dense retrieval answered more queries per second; the comparison does not show that dense retrieval is faster to query in general. Dense retrieval is by far the slower to build.

Lexical retrieval gives high precision where query and passage share terms, dense retrieval higher recall on meaning, and hybrid retrieval — fusing the two rankings, optionally followed by a re-ranker — tends to beat either alone.

Hybrid Retrieval and Rank Fusion

A hybrid retriever runs a lexical and a dense retriever over the same corpus and combines the two rankings. It combines the ranks, not the scores, because the two numbers are calibrated against different things: a BM25 score moves with the corpus and with the rarity of the query's terms, while a cosine similarity lies in $[-1,1]$ and, for a trained embedder, is concentrated in a narrow band. Adding them requires a normalisation, and every normalisation is a parameter that does not transfer between corpora, query types or embedder versions.

Reciprocal rank fusion (Cormack et al., 2009) needs none. For a document $d$ and a set $R$ of rankings, each assigning $d$ the rank $r(d)$:

$$\mathrm{RRF}(d) = \sum_{r \in R} \frac{1}{k + r(d)}, \qquad k = 60 .$$

Documents are then sorted by that score: no training, no calibration, no per-corpus tuning. The reciprocal shape keeps lower ranks from vanishing as an exponential would, and the constant $k$ "mitigates the impact of high rankings by outlier systems" (Cormack et al., 2009).

Two documents, worked out. Document $A$ is placed 3rd by the lexical retriever and 3rd by the dense one. Document $B$ is placed 1st by the dense retriever and is missing from the lexical ranking entirely:

$$\mathrm{RRF}(A) = \tfrac{1}{63} + \tfrac{1}{63} \approx 0.0317, \qquad \mathrm{RRF}(B) = \tfrac{1}{61} \approx 0.0164 .$$

$A$ wins, although no retriever ever ranked it first. That is the point of fusing at all: agreement between two different failure modes is evidence, and one confident system is not.

Retrieval Variants

The returned unit need not be the unit that is indexed and scored: sentence-window, parent–child, summary-tree and auto-merge retrieval match one unit and return another (see Chunking Policies in RAG), so the generator may receive units of different sizes.

The ranking — which candidates are considered, and in which order:

Variant The step it changes
single ranking (the base case) none: one retriever scores the whole index
metadata filter the candidate set — only chunks whose metadata matches (a date range, a source, an access level) are ranked at all
hybrid the ranking — a lexical and a dense ranking are fused by rank (see Hybrid Retrieval and Rank Fusion)
re-ranked the order — a larger shortlist is re-scored by a more expensive model (see Re-ranking and the Cross-Encoder)

Once the returned units differ in size, the same $k$ delivers different amounts of text. Two methods compared at equal $k$ then differ in the length of the context as well as in the quality of the ranking, and a method with larger units scores a higher recall@$k$ without ranking better. Methods are therefore compared, and the context is bounded, by a token budget: the number of tokens returned, of which top-$k$ is the special case in which every unit has the same length.

Re-ranking and the Cross-Encoder

A cross-encoder scores a query–passage pair by reading both texts as one sequence, without a vector for either (→ L-Embed). Because attention runs across query and passage, the score can encode this passage answers this question rather than this passage is about this topic. Because nothing about the passage can be computed before the query is known, the cross-encoder is the model the decomposability constraint excludes from first-stage retrieval. It is therefore used where a small candidate set makes it affordable: as a re-ranker over the shortlist a fast retriever returned, and offline as the teacher from which fast retrievers are distilled.

The cross-encoder processes the query and the passage together as one concatenated input sequence (Devlin et al., 2019); its use as a re-ranker over a BM25 shortlist is due to Nogueira & Cho (2019). A linear layer on the final [CLS] vector returns the relevance score $s(q,p)$. Because no representation of the passage can be computed before the query is known, the model runs once per (query, passage) pair of the shortlist, at query time.

query q[CLS] q [SEP] p [SEP]one input sequencepassage p(from the shortlist)transformer:every token attends toevery other,across q and pfinal vectorat [CLS]linear layer:relevance score s(q, p)

The contrast with the bi-encoder is the position at which query and passage meet: there in one cosine between two finished vectors, here in every attention layer.

A re-ranker cannot exceed the pool it is given, and that ceiling is measurable. Re-ranking the first thousand results of a lexical retriever, a far stronger neural retriever reaches recall@1000 of 81.4 — which is exactly the lexical retriever's own recall@1000, since re-ranking only re-orders that pool. Removing the lexical stage and searching the whole collection lifts the same model to 96.8, and improves the top of the ranking as well, because it reaches documents "missed entirely" by the first stage (Khattab & Zaharia, 2020). Two stages buy latency, and they cost recall.

Part IV — Synthesis

Synthesis is the stage of RAG that turns the retrieved passages into one coherent, grounded response.

Perfect retrieval only supplies raw materials; synthesis governs how context is ordered inside the prompt, how conflicting evidence is resolved, and how strict generation boundaries prevent hallucinations.

Chunk Order and Grounding

Where a passage sits in the prompt changes whether it is used. Holding content fixed and varying only its position, accuracy follows a U-shaped curve: performance peaks when key information is placed at the very beginning or end, but plummets in the middle—sometimes dropping below closed-book baselines where providing documents performs worse than providing none at all (Liu et al., 2024). Context layout is therefore an explicit ordering decision, and top-ranked passages belong at the edges rather than in the center.

Grounding is not verification, and the two are easy to confuse.

  • Grounded means the answer was produced from the supplied passage.
  • Verified would mean something checked that the passage is true and no stage of the pipeline does that.

Given documents whose answers had been deliberately falsified, and a system instruction warning that documents may contain errors, accuracy falls from 91 % without documents to 17 % with them, with the error detected in 1–8 % of cases (Chen, J. et al., 2024). The pipeline contains no step that compares the corpus against anything.

RAG models follow retrieved context blindly rather than fact-checking it.

Standard retrieval and generation do not automatically verify citations: Citation precision asks whether every claim in the answer is supported by the passage it cites. Retrieval-augmented instruction-tuned models left to themselves reach 2–6 % on long-form answers, where a system that explicitly judges support for each segment reaches 66.9–70.3 % (Asai et al., 2024). The judgement is a separate step; retrieval does not perform it.

To ensure reliable attribution, your RAG pipeline must treat attribution evaluation as an explicit, post-generation judging step.

Response Synthesis over $k$ Passages

Retrieval returns passages; the answer is built from them, and how it is built is a decision of its own with three standard forms. Write $k$ for the number of passages and $b$ for how many of them fit in one prompt.

Strategy Mechanism Model calls Also called Where it wins
single pass all $k$ passages in one prompt 1 compact fast and cheapest; the sensible default
iterative refinement passage 1 → initial answer → passage 2 → refined answer → … → final answer $k$, strictly sequential refine the most nuanced answer, at $k$ latencies
hierarchical merging summarise the passages in groups, then merge the summaries, recursively $\lceil k/b \rceil$ per round over $O(\log_b k)$ rounds, parallelisable tree_summarize long-form summarisation over many passages

What each strategy carries forward is what separates them. The single pass carries nothing and is the only form in which attention can compare two passages directly. Refinement carries the answer: every passage after the first is shown the answer so far and rewrites it, so the result is order-dependent and the last passage has the most influence over the wording. Merging carries intermediate summaries: each group is compressed once and the compressions are combined, so no passage ever sees another passage's text.

And the arithmetic, for $k = 20$ passages and $b = 5$ per prompt. The single pass makes 1 call. Refinement makes 20, strictly one after another. Merging makes $\lceil 20/5 \rceil = 4$ calls in the first round and $\lceil 4/5 \rceil = 1$ in the second — 5 calls in 2 rounds, and the four calls of a round run in parallel. The total work of merging is therefore linear in $k$ while its depth is logarithmic, and only depth is unavoidably sequential.

The recursion may be paid once instead of once per query. RAPTOR (Sarthi et al., 2024) runs the same cluster-and-summarise recursion over the corpus at indexing time — the summary tree of the chunking table — so that the merged summaries are retrievable chunks rather than work done per query. Restricting retrieval to any single layer of that tree scores about 57.9 on one document and allowing three layers 73.68: the summaries answer thematic questions no leaf contains, and the leaves answer the detail the summaries have compressed away.

Part V — Evaluation

Three stages of design decisions have now been made, and none of them can be settled by argument.

Retrieval is measured separately from generation, and it is measured first: a better generator or an agentic loop placed around a retriever that never returned the evidence inherits the miss, and no amount of work on the second stage recovers it. Separate measurement is what tells the two apart — and it is also what decides the question of the final part.

A failure of a RAG pipeline is located by the stage at which the answer was lost. Barnett et al. (2024) name seven failure points from three deployed systems — a tutor over a university unit's learning material, a literature-review tool and a biomedical question-answering system over 4,017 documents:

Stage Failure point The answer …
corpus missing content does not exist in the documents, and the system answers anyway
retrieval missed the top-ranked documents is in a document ranked below the cut-off $k$
between retrieval and generation not in context was retrieved and dropped when the passages were fitted into the context budget
generation not extracted is in the context; noise or contradicting passages prevent its extraction
generation wrong format is given, but not in the requested format (a table, a list)
generation incorrect specificity is too general or too specific for the question
generation incomplete is partly given, although the context held all of it

The first three points are failures before the model reads anything; the last four occur with the evidence in the context. The report is a case study and gives no frequency for any point. Its conclusion is a statement about testing: "validation of a RAG system is only feasible during operation", because the questions a deployed system receives are not known in advance.

Retrieval Metrics and the Three Quality Scores

Measure retrieval before improving it. The retrieval stage is measured on its own, against a set $R$ of gold passages marked relevant for a query by hand. Write $T_k$ for the top $k$ the retriever returned:

$$\text{recall@}k = \frac{|R \cap T_k|}{|R|}, \qquad \text{precision@}k = \frac{|R \cap T_k|}{k}.$$

Worked. Four passages in the corpus answer the query, and the retriever's top 10 contains three of them. Then $\text{recall@}10 = 3/4 = 0.75$ and $\text{precision@}10 = 3/10 = 0.30$.

The two answer different questions, and recall@$k$ is the one that bounds everything downstream: it asks whether the evidence reached the generator at all, and nothing later in the pipeline can recover a passage that was never returned. Precision@$k$ asks how much of the context window was spent on passages that were not needed.

Three further scores measure the pipeline end to end — the triad of Es et al. (2024), collected in Gao et al., 2024, §VI.C. A query produces three objects — the query itself, the retrieved context, the response — and the three scores are the three edges between them:

context relevancefaithfulnessanswer relevancequeryretrieved contextresponse
Score The question it asks Compares What it targets
Context relevance is the retrieved context precise and specific for this query? query → context retrieval
Answer faithfulness does the answer stay inside the retrieved context? context → response generation
Answer relevance does the answer address the question that was asked? response → query generation

Faithfulness and relevance are not the same score, and an example separates them. Asked "how long is the refund window?" over a context stating "14 days", the answer "30 days" is perfectly relevant and flatly unfaithful; the answer "our support team is available 24/7" is faithful to nothing in particular and not relevant. Only faithfulness is checkable against something outside the model, which is why citation precision — is every claim supported by the passage it cites? — is the form in which faithfulness is usually made concrete.

Faithfulness

Faithfulness is the share of the answer's statements that the retrieved context supports. Es et al. (2024) compute it, like the two scores that follow, by prompting a model, and all three are reference-free: they use the question $q$, the retrieved context $c(q)$ and the answer $a_s(q)$, never a gold answer. Faithfulness takes two prompts:

  1. Decomposition. The model rewrites the answer as a set $S$ of short statements, each of which makes a single assertion.
  2. Verification. For each statement $s_i \in S$, the model returns the verdict yes or no to the question whether $s_i$ can be inferred from $c(q)$. The statements that receive yes form the subset $V \subseteq S$ of verified statements.

$$F = \frac{|V|}{|S|} \in [0, 1].$$

Worked. The context states "Refunds are accepted within 14 days of delivery." The answer "Refunds are accepted within 14 days, and the customer pays the return shipping." decomposes into $s_1$ = refunds are accepted within 14 days and $s_2$ = the customer pays the return shipping. The context supports $s_1$ and says nothing about $s_2$, so $V = \{s_1\}$ and $F = 1/2$.

An unsupported statement lowers the score because it enters the denominator $|S|$ without entering the numerator $|V|$ — whether $s_2$ is true does not matter, only whether the context supports it. Since the decomposition is itself a model call, a different split of the same answer changes $|S|$, and $F$ with it: had $s_1$ been split into two statements, $F$ would be $2/3$.

Answer Relevance

Answer relevance measures whether the answer addresses the question that was asked, and it does so in reverse. From the answer alone, the model generates $n$ questions $q_1, \dots, q_n$ that the answer would answer. Each generated question and the real question $q$ are embedded, and $\mathrm{sim}(q, q_i)$ is the cosine similarity of the two embedding vectors:

$$AR = \frac{1}{n}\sum_{i=1}^{n}\mathrm{sim}(q, q_i).$$

An answer to a different question generates questions close to that other question, so each $\mathrm{sim}(q, q_i)$ falls, and $AR$ with it. The authors state that the score also penalises an answer that is incomplete or contains redundant information; the route is the same, since questions generated from such an answer cover only part of $q$, or cover topics that $q$ does not contain.

The score is blind to factuality by construction, as its authors state. In the refund example, the wrong answer "30 days" generates "how long is the refund window?" as readily as the correct "14 days" does: the generated question depends on what the answer is about, not on whether it is true.

Context Relevance

Context relevance is the share of the retrieved context that is needed to answer $q$. The model extracts from $c(q)$, without changing them, the sentences needed to answer $q$ — or returns "Insufficient Information" when there are none — and the score divides their number by the length of the context:

$$CR = \frac{|S_{\text{ext}}|}{\text{number of sentences in } c(q)}.$$

Worked. The retriever returns three passages of 20 sentences in total, and one sentence states the 14-day refund window. Then $|S_{\text{ext}}| = 1$ and $CR = 1/20 = 0.05$, although the context contains the correct answer.

The score is therefore a penalty on length, not on error: every retrieved sentence enters the denominator, and only a needed sentence enters the numerator. The authors motivate the penalty by the cost of long contexts and by the weaker use a model makes of information placed in the middle of a long context (Liu et al., 2024).

All three scores are judgements of a model, so each inherits the biases of a judge; and answer relevance is a cosine between embeddings, which cannot become a factuality score however well it correlates.

Reference-Based and Reference-Free Evaluation

Reference-based evaluation compares an answer with a gold answer written in advance; reference-free evaluation has no gold answer and judges the answer against the question and the retrieved context.

Reference-based Reference-free
Compares the answer with a gold answer written in advance the question and the retrieved context, both available at run time
Instruments exact match, ROUGE, BERTScore a model acting as judge — the three scores above
Needs a labelled set per corpus no labels
Fails when the answer is right in different words the judge is biased

Why the left column is not enough. It measures word overlap, not correctness: against the gold answer "14 days", the perfectly correct "two weeks" scores zero on exact match and close to zero on ROUGE. The effect is not a curiosity of that one example — re-running 23 summarization systems under a single protocol against expert human annotations, ROUGE and BERTScore correlate poorly with human judgement (Fabbri et al., 2021). And a corpus that changes weekly never has a current labelled set at all.

Why the right column is not enough either. The score is produced by a model, so it inherits that model's biases. G-Eval gives the judge the criterion, has it write its own evaluation steps, and takes the probability-weighted sum over the score tokens rather than the integer the model emits, reaching a Spearman Correlation Coefficient of 0.514 with human judgement on that same benchmark — ahead of every reference-based metric in the table there (Liu, Y. et al., 2023). Its own authors nevertheless report a "bias towards the LLM-generated texts."

So the two are used together. Report a judged score with a second judge and the disagreement between them, keep a reference-based metric beside it, and treat a difference that only one of the two can see as a hypothesis rather than as a result.

Part VI — Agentic RAG

The pipeline built so far fixes three decisions before it has read a single passage: it retrieves for every query, it retrieves with the query as the user wrote it, and it accepts whatever the top $k$ contains. Agentic RAG returns these decisions to run time, where they can depend on what retrieval has already returned.

The survey literature arranges RAG systems on four rungs, which differ in control flow rather than in quality — the first three after Gao et al. (2024), the fourth after Singh et al. (2026), who extend that ladder by Graph RAG and Agentic RAG:

Rung What it adds Shape
Naive RAG index → retrieve top-$k$ → generate a chain
Advanced RAG optimisation around that chain — query rewriting (Ma et al., 2023) and expansion before retrieval, re-ranking and context compression after it still a chain: one static pass
Modular RAG modules exchanged and re-ordered: routing, memory, repeated retrieval a graph
Agentic RAG the agent decides the retrieval strategy at run time a loop

Most production systems stand on the second rung. It improves every step of the chain, but the steps and their order are still fixed before anything has been read. Whether the fourth rung repays its additional calls is decided by measurement, not by its position on the ladder.

The same four rungs, drawn as the control flow each one executes for a single query (the first three after Singh et al., 2026, Figs. 3–5):

Agentic RAG — a looptool callobservationdonequeryagentretrieveanswerModular RAG — modules recombinedfixed number of roundsqueryroutesearch the webgenerateretrieve from the indexAdvanced RAG — a longer chainqueryrewrite / expandretrieve top-kre-rank, compressgenerateNaive RAG — a chainqueryretrieve top-kgenerate

In the first three the path is fixed by the designer of the system, even where it branches or repeats; in the last it is chosen by the model at run time, and the number of retrievals is unknown before the query arrives.

Agentic RAG in Brief

Agentic RAG is retrieval-augmented generation in which an agent, and not a fixed pipeline, decides how to retrieve (Singh et al., 2026).

In the agentic RAG retrieval is a tool inside the agent loop (→ L-ReAct): the model reasons, calls a tool, observes the result, and repeats until it decides to answer. Every retrieval is therefore preceded by a decision, and every result is read before the next decision is made.

noyesnoyesnoyesqueryretrievalneeded?generateselect a source,write the queryretrieveevidence relevantand sufficient?every claimsupported?answer

The loop makes five decisions that the static pipeline makes once or not at all:

  1. Analyse the query — is retrieval needed, and how much? A question the weights can answer needs none; a question whose second fact depends on the first needs several retrievals.
  2. Select the source — a vector index over documents, a relational database queried in SQL, a web search or another API. The agent acts as a router over knowledge sources (Singh et al., 2026, §5).
  3. Formulate the query — rewrite the question, divide it into sub-questions, or use a term that appeared only in an earlier result.
  4. Judge the evidence — are the returned passages relevant, and do they suffice? If not, the loop returns to the second or third decision.
  5. Generate and check — write the answer from the evidence and test whether every claim is supported by a passage. An unsupported claim is a further reason to retrieve.

Each return edge in the diagram costs one more retrieval and at least one more model call, so a production loop also carries a stopping criterion — a maximum number of iterations or a token budget — after which it answers from the evidence it holds.

Agentic Patterns in the Loop

Each of the five decisions is an instance of a pattern the agent literature already names. Singh et al. (2026), §3, build agentic RAG from four such patterns:

Pattern Definition Its role in the retrieval loop
Tool use the model calls external functions and reads their results retrieval, SQL and web search are tools; the source is chosen by choosing the tool
Planning the task is decomposed into sub-tasks before or during execution a multi-hop question becomes a sequence of sub-questions, one retrieval each
Reflection the model critiques its own intermediate output and revises it judging the evidence; checking that the answer is supported
Multi-agent collaboration several agents, each with its own role and tools, divide the task retrieval, judgement and writing are assigned to different agents
reviseacceptqueryLLMresponse draftcritique: supported?relevant? complete?answer

The diagram is the reflection pattern (after Singh et al., 2026, Fig. 8).

Retrieval as a Tool

What an agent can do after a failed retrieval is bounded by the operations its retrieval tool offers. A tool with one operation, search(query), permits one response to a poor result: rephrase the query and search again. An agent that can additionally search lexically, restrict a search to one named entity, and include or exclude documents from its own candidate set scores 22.5 % higher in exact match, relative, than the strongest agent limited to issuing queries (Hui et al., 2026). The tool interface is therefore a design decision of the same weight as the embedder.

The agent knows its retrieval options only from their definitions in its context. Each tool is presented to the model as a name, a natural-language description and a parameter schema; the model selects a source by emitting a call to one of these names with arguments that satisfy the schema, and nothing outside the definitions is visible to it. Whether a question about an order reaches the SQL database rather than the index over the manuals is therefore decided by what the two descriptions say. The definitions belong to what Yang et al. (2024) call the agent–computer interface (ACI): the commands available to the model and the form in which their results are returned to it.

Self-RAG (Asai et al., 2024) is a language model trained to emit reflection tokens — special tokens with which it requests a retrieval, grades a retrieved passage and grades its own output. They encode the three judgements the static pipeline never makes: retrieve at all? · is this passage relevant? · is the answer supported by it? Agentic RAG makes the same judgements with an unmodified model, through prompts and tool calls in the agent loop; Self-RAG moves them into the weights, which requires training the generator.

One trace that the static pipeline cannot produce. The question is "How long is the refund window?", asked of a corpus in which the answer is divided between two documents:

search("refund policy")           →  §4: "Refunds are governed by the terms in Annex B."
search("Annex B refund window")   →  Annex B: "14 days from delivery."
answer: 14 days from delivery.

The first result does not answer the question; it names where the answer is. The second query could not have been written in advance, because it contains a term — Annex B — that appears only in the first result. A static pipeline embeds the original question once, retrieves once, and stops.

The Retriever Ceiling

A fixed-context reader cannot outperform its retriever. It sees exactly the top $k$ chunks it was handed, so "if the embedding search retriever fails to surface the gold article using the provided question, the fixed-context baselines are guaranteed to never see the gold article" (Packer et al., 2024). That is a ceiling, not a tendency: whatever the reader's quality, the evidence it can see is bounded above by recall@$k$, and no amount of prompt work on the reader raises it.

An agent that can query again and page onwards is not bounded that way. A second query with different wording, or the next page of the same ranking, reaches documents the first call never showed. Agentic retrieval therefore converts a one-shot top-$k$ into a search over the index, and the ceiling moves from recall@$k$ to recall over the whole ranking.

Where it matters most is the multi-hop question, in which the value retrieved is itself the key to the next lookup, so a single retrieval cannot succeed by construction. Packer et al. (2024) measure it on a synthetic nested key–value task: 140 pairs of random identifiers (UUIDs), about 8,000 tokens, in which a value may itself be a key, so that $n$ nesting levels require $n+1$ lookups. The identifiers are random, so no model holds them in its weights, and the fixed-context baselines receive all 140 pairs in their context window: the only difficulty is chaining the lookups. GPT-3.5 falls to 0 % accuracy at one nesting level, GPT-4 by three. MemGPT with GPT-4, which looks up each key with a search function call, is unaffected by the nesting depth; with GPT-4 Turbo or GPT-3.5 it improves on the corresponding baseline but still declines from two levels, "as a result of failing to perform enough lookups".

The gain is theoretical until the agent uses it: the same authors observe that their agent "will often stop paging through retriever results before exhausting the retriever database". Agentic RAG buys a higher ceiling, not a guarantee of reaching it.

Agentic RAG Architectures

The architectures differ in where the retrieval decisions are made and how many contexts hold them. One agent may make every decision in one context, or the decisions may be distributed over several agents, each of which sees only its own part (Singh et al., 2026, §5):

Architecture Who decides Typical use
Single-agent router one agent selects the source and tool for each query few sources, one domain
Multi-agent a coordinator delegates to retrieval agents, one per source type, which run in parallel many heterogeneous sources
Hierarchical agents delegate to agents over several levels; results are aggregated upwards large tasks that decompose recursively
Adaptive a classifier over the query selects no, single-step or multi-step retrieval mixed workloads of simple and complex questions
Corrective an evaluator grades the retrieved documents and triggers a new query or another source corpora with gaps
Graph-based the agent retrieves over a knowledge graph — entities as nodes, typed relations as edges, each fact a triple $\langle$subject, relation, object$\rangle$ — as well as a vector index questions about relations between entities
Agentic document workflow (ADW) agents parse a document, keep state across steps, retrieve reference material and apply business rules processing a document — an invoice, a contract — into a structured result

The last row changes the task rather than the control flow: the input is a document to be processed, not a question to be answered, and the output is a structured record rather than an answer. The term was introduced by a framework vendor (LlamaIndex) and is not yet established in the research literature; the survey's own diagram of it is taken from that vendor's blog.

Agentic versus Static RAG

Agentic RAG buys recall on questions that one retrieval cannot answer, and pays for it in calls, latency and predictability; on questions that one retrieval does answer, it buys nothing.

Static RAG Agentic RAG Mechanism
Multi-hop questions bounded by recall@$k$ of one query a later query may use a term from an earlier result the retriever ceiling (Packer et al., 2024)
Simple questions sufficient same answer, more calls a multi-step loop on every query takes 3.33× the time of single-step retrieval; routing reaches the same F1 at 1.46× (Jeong et al., 2024)
Knowledge source fixed at design time selected per query the gain lies in the decision: the web added when the corpus failed beats the web always added (Yan et al., 2024)
Cost per query one retrieval, one model call one retrieval and at least one model call per iteration the number of iterations is decided at run time, so the cost varies per query
Poor index bounds the answer still bounds the answer the loop chooses only among what the index returns
Traceability one path for every query; a failure reproduces a different path per query the trace must be logged and evaluated step by step, not only the final answer (Singh et al., 2026, §10)
Termination after one pass only by a stopping criterion the model may stop too early (Packer et al., 2024) or invoke tools excessively (Singh et al., 2026, §10)

Part VII — Retrieval for Code

Retrieval for code supplies a code generator or a coding agent with the parts of a repository it needs: the definitions the new code calls, code similar to the code to be written, and the lines a change must edit. The three stages of the pipeline remain. The properties of source code in the table change how each stage is built.

Property of source code Consequence for retrieval
Identifiers must match exactly. load_config and parse_config lie close together in an embedding space and are different functions. Lexical matching of identifiers is a strong signal; a query that contains an identifier needs an exact hit.
Structure is given by a parser. Modules, classes, functions, imports and calls are read off the abstract syntax tree (AST), the tree of syntactic units that a parser builds from the source text. Chunk boundaries and a graph of references are computed, not estimated.
Relevance follows dependencies. The code needed to change a function is the code that calls it, the types it uses and its tests, which may share no word with the request. Similarity to the request misses dependencies; the structure of the program or a second query supplies them.
The corpus changes with every edit. An index computed in advance becomes stale; a search at query time does not.

Syntactic Chunking

Syntactic chunking cuts source code along its abstract syntax tree, so that a chunk holds whole functions, classes or statements instead of a fixed number of lines. A line-based chunk may end inside a function: in the example of Zhang et al. (2025), a chunk boundary separates the function compute_stats from its return line, and the generator that completes a caller of compute_stats assumes a wrong return value.

The method of Zhang et al. (2025), cAST, parses a file with the parser library tree-sitter and applies split-then-merge:

  1. A file within the size budget is one chunk.
  2. Otherwise the children of the root are visited in order, and adjacent siblings are merged into one chunk while their total size stays within the budget.
  3. A node that alone exceeds the budget is split: the procedure recurses into its children.

The budget counts non-whitespace characters, not lines, because one line may hold an import or a long expression. The chunks concatenated reproduce the file.

Evidence. Zhang et al. (2025, Tables 1, 2 and 7) replace fixed-size line chunks by cAST chunks and keep retriever and generator unchanged. On RepoEval, where an unfinished function is completed from code of the same repository, the share of the relevant snippets that appear among the five retrieved ones (Recall@5) rises from 70.7 % to 75.0 %, and the share of completed functions that pass the repository's unit tests (Pass@1) from 51.2 % to 57.9 % (retriever GIST-base, generator StarCoder2-7B). On SWE-bench Lite, where a GitHub issue written in prose is resolved by a patch, Pass@1 changes by between −1.3 and +2.7 percentage points across five retrievers (generator Claude 3.7 Sonnet). Without the merge step every import line and assignment becomes a chunk of its own, and retrieval and generation fall with all three retrievers tested.

Design rule. Source code is chunked along its syntax tree, and adjacent small units are merged up to the budget. A gain is to be expected where both the query and the documents are code.

Iterative Retrieval

Iterative retrieval uses the model's draft output as the query of the next retrieval. In code completion the query is the unfinished code before the cursor, while the code to be retrieved resembles the code after it. Zhang et al. (2023) close this gap in RepoCoder:

  1. The repository is indexed as windows of $S_w$ consecutive lines, each shifted by $S_s$ lines against the previous one ($S_w = 50$, $S_s = 10$ for function bodies).
  2. The first query is the last $S_w$ lines of the unfinished code $X$. The retrieved windows and $X$ form the prompt, and the model generates a draft $\hat Y^{1}$.
  3. Each further query is the last $S_w - S_s$ lines of $X$ followed by the first $S_s$ lines of the previous draft; retrieval and generation are repeated.

The retriever compares token sets with the Jaccard index $|S_q \cap S_c| / |S_q \cup S_c|$, where $S_q$ and $S_c$ are the sets of tokens of the query and of a candidate window. The draft may be wrong; it contains the identifiers and the statement shapes of the target, and these are what a lexical retriever matches. The principle is the one of HyDE: a generated text resembles the document more than the request does.

Evidence. Zhang et al. (2023, Table 3) complete 373 function bodies from six Python repositories with GPT-3.5-Turbo and measure the pass rate, the share of completions that pass all unit tests of the function: 23.32 % without retrieval, 38.34 % after one retrieval, 42.63 % after two. An oracle that builds the query from the true completion reaches the same 42.63 %. A third and a fourth iteration do not exceed the second (41.82 %, 42.36 %), and the authors report little gain in repositories that contain little duplicated code.

Design rule. Where the request does not resemble the document to be retrieved, a draft is generated first and used as the query of a second retrieval.

Repository Map

A repository map is a listing of a repository's files with the signatures of their most-referenced definitions, cut to a fixed token budget, which a coding agent receives with every request. The map shows the model the structure of the repository without the bodies of the files; the model then asks for the files it needs. The coding assistant aider builds the map in five steps (Aider-AI, 2026):

  1. tree-sitter lists, for every file, the identifiers it defines and the identifiers it references.
  2. A directed graph has one node per file and, for each identifier, an edge from every file that references it to every file that defines it. The weight of an edge grows with the square root of the number of references; it is multiplied by 10 when the identifier is mentioned in the conversation and by 50 when the referencing file is one the user is editing.
  3. Personalized PageRank scores the files: the stationary probability of a random walk that follows an outgoing edge, chosen in proportion to its weight, with probability 0.85, and otherwise restarts at one of the files being edited. A file scores high when many files depend on it, the edited files above all.
  4. Each file passes its score along its outgoing edges to the definitions it references, and the definitions are sorted by the score they receive.
  5. A binary search over the number of top-ranked definitions finds the largest map within the token budget (1 024 tokens by default).

The request enters only through the restart files and the multipliers; the map uses no embedding and no text similarity. aider publishes no measurement of the map's effect.

Design rule. A coding agent receives an overview of the repository that is ranked by dependencies and bounded by a token budget, and reads complete files only on request.

Hierarchical Localization

Localization finds the lines of a repository that a change must edit. Hierarchical localization narrows the candidates in stages, and each stage shows the model a more detailed representation of a smaller part of the repository. Xia et al. (2025) use three stages in Agentless, a fixed pipeline in which the model performs each step but never chooses the next one. The skeleton of a file lists its class headers, class fields, function and method signatures and module-level comments, without the bodies.

issue textfile paths only→ model names 3 filesembedding search overfilesoutside excluded folders3 filesskeletons of the files→ model names classesand functionscode of those elements→ model names the lines

Evidence. Xia et al. (2025, Tables 1 and 2) measure on SWE-bench Lite (300 issues, GPT-4o) the share of issues whose true edit location is still among the candidates after a stage. For files, the model reading only the paths keeps it in 78.67 % of the issues, embedding search over the file contents in 70.33 %, both combined in 81.67 %. For classes and functions, skeletons keep it in 58.33 % at an average cost of $0.02 per issue, the complete files in 53.67 % at $0.15. Going from files directly to lines keeps it in 47.00 %, against 50.67 % through the skeleton stage. The whole pipeline resolves 96 of the 300 issues (32.00 %) at $0.70 per issue; the single-pass retrieval baseline of the SWE-bench authors, reported in the same table, resolves 2.67 % with GPT-4. Xia et al. attribute the advantage of the shorter input to the model's difficulty with long contexts; they do not measure that cause.

Design rule. A coding agent localizes in stages over compressed views — paths, then signatures, then code — and combines the model's choice over paths with a search over contents.

Command-Driven Retrieval

In command-driven retrieval the agent uses no index: it issues search commands such as grep and find over the files as tool calls and decides from each result what to search or read next (Tao et al., 2026, §4.1.2). It is retrieval as a tool (see Retrieval as a Tool) with a lexical matcher over the current files. No index is built, so none becomes stale and no code is sent to an embedding service.

Evidence. Yang et al. (2024) (Table 3) vary only the search commands of the agent SWE-agent on SWE-bench Lite with GPT-4 Turbo and measure the share of issues resolved: 18.0 % with a summarized search, which lists the files that contain a match and, above 50 matches, shows none and asks for a narrower query; 12.0 % with an editor-style search, which shows one match at a time with the commands next and prev; 15.7 % with no search command at all. Yang et al. state the mechanism: "when given a large number of search results, agents tend to look through every match exhaustively", which consumes the budget of the run.

A practitioner's report. The code assistant Cody replaced its embedding index by keyword search with BM25 ranking (Isken, 2024), for three stated reasons: the code had to be sent to an external embedding service, the embeddings had to be recomputed as the code changed, and vector search over more than 100 000 repositories was resource-intensive. The post reports no measurement of retrieval quality and marks the change "(for now)".

Design rule. A coding agent receives a lexical search command whose result is a short summary with a cap on the number of matches. An embedding index is added where the requests are written in prose and share few terms with the code.

Three production coding agents retrieve code without an index. Qwen Code (Qwen Team, 2026), Kimi Code (Moonshot AI, 2026) and oh-my-pi (Stencil Labs, 2026) build no embedding index over the code; each retrieves through a bounded regular-expression search, a search for file names, and a read-only search subagent. Two of the measured designs of this part are defaults there:

Agent Default Measured design
Kimi Code the search returns only the paths of matching files; matching lines on request; pages of 250 the summarized search of SWE-agent
oh-my-pi reading a code file of 100 lines or more returns its declarations, the bodies elided, and names the line ranges to re-read the skeleton of Agentless
Qwen Code the search returns matching lines, cut at 1 000 lines or 25 000 characters with the number of omitted lines —

Two of the agents also retrieve instruction files by the agent's action rather than by a query: Qwen Code adds the rules for a part of the repository when the agent reads a file there, and Kimi Code adds an AGENTS.md file when a tool first touches its directory.

Design Space of Code Retrieval

Each method changes one element of the static pipeline, and the methods combine.

Method Element it changes Signal Index Evidence
Syntactic chunking the unit the syntax tree chunk index measured (Zhang et al., 2025)
Iterative retrieval the query the model's draft lexical, over line windows measured (Zhang et al., 2023)
Repository map the index and the score the reference graph graph, rebuilt per request none published (Aider-AI, 2026)
Hierarchical localization the representation per stage paths, signatures, code; embeddings embeddings over the files kept measured (Xia et al., 2025)
Command-driven retrieval the retriever exact text match none measured (Yang et al., 2024)

Agentless combines the model's choice over paths with embedding search; in aider the repository map is followed by the model's request for the complete files it needs.

In Practice / This Week's Lab

lecture-RAG-exercises.ipynb — by hand: recall@$k$ and precision@$k$; reciprocal rank fusion; the curse of dimensionality; an HNSW search and the size of the index it needs.

lecture-RAG-lab.ipynb — tutorials with questions: a RAG pipeline from scratch, a vector database behind a search tool the agent decides to call, an evaluation set with precision@$k$, recall@$k$ and MRR, sparse retrieval with BM25, chunk size against a span-level gold set, and the same pipeline in LlamaIndex; two short exercises: gold questions of one's own, and reciprocal rank fusion.

Summary

The seven questions, answered.

  • Why retrieve? Retrieval repairs the failures whose cause is knowledge missing from the weights — stale, private and one-directional facts — by editing a corpus instead of a model. It does not repair a belief the weights hold confidently, and it creates one new failure: an answer unfaithful to the passage it cites.
  • What goes into the index? Where the document is cut, what the indexed string says, and which embedder produced the vector. None of it is visible afterwards, and an error there costs a missing answer. The index itself is a data structure: ANN makes search sublinear, HNSW is a skip list over proximity graphs searched best-first, and the curse of dimensionality is why the approximation is needed at all.
  • How is a query matched? By a similarity function whose passage side must be computable in advance — which is why a retriever is two encoders, why the cross-encoder that answers no to that becomes a re-ranker, and why a re-ranker can never exceed the pool it is given. Hybrid retrieval fuses ranks, not scores.
  • How do $k$ passages become one answer? Order them, ground the answer in them, make each claim traceable — then choose a single pass, iterative refinement, or a recursion that may be paid once at index time instead of once per query.
  • How is it measured? Recall@$k$ and precision@$k$ for retrieval, the three quality scores for the pipeline, and a reference-free judge read beside a reference-based metric, never alone.
  • Should the agent retrieve for itself? Agentic RAG returns the retrieval decisions to run time — whether to retrieve, from which source, with which query, and whether the evidence and the answer suffice. It raises the retriever ceiling on questions one retrieval cannot answer, at the price of calls, latency and a path that differs per query; it does not repair the index — so fix the index first, and let the measurements decide.
  • What changes for code? Identifiers match exactly, structure is given by a parser, relevance follows dependencies, and the corpus changes with every edit. Code is therefore chunked along its syntax tree, a draft serves as the query, a map ranked by references and a staged localization show signatures before bodies, and an agent may search the current files with commands instead of an index.

References

Peer-reviewed papers

  • Asai, Akari, et al. "Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection." International Conference on Learning Representations. Vol. 2024. 2024. arXiv:2310.11511.
  • Barnett, Scott, et al. "Seven Failure Points When Engineering a Retrieval Augmented Generation System." Proceedings of the IEEE/ACM 3rd International Conference on AI Engineering – Software Engineering for AI. 2024, pp. 194–199. arXiv:2401.05856. — seven failure points of a deployed RAG pipeline, by stage.
  • Berglund, Lukas, et al. "The Reversal Curse: LLMs trained on 'A is B' fail to learn 'B is A'." International Conference on Learning Representations. Vol. 2024. 2024. arXiv:2309.12288. — a fact fine-tuned in one direction is answered 96.7 % that way and 0.1 % in reverse, with no detectable likelihood difference from a random name, and no training-side repair; the same sentence in context is usable in both directions.
  • Beyer, Kevin, et al. "When Is 'Nearest Neighbor' Meaningful?" Database Theory — ICDT'99. Lecture Notes in Computer Science, vol. 1540, Springer, 1999, pp. 217–235. doi:10.1007/3-540-49257-7_15.
  • Borgeaud, Sebastian, et al. "Improving Language Models by Retrieving from Trillions of Tokens." Proceedings of the 39th International Conference on Machine Learning. Vol. 162. 2022, pp. 2206–2240. arXiv:2112.04426.
  • Chen, Jiawei, et al. "Benchmarking Large Language Models in Retrieval-Augmented Generation." Proceedings of the AAAI Conference on Artificial Intelligence. Vol. 38. 2024, pp. 17754–17762. arXiv:2309.01431. — the RGB benchmark: counterfactual robustness 91 % → 17 %, negative rejection at ≤ 45 %, and the near-miss definition of noise. (Cited as Chen, J. et al.)
  • Cormack, Gordon V., Charles L. A. Clarke, and Stefan Büttcher. "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods." Proceedings of the 32nd International ACM SIGIR Conference on Research and Development in Information Retrieval. 2009, pp. 758–759. doi:10.1145/1571941.1572114. — RRF: $\sum_r 1/(k+r(d))$ with $k=60$, and the measured flatness of that constant.
  • Cuconasu, Florin, et al. "The Power of Noise: Redefining Retrieval for RAG Systems." Proceedings of the 47th International ACM SIGIR Conference on Research and Development in Information Retrieval. 2024, pp. 719–729. arXiv:2401.14887. — distracting passages (the retriever’s own top scorers, without the answer) cost up to 0.24 accuracy; random passages help by up to 35 %.
  • Devlin, Jacob, et al. "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding." Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers). 2019, pp. 4171–4186. arXiv:1810.04805. — the [CLS]/[SEP] sentence-pair input and the classification layer on the final [CLS] vector: the cross-encoder.
  • Es, Shahul, et al. "RAGAs: Automated Evaluation of Retrieval Augmented Generation." Proceedings of the 18th Conference of the European Chapter of the Association for Computational Linguistics: System Demonstrations. 2024, pp. 150–158. arXiv:2309.15217. — the three reference-free scores and their definitions: faithfulness as the supported share of extracted statements, answer relevance as the mean similarity of questions generated back from the answer, context relevance as extracted sentences over total.
  • Fabbri, Alexander R., et al. "SummEval: Re-evaluating Summarization Evaluation." Transactions of the Association for Computational Linguistics, vol. 9, 2021, pp. 391–409. arXiv:2007.12626. — 23 summarization systems re-run under one protocol with expert and crowd human annotations: ROUGE and BERTScore correlate poorly with human judgement, which is the case against reference-based evaluation alone.
  • Farquhar, Sebastian, et al. "Detecting hallucinations in large language models using semantic entropy." Nature, vol. 630, 2024, pp. 625–630. doi:10.1038/s41586-024-07421-0. — confabulation defined as the arbitrary subset of hallucination, and entropy computed over meanings rather than over token sequences.
  • Gao, Luyu, et al. "Precise Zero-Shot Dense Retrieval without Relevance Labels." Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). 2023, pp. 1762–1777. arXiv:2212.10496. — HyDE: a hypothetical passage as the query vector, which turns retrieval into a symmetric task. (Cited as Gao, L. et al. to separate it from Gao, Y. et al.)
  • Geva, Mor, et al. "Transformer Feed-Forward Layers Are Key-Value Memories." Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing. 2021, pp. 5484–5495. arXiv:2012.14913. — the feed-forward layer as a key-value memory: where parametric knowledge is stored (correlational; no ablation).
  • Greshake, Kai, et al. "Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection." Proceedings of the ACM Workshop on Artificial Intelligence and Security. 2023. arXiv:2302.12173. — retrieval as the delivery mechanism for indirect prompt injection: the passive method plants the payload where the index will find it.
  • Huang, Lei, et al. "A Survey on Hallucination in Large Language Models: Principles, Taxonomy, Challenges, and Open Questions." ACM Transactions on Information Systems, vol. 43, no. 2, 2025, art. 42. arXiv:2311.05232. — the factuality / faithfulness taxonomy this week's first slide uses. (A survey: cited for its own taxonomy, not for a measurement.)
  • Hui, Yulong, et al. "Interact-RAG: Reason and Interact with the Corpus, Beyond Black-Box Retrieval." International Conference on Learning Representations. Vol. 2026. 2026. arXiv:2510.27566. — the retrieval tool's action space as a design decision: lexical search, entity anchoring and candidate-set primitives beside search.
  • Indyk, Piotr, and Rajeev Motwani. "Approximate Nearest Neighbors: Towards Removing the Curse of Dimensionality." Proceedings of the 30th Annual ACM Symposium on Theory of Computing (STOC 1998), 1998, pp. 604–613. doi:10.1145/276698.276876. — LSH.
  • Jégou, Hervé, et al. "Product Quantization for Nearest Neighbor Search." IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 33, no. 1, 2011, pp. 117–128. inria-00514462. — IVF / PQ.
  • Jeong, Soyeong, et al. "Adaptive-RAG: Learning to Adapt Retrieval-Augmented Large Language Models through Question Complexity." Proceedings of the 2024 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (Volume 1: Long Papers). 2024, pp. 7036–7050. arXiv:2403.14403. — routing each query to no, single-step or multi-step retrieval before the first call; the labels built from the simplest strategy that succeeded.
  • Ji, Ziwei, et al. "Survey of Hallucination in Natural Language Generation." ACM Computing Surveys, vol. 55, no. 12, 2023, pp. 1–38. arXiv:2202.03629. — the intrinsic / extrinsic split and the definitions of faithfulness and factuality that Huang et al. refine. (A survey: cited for its definitions, not for a measurement.)
  • Jiang, Huiqiang, et al. "LongLLMLingua: Accelerating and Enhancing LLMs in Long Context Scenarios via Prompt Compression." Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers). 2024, pp. 1658–1677. arXiv:2310.06839. — context compression by the shift in perplexity the question causes, i.e. conditional pointwise mutual information.
  • Johnson, Jeff, et al. "Billion-scale similarity search with GPUs." IEEE Transactions on Big Data, vol. 7, no. 3, 2021, pp. 535–547. arXiv:1702.08734. — FAISS.
  • Karpukhin, Vladimir, et al. "Dense Passage Retrieval for Open-Domain Question Answering." Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing. 2020. arXiv:2004.04906. — the decomposability constraint that forces two encoders, and the sparse/dense quality and cost comparison over 21 M passages.
  • Khandelwal, Urvashi, et al. "Generalization through Memorization: Nearest Neighbor Language Models." International Conference on Learning Representations. 2020. arXiv:1911.00172.
  • Khattab, Omar, and Matei Zaharia. "ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT." Proceedings of the 43rd International ACM SIGIR Conference on Research and Development in Information Retrieval. 2020, pp. 39–48. arXiv:2004.12832. — the measured ceiling a re-ranker inherits from its candidate generator (recall@1000 81.4 → 96.8).
  • Kwiatkowski, Tom, et al. "Natural Questions: A Benchmark for Question Answering Research." Transactions of the Association for Computational Linguistics, vol. 7, 2019, pp. 453–466. aclanthology.org/Q19-1026. — real search queries, a Wikipedia page from the top five results, and long / short / null answers; the null option is what lets it score abstention.
  • Kwon, Woosuk, et al. "Efficient Memory Management for Large Language Model Serving with PagedAttention." Proceedings of the 29th Symposium on Operating Systems Principles. 2023. arXiv:2309.06180.
  • Lewis, Patrick, et al. "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks." Advances in Neural Information Processing Systems. Vol. 33. 2020. arXiv:2005.11401. — parametric vs. non-parametric memory, and the index swap that changes what the system knows.
  • Lin, Chin-Yew. "ROUGE: A Package for Automatic Evaluation of Summaries." Text Summarization Branches Out. Association for Computational Linguistics, 2004, pp. 74–81. aclanthology.org/W04-1013. — the reference-based summarization metric of the evaluation table.
  • Liu, Nelson F., et al. "Lost in the Middle: How Language Models Use Long Contexts." Transactions of the Association for Computational Linguistics, vol. 12, 2024. arXiv:2307.03172. — the U-shaped accuracy curve over the position of the relevant passage, and mid-context accuracy falling below the model's own closed-book 56.1 %.
  • Liu, Yang, et al. "G-Eval: NLG Evaluation using GPT-4 with Better Human Alignment." Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing. 2023, pp. 2511–2522. aclanthology.org/2023.emnlp-main.153. — the reference-free judged metric: an automatically generated chain of evaluation steps, a form-filling prompt, and the probability-weighted score; Spearman 0.514 with human judgement, and its authors' own caution that such evaluators are biased toward model-generated text.
  • Longpre, Shayne, et al. "Entity-Based Knowledge Conflicts in Question Answering." Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing. 2021, pp. 7052–7063. arXiv:2109.05052. — knowledge conflict: substituting the answer entity throughout the retrieved passage measures how often the reader answers from its weights anyway, and the five factors that move it — question familiarity, model size, the retrieval quality the reader was trained with, the answer's entity type, and entity popularity.
  • Ma, Xinbei, et al. "Query Rewriting in Retrieval-Augmented Large Language Models." Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing. 2023, pp. 5303–5315. arXiv:2305.14283. — Rewrite-Retrieve-Read: the rewrite step before the retriever, and the HotpotQA result that retrieval with the raw question can lower accuracy.
  • Malkov, Yu A., and D. A. Yashunin. "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs." IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 42, no. 4, 2020, pp. 824–836. arXiv:1603.09320. — HNSW.
  • Min, Sewon, et al. "FActScore: Fine-grained Atomic Evaluation of Factual Precision in Long Form Text Generation." Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing. 2023, pp. 12076–12100. arXiv:2305.14251. — factual precision over atomic facts; citations present in 36.0 % of supported and 37.6 % of unsupported sentences.
  • Nussbaum, Zach, et al. "Nomic Embed: Training a Reproducible Long Context Text Embedder." Transactions on Machine Learning Research, 2025. arXiv:2402.01613. — retrieval quality decided before the index, and the MTEB→LoCo reversal (text-embedding-ada-002 60.99 → 52.7) that argues for evaluating the embedder on your own documents.
  • Ram, Ori, et al. "In-Context Retrieval-Augmented Language Models." Transactions of the Association for Computational Linguistics, vol. 11, 2023, pp. 1316–1331. arXiv:2302.00083. — the primary for the pipeline this lecture builds: "leaving the LM architecture unchanged and prepending grounding documents to the input, without any further training of the LM." A 345 M model with BM25 beats a 762 M one, and with a trained re-ranker a 1.5 B one.
  • Reimers, Nils, and Iryna Gurevych. "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks." Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP). 2019, pp. 3982–3992. arXiv:1908.10084. — the bi-encoder: two weight-tied towers, mean pooling, cosine similarity.
  • Robertson, Stephen, and Hugo Zaragoza. "The Probabilistic Relevance Framework: BM25 and Beyond." Foundations and Trends in Information Retrieval, vol. 3, no. 4, 2009, pp. 333–389. doi:10.1561/1500000019. — BM25.
  • Ru, Dongyu, et al. "RAGChecker: A Fine-grained Framework for Diagnosing Retrieval-Augmented Generation." Advances in Neural Information Processing Systems. Vol. 37. 2024, pp. 21999–22027. arXiv:2408.08067. — claim-level metrics that attribute a failure to the retriever or the generator, and the relevant/irrelevant noise split.
  • Saad-Falcon, Jon, et al. "Benchmarking and Building Long-Context Retrieval Models with LoCo and M2-BERT." Proceedings of the 41st International Conference on Machine Learning. Vol. 235. 2024, pp. 42918–42946. arXiv:2402.07440.
  • Sarthi, Parth, et al. "RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval." International Conference on Learning Representations. Vol. 2024. 2024. arXiv:2401.18059. — recursive cluster-and-summarise at index time: a tree whose upper nodes are text absent from the corpus, and the layer ablation (any single layer ≈ 57.9, three layers 73.68).
  • Shim, Seongwoong, et al. "Beyond RAG vs. Long-Context: Learning Distraction-Aware Retrieval for Efficient Knowledge Grounding." International Conference on Learning Representations. Vol. 2026. 2026. arXiv:2509.21865. — the generator's long-context capacity moves the retrieval threshold; distraction as a property of the retrieved set.
  • Spärck Jones, Karen. "A statistical interpretation of term specificity and its application in retrieval." Journal of Documentation, vol. 28, no. 1, 1972, pp. 11–21. doi:10.1108/eb026526. — IDF.
  • Wang, Pengbo, et al. "One SPACE to Rule Them All: Jointly Mitigating Factuality and Faithfulness Hallucinations in LLMs." Advances in Neural Information Processing Systems. Vol. 38. 2025. arXiv:2506.11088.
  • Wang, Weizhi, et al. "Augmenting Language Models with Long-Term Memory." Advances in Neural Information Processing Systems. Vol. 36. 2023. arXiv:2306.07174. — LongMem; memory staleness and the frozen memory writer.
  • Wang, Zora Zhiruo, et al. "CodeRAG-Bench: Can Retrieval Augment Code Generation?" Findings of the Association for Computational Linguistics: NAACL 2025. 2025, pp. 3199–3214. arXiv:2406.14497. — BM25 and nine embedding models on code retrieval and on the retrieval of library documentation; a re-ranker applied to retrieved code.
  • Xia, Chunqiu Steven, et al. "Demystifying LLM-Based Software Engineering Agents." Proceedings of the ACM on Software Engineering, vol. 2, no. FSE, 2025, pp. 801–824. arXiv:2407.01489. — hierarchical localization (Agentless; the arXiv title is Agentless: Demystifying LLM-based Software Engineering Agents).
  • Xie, Jian, et al. "Adaptive Chameleon or Stubborn Sloth: Revealing the Behavior of Large Language Models in Knowledge Conflicts." International Conference on Learning Representations. Vol. 2024. 2024. arXiv:2305.13300.
  • Yang, John, et al. "SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering." Advances in Neural Information Processing Systems. Vol. 37. 2024. arXiv:2405.15793. — the agent–computer interface (ACI): the commands available to a model and the form in which their results return to it.
  • Zhang, Fengji, et al. "RepoCoder: Repository-Level Code Completion Through Iterative Retrieval and Generation." Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing. 2023, pp. 2471–2484. arXiv:2303.12570. — the draft as the query of the next retrieval; the RepoEval benchmark.
  • Zhang, Tianyi, et al. "BERTScore: Evaluating Text Generation with BERT." International Conference on Learning Representations. Vol. 2020. 2020. arXiv:1904.09675. — token-level similarity under a contextual embedding, the second reference-based instrument of the table.
  • Zhang, Yilin, et al. "cAST: Enhancing Code Retrieval-Augmented Generation with Structural Chunking via Abstract Syntax Tree." Findings of the Association for Computational Linguistics: EMNLP 2025. 2025, pp. 8106–8116. arXiv:2506.15655. — chunking along the syntax tree.

Preprints & other non-peer-reviewed papers

  • Cochran, Theodore O. "Single-Round Vector RAG vs an LLM-Compiled Wiki: A Preregistered Comparison on a Small Multi-Domain Research Corpus." arXiv preprint arXiv:2605.18490 (2026). — the index-and-pages design measured against single-round and decomposition retrieval: better cross-paper synthesis, about 21× the query tokens.
  • Edge, Darren, et al. "From Local to Global: A GraphRAG Approach to Query-Focused Summarization." arXiv preprint arXiv:2404.16130 (2025). — the question no top-$k$ answers at any $k$, and query-focused summarization as the task it really is.
  • Gao, Yunfan, et al. "Retrieval-Augmented Generation for Large Language Models: A Survey." arXiv preprint arXiv:2312.10997 (2024). — the three stages; the Naive / Advanced / Modular paradigms; the three quality scores.
  • Günther, Michael, et al. "Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models." arXiv preprint arXiv:2409.04701 (2024). — late chunking: the embedding model reads the whole document once, and a chunk vector is the mean of the token vectors inside the chunk's boundaries.
  • Lu, Wensheng, et al. "HiChunk: Evaluating and Enhancing Retrieval-Augmented Generation with Hierarchical Chunking." arXiv preprint arXiv:2509.11552 (2025). — evidence sparsity: the standard document-QA collections carry 1.7–10.5 sentences of evidence per document, so they cannot separate one chunker from another; and the auto-merge retrieval rule.
  • Nogueira, Rodrigo, and Kyunghyun Cho. "Passage Re-ranking with BERT." arXiv preprint arXiv:1901.04085 (2019). — the cross-encoder re-ranker over the BM25 top-1,000.
  • Oord, Aaron van den, et al. "Representation Learning with Contrastive Predictive Coding." arXiv preprint arXiv:1807.03748 (2018). — InfoNCE, the loss a text embedder is trained with: the cross-entropy of picking the positive out of $N$ candidates, whose optimum is the density ratio $p(x\mid c)/p(x)$ and which bounds the mutual information from below, $I(x;c) \ge \log N - \mathcal{L}_N$ — tighter the more negatives the batch holds.
  • OpenAI. "GPT-4 Technical Report." arXiv preprint arXiv:2303.08774 (2023). — System Card, fn. 10: closed-domain and open-domain hallucination.
  • Packer, Charles, et al. "MemGPT: Towards LLMs as Operating Systems." arXiv preprint arXiv:2310.08560 (2024). — the retriever ceiling on a fixed-context reader; paging and re-querying as the escape; the nested key-value multi-hop task.
  • Rackauckas, Zackary. "RAG-Fusion: a New Take on Retrieval-Augmented Generation." arXiv preprint arXiv:2402.03367 (2024). — multi-query retrieval fused by reciprocal rank fusion; the drift of generated queries and the latency cost. (A case study: cited for the mechanism, not for a size of effect.)
  • Singh, Aditi, et al. "Agentic Retrieval-Augmented Generation: A Survey on Agentic RAG." arXiv preprint arXiv:2501.09136 (2026). — §10's cautions: agentic reasoning does not compensate for poor retrieval. (Judgement, not measurement.)
  • Tao, Yicheng, et al. "Retrieval-Augmented Code Generation: A Survey with Focus on Repository-Level Approaches." arXiv preprint arXiv:2510.04905 (2026). — survey; the term command-driven retrieval.
  • Yan, Shi-Qi, et al. "Corrective Retrieval Augmented Generation." arXiv preprint arXiv:2401.15884 (2024). — the retrieval evaluator, the three actions and the web-search fallback; the control showing that the gain is the decision, not the web.
  • Zhang, Yue, et al. "Siren's Song in the AI Ocean: A Survey on Hallucination in Large Language Models." arXiv preprint arXiv:2309.01219 (2025).

Textbooks & monographs

  • Jurafsky, Daniel, and James H. Martin. Speech and Language Processing: An Introduction to Natural Language Processing, Computational Linguistics, and Speech Recognition with Language Models. 3rd ed., online manuscript released August 19, 2026. https://web.stanford.edu/~jurafsky/slp3/ — tf-idf and BM25 term weighting, document scoring and the inverted index (ch. 11, §11.1); the evaluation of ranked retrieval (§11.2); retrieval with dense vectors (§11.3).
  • Manning, Christopher D., et al. Introduction to Information Retrieval. Cambridge University Press, 2008. — §11.4.3 Okapi BM25 and its parameter values.

Blogs, documentation & other web sources