Chapter 3: From BM25 to Agentic RAG
Production retrieval grounds AI agents in live, verifiable knowledge that parametric weights cannot store reliably. Modern retrieval pipelines combine sparse lexical matching (Okapi BM25) with dense semantic embeddings via Reciprocal Rank Fusion (RRF) and cross-encoder reranking, then elevate retrieval from a brittle single-pass pipeline into Agentic RAG—where the agent iteratively formulates queries, inspects results, traverses filesystems with CLI tools like ripgrep or GraphRAG, and verifies evidence sufficiency.
1. Why Non-Parametric Retrieval Matters for Agents
Pretrained model weights store parametric memory—compressed statistical associations frozen at a training cutoff. Relying on parametric memory alone causes three structural failures in production agents:
- Staleness & Private Data Blindness: Internal repositories, live APIs, and recent incident logs are absent from pretraining weights.
- Unverifiable Hallucinations: Parametric recall cannot emit exact source citations, line numbers, or provenance.
- Expensive Updates: Fine-tuning weights to inject mutable facts is slow, costly, and prone to catastrophic forgetting.
Retrieval-Augmented Generation (RAG) equips the agent with non-parametric memory queried dynamically at inference time. Stanford CS329Z (Lectures 3 & 4) traces the evolution from classical lexical search to hybrid pipelines and Agentic RAG.
2. Sparse Lexical Retrieval: TF-IDF & Okapi BM25
Despite the rise of neural embeddings, lexical retrieval remains indispensable in engineering agents because it enforces exact token matching on identifiers, stack-trace symbols, UUIDs, SQL column names, and error codes (ERR_CONNECTION_REFUSED).
Okapi BM25 scores a document against query as:
where the Inverse Document Frequency (Lucene non-negative variant of the Robertson–Sparck Jones formulation) is:
- : Term frequency of in document .
- and : Length of document (in tokens) and average document length across the corpus of documents.
- : Number of documents containing term .
- (Term-Frequency Saturation): Unlike raw TF-IDF where score grows linearly with repetitions, BM25 saturates asymptotically toward as , preventing keyword-stuffed documents from dominating.
- (Length Normalization, typically ): Penalizes overly long documents that contain query terms merely by volume; disables length normalization.
Limitation (Vocabulary Mismatch): BM25 treats words as orthogonal discrete IDs. A query for “GPU out of memory” achieves zero lexical overlap with a document discussing “CUDA allocation failure” unless synonyms are explicitly expanded.
3. Dense Retrieval, Late Interaction & Vector Indexing
3.1 Bi-Encoders vs. Late Interaction (ColBERT)
Dense Bi-Encoders map queries and documents independently into a shared embedding space and score similarity via inner product or cosine similarity:
- Advantage: Document vectors are precomputed offline, making online retrieval a single query encoding plus an Approximate Nearest Neighbor (ANN) lookup.
- Limitation (Information Bottleneck): Compressing a 500-token technical document into one vector loses fine-grained entity distinctions.
- Late Interaction (ColBERT): Retains per-token vectors for both query and document, computing MaxSim across token pairs: This preserves fine-grained token matching while still precomputing document token embeddings offline.
3.2 Vector Indexing Trade-offs (Flat vs. HNSW vs. IVF-PQ)
| Index Type | Search Mechanism | Query Time | Recall vs. Exact | Memory Footprint & Systems Trade-off |
|---|---|---|---|---|
| Flat (Brute-Force) | Exact scan over all vectors | exact | Zero index overhead; best for chunks or strict exactness | |
| HNSW | Multi-layer navigable proximity graph | (empirical) | Very high () | High RAM usage (vectors + graph adjacency lists); fast low-latency serving |
| IVF-PQ | K-means cluster partitioning + Product Quantization | Sublinear (probes nprobe cells) |
Moderate (quantization loss) | RAM compression; scales to vectors on disk/RAM |
3.3 Chunking & Contextual Retrieval
Retrieval fails most often before indexing, due to naive fixed-size chunking that severs pronouns from subjects or splits functions mid-body:
- Structure-Aware / AST Chunking: Split Markdown by heading hierarchy and source code by Abstract Syntax Tree (AST) boundaries (functions, classes, methods) rather than arbitrary character counts.
- Contextual Retrieval (Anthropic pattern): Prepend a short LLM-generated situating header to each chunk before embedding and BM25 indexing (e.g., “From
auth/oauth.py, classTokenVerifier: this method validates PKCE challenges…”). Retaining document-level provenance prevents orphaned chunks from losing meaning.
4. Hybrid Retrieval, RRF, and Two-Stage Reranking
Because BM25 excels at exact lexical precision while dense vectors capture semantic paraphrases, production RAG pipelines run Hybrid Search in parallel and fuse rankings.
4.1 Reciprocal Rank Fusion (RRF)
Raw BM25 scores (unbounded positive floats) and cosine similarities () live on incompatible scales. Reciprocal Rank Fusion avoids fragile score-calibration tuning by combining ranks instead of raw scores:
where is the set of retrievers (e.g., BM25 + dense vector search), is the rank of document in retriever , and is a smoothing constant (standard ) that dampens the impact of outlier top-1 spikes from any single retriever.
4.2 Cross-Encoder Reranking (Two-Stage Architecture)
- Stage 1 — High-Recall Candidate Generation: Hybrid BM25 + Bi-Encoder retrieves candidates in .
- Stage 2 — High-Precision Reranking: A Cross-Encoder concatenates the query and each candidate document so self-attention interacts across every query-document token pair jointly, outputting a calibrated relevance logit. We pass only the top reranked chunks into the generator’s context window—maximizing signal density and mitigating Context Distraction (Chapter 2).
5. Evaluating Retrieval Quality
Before debugging the LLM generator, isolate retrieval errors using standard IR metrics:
- Recall@: Fraction of all ground-truth relevant documents appearing in the top retrieved results (critical for Stage 1 candidate generation).
- MRR (Mean Reciprocal Rank): where is the position of the first relevant document.
- nDCG@ (Normalized Discounted Cumulative Gain): Evaluates graded relevance () with logarithmic position discounting:
where is the ideal DCG obtained by sorting candidates in descending order of true relevance.
6. The Evolution: Static RAG Corrective RAG Agentic RAG
| Paradigm | Control Flow | Query Formulation | Failure Handling |
|---|---|---|---|
| Static Naive RAG | Fixed 1-pass: Embed Top- Generate | Raw user prompt verbatim | Fails silently; hallucinates or says “I don’t know” if top- misses |
| Advanced / Corrective RAG (CRAG / Self-RAG) | Fixed pipeline with conditional branches | Query rewriting, sub-query decomposition, or HyDE (embed a hypothetical answer) | Grades retrieved chunks; falls back to web/secondary search if relevance grade is low |
| Agentic RAG | Autonomous multi-turn loop | Agent plans search strategy, writes targeted queries, inspects snippets, and refines | Detects insufficient evidence, pivots query terms, follows cross-references, or abstains |
6.1 Why Static RAG Fails on Multi-Hop & Analytical Queries
Consider asking: “Why did the checkout-service latency spike after PR #4182?”
- A static vector search matches documents containing
"checkout-service"and"latency", missing the actual diff in PR #4182 and the downstream database migration it triggered. - Agentic RAG treats retrieval as a suite of agentic tools:
- Call
git_show(pr=4182)discovers modified filebilling/queries.sql. - Call
grep_search("get_user_invoices")finds callers across microservices. - Call
read_file_range("billing/queries.sql", 120, 180)identifies an unindexedJOIN. - Synthesize root cause with exact file-and-line citations.
- Call
6.2 Filesystem & CLI Search vs. Vector DBs (The Coding-Agent Insight)
A major engineering lesson emphasized in Stanford CS329Z (and demonstrated by systems like Claude Code and SWE-agent) is that pre-indexed vector databases are often inferior to direct filesystem & CLI search for live codebases:
- Zero Index Staleness: After an agent edits a file, a vector DB index is immediately out of date unless re-embedded;
ripgrep(rg),fd, andgit grepalways query live ground-truth state. - Exact Structural Navigation: Codebases are sparse graphs of exact symbol names, imports, and file paths. Regex search (
rg -n "class AuthMiddleware") + AST symbol lookup + targeted line-range reads (sed -n '40,120p') preserve exact syntax without chunk-boundary truncation. - When Vector / Hybrid Search Still Wins: Unstructured prose corpora (millions of PDFs, support tickets, internal wikis, Slack archives) where vocabulary mismatch is high and exhaustive CLI scanning is too slow.
6.3 GraphRAG for Global Synthesis
Standard chunk retrieval (whether BM25, dense, or grep) excels at local needle queries (“What is the timeout configured in redis.yaml?”) but fails at global corpus-wide synthesis (“What are the five most common recurring failure modes across 5,000 postmortems?”), because no 5 chunks represent the entire dataset.
GraphRAG builds an offline entity-relationship knowledge graph over the corpus, runs hierarchical community detection (e.g., Leiden clustering), and pre-summarizes each community. At query time, the agent can traverse local multi-hop entity neighborhoods or map-reduce across community summaries to answer global thematic questions.
7. Key Takeaways & Interview Synthesis
- Hybrid + Rerank is the baseline: Combine Okapi BM25 (exact lexical tokens, identifiers) with dense Bi-Encoders (semantic similarity) via RRF (), then refine with a Cross-Encoder before entering the LLM context.
- Evaluate retrieval independently of generation: Measure Recall@ and nDCG@ on curated query-relevance pairs before tuning system prompts.
- Upgrade to Agentic RAG when queries require multi-hop reasoning or live state: Expose search as composable tools (
grep, semantic search, graph lookup, targeted file reads) and prefer live CLI tools over stale vector indices in dynamic codebases.