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 response-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. Indexing, retrieval and generation 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 · Generation How do $k$ retrieved passages become one answer? Passage Position in the Prompt · Grounding and Citation · 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? Limitations of Static RAG · The Retriever Ceiling · RAG Paradigms · Agentic Retrieval Loop · Adaptive Retrieval · Retrieval as a Tool · Evidence Assessment and Stopping · Agentic RAG Architectures · Agentic versus Static RAG · Further Reading on Agentic 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, Yilin 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.

Hierarchical Navigable Small World (HNSW) is a graph index for approximate nearest-neighbour search (Malkov & Yashunin, 2020). Every stored vector is a node, and an edge joins two vectors that lie close to each other. A query $q$ is answered by a walk along the edges towards $q$: only the nodes reached by the walk are compared with $q$, not all $N$ vectors.

  • Greedy routing. The walk moves to the neighbour nearest to $q$ as long as that neighbour is nearer than the current node. The node where it stops is a local minimum of the distance to $q$: none of its neighbours is nearer, but a node elsewhere in the graph may be.
  • Beam search. The search keeps the $\textit{ef}$ nearest nodes found so far instead of one, and stops when the nearest unexamined node is further from $q$ than all of them. A larger $\textit{ef}$ keeps nodes that are further than the best one found, so the search can pass through them and leave a local minimum, at the cost of more distance computations: $\textit{ef}$ is the efSearch setting.
  • Layers. Layer 0 holds every node; each higher layer holds about one node in $M$ of the layer below, $M$ being the number of edges per node fixed at build time, so its edges span longer distances. The search routes greedily through the upper layers from the top and runs the beam search only on layer 0, starting from the node the upper layers reached.

Design rule. efSearch is set per query from a recall measurement on the system's own questions: recall and latency both rise with it. $M$ and efConstruction are fixed when the index is built and change only by rebuilding it.

The descent of an HNSW search, as a figure. Each layer hands its nearest element down as the enter point of the next layer; only the bottom layer is searched with a beam of width ef.

upper layers — ef = 1, greedy routingenter pointlayer 3 · ~240 elementslayer 2 · ~3,900layer 1 · ~62,500layer 0 · 1,000,000 — beamsearch, width efK nearest

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 — Generation

Generation, also called synthesis, is the third stage of RAG: the model writes one answer from the question and the $k$ retrieved passages. It decides where each passage stands in the prompt and how many model calls read the passages. It adds no new component: it is a prompt, or a sequence of prompts, sent to the same model. Generation does not check the passages: an answer grounded in them repeats their errors, and its citations are supported only as often as a measurement shows.

Passage Position in the Prompt

The position of a passage in the prompt changes whether the model uses it. Liu et al. (2024) give language models 20 Wikipedia passages per question of NaturalQuestions-Open, exactly one of which contains the answer, and move that passage from the first to the last position. Accuracy, the share of questions whose output contains one of the annotated answers, is U-shaped: highest when the answer passage is first or last, lowest in the middle. With the answer passage in the middle, the accuracy of GPT-3.5-Turbo falls below 56.1 %, its accuracy with no passages at all.

Design rule. The highest-ranked passages are placed at the beginning and at the end of the prompt, not in the middle. Liu et al. measure the curve, not this reordering.

Grounding and Citation

Grounding is not verification. An answer is grounded when it is produced from the supplied passages; it would be verified if a step checked that the passages are true. No stage of the RAG pipeline contains such a step.

Evidence. Chen, J. et al. (2024) give ChatGPT news passages in which the answer was falsified by hand, and warn it that the passages may contain errors. Its accuracy falls from 91 % without the passages to 17 % with them (Chinese questions; English: 89 % to 9 %), and it reports the error in at most 8 % of the cases.

Design rule. A RAG answer inherits the errors of its corpus. Documents that may be wrong are checked before they are indexed; an instruction to the model to doubt them does not replace that check.

