Back to all articlesAI & Agents

Building a RAG Retriever That Earns Its Place (Part 5)

Retrieval in three stages

Chunkingsentence-aware, 420 chars, 90 overlap
Hybrid recallBM25 + dense, fused by RRF
Rerankingpay latency, buy precision
Relevance floora miss becomes ERROR[not_found]

One search call, three stages

The pool exists for recall; the reranker exists for order.

One search call, three stages — flow diagramOne search call, three stages. Flow diagram with 6 steps. Shapes: pill = input, rounded rect = process, diamond = decision, double border = output, dashed = loop. Steps in order: Step 1, query (input), minLength 2, validated by schema; Step 2, BM25 over postings (process), 0.015 ms on 19 chunks; Step 3, dense cosine (process), hashed n-gram embedder, 0.6 ms; Step 4, RRF fusion (decision), rank position only, k = 60; Step 5, rerank pool (process), coverage + phrase + proximity; Step 6, top-k with citations (output), doc#n or ERROR[not_found]. Then loops back to step 4: ↺ every search tool call goes through all three stages.queryminLength 2, validated by schemaBM25 over postings0.015 ms on 19 chunksdense cosinehashed n-gram embedder, 0.6 msRRF fusionrank position only, k = 60rerank poolcoverage + phrase + proximitytop-k with citationsdoc#n or ERROR[not_found]
  • input
  • process
  • decision
  • output

Measured on 19 chunks, 8 queries

Recall@12 (pool)P@1 (precision)
BM25 alone0.880.62
Dense alone1.000.38
Hybrid (RRF)1.000.50
Verdictfusion earns its keepbuy a real model

The search tool from Part 1 is a five-entry dictionary. Ask it about the agent loop and it returns a sentence; ask it anything else and it returns no matches. Every claim the agent makes is therefore either one of those five sentences or an invention, and the loop has no way to tell the difference.

The reflex is to bolt on a vector database. That reflex is half right: dense retrieval is genuinely better at paraphrase. But it is only one of three stages, and the other two are where most production RAG systems quietly fail. A retriever that returns the wrong chunk with a high cosine score is worse than one that returns nothing, because the agent will cite it.

This part builds the retriever as three separable stages — chunk, recall, rerank — each with a measurable job, plus the harness that tells you whether a stage is helping or just adding latency. The pipeline is wired into the same Tool contract from Part 2, so citations survive into the final answer and Part 7 can verify them.

What you’ll build

A rag.py module with five pieces:

  • chunk_document — sentence-aware packing with a configurable overlap, producing Chunk objects whose citation is doc#n.
  • BM25Index — Okapi BM25 over an inverted index, 0.015 ms per query on 19 chunks, no dependency.
  • HashedEmbedder + VectorIndex — a dense leg behind an embed(text) -> list[float] interface, so swapping in a real model is a twenty-line adapter.
  • HybridRetriever — BM25 and dense lists fused by reciprocal rank fusion.
  • CorpusRetriever + make_search_tool — reranking, a relevance floor, and the search tool the agent already knows how to call.

The current state of research-agent after Parts 1–4: a loop with validated tool contracts, a context budget, and SQLite memory. search is the last stub. This part replaces it without touching AgentLoop, which is the test of whether the earlier abstractions were real.

Prerequisites

  • Parts 1–4. rag.py imports Tool, ToolResult and ErrorCode from contracts.py; the demo imports AgentLoop and ScriptedLLM.
  • Python 3.10+, standard library only. No numpy, no vector database, no embedding API key.
  • A corpus as a dict[str, str] mapping document id to text. The fixture below is twelve short documents about agent engineering, which chunk into nineteen passages.

The fixture is a dict of documents, twelve of them, each a few sentences. It is small on purpose: small enough that every score in this article can be reproduced on one core in under a second, and varied enough to contain the lexical traps that break a naive index.

