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.
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:
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 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.
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.
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
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:
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:
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.
A retrieval pipeline consists of three stages — indexing, retrieval and generation (Gao et al., 2024):
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.
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.
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.
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:
Three of these seven steps involve permanent, unrecoverable decisions:
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.
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.
A chunk is two things at once, and they want opposite sizes:
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.
| 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.
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 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.
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.
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.
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.
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.
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:
nprobe: how many of those cells a single query actually searches).efSearch: the size of the candidate list HNSW keeps while it searches).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."
Structure. The index has two parts (Manning et al., 2008, §1.2, §6.3.3):
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):
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).
Retrieval is the selection of a few passages from a large collection, given a query. Two components perform it.
Three practical principles follow from how scoring and ranking work in practice:
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
| 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 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:
$$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 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 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 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.
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):
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 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.
The loop makes five decisions that the static pipeline makes once or not at all:
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.
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 |
The diagram is the reflection pattern (after Singh et al., 2026, Fig. 8).
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.
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.
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 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) |
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 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:
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 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:
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.
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):
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.
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.
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.
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.
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.
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.
The seven questions, answered.
Peer-reviewed papers
[CLS]/[SEP] sentence-pair input and the classification layer on the final [CLS] vector: the cross-encoder.search.text-embedding-ada-002 60.99 → 52.7) that argues
for evaluating the embedder on your own documents.Preprints & other non-peer-reviewed papers
Textbooks & monographs
Blogs, documentation & other web sources
compact, refine, tree_summarize).
(Cited for the vocabulary only; it reports no measurement.)