Retrieval does not make citations supported. Citation precision is the share of cited claims that the cited passage supports. On long-form answers, Asai et al. (2024) measure 2–6 % for Llama 2 and Alpaca (7B, 13B) with retrieval and 65 % for ChatGPT with retrieval. Self-RAG, a model trained to check each generated sentence against its passage, reaches 67–70 %.

Design rule. Whether citations are supported is measured, not assumed. Where they must be, each claim is checked against its passage — by a trained model as in Self-RAG, or by a separate judge after generation.

Response Synthesis over $k$ Passages

Response synthesis turns the $k$ retrieved passages into one answer. Four of the response modes of LlamaIndex are synthesis strategies, and they differ in how many passages one model call reads and what is kept between calls (LlamaIndex, 2026); compact is the default.

$b$ is the number of passages placed in one prompt. The context window sets its upper limit: the space left after the instructions and the answer, divided by the length of one passage. Below that limit $b$ is a design choice. A smaller $b$ keeps each prompt short, so fewer passages sit in the poorly used middle (Passage Position in the Prompt) and each call costs less, at the price of more calls.

Design rule. No study gives a value for $b$. It is raised step by step on an evaluation set of the application, and the increase stops where the answer accuracy no longer rises (Part V — Evaluation).

Strategy How it works Model calls LlamaIndex mode Suited to
single pass all passages in one prompt 1; possible only if $k \le b$ compact (with $k \le b$) the default: fastest and cheapest
truncated single pass every passage is cut short until all fit into one prompt 1 simple_summarize quick summaries; the cut text is lost
iterative refinement one group of $b$ passages per call; the model revises its answer after each call $\lceil k/b \rceil$, one after another ($k$ for $b = 1$) refine ($b = 1$); compact with $k > b$ more passages than one prompt holds; slow
hierarchical merging summarise groups of $b$ passages, then summarise the summaries, until one text is left about $k/b$ in the first round, fewer after it; the calls of one round run in parallel tree_summarize summarising many passages

Each strategy has its own weakness. The single pass under-uses passages in the middle of a long prompt (Passage Position in the Prompt), but it is the only strategy that places all $k$ passages in one prompt, so that the model can compare any two of them. The truncated single pass discards retrieved text after retrieval: a passage counted by recall@$k$ never reaches the model, the failure point not in context of Barnett et al. (2024). Refinement keeps only the answer between calls: a passage of an earlier group reaches the final answer only through the text of the answer so far, and a later call may rewrite that text; no measurement of this order effect is published. Merging compresses in every round: Wu et al. (2021) rate summaries of whole books lower than the summaries of any of the individual sub-tasks the tree was built from, and attribute the gap to errors accumulated at each depth.

Sources. The LlamaIndex documentation describes the modes and reports no measurement. Hierarchical merging over retrieved text is the summary tree of Wu et al. (2021), built at query time. Neither source compares the three strategies on one task; the choice follows from the properties above.

Part V — Evaluation

Evaluation measures the pipeline stage by stage, so that the design decisions of each stage — indexing, retrieval and generation — can be compared. Chunking policy, embedder, retriever, re-ranker and response-synthesis strategy are each chosen by a measurement on questions of the application, not by argument.

Retrieval is measured separately from generation, and it is measured first: a generator or an agentic loop placed around a retriever that never returned the evidence cannot recover the missing passage. Separate measurement tells the two failures apart, and it decides whether retrieval should become a tool of the agent (Part VI — Agentic RAG).

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 …
indexing: the 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$
generation: fitting the passages into the prompt not in context was retrieved and dropped when the passages were fitted into the context budget (the truncated single pass of Response Synthesis over $k$ Passages is one way)
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 the gold set $G$ of a query, the passages marked relevant for it by hand. Write $R_k$ for the first $k$ passages the retriever returned:

$$\text{recall@}k = \frac{|R_k \cap G|}{|G|}, \qquad \text{precision@}k = \frac{|R_k \cap G|}{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 which share of the $k$ passages placed in the context is needed; $1 - \text{precision@}k$ is the share spent on passages that are not. Where fewer than $k$ passages are relevant, precision@$k$ cannot reach 1: its maximum is $|G|/k$, here $4/10 = 0.40$.

Three further scores measure the pipeline on one query — the triad of Es et al. (2024), collected by 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
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 different scores, and an example separates them. The context states "Refunds are accepted within 14 days of delivery and are paid to the original payment method." Asked "how long is the refund window?", the answer "30 days" is relevant and unfaithful: it addresses the question, and the context does not support it. The answer "Refunds are paid to the original payment method" is faithful and not relevant: the context supports it, and it does not address the question. Faithfulness is checked statement by statement against a passage that a reader can inspect; citation precision (Grounding and Citation) applies the same check to the passage an answer cites.

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 model calls, one after the other, each with its own prompt; the output of the first call is the input of the second:

  1. Call 1 — decomposition. The prompt contains the question and the answer; the model rewrites the answer as a set $S$ of short statements, each of which makes a single assertion.
  2. Call 2 — verification. The prompt contains the context $c(q)$ and all statements of $S$; the model returns, in one reply, the verdict yes or no for each statement $s_i$ — whether $s_i$ can be inferred from $c(q)$. The statements that receive yes form the subset $V \subseteq S$ of verified statements.

The cost is therefore two calls per answer, whatever the number of 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. Es et al. (2024) 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 Es et al. 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. Es et al. (2024) 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, and their agreement with human judges was measured. On WikiEval, questions about 50 Wikipedia pages on events after the start of 2022, two annotators chose the better of two answers (or two contexts) for each question; the scores of Es et al. (2024) chose the same one in 95 % of the pairs for faithfulness, 78 % for answer relevance and 70 % for context relevance, against 72 %, 52 % and 63 % for ChatGPT asked directly for a score from 0 to 10. Answer relevance is a cosine between embeddings: it measures whether the answer is about the question, not whether it is true.

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 prefers model-written text, or a second judge disagrees

Why the left column is not enough. It measures word overlap, not correctness: against the gold answer "14 days", the correct "two weeks" scores zero on exact match and close to zero on ROUGE. On SummEval, 23 summarization systems re-run under one protocol and rated by experts, 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 SummEval — 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": on news summaries written by freelance writers and by GPT-3.5, G-Eval scores the GPT-3.5 summaries higher on average, also where human judges preferred the human-written one (Liu, Y. et al., 2023, §4).

Design rule. A judged score is reported with a second judge and the disagreement between them, a reference-based metric is kept beside it, and a difference that only one of the two can see is treated as a hypothesis rather than as a result. Both measurements above concern summaries; for RAG answers the same check is run on the application's own questions.

Part VI — Agentic RAG

The static pipeline answers three questions in advance, the same way for every query: whether to retrieve — always; with which query — one formed by the same steps every time, the user's wording or its fixed rewrite; and whether the result suffices — the top $k$ is always accepted. Agentic RAG answers them at run time, where the answers can depend on what retrieval has already returned.

Limitations of Static RAG

A pipeline that answers the three questions in advance — static RAG — has three limitations that Singh et al. (2026), §2.4, name: the retrieved passages are not combined into one answer, a later retrieval cannot use an earlier result, and the cost of every query grows with the number of sources. Singh et al. call it traditional RAG and illustrate each limitation with an example query; the survey reports no measurement.

Limitation Example query (Singh et al., 2026, §2.4) Where the static pipeline fails
Contextual integration — each passage is relevant, and the answer does not connect them: it is fragmented, inconsistent or generic "What are the best sustainable practices for small-scale agriculture in arid regions?" returns documents on general agricultural methods and misses the practices for arid regions the question is embedded once, as one vector, in which the general topic dominates; passages on the qualifying condition (arid) rank below the top $k$, and no step checks the answer against every part of the question
Multi-step reasoning — the question needs information that can be found only after a first retrieval "What lessons from renewable energy policies in Europe can be applied to developing nations, and what are the potential economic impacts?" needs the policies, then their transfer to developing nations, then the economic impact every query is formed before any result is read, so a second retrieval cannot use a term that appears only in the first result
Scalability and latency — querying and ranking more sources takes more time live customer support or financial analytics that query several databases per question every source is queried and ranked for every query, whether the query needs it or not

An agent does not remove the third limitation. An agentic loop performs one retrieval per iteration, so its latency grows with the number of iterations; it saves time only on the queries for which it skips a source or a retrieval (see Agentic versus Static RAG).

A query that could not have been written in advance. 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 contains a term — Annex B — that appears only in the first result. A pipeline that retrieves once embeds the original question, retrieves once, and stops. A pipeline with a fixed second round can write the second query as well, but it performs that round for every query, also where the first result already answers it.

The Retriever Ceiling

Contextual integration and multi-step reasoning fail at the same bound: a reader that receives a fixed context cannot outperform its retriever, and the evidence it sees is bounded above by recall@$k$. The reader receives exactly the top $k$ chunks, 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). No prompt work on the reader raises this bound.