DOCUMENTS = {
"chunking": (
"Chunk size sets the ceiling on retrieval precision. A 900-character chunk that "
"contains three unrelated points will rank for all three and answer none of them "
"cleanly. A 120-character chunk loses the pronoun and the subject of its own "
"sentence. The band that survives contact with real corpora is 300 to 500 "
"characters with an overlap of roughly one fifth of the window. Overlap exists so "
"a sentence split across a boundary is still retrievable from one side; it also "
"duplicates text, so a 20 percent overlap inflates the index by 20 percent. Split "
"on sentence boundaries, never mid-word. Then measure: recall at five on a "
"labelled query set is the only number that tells you whether the window is right."
),
"retrieval-design": (
"A retrieval pipeline has three stages and they fail differently. Recall stage: "
"fetch a candidate pool of twenty to fifty passages. Lexical scoring with BM25 "
"catches exact identifiers, error codes and product names; dense retrieval catches "
"paraphrase such as retrieve versus retrieval. Fuse the two ranked lists by "
"reciprocal rank fusion rather than by adding raw scores, because BM25 scores are "
"unbounded while cosine similarity lives in a fixed range. Rerank stage: a "
"cross-encoder scores each query and passage pair jointly and is far more accurate "
"than either first stage, at roughly ten milliseconds per pair. Generation stage: "
"the model receives four passages with citation ids and must cite one per claim."
),
"latency-budget": (
"Search latency is a budget, not a property. On a single CPU core, BM25 over "
"twenty thousand chunks answers in about 4 milliseconds because it touches only "
"the postings of query terms. Brute-force cosine over the same set costs 38 "
"milliseconds in pure Python and 3 milliseconds with a matrix multiply. A "
"cross-encoder reranker over twenty candidates costs 180 to 240 milliseconds per "
"query at 12 layers. If the agent issues five searches per run, reranking adds "
"more than a second to the run and the p95 latency of the tool dominates the p95 "
"of the answer. Cap the rerank set at eight candidates and the added cost falls "
"under 100 milliseconds."
),
"planner": (
"A planner turns one goal into a graph of tasks with explicit dependencies. The "
"graph, not the prose plan, is what the executor runs: a task becomes ready only "
"when every task it depends on has completed. Two invariants matter. The graph "
"must be acyclic, checked before execution rather than discovered by a stack "
"overflow, and every dependency must name a task that exists. When a task fails, "
"the planner is invoked again with the failure as input; the cheapest replan adds "
"remediation tasks in front of the remaining work instead of rebuilding the whole "
"plan, which is why replans are bounded to two per run."
),
"reflection": (
"Reflection is a second pass that critiques the first answer and, if the critique "
"finds a defect, produces a revision. It improves answers when the critique is "
"anchored to evidence and degrades them when the model is asked to judge itself in "
"the abstract. A loop needs three stop conditions: a hard round limit, a minimum "
"score improvement below which another round is waste, and an oscillation check "
"that fires when the same critique returns twice. Without the second condition "
"the loop spends tokens rewriting a correct answer; without the third it "
"alternates between two versions forever."
),
"citations": (
"A citation id is a pointer from a claim to a passage, and it is the only cheap "
"way to verify an answer mechanically. Format the id as document plus chunk "
"ordinal, for example latency-budget#1, so a checker can reload the exact text. "
"Verification then becomes decidable: does the cited chunk exist, does it contain "
"the number in the claim, does the quote appear verbatim. An answer with no "
"citation is not automatically wrong, but it is unverifiable, and the difference "
"matters when a downstream step trusts the number."
),
"cdn-transfer": (
"Chunked transfer encoding splits an HTTP response into chunks of up to 64 KB so "
"a proxy can forward bytes before the origin finishes writing. The chunk size is a "
"transport decision, unrelated to how much text a reader can absorb at once, and "
"changing it never changes answer quality. A CDN that buffers whole responses "
"defeats the purpose: the first byte arrives only after the last chunk."
),
"cache-latency": (
"A read-through cache in front of the index drops p95 latency from 240 ms to 9 ms "
"for repeated queries, but the hit rate on a research workload is 31 percent "
"because every run asks new questions. Cache the embedding of a query, not the "
"result of a search, and the hit rate rises to 68 percent without returning stale "
"passages."
),
"document-store": (
"A document database stores JSON documents and indexes their fields. Retrieving a "
"document by primary key is a hash lookup and takes microseconds; retrieving by an "
"unindexed field is a full collection scan. Documents in this sense are rows, not "
"prose, and no amount of chunk size tuning changes that."
),
"self-critique": (
"Asking a model to reflect on its answer in the abstract produces longer answers "
"with the same errors. The model has no new information, so the critique restates "
"the answer with more confident wording. Reflection helps only when the critique is "
"given evidence the first pass did not have, or a checker it cannot argue with."
),
"ide-plan-mode": (
"Plan mode in an editor writes a plan file, waits for approval, then executes. When "
"a step fails the developer edits the plan by hand and reruns; there is no automatic "
"replan and no dependency graph, which is fine because a human is the scheduler."
),
"prompt-caching": (
"Prompt caching bills the unchanged prefix at a tenth of the input price. The "
"saving depends on prefix stability: an agent that injects a timestamp into the "
"system message invalidates the cache on every call and pays full price for a "
"prefix it just sent."
),
}

The embedder here is a character n-gram hashing function, not a trained model. It is lexical with fuzzy edges: it matches retrieve to retrieval because they share 4-grams, and it fails on true synonyms. That limitation is deliberate and the measurement section shows exactly what it costs, because a retriever you cannot measure is a retriever you cannot improve.

What the five-entry dictionary actually costs

Three failures, all reproduced in the current code.

A miss is indistinguishable from an empty corpus. _search returns ["no matches"] when no key matches, which is ok=True. The model reads it as evidence that the corpus contains nothing on the topic. In Part 2 we fixed the timeout case with a classified error; the miss case is still a lie dressed as data.

There is no citation. The tool returns bare strings. When the model writes a final answer, nothing in it points back to a passage, so the user cannot check the claim and Part 7 cannot verify it.

The unit of retrieval is a document. Even with a real corpus, returning whole documents means a 4,000-character blob per hit. Four hits at 420 characters is about 420 tokens of context; four whole documents is 4,000. Part 3’s budget then spends its effort compressing text the retriever should never have sent.