An agent that can query again and page onwards is bounded by recall over the whole ranking instead. A second query with different wording, or the next page of the same ranking, reaches documents that the first call did not return. The difference is largest for a multi-hop question, in which a retrieved value is the key of the next lookup. On a synthetic nested key–value task, in which a value may itself be a key, GPT-4 with all pairs in its context falls to 0 % accuracy at three nesting levels; MemGPT with GPT-4, which looks up each key with a search call, is unaffected by the nesting depth (Packer et al., 2024).

The higher bound is not reached automatically: the agent "will often stop paging through retriever results before exhausting the retriever database" (Packer et al., 2024). In a controlled comparison on two retrieval benchmarks, an agent with one retrieval tool and up to three turns retrieved a second time for 10 % of the queries, and the second retrieval returned the same documents as the first for 53 % of them (Ferrazzi et al., 2026, §3.4).

RAG Paradigms

Static RAG fixes its retrieval steps before the query arrives, so the retriever ceiling bounds it by the recall of the queries that those fixed steps issue; agentic RAG lets an agent choose the steps while the query is answered. The survey literature arranges RAG systems on four rungs, the RAG paradigms, which differ in control flow rather than in quality — the first three after Gao et al. (2024), the fourth after Singh et al. (2026):

Rung What it adds Shape
Naive RAG index → retrieve top-$k$ with the original query → generate, in one pass a chain
Advanced RAG query rewriting and expansion before retrieval, re-ranking and context compression after it a longer chain: still one pass
Modular RAG interchangeable modules — search, routing, fusion, memory, rewriting, re-ranking — which the designer connects a graph whose path may branch and repeat
Agentic RAG an agent decides the retrieval strategy at run time a loop

The two surveys define the retriever of naive RAG differently. Gao et al. (2024, §II.A) describe a dense retriever: chunks and query are encoded with "the same encoding model", and the $k$ chunks with the highest vector similarity are retrieved — the pipeline of The Three Stages: Indexing, Retrieval, Generation. Singh et al. (2026, §2.3.1), who cite Gao et al. for the term, describe a lexical one: "simple keyword-based retrieval techniques, such as TF-IDF and BM25". Both surveys agree on the shape — one retrieval with the original query, then generation — and the table defines the rung by that shape.

The first three rungs are static: in modular RAG the path may branch or repeat, but the designer fixed the modules and their connections. In agentic RAG the number of retrievals is unknown before the query arrives (Singh et al., 2026).

Agentic Retrieval Loop

Agentic RAG is retrieval-augmented generation in which an agent, and not a fixed pipeline, decides how to retrieve (Singh et al., 2026). A blog post of a vector-database vendor names the agent's decisions — whether to retrieve, which tool to use, how to formulate the query, whether to retrieve again — and its minimal form:

"In its simplest form, agentic RAG is a router." — Shorten & Monigatti (2024), Weaviate blog

In agentic RAG, retrieval is a tool inside the agent loop: 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.

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

The loop answers the three questions of the static pipeline per query, each with its own steps:

  1. Whether to retrieve — analyse the query. A question the weights can answer needs no retrieval; a question whose second fact depends on the first needs several (Adaptive Retrieval).
  2. With which query — select the source: a vector index, a relational database queried in SQL, a web search, another API, so that the agent acts as a router over knowledge sources (Singh et al., 2026, §5); and formulate the query: rewrite the question, divide it into sub-questions, or add a name that the question does not contain and an earlier retrieval result supplied — in the refund example of Limitations of Static RAG, Annex B.
  3. Whether the result suffices — judge the evidence: are the passages relevant, and do they suffice; then generate and check: is every claim of the answer supported by a passage. A failed judgement leads back to with which query: the loop selects another source or rewrites the query, until the stopping criterion ends it (Evidence Assessment and Stopping).

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.

The steps are agent patterns applied to retrieval. Tool use, planning, reflection and routing are developed for agents in general (→ L-Decomp); in agentic RAG the step they control is a retrieval (Singh et al., 2026, §3).

Adaptive Retrieval

Adaptive retrieval decides for each query whether to retrieve, and how often, instead of retrieving in the same way for every query. A multi-step loop spends several model and retriever calls on a query that one retrieval, or none, would have answered. Adaptive-RAG (Jeong et al., 2024) makes the decision before the first retrieval, from the query alone: a router — a small classifier over the query $q$ — selects one of three fixed strategies:

Class Strategy Calls
A — answerable from the weights no retrieval: $\bar a = \mathrm{LLM}(q)$ one model call
B — one retrieval suffices single-step: one call $d = \mathrm{Retriever}(q)$ returns the documents $d$, then $\bar a = \mathrm{LLM}(q, d)$ one of each
C — multi-hop multi-step: retrieval and generation alternate in rounds $i = 1, 2, \dots$ one retrieval and one model call per round

$\bar a$ is the generated answer and $d$ the set of documents that one call of the retriever returns — the top $k$ of its ranking, not a single document.

Strategy C retrieves and answers in rounds, and each round searches with what the earlier rounds found. In round $i$ the retriever receives the query $q$ together with the context $c_i = (d_1, \dots, d_{i-1}, \bar a_1, \dots, \bar a_{i-1})$ — the documents and the intermediate answers of all earlier rounds — and returns new documents, $d_i = \mathrm{Retriever}(q, c_i)$; the model then writes the intermediate answer $\bar a_i = \mathrm{LLM}(q, d_i, c_i)$. For "What currency is in Billy Giles' birthplace?" the first round finds the birthplace, and the second round, with the birthplace in its context, retrieves the currency (Jeong et al., 2024, §3.1, Fig. 2). The rounds end when the model writes the final answer. Jeong et al. implement strategy C with IRCoT, which interleaves chain-of-thought steps with retrievals; it takes 2.81 rounds per query on average (§4.2, Table 1).

The router is not an agent: it decides once, among strategies the designer fixed.

Evidence. Measured with GPT-3.5 over six question-answering benchmarks, three single-hop and three multi-hop, with F1 the word overlap between the generated and the gold answer (Jeong et al., 2024):

Strategy F1 Time per query, relative to single-step
no retrieval on every query 48.56 0.71
single-step on every query (standard RAG) 46.99 1.00
multi-step loop on every query 50.87 3.33
routed 50.91 1.46

Against standard RAG, the router raises F1 from 46.99 to 50.91 at 1.46 times the time per query; against the multi-step loop, it keeps F1 (50.91 against 50.87) at 1.46 instead of 3.33. The time is saved on the queries routed to A or B, which never enter the loop. The two directions of router error cost different things: a multi-hop query sent to B loses accuracy, because one retrieval cannot resolve it; a simple query sent to C loses only time.

The same decision can be made during generation. Self-RAG (Asai et al., 2024) trains the generator to emit a token that requests a retrieval; an agent on an unmodified model makes the decision by calling, or not calling, its retrieval tool.

Design rule. The loop runs only for the queries that need it: a decision in front of the loop keeps the cost of a simple query at that of single-step retrieval or below.

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 e.g. one named entity, and include or exclude documents from its own candidate set answers more questions correctly than the same agent restricted to search(query): without the additional operations, exact match falls from 69.6 to 63.4 on 2WikiMultiHopQA and from 34.8 to 30.1 on MuSiQue, two multi-hop question-answering benchmarks (Hui et al., 2026, Table 2). The operations a retrieval tool offers are therefore a design decision: they bound what the agent can do after a failed retrieval.

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; → L-ReAct): the commands available to the model and the form in which their results are returned to it.

Evidence Assessment and Stopping

Evidence assessment judges whether the retrieved passages are relevant and sufficient before the answer is written, and selects another source when they are not. Corrective RAG (CRAG; Yan et al., 2024) inserts a retrieval evaluator between the retriever and the generator: a small model that scores each (question, document) pair in $[-1, 1]$. Two thresholds turn the $k$ scores into one of three actions:

Action Condition What the generator receives
Correct at least one score above the upper threshold the retrieved documents, reduced to their relevant sentences
Incorrect all scores below the lower threshold the results of a web search with the question rewritten as keywords
Ambiguous otherwise both

CRAG decides once, after one retrieval, and never returns to the retriever. On PopQA, an entity-centric question-answering benchmark, with LLaMA2-7B as generator, accuracy is 50.5 % for plain RAG, 52.2 % when the web results are always added, and 54.9 % for CRAG: the web results raise accuracy by 1.7 percentage points when always added and by 4.4 when added on the evaluator's decision.

A prompted judge is weaker than CRAG's. The evaluator is T5-Large fine-tuned for the judgement and classifies retrieval quality correctly in 84.3 % of the test cases; ChatGPT, prompted for the same judgement, in 58.0 %, and in 64.7 % with few-shot examples (Yan et al., 2024, Table 4). An agent on an unmodified model judges with a prompt.

Design rule. A loop that judges its own evidence is bounded by the stopping criterion of Agentic Retrieval Loop; when the budget is exhausted, it answers from the evidence it holds or states that the evidence is insufficient. A fallback to the web moves the trust boundary: a web page is neither curated nor owned by the organisation that deployed the system.

Agentic RAG Architectures

The architectures of agentic RAG differ in how many agents hold the three decisions of the agentic retrieval loop and which sources they consult; the number of agents does not decide how often they retrieve: "a multi-agent system may still perform one-shot retrieval if its control policy is static" (Mishra et al., 2026, §IV.A).

Architecture Who decides Cost
Single-agent router one agent selects the source and the tool for each query; every result enters its one context every tool description is part of every prompt, so the survey recommends it for a limited number of tools or sources (Singh et al., 2026, §5.1)
Multi-agent, hierarchical a coordinator delegates to retrieval agents, one per source type, which may delegate further; each agent reads passages in its own context and returns a summary a multi-agent research system uses about fifteen times the tokens of a chat interaction (Hadfield et al., 2025); a wrong answer may originate in any agent's summary
Graph-based the agent consults a knowledge graph — entities as nodes, typed relations as edges — beside a text index, and follows edges for a question about a relation between entities a model extracts the graph from the corpus once; an entity it misses is absent from every later traversal (Edge et al., 2025)

Agentic versus Static RAG

Agentic RAG raises recall on questions that one retrieval cannot answer, at the cost of calls, latency and predictability; on questions that one retrieval does answer, it raises nothing.

Static RAG Agentic RAG Mechanism
Multi-hop questions bounded by recall@$k$ of the queries its fixed steps issue a later query may use a term from an earlier result The Retriever Ceiling
Simple questions sufficient same answer, more calls Adaptive Retrieval
Knowledge source fixed at design time selected per query Evidence Assessment and Stopping
Cost per query the same number of retrievals and model calls for every query one retrieval and at least one model call per iteration with four retrieval tools, 2.6 times the tokens of one search call on BRIGHT and 7.8 times on FinanceBench (Suresh et al., 2026); a one-tool agent against a fixed pipeline: 3.3 times the input tokens and 1.5 times the latency (Ferrazzi et al., 2026)
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 is logged and evaluated step by step (Singh et al., 2026, §10)
Termination after its fixed steps only by a stopping criterion the model may stop too early or invoke tools excessively (Singh et al., 2026, §10)

Evidence. Ferrazzi et al. (2026) compare an agent with one retrieval tool, which may rewrite the query and retrieve again for at most three turns, and a fixed pipeline with a semantic router, HyDE rewriting and a cross-encoder re-ranker. The agent's rewritten queries retrieve better (nDCG@10 55.6 against 52.8, mean of four datasets); its option to retrieve again leaves the retrieved list worse ordered than the re-ranker does (nDCG@10 43.9 against 49.5, mean of FiQA and CQADupStack).

Design rule. The index is measured and repaired first. The loop is added where the measurements show questions that one retrieval cannot answer, and it receives the decisions it measurably makes better — whether to retrieve, how to rewrite the query — while a re-ranking step stays in the pipeline.

Further Reading on Agentic RAG

Each topic that this part treats in outline is developed in a primary source:

Topic Where to read
The four rungs and the modules of modular RAG Gao et al. (2024), §II
Architectures, agentic patterns and workflow patterns of agentic RAG Singh et al. (2026), §§3–5
Necessary properties of agentic RAG; the loop as answer quality minus weighted cost Mishra et al. (2026), §III.D.2, Eq. 2
Retrieval policies trained with reinforcement learning Liang et al. (2025), §4.2
Retrieval decisions learned as tokens of the generator (Self-RAG) Asai et al. (2024)
Knowledge graphs extracted from a corpus (GraphRAG) Edge et al. (2025)
An agent against a fixed pipeline, decision by decision Ferrazzi et al. (2026)
Tool sets for an agentic retriever and their token cost Suresh et al. (2026); Du et al. (2026)

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, Yilin 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, Yilin 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, Yilin 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. It is the iterative pattern of modular RAG (see Part VI — Agentic RAG): the number of rounds is fixed before the query arrives. 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, but 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 a file in the chat, a file the conversation names, or a file whose path contains an identifier the conversation names. 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. No measurement isolates the map. The nearest is the skeleton stage of Hierarchical Localization: signatures without bodies keep the true edit location in 58.33 % of the issues, the complete files in 53.67 %.

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 — modular RAG in the terms of Part VI — Agentic RAG — 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 filesmodel names irrelevantfolders;embedding search over therestthe 3 files mostcommon to both listsskeletons 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. The two rows use different models, so the difference does not measure the pipeline alone. 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 system, a fixed pipeline or an 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. The mechanism is not specific to code: a question-answering agent over a prose corpus uses a keyword scan at query time beside a semantic search, and removing it lowers accepted answers on MuSiQue from 74.1 % to 72.6 % (Du et al., 2026, Table 2).

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. Where the requests are prose, a search over contents adds what a lexical or path-based choice misses: on SWE-bench Lite, whose requests are issue texts, embedding search over file contents added to the model's choice over paths keeps the true file in 81.67 % of the issues instead of 78.67 % (Hierarchical Localization).

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 naive pipeline, and the methods combine.

Method Element it changes Signal Index Next step chosen by Evidence
Syntactic chunking the unit the syntax tree chunk index the designer measured (Zhang, Yilin et al., 2025)
Iterative retrieval the query the model's draft lexical, over line windows the designer: a fixed number of rounds measured (Zhang et al., 2023)
Repository map the index and the score the reference graph graph, rebuilt per request the model, which requests files none published (Aider-AI, 2026)
Hierarchical localization the representation per stage paths, signatures, code; embeddings embeddings over the files kept the designer: fixed stages measured (Xia et al., 2025)
Command-driven retrieval the retriever exact text match none the agent 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

The exercises and the lab each have two sections, one for Parts I–III and one for Parts IV–VII of this note.

Parts lecture-RAG-exercises.ipynb — by hand lecture-RAG-lab.ipynb — programming
I–III index, context or neither; the curse of dimensionality; the search effort of HNSW and the size of its index, with quantization; filtered search; reciprocal rank fusion tutorials on a RAG pipeline from scratch, a vector database, an evaluation set with precision@$k$, recall@$k$ and MRR, lexical retrieval with BM25, reciprocal rank fusion, chunk size and superseded sources; optional tutorials on contextual retrieval, HNSW search effort, quantization, filtered search and adaptive retrieval with truncated vectors
IV–VII recall@$k$ and precision@$k$; static versus agentic RAG; the cost of a deep-search tree tutorials on retrieval as a tool of the agent loop, the static pipeline in LlamaIndex, and gold questions with near misses

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? The strongest passages are placed at the start and the end of the prompt; the answer is grounded in the passages, not verified, and whether its citations are supported is measured. A single pass reads all $k$ passages when they fit into one prompt; iterative refinement and hierarchical merging read them in groups when they do not.
  • 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.)
  • 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. (Cited as Zhang, Yilin et al. to separate it from Zhang, Yue et al.)
  • Zou, Wei, et al. "PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models." 34th USENIX Security Symposium (USENIX Security 25). 2025, pp. 3827–3844. arXiv:2402.07867. — five planted texts per question in millions of passages; the retrieval and generation conditions; failed defenses.

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.
  • Du, Mingxuan, et al. "A-RAG: Scaling Agentic Retrieval-Augmented Generation via Hierarchical Retrieval Interfaces." arXiv preprint arXiv:2602.03442 (2026). — keyword, sentence and chunk-level retrieval tools with snippets; accuracy, corpus tokens read and failure analysis on multi-hop QA.
  • 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.
  • Ferrazzi, Pietro, et al. "Is Agentic RAG Worth It? An Experimental Comparison of RAG Approaches." arXiv preprint arXiv:2601.07711 (2026). — a one-tool agent against a router, HyDE and re-ranking pipeline, dimension by dimension, with token cost and latency.
  • 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.
  • Liang, Jintao, et al. "Reasoning RAG via System 1 or System 2: A Survey on Reasoning Agentic Retrieval-Augmented Generation for Industry Challenges." arXiv preprint arXiv:2506.10408 (2025). — predefined versus agentic reasoning; training-based retrieval policies. (Cited for the taxonomy only; its descriptions of CRAG and Adaptive-RAG disagree with the primaries.)
  • 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.
  • Mishra, Saroj, et al. "SoK: Agentic Retrieval-Augmented Generation (RAG): Taxonomy, Architectures, Evaluation, and Research Directions." arXiv preprint arXiv:2603.07379 (2026). — agentic RAG as a sequential decision process with a cost term; four necessary properties; active versus agentic retrieval; topology independent of retrieval strategy. (No experiments of its own.)
  • 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.)
  • Suresh, Susheel, et al. "AgenticRAG: Agentic Retrieval for Enterprise Knowledge Bases." arXiv preprint arXiv:2605.05538 (2026). — search, find, open and summarize over an enterprise search engine; recall@1 and token cost on BRIGHT. (Vendor system, self-run baselines.)
  • 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.
  • Wu, Jeff, et al. "Recursively Summarizing Books with Human Feedback." arXiv preprint arXiv:2109.10862 (2021). — the query-time summary tree behind hierarchical merging. (A training paper; only its inference-time tree is cited.)
  • 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). (Cited as Zhang, Yue et al. to separate it from Zhang, Yilin et al.)

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