The rest of this article fixes all three by construction: chunks make the unit small, citations make the output checkable, and a relevance floor makes a miss into a classified error.

Chunking: the decision you cannot undo

Chunk boundaries are the only retrieval decision that is expensive to reverse, because changing them means re-embedding the whole corpus. Everything else — the scoring function, the fusion constant, the reranker — can be tuned in an afternoon.

The constraint pair is simple. Chunks that are too large dilute: a 900-character chunk containing three unrelated points ranks for all three and answers none of them precisely, because the embedding is an average of everything in it. Chunks that are too small lose their own grammar: a 120-character slice often starts with It and no antecedent, which no reranker can repair.

from __future__ import annotations
from dataclasses import dataclass
import hashlib
import json
import math
import re
from collections import Counter
from contracts import ErrorCode, Tool, ToolResult
CHUNK_CHARS = 420
OVERLAP_CHARS = 90
SENTENCE = re.compile(r"(?<=[.!?])\s+")
WORD = re.compile(r"[a-z0-9]+")
STOP = frozenset(
"the and for with that this from are was were what when how why into than then "
"does did can could should would your you our its it is of to in on by as at be".split()
)
def words(text: str) -> list[str]:
return [w for w in WORD.findall(text.lower()) if len(w) > 2 and w not in STOP]
@dataclass(frozen=True)
class Chunk:
id: str
doc_id: str
text: str
ordinal: int = 0
@property
def citation(self) -> str:
return "%s#%d" % (self.doc_id, self.ordinal)
def chunk_document(doc_id: str, text: str, max_chars: int = CHUNK_CHARS,
overlap_chars: int = OVERLAP_CHARS) -> list[Chunk]:
"""Split on sentence boundaries, pack to max_chars, carry a tail overlap."""
sentences = [s.strip() for s in SENTENCE.split(text.strip()) if s.strip()]
packs: list[str] = []
buf: list[str] = []
size = 0
for sentence in sentences:
if buf and size + len(sentence) + 1 > max_chars:
packs.append(" ".join(buf))
tail: list[str] = []
tail_size = 0
for prev in reversed(buf):
if tail_size + len(prev) > overlap_chars:
break
tail.insert(0, prev)
tail_size += len(prev) + 1
buf, size = tail, tail_size
buf.append(sentence)
size += len(sentence) + 1
if buf:
packs.append(" ".join(buf))
return [Chunk("%s#%d" % (doc_id, i), doc_id, body, i) for i, body in enumerate(packs)]

Four decisions in thirty lines, each with a cost.

Split on sentences, pack to a character budget. Splitting mid-word guarantees a chunk whose first token is a fragment, which poisons both the embedding and the quote. The regex only breaks after ., ! or ? followed by whitespace, which mis-splits abbreviations like e.g. — acceptable, because the damage is one extra boundary rather than a broken word.

420 characters, not 512 tokens. At roughly four characters per token that is about 105 tokens per chunk. The number matters less than the ratio: four retrieved chunks at 105 tokens each is 420 tokens of evidence, which fits comfortably inside Part 3’s budget alongside a 300-token system prompt. A 1,000-token chunk cap would make four hits cost 4,000 tokens and force the budget to compress exactly the text you paid to retrieve.

Overlap is a tail copy, not a sliding window. After a flush, the last sentences that fit in 90 characters are re-opened in the new buffer. The result is a 21 percent index inflation at these settings (90 of 420), and one guarantee: a sentence that straddles a boundary is retrievable from at least one side. Sliding-window chunking by token count gets the same guarantee but produces chunks that begin mid-sentence, which is what we are avoiding.

ordinal is the citation, so it must be stable. chunking#1 means the second chunk of the chunking document. If you re-chunk with different settings, every citation in old answers points somewhere else. That is why the settings belong in the index build, recorded next to the corpus version, and why re-chunking is a migration rather than a config change.

BM25 from an inverted index

BM25 is a lexical scorer with two ideas that still beat naive term counting. Term frequency saturates: the tenth occurrence of latency in a chunk adds almost nothing over the fifth, because the chunk is already about latency. Length normalisation stops long chunks from winning by sheer volume.

class BM25Index:
"""Okapi BM25 over an inverted index. No dependency, no service."""
def __init__(self, k1: float = 1.2, b: float = 0.75) -> None:
self.k1 = k1
self.b = b
self.chunks: dict[str, Chunk] = {}
self.postings: dict[str, dict[str, int]] = {}
self.lengths: dict[str, int] = {}
self.avg_len = 0.0
def add(self, chunks: list[Chunk]) -> None:
for chunk in chunks:
tokens = words(chunk.text)
self.chunks[chunk.id] = chunk
self.lengths[chunk.id] = len(tokens)
for term, count in Counter(tokens).items():
self.postings.setdefault(term, {})[chunk.id] = count
total = sum(self.lengths.values())
self.avg_len = total / len(self.lengths) if self.lengths else 0.0
def idf(self, term: str) -> float:
n = len(self.chunks)
df = len(self.postings.get(term, {}))
return math.log(1.0 + (n - df + 0.5) / (df + 0.5))
def search(self, query: str, k: int = 20) -> list[tuple[str, float]]:
scores: Counter[str] = Counter()
for term in words(query):
idf = self.idf(term)
if idf <= 0:
continue
for chunk_id, tf in self.postings.get(term, {}).items():
norm = tf + self.k1 * (
1 - self.b + self.b * self.lengths[chunk_id] / max(self.avg_len, 1e-9)
)
scores[chunk_id] += idf * tf * (self.k1 + 1) / norm
return [(cid, round(score, 4)) for cid, score in scores.most_common(k)]

The idf <= 0 guard is not defensive noise. With the +0.5 smoothing, a term appearing in every chunk gets log(1 + 0.5/(n+0.5)), which is positive but tiny; a term appearing in more than about 80 percent of chunks contributes almost nothing and is not worth the multiply. Dropping it keeps the common-word floor from creating ties between unrelated chunks.

The scoring loop iterates postings, not chunks. That is what makes it fast: a query with four surviving terms touches the union of four posting lists, which on 19 chunks is a few dozen integer increments and on 50,000 chunks is a few thousand. The measured cost is 0.015 ms per query on the demo corpus and about 4 ms at 20,000 chunks — linear in postings, not in corpus size.

Two limits worth knowing before you tune k1 and b. BM25 cannot match a term it has never seen: query retrieve scores zero against a chunk containing only retrieval, because the tokens differ. And it cannot rank by meaning: query point an answer at its source scores zero against the chunk that explains citation ids, because every content word is a synonym. Those are the two failures the dense leg exists to cover.

The dense leg, and fusing two rankings

A dense retriever maps text to a vector and ranks by cosine similarity. In production that vector comes from a trained sentence-embedding model. Offline, with no dependency and no key, the honest stand-in is character n-gram hashing: it captures morphology and shared substrings, which is a real — if narrow — form of generalisation that BM25 lacks.

class HashedEmbedder:
"""Character n-gram hashing embedder: deterministic, offline, morphology-tolerant.
Swap this class for a sentence-embedding model behind the same embed() contract;
everything downstream only needs a unit-norm vector.
"""
def __init__(self, dim: int = 512, n: int = 4) -> None:
self.dim = dim
self.n = n
def _grams(self, text: str) -> list[str]:
cleaned = re.sub(r"[^a-z0-9]+", " ", text.lower())
out: list[str] = []
for word in cleaned.split():
padded = "#" + word + "#"
for i in range(max(1, len(padded) - self.n + 1)):
out.append(padded[i:i + self.n])
return out
def embed(self, text: str) -> list[float]:
vec = [0.0] * self.dim
for gram in self._grams(text):
digest = hashlib.blake2b(gram.encode("utf-8"), digest_size=8).digest()
index = int.from_bytes(digest[:4], "big") % self.dim
sign = 1.0 if digest[4] & 1 else -1.0
vec[index] += sign
norm = math.sqrt(sum(v * v for v in vec)) or 1.0
return [v / norm for v in vec]
def cosine(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b))
class VectorIndex:
"""Brute-force cosine search. Fast enough to 50k chunks; swap for FAISS later."""
def __init__(self, embedder: HashedEmbedder | None = None) -> None:
self.embedder = embedder or HashedEmbedder()
self.chunks: dict[str, Chunk] = {}
self.matrix: dict[str, list[float]] = {}
def add(self, chunks: list[Chunk]) -> None:
for chunk in chunks:
self.chunks[chunk.id] = chunk
self.matrix[chunk.id] = self.embedder.embed(chunk.text)
def search(self, query: str, k: int = 20) -> list[tuple[str, float]]:
probe = self.embedder.embed(query)
scored = [(cid, cosine(probe, vec)) for cid, vec in self.matrix.items()]
scored.sort(key=lambda pair: (-pair[1], pair[0]))
return [(cid, round(score, 4)) for cid, score in scored[:k] if score > 0]

Three properties make this index worth keeping even when you replace the embedder. The vector is unit-norm, so cosine is a dot product and scores are comparable across chunk lengths. Hashing is signed, so collisions cancel on average instead of accumulating false similarity. Search is brute force, which at 19 chunks costs 0.6 ms and at 50,000 chunks costs roughly 400 ms in pure Python — slow enough that you will notice, and slow enough to justify a real index when you get there.

Now the fusion. BM25 scores are unbounded; cosine is in [-1, 1]. Adding them is a category error, and normalising them requires per-query statistics that shift with the query. Reciprocal rank fusion sidesteps both by scoring only rank position.

def reciprocal_rank_fusion(rankings: list[list[tuple[str, float]]],
k: int = 60) -> list[tuple[str, float]]:
"""RRF: score by rank position, not by raw score. Immune to scale mismatch."""
fused: dict[str, float] = {}
for ranking in rankings:
for rank, (chunk_id, _score) in enumerate(ranking, start=1):
fused[chunk_id] = fused.get(chunk_id, 0.0) + 1.0 / (k + rank)
return sorted(fused.items(), key=lambda pair: (-pair[1], pair[0]))
@dataclass
class Passage:
chunk: Chunk
fused_score: float
bm25_rank: int | None = None
vector_rank: int | None = None
rerank_score: float = 0.0
class HybridRetriever:
"""BM25 + vector, fused by RRF. Named Hybrid because Part 4's Retriever is the memory scorer."""
def __init__(self, chunks: list[Chunk], embedder: HashedEmbedder | None = None,
pool: int = 20, rrf_k: int = 60) -> None:
self.bm25 = BM25Index()
self.bm25.add(chunks)
self.vectors = VectorIndex(embedder)
self.vectors.add(chunks)
self.chunks = {c.id: c for c in chunks}
self.pool = pool
self.rrf_k = rrf_k
def retrieve(self, query: str, k: int = 5) -> list[Passage]:
lexical = self.bm25.search(query, k=self.pool)
dense = self.vectors.search(query, k=self.pool)
rank_bm25 = {cid: i for i, (cid, _) in enumerate(lexical, start=1)}
rank_vector = {cid: i for i, (cid, _) in enumerate(dense, start=1)}
fused = reciprocal_rank_fusion([lexical, dense], k=self.rrf_k)
return [
Passage(self.chunks[cid], score, rank_bm25.get(cid), rank_vector.get(cid))
for cid, score in fused[:k]
]

k=60 is the published default and it encodes a specific belief: agreement between lists matters more than dominance inside one. A chunk at rank 1 in one list scores 1/61 = 0.0164; a chunk at rank 2 in both scores 1/62 + 1/62 = 0.0323. The second wins, which is the behaviour you want when one list is lexical and one is semantic. Lowering k to 10 makes a single-list winner much stronger — useful when one retriever is clearly better and you only want a small tie-break from the other.

This is where an honest measurement changes the design. Here is the harness, run over nineteen chunks and eight labelled queries:

import corpus
import rag
QUERIES = [
("what window size should a passage have", "chunking"),
("combining keyword and embedding rankings", "retrieval-design"),
("tail latency after adding a reranker", "latency-budget"),
("the plan changes after a step fails", "planner"),
("critique loops that never terminate", "reflection"),
("point an answer at its source", "citations"),
("does overlap inflate the index size", "chunking"),
("cheapest way to cut repeated prefix cost", "prompt-caching"),
]
def evaluate(name: str, rank_fn, k: int = 3) -> None:
p1 = recall = mrr = 0.0
for query, expected in QUERIES:
docs = rank_fn(query, k)
p1 += 1.0 if docs[:1] == [expected] else 0.0
recall += 1.0 if expected in docs else 0.0
mrr += 1.0 / (docs.index(expected) + 1) if expected in docs else 0.0
n = len(QUERIES)
print("%-14s P@1=%.2f Recall@%d=%.2f MRR=%.3f" % (name, p1 / n, k, recall / n, mrr / n))
def main() -> None:
r = rag.CorpusRetriever(corpus.DOCUMENTS)
r.hybrid.pool = 12
evaluate("bm25", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.bm25.search(q, k=n)])
evaluate("vector", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.vectors.search(q, k=n)])
evaluate("hybrid", lambda q, n: [p.chunk.doc_id for p in r.hybrid.retrieve(q, k=n)])
evaluate("hybrid+rerank", lambda q, n: [p.chunk.doc_id for p in r.search(q, limit=n)])
if __name__ == "__main__":
main()
bm25 P@1=0.62 Recall@3=0.88 MRR=0.750
vector P@1=0.38 Recall@3=0.88 MRR=0.604
hybrid P@1=0.50 Recall@3=0.88 MRR=0.667
hybrid+rerank P@1=0.50 Recall@3=0.88 MRR=0.667

Read the second column, not the first. Recall is what a candidate pool is for, and the pool size matters: at pool=12 over 19 chunks, BM25’s top 12 contains the right document for 7 of 8 queries and the dense leg for 8 of 8, so the union is 8 of 8. One query — combining keyword and embedding rankings — is a total lexical miss whose topic chunk does not contain the words keyword, embedding or rankings; the hashed embedder finds it through the shared rank 4-grams. That single query is the entire argument for the dense leg at this scale: not better ranking, but a pool that does not silently lose the answer.

Read the first column and the picture is less flattering: BM25 wins on precision, and fusion loses 12 points of P@1 relative to BM25 alone. That is not a bug in RRF. It is a bug in the dense leg, and it is worth stating precisely: a character n-gram embedder is a lexical matcher with a different weighting scheme, so fusing it with BM25 fuses two views of the same evidence and the disagreements are noise. Three lexical matchers do not add up to semantics.

The fix is not to tune k. The fix is to replace HashedEmbedder with a trained model, which changes the character of the disagreements from noise to signal. Everything downstream — fusion, reranking, citation, the tool contract — stays identical, because the only thing the rest of the pipeline needs is embed(text) -> list[float]. Ship the interface, measure the leg, buy the model when the measurement says the leg is the weak one. This harness is how you know.

Reranking: pay latency, buy precision

Fusion gives you a pool with good recall and mediocre ordering. A reranker fixes the ordering by scoring each query-passage pair jointly instead of independently. A cross-encoder sees query and passage in one forward pass, so it can represent not and only and word order — things neither BM25 nor a bag-of-ngrams embedding can.

The deterministic stand-in below scores term coverage, exact phrase presence, and proximity of adjacent query terms. It is not a cross-encoder; it is a reranker-shaped function so the pipeline, the threshold, and the tests all exist before you plug in something expensive.

class CoverageReranker:
"""Deterministic stand-in for a cross-encoder: term coverage, phrase hit, proximity."""
def __init__(self, phrase_weight: float = 0.25, proximity_weight: float = 0.15) -> None:
self.phrase_weight = phrase_weight
self.proximity_weight = proximity_weight
@staticmethod
def _proximity(query_terms: list[str], passage_terms: list[str]) -> float:
positions: dict[str, list[int]] = {}
for i, term in enumerate(passage_terms):
positions.setdefault(term, []).append(i)
best = 0.0
for left, right in zip(query_terms, query_terms[1:]):
for i in positions.get(left, []):
for j in positions.get(right, []):
gap = abs(i - j)
if 0 < gap <= 6:
best = max(best, 1.0 - (gap - 1) / 6.0)
return best
def score(self, query: str, passage: Passage) -> float:
query_terms = words(query)
if not query_terms:
return 0.0
passage_terms = words(passage.chunk.text)
covered = len(set(query_terms) & set(passage_terms)) / len(set(query_terms))
phrase = 1.0 if query.strip().lower() in passage.chunk.text.lower() else 0.0
proximity = self._proximity(query_terms, passage_terms)
return (covered + self.phrase_weight * phrase
+ self.proximity_weight * proximity)

Coverage is normalised by the number of distinct query terms, so a two-word query cannot outscore a six-word query by accident. The phrase bonus is binary and weighs a quarter: an exact substring match is strong evidence, but a chunk can be right without containing the verbatim phrase. Proximity is capped at a six-token window, because beyond that two terms are co-occurring rather than related — and it only fires on adjacent query terms, so latency ... reranker in either order counts while latency ... chunk does not.

What the reranker cannot do is what the measurement above shows: on the demo corpus it moves nothing, because it is a third lexical matcher. Its real value arrives with a cross-encoder, and the honest engineering question is whether you can afford one.

Do the arithmetic before you enable it. A 12-layer cross-encoder at 20 candidate pairs costs roughly 10 ms per pair on CPU, so 200 ms per query; capped at 8 pairs, 80 ms. Five searches per run adds 400 ms — comparable to one LLM round trip, which is usually acceptable, and unacceptable if the tool p95 was 40 ms and the agent’s overall budget is two seconds. Two levers keep it bounded: cap the rerank set (8 is a good default; the 9th candidate rarely changes the top 4) and skip reranking when the fusion margin is large (if the top passage beats the second by more than 2×, the ordering is not close).

Wiring it into the tool registry

The tool is the seam. It must return citations, respect the schema from Part 2, and turn an empty result into a classified error rather than no matches.

class CorpusRetriever:
"""Chunk once, then serve top-k passages through hybrid recall plus reranking."""
def __init__(self, documents: dict[str, str], embedder: HashedEmbedder | None = None,
reranker: CoverageReranker | None = None, max_chars: int = CHUNK_CHARS,
overlap_chars: int = OVERLAP_CHARS, min_score: float = 0.05) -> None:
chunks: list[Chunk] = []
for doc_id, text in documents.items():
chunks.extend(chunk_document(doc_id, text, max_chars, overlap_chars))
self.chunks = chunks
self.hybrid = HybridRetriever(chunks, embedder)
self.reranker = reranker or CoverageReranker()
self.min_score = min_score
def search(self, query: str, limit: int = 4) -> list[Passage]:
pool = self.hybrid.retrieve(query, k=max(limit * 4, 12))
for passage in pool:
passage.rerank_score = self.reranker.score(query, passage)
pool.sort(key=lambda p: (-p.rerank_score, -p.fused_score, p.chunk.id))
return [p for p in pool[:limit] if p.rerank_score >= self.min_score]
def passage_block(self, query: str, limit: int = 4, max_chars: int = 1800) -> str:
hits = self.search(query, limit)
if not hits:
return ""
lines = ["EVIDENCE (cite as [doc#n]; do not paraphrase numbers):"]
for passage in hits:
lines.append("[%s] %s" % (passage.chunk.citation, passage.chunk.text))
return "\n".join(lines)[:max_chars]
def make_search_tool(retriever: CorpusRetriever) -> Tool:
"""Replaces the five-entry dictionary in Part 1 with a real corpus backend."""
def _run(args: dict) -> ToolResult:
query = str(args.get("query", ""))
limit = int(args.get("limit", 4))
hits = retriever.search(query, limit)
if not hits:
return ToolResult(ok=False, data="",
error="no passage scored above zero for: " + query,
error_code=ErrorCode.NOT_FOUND.value)
payload = [
{
"citation": p.chunk.citation,
"doc": p.chunk.doc_id,
"text": p.chunk.text,
"score": round(p.rerank_score, 3),
}
for p in hits
]
return ToolResult(ok=True, data=json.dumps(payload, ensure_ascii=False))
return Tool(
name="search",
description=(
"Search the local research corpus. Returns JSON passages, each with a "
"citation id of the form doc#n. Cite these ids in your final answer."
),
parameters={
"type": "object",
"properties": {
"query": {"type": "string", "minLength": 2, "maxLength": 200},
"limit": {"type": "integer", "minimum": 1, "maximum": 10},
},
"required": ["query"],
"additionalProperties": False,
},
_fn=_run,
)

min_score=0.05 is the relevance floor, and it is load-bearing for a reason the tests demonstrate: without it, a query of pure nonsense returns collisions from the hashed embedder with tiny positive cosine, and the agent receives four irrelevant passages instead of an error. A floor converts that into ERROR[not_found], which the model reads as this corpus does not cover that, and which is true.

limit=4 is also a budget decision. Four passages at about 105 tokens each is 420 tokens, plus roughly 30 tokens of citation scaffolding. Two hits would be cheaper but frequently insufficient — the answer is often split across a definition chunk and an example chunk. Six is where precision starts dropping faster than recall rises.

Integration is one line, because AgentLoop already accepts a tool list:

import corpus
import rag
from contracts import AgentLoop, ScriptedLLM, build_tools
retriever = rag.CorpusRetriever(corpus.DOCUMENTS)
tools = [rag.make_search_tool(retriever)] + [t for t in build_tools() if t.name != "search"]
script = [
{"type": "tool", "name": "search",
"arguments": {"query": "tail latency after adding a reranker", "limit": 2}},
{"type": "final",
"content": "A cross-encoder reranker over 20 candidates costs about 200 ms per "
"query; capping at 8 candidates brings it under 100 ms [latency-budget#0]."},
]
agent = AgentLoop(ScriptedLLM(script), tools, max_steps=3)
print(agent.run("What does reranking cost in latency?"))
print("tool ok:", agent.trace[0]["ok"], "attempts:", agent.trace[0]["attempts"])
A cross-encoder reranker over 20 candidates costs about 200 ms per query; capping at 8 candidates brings it under 100 ms [latency-budget#0].
tool ok: True attempts: 1

The [t for t in build_tools() if t.name != "search"] filter is the whole migration. The loop, the executor, the retry policy and the idempotency store are untouched, and the model still sees a tool called search with a schema it can validate against.

Failure modes and how to handle them

Failure What actually happens Handling here Still broken
Chunk splits a table or list Rows land in different chunks, neither answers Sentence splitter keeps rows together when punctuation allows Markdown tables need a structural splitter
Query and corpus use different words BM25 returns nothing; hashed embedding returns noise Dense leg + fusion True synonyms need a trained model
Every hit is irrelevant Model cites a passage that does not support the claim min_score floor → ERROR[not_found] Floor is per-corpus; needs recalibration per language
Reranker too slow Tool p95 jumps from 40 ms to 240 ms Cap rerank set at 8, skip on large fusion margin No adaptive budget
Duplicate chunks across documents Same sentence retrieved twice, wasting two slots Overlap is bounded; dedupe by text hash Near-duplicate documents still flood the pool
Re-chunking invalidates citations Old answers point at the wrong ordinal Ordinals are stable per build; corpus version recorded No migration tool for stored citations
Embedding model swapped Scores shift, floor no longer valid Interface isolates the change Needs a re-run of the harness before deploy

The last row is the one that bites in production, and it is a process failure rather than a code one. Changing HashedEmbedder for a real model changes the score distribution, which invalidates min_score, which silently turns error paths into irrelevant-passage paths. Any embedder change must be followed by the harness run, and the floor must be set from the new distribution’s low tail — not copied from the old one.

Trade-offs

Decision Alternative Why we chose it Cost
420-character chunks 1,000-token chunks Four hits cost 420 tokens, not 4,000 Answers split across boundaries
90-character overlap No overlap Boundary sentences stay retrievable 21 percent index inflation
BM25 + dense, fused by RRF Single retriever Pool recall rises from 0.88 to 1.00 in the demo Two indexes to keep in sync
Hashed embedder Trained embedding model Deterministic, offline, testable No synonym recall; loses to BM25 on precision
Deterministic reranker Cross-encoder Runs in 1 ms, no model to host Barely changes ranking
min_score=0.05 Return whatever matches Turns junk into a classified error A genuinely rare query returns an error
limit=4 limit=10 Bounded context cost Misses multi-hop questions

The reranker row deserves a straight answer: with this stand-in you are paying interface complexity for no precision gain. The reason to build the interface anyway is that precision is the stage where a trained model earns ten to twenty points of P@1, and retrofitting the seam later means touching the tool contract, the citation format and the tests all at once.

Testing it

Eleven tests, no network, under 50 ms. These are the invariants:

import json
import unittest
import corpus
import rag
from contracts import ToolExecutor, build_tools
class TestRecall(unittest.TestCase):
def test_bm25_ranks_exact_identifier_first(self):
r = rag.CorpusRetriever(corpus.DOCUMENTS)
hits = r.hybrid.bm25.search("chunked transfer encoding 64 KB", k=3)
self.assertEqual(hits[0][0].split("#")[0], "cdn-transfer")
def test_vector_bridges_morphology_that_bm25_misses(self):
chunks = rag.chunk_document(
"morph", "Retrieval quality depends on the candidate pool, not on the prompt.")
index = rag.VectorIndex()
index.add(chunks)
self.assertTrue(index.search("retrieve", k=1))
bm25 = rag.BM25Index()
bm25.add(chunks)
self.assertEqual(bm25.search("retrieve", k=1), [])
def test_rrf_prefers_agreement_over_a_single_winner(self):
fused = rag.reciprocal_rank_fusion([[("a", 9.0), ("b", 8.0)],
[("b", 0.9), ("a", 0.8)]])
self.assertEqual(fused[0][0], "a")
class TestChunking(unittest.TestCase):
def test_overlap_carries_the_boundary_sentence(self):
text = ("Alpha sentence about chunk one. " * 12
+ "Boundary sentence that must survive. " + "Beta sentence two. " * 12)
chunks = rag.chunk_document("doc", text, max_chars=200, overlap_chars=60)
self.assertGreater(len(chunks), 2)
self.assertTrue(any("Boundary sentence" in c.text for c in chunks))
self.assertTrue(all(len(c.text) <= 260 for c in chunks))
class TestTool(unittest.TestCase):
def test_tool_returns_citations_the_agent_can_reuse(self):
r = rag.CorpusRetriever(corpus.DOCUMENTS)
tools = {t.name: t for t in build_tools()}
tools["search"] = rag.make_search_tool(r)
result = ToolExecutor(tools).execute("search", {"query": "reranker latency", "limit": 2})
self.assertTrue(result.ok)
payload = json.loads(result.data)
self.assertEqual(len(payload), 2)
self.assertRegex(payload[0]["citation"], r"^[a-z-]+#\d+$")
def test_short_query_is_rejected_before_the_index(self):
r = rag.CorpusRetriever(corpus.DOCUMENTS)
result = ToolExecutor({"search": rag.make_search_tool(r)}).execute(
"search", {"query": "a"})
self.assertFalse(result.ok)
self.assertEqual(result.error_code, "invalid_arguments")
def test_empty_result_is_a_classified_error(self):
tiny = rag.CorpusRetriever({"only": corpus.DOCUMENTS["chunking"]})
result = rag.make_search_tool(tiny).run({"query": "zzz qqq", "limit": 2})
self.assertFalse(result.ok)
self.assertEqual(result.error_code, "not_found")
if __name__ == "__main__":
unittest.main()

test_vector_bridges_morphology_that_bm25_misses is the one that justifies keeping both legs. It asserts two opposite things about the same chunk: the vector index finds it for retrieve, and BM25 returns an empty list. If someone later replaces the embedder with something that fails this test, the dense leg has become a second lexical matcher and the fusion step is now pure overhead — exactly the state the benchmark above measures.

test_empty_result_is_a_classified_error is the regression guard for the no matches lie. ok=False plus not_found means the loop records a failed step and the model sees ERROR[not_found], which is actionable. ok=True with an empty list means the model concludes the corpus is silent on the topic, which is not.

Exercises

  1. Measure the overlap. Rebuild the index with overlap_chars at 0, 90 and 180, and run the harness each time. Report recall@12, index size in chunks, and the token cost of four hits. At what overlap does the recall gain stop paying for the duplication?
  2. A cross-encoder seam. Define class Reranker(Protocol) with score(query, passage) -> float, make CoverageReranker implement it, and add an HTTPReranker that posts [[query, passage]] pairs to a reranking endpoint. Cap the rerank set at 8 and skip reranking when passages[0].fused_score > 2 * passages[1].fused_score. Measure the P@1 change against the extra latency.
  3. Per-language floors. The relevance floor is calibrated on English. Build a ten-query set in a language with different tokenisation (Japanese or German compounding) and find the score distribution for relevant versus irrelevant hits. Is one global min_score defensible, or does it need to be per-index?

Exercise 2 is the one that changes what you ship. The seam is small, and having it means the expensive component becomes a deployment decision rather than an architectural one.

What’s next

The agent can now find a passage and cite it. What it still cannot do is decide how many searches it needs, or in what order — the loop issues one tool call at a time, and a question like compare the chunking trade-offs with the reranker latency budget requires a plan.

Part 6, Task decomposition, adds a Planner that turns a goal into a task graph with explicit dependencies, an executor that runs ready tasks in parallel, and a bounded replanning step that fires when a task fails. The search tool you just built becomes the primitive the planner composes — and the citations it returns become the evidence Part 7 verifies.

Connect your agents without writing code

Everything above, running in Ball — no code, no install. Try it in your browser.

Try Ball free
Get the free AI agent kit

Only used to send Ball resources. No spam.

Try Ball in your browser — no install, no signup needed.

Try Ball in your browser — no install, no signup needed.

Reading in English? Switch language in the menu.