Torna a tutti gli articoliIA e agenti

Costruire un RAG Retriever che si merita il suo posto (Parte 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

Lo strumento search della Parte 1 è un dizionario di cinque voci. Chiedigli dell’agent loop e restituisce una frase; chiedigli qualsiasi altra cosa e restituisce no matches. Ogni affermazione dell’agente è quindi una di quelle cinque frasi o un’invenzione, e il loop non ha modo di distinguere l’una dall’altra.

Il riflesso è aggiungere un database vettoriale. Quel riflesso è per metà giusto: il dense retrieval è davvero migliore con le parafrasi. Ma è solo una di tre fasi, e nelle altre due la maggior parte dei sistemi RAG in produzione fallisce in silenzio. Un retriever che restituisce il chunk sbagliato con un punteggio coseno alto è peggiore di uno che non restituisce nulla, perché l’agente lo citerà.

Questa parte costruisce il retriever come tre fasi separabili — chunk, recall, rerank — ciascuna con un compito misurabile, più l’harness che ti dice se una fase sta aiutando o si limita ad aggiungere latenza. La pipeline è collegata allo stesso contratto Tool della Parte 2, così le citazioni sopravvivono fino alla risposta finale e la Parte 7 può verificarle.

Cosa costruirai

Un modulo rag.py con cinque pezzi:

  • chunk_document — impacchettamento consapevole delle frasi con overlap configurabile, che produce oggetti Chunk la cui citation è doc#n.
  • BM25Index — Okapi BM25 su un indice invertito, 0.015 ms per query su 19 chunk, nessuna dipendenza.
  • HashedEmbedder + VectorIndex — un ramo denso dietro un’interfaccia embed(text) -> list[float], così sostituirlo con un modello vero è un adattatore di venti righe.
  • HybridRetriever — liste BM25 e dense fuse con reciprocal rank fusion.
  • CorpusRetriever + make_search_tool — reranking, una soglia minima di rilevanza e lo strumento search che l’agente sa già chiamare.

Lo stato attuale di research-agent dopo le Parti 1–4: un loop con contratti degli strumenti validati, un budget di contesto e memoria SQLite. search è l’ultimo stub. Questa parte lo sostituisce senza toccare AgentLoop, ed è proprio la prova che le astrazioni precedenti erano vere.

Prerequisiti

  • Parti 1–4. rag.py importa Tool, ToolResult ed ErrorCode da contracts.py; la demo importa AgentLoop e ScriptedLLM.
  • Python 3.10+, solo libreria standard. Niente numpy, niente database vettoriale, niente chiave per l’API di embedding.
  • Un corpus come dict[str, str] che mappa gli id dei documenti nei testi. La fixture qui sotto è di dodici brevi documenti sull’ingegneria degli agenti, che si spezzano in diciannove passaggi.

La fixture è un dict di documenti, dodici in tutto, ognuno di qualche frase. È piccola di proposito: abbastanza piccola perché ogni punteggio dell’articolo possa essere riprodotto su un core in meno di un secondo, e abbastanza varia da contenere le trappole lessicali che rompono un indice ingenuo.

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."
),
}

L’embedder qui è una funzione di hashing di character n-gram, non un modello addestrato. È lessicale con bordi sfumati: abbina retrieve a retrieval perché condividono 4-gram, e fallisce sui sinonimi veri. Questa limitazione è voluta, e la sezione di misura mostra esattamente quanto costa, perché un retriever che non sai misurare è un retriever che non sai migliorare.

Quanto costa davvero il dizionario di cinque voci

Tre difetti, tutti riprodotti nel codice attuale.

Un mancato match è indistinguibile da un corpus vuoto. _search restituisce ["no matches"] quando nessuna chiave corrisponde, e questo è ok=True. Il modello lo legge come prova che il corpus non contiene nulla sull’argomento. Nella Parte 2 abbiamo risolto il caso del timeout con un errore classificato; il caso del mancato match è ancora una bugia vestita da dato.

Manca la citazione. Lo strumento restituisce stringhe nude. Quando il modello scrive la risposta finale, nulla in essa rimanda a un passaggio, così l’utente non può verificare l’affermazione e la Parte 7 non può validarla.

L’unità di recupero è il documento. Anche con un corpus vero, restituire documenti interi significa un blob di 4.000 caratteri per hit. Quattro hit da 420 caratteri sono circa 420 token di contesto; quattro documenti interi sono 4.000. Il budget della Parte 3 spende poi il suo sforzo comprimendo testo che il retriever non avrebbe mai dovuto inviare.

Il resto dell’articolo corregge tutti e tre per costruzione: i chunk rendono l’unità piccola, le citazioni rendono l’output verificabile, e una soglia minima di rilevanza trasforma un mancato match in un errore classificato.

Chunking: la decisione che non puoi annullare

I confini dei chunk sono l’unica decisione di recupero il cui ripensamento è costoso, perché cambiarli significa ri-embeddare tutto il corpus. Tutto il resto — la funzione di punteggio, la costante di fusione, il reranker — si può regolare in un pomeriggio.

La coppia di vincoli è semplice. I chunk troppo grandi diluiscono: un chunk di 900 caratteri con tre punti non correlati si posiziona per tutti e tre e non risponde con precisione a nessuno, perché l’embedding è una media di tutto il suo contenuto. I chunk troppo piccoli perdono la propria grammatica: una porzione di 120 caratteri spesso inizia con It senza antecedente, cosa che nessun reranker può riparare.

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)]

Quattro decisioni in trenta righe, ciascuna con un costo.

Spezza sulle frasi, impacchetta entro un budget di caratteri. Spezzare a metà parola garantisce un chunk il cui primo token è un frammento, il che avvelena sia l’embedding sia la citazione. La regex spezza solo dopo ., ! o ? seguiti da spazio, il che taglia male abbreviazioni come e.g. — accettabile, perché il danno è un confine in più, non una parola spezzata.

420 caratteri, non 512 token. A circa quattro caratteri per token sono circa 105 token per chunk. Il numero conta meno del rapporto: quattro chunk recuperati da 105 token ciascuno sono 420 token di evidenza, che entrano comodamente nel budget della Parte 3 accanto a un system prompt da 300 token. Un tetto di 1.000 token per chunk farebbe costare a quattro hit 4.000 token e costringerebbe il budget a comprimere esattamente il testo che hai pagato per recuperare.

L’overlap è una copia della coda, non una finestra scorrevole. Dopo un flush, le ultime frasi che stanno in 90 caratteri vengono riaperte nel nuovo buffer. Il risultato è un inflazione dell’indice del 21 per cento con queste impostazioni (90 su 420), e una garanzia: una frase che attraversa un confine è recuperabile almeno da un lato. Il chunking a finestra scorrevole per numero di token dà la stessa garanzia, ma produce chunk che iniziano a metà frase — proprio ciò che stiamo evitando.

ordinal è la citazione, quindi deve essere stabile. chunking#1 indica il secondo chunk del documento chunking. Se ri-spezzi con impostazioni diverse, ogni citazione nelle vecchie risposte punta altrove. Per questo le impostazioni appartengono alla build dell’indice, registrate accanto alla versione del corpus, e per questo ri-spezzare è una migrazione, non una modifica di configurazione.

BM25 da un indice invertito

BM25 è uno scorer lessicale con due idee che battono ancora il conteggio ingenuo dei termini. La frequenza dei termini satura: la decima occorrenza di latency in un chunk non aggiunge quasi nulla rispetto alla quinta, perché il chunk è già sulla latenza. La normalizzazione per lunghezza impedisce ai chunk lunghi di vincere per puro 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)]

La protezione idf <= 0 non è rumore difensivo. Con la regolarizzazione +0.5, un termine presente in ogni chunk ottiene log(1 + 0.5/(n+0.5)), positivo ma minuscolo; un termine presente in più dell’80 per cento circa dei chunk contribuisce quasi nulla e non vale la moltiplicazione. Scartarlo evita che il pavimento delle parole comuni crei pari tra chunk non correlati.

Il ciclo di punteggio itera le posting, non i chunk. È questo che lo rende veloce: una query con quattro termini superstiti tocca l’unione di quattro posting list, che su 19 chunk sono qualche decina di incrementi interi e su 50.000 chunk sono qualche migliaio. Il costo misurato è 0.015 ms per query sul corpus demo e circa 4 ms a 20.000 chunk — lineare nelle posting, non nella dimensione del corpus.

Due limiti da conoscere prima di regolare k1 e b. BM25 non può abbinare un termine che non ha mai visto: la query retrieve fa punteggio zero contro un chunk che contiene solo retrieval, perché i token differiscono. E non può ordinare per significato: la query point an answer at its source fa punteggio zero contro il chunk che spiega gli id delle citazioni, perché ogni parola di contenuto è un sinonimo. Sono i due difetti che il ramo denso esiste per coprire.

Il ramo denso, e la fusione di due classifiche

Un retriever denso mappa il testo in un vettore e ordina per similarità del coseno. In produzione quel vettore viene da un modello addestrato di sentence embedding. Offline, senza dipendenze né chiavi, la sostituzione onesta è l’hashing di character n-gram: cattura morfologia e sottostringhe condivise, che è una forma reale — seppur stretta — di generalizzazione che manca a BM25.

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]

Tre proprietà rendono questo indice degno di conservazione anche quando sostituirai l’embedder. Il vettore è a norma unitaria, quindi il coseno è un prodotto scalare e i punteggi sono confrontabili tra lunghezze di chunk diverse. L’hashing è con segno, quindi le collisioni si annullano in media invece di accumulare similarità spurie. La ricerca è brute force, che su 19 chunk costa 0.6 ms e su 50.000 chunk costa circa 400 ms in Python puro — abbastanza lenta da farsi notare, e abbastanza lenta da giustificare un vero indice quando arrivi lì.

Ora la fusione. I punteggi BM25 non hanno limiti; il coseno sta in [-1, 1]. Sommarli è un errore di categoria, e normalizzarli richiede statistiche per query che cambiano con la query. La reciprocal rank fusion aggira entrambi i problemi assegnando punteggio solo alla posizione in classifica.

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 è il default pubblicato e codifica una convinzione precisa: l’accordo tra liste conta più del dominio dentro una sola. Un chunk al rango 1 in una lista fa 1/61 = 0.0164; un chunk al rango 2 in entrambe fa 1/62 + 1/62 = 0.0323. Vince il secondo, ed è il comportamento che vuoi quando una lista è lessicale e l’altra semantica. Abbassare k a 10 rafforza molto il vincitore di una sola lista — utile quando un retriever è chiaramente migliore e vuoi dall’altro solo un piccolo spareggio.

È qui che una misura onesta cambia il design. Ecco l’harness, eseguito su diciannove chunk e otto query etichettate:

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

Leggi la seconda colonna, non la prima. Il recall è la ragion d’essere di un pool di candidati, e la dimensione del pool conta: con pool=12 su 19 chunk, la top 12 di BM25 contiene il documento giusto per 7 query su 8 e il ramo denso per 8 su 8, quindi l’unione è 8 su 8. Una query — combining keyword and embedding rankings — è un mancato match lessicale totale il cui chunk tematico non contiene le parole keyword, embedding né rankings; l’embedder con hash la trova grazie ai 4-gram condivisi di rank. Questa sola query è l’intero argomento a favore del ramo denso a questa scala: non un ordine migliore, ma un pool che non perde silenziosamente la risposta.

Leggi la prima colonna e il quadro è meno lusinghiero: BM25 vince in precisione, e la fusione perde 12 punti di P@1 rispetto a BM25 da solo. Non è un bug della RRF. È un bug del ramo denso, e vale la pena dirlo con precisione: un embedder a character n-gram è un matcher lessicale con uno schema di pesi diverso, quindi fonderlo con BM25 fonde due vedute della stessa evidenza e i disaccordi sono rumore. Tre matcher lessicali non fanno semantica.

La correzione non è regolare k. La correzione è sostituire HashedEmbedder con un modello addestrato, il che cambia il carattere dei disaccordi da rumore a segnale. Tutto a valle — fusione, reranking, citazioni, il contratto dello strumento — resta identico, perché l’unica cosa di cui ha bisogno il resto della pipeline è embed(text) -> list[float]. Spedisci l’interfaccia, misura il ramo, compra il modello quando la misura dice che il ramo è l’anello debole. Questo harness è il modo per saperlo.

Reranking: paghi latenza, compri precisione

La fusione ti dà un pool con buon recall e un ordinamento mediocre. Un reranker sistema l’ordinamento assegnando punteggio a ogni coppia query-passaggio congiuntamente invece che indipendentemente. Un cross-encoder vede query e passaggio in un solo passaggio forward, quindi può rappresentare not e only e l’ordine delle parole — cose che né BM25 né un embedding bag-of-n-grams possono.

La sostituzione deterministica qui sotto assegna punteggio a copertura dei termini, presenza esatta della frase e vicinanza dei termini adiacenti della query. Non è un cross-encoder; è una funzione dalla forma di un reranker, perché pipeline, soglia e test esistano prima che tu inserisca qualcosa di costoso.

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)

La copertura è normalizzata per il numero di termini distinti della query, così una query di due parole non supera per caso una di sei. Il bonus di frase è binario e pesa un quarto: una corrispondenza esatta di sottostringa è evidenza forte, ma un chunk può essere giusto senza contenere la frase letterale. La vicinanza è limitata a una finestra di sei token, perché oltre quel punto due termini co-occorrono anziché essere in relazione — e scatta solo su termini di query adiacenti, così latency ... reranker in entrambi gli ordini conta, mentre latency ... chunk no.

Ciò che il reranker non può fare è ciò che mostra la misura qui sopra: sul corpus demo non muove nulla, perché è un terzo matcher lessicale. Il suo vero valore arriva con un cross-encoder, e la domanda ingegneristica onesta è se puoi permettertelo.

Fai i conti prima di attivarlo. Un cross-encoder a 12 layer su 20 coppie candidati costa sulla CPU circa 10 ms per coppia, cioè 200 ms per query; limitato a 8 coppie, 80 ms. Cinque ricerche per esecuzione aggiungono 400 ms — paragonabile a un round trip verso l’LLM, di solito accettabile, e inaccettabile se il p95 dello strumento era 40 ms e il budget complessivo dell’agente è di due secondi. Due leve lo tengono limitato: limitare l’insieme di rerank (8 è un buon default; il nono candidato raramente cambia la top 4) e saltare il reranking quando il margine di fusione è ampio (se il passaggio in testa batte il secondo di più di 2×, l’ordine non è conteso).

Il collegamento al registro degli strumenti

Lo strumento è la cucitura. Deve restituire citazioni, rispettare lo schema della Parte 2 e trasformare un risultato vuoto in un errore classificato invece che in 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 è la soglia minima di rilevanza, ed è portante per un motivo che i test dimostrano: senza, una query di puro nonsenso restituisce collisioni dell’embedder con hash e coseno positivo minuscolo, e l’agente riceve quattro passaggi irrilevanti invece di un errore. Una soglia trasforma questo in ERROR[not_found], che il modello legge come questo corpus non copre questo, ed è vero.

limit=4 è anche una decisione di budget. Quattro passaggi da circa 105 token ciascuno sono 420 token, più circa 30 token di impalcatura delle citazioni. Due hit sarebbero più economici ma spesso insufficienti — la risposta è spesso divisa tra un chunk di definizione e un chunk di esempio. A sei la precisione inizia a calare più in fretta di quanto cresca il recall.

L’integrazione è una riga, perché AgentLoop accetta già una lista di strumenti:

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

Il filtro [t for t in build_tools() if t.name != "search"] è l’intera migrazione. Loop, executor, politica di retry e archivio di idempotenza restano intatti, e il modello continua a vedere uno strumento chiamato search con uno schema contro cui può validare.

Modalità di fallimento e come gestirle

Fallimento Cosa succede davvero Gestione qui Ancora rotto
Un chunk spezza una tabella o una lista Le righe finiscono in chunk diversi, nessuno risponde Il divisore di frasi tiene le righe insieme quando la punteggiatura lo permette Le tabelle Markdown richiedono un divisore strutturale
Query e corpus usano parole diverse BM25 non restituisce nulla; l’embedding con hash restituisce rumore Ramo denso + fusione I sinonimi veri richiedono un modello addestrato
Ogni hit è irrilevante Il modello cita un passaggio che non sostiene l’affermazione Soglia min_score → ERROR[not_found] La soglia è per corpus; richiede ricalibrazione per lingua
Reranker troppo lento Il p95 dello strumento salta da 40 ms a 240 ms Limitare l’insieme di rerank a 8, saltare con margine di fusione ampio Nessun budget adattivo
Chunk duplicati tra documenti La stessa frase viene recuperata due volte, sprecando due posti L’overlap è limitato; dedup per hash del testo I documenti quasi duplicati intasano comunque il pool
Ri-spezzare invalida le citazioni Le vecchie risposte puntano all’ordinal sbagliato Gli ordinal sono stabili per build; la versione del corpus è registrata Nessun strumento di migrazione per le citazioni salvate
Modello di embedding sostituito I punteggi si spostano, la soglia non vale più L’interfaccia isola il cambiamento Richiede una nuova esecuzione dell’harness prima del deploy

L’ultima riga è quella che morde in produzione, ed è un fallimento di processo, non di codice. Sostituire HashedEmbedder con un modello vero cambia la distribuzione dei punteggi, il che invalida min_score, il che trasforma in silenzio i percorsi di errore in percorsi di passaggi irrilevanti. Ogni cambio di embedder deve essere seguito dall’esecuzione dell’harness, e la soglia va fissata dalla coda bassa della nuova distribuzione — non copiata dalla vecchia.

Trade-off

Decisione Alternativa Perché l’abbiamo scelta Costo
Chunk da 420 caratteri Chunk da 1.000 token Quattro hit costano 420 token, non 4.000 Risposte spezzate sui confini
Overlap di 90 caratteri Nessun overlap Le frasi di confine restano recuperabili 21 per cento di inflazione dell’indice
BM25 + denso, fuso con RRF Un solo retriever Il recall del pool sale da 0.88 a 1.00 nella demo Due indici da tenere sincronizzati
Embedder con hash Modello di embedding addestrato Deterministico, offline, testabile Nessun recall dei sinonimi; perde contro BM25 in precisione
Reranker deterministico Cross-encoder Gira in 1 ms, nessun modello da ospitare Cambia appena l’ordine
min_score=0.05 Restituire tutto ciò che corrisponde Trasforma spazzatura in errore classificato Una query davvero rara riceve un errore
limit=4 limit=10 Costo di contesto limitato Perde le domande multi-hop

La riga del reranker merita una risposta diretta: con questa sostituzione paghi complessità di interfaccia senza guadagno di precisione. Il motivo per costruire comunque l’interfaccia è che la precisione è la fase in cui un modello addestrato guadagna da dieci a venti punti di P@1, e adattare la cucitura in seguito significa toccare contratto dello strumento, formato delle citazioni e test tutti insieme.

Testarlo

Undici test, nessuna rete, sotto i 50 ms. Questi sono gli invarianti:

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 è quello che giustifica il mantenimento di entrambi i rami. Afferma due cose opposte sullo stesso chunk: l’indice vettoriale lo trova per retrieve, e BM25 restituisce una lista vuota. Se qualcuno in futuro sostituisce l’embedder con qualcosa che fallisce questo test, il ramo denso è diventato un secondo matcher lessicale e la fase di fusione è puro overhead — esattamente lo stato che il benchmark qui sopra misura.

test_empty_result_is_a_classified_error è la guardia di regressione contro la bugia di no matches. ok=False più not_found significa che il loop registra un passo fallito e il modello vede ERROR[not_found], cosa azionabile. ok=True con lista vuota significa che il modello conclude che il corpus tace sull’argomento, il che non è vero.

Esercizi

  1. Misura l’overlap. Ricostruisci l’indice con overlap_chars a 0, 90 e 180, ed esegui l’harness ogni volta. Riporta il recall@12, la dimensione dell’indice in chunk e il costo in token di quattro hit. A quale overlap il guadagno di recall smette di pagare la duplicazione?
  2. Una cucitura per cross-encoder. Definisci class Reranker(Protocol) con score(query, passage) -> float, fai implementare a CoverageReranker e aggiungi un HTTPReranker che invia coppie [[query, passage]] a un endpoint di reranking. Limita l’insieme di rerank a 8 e salta il reranking quando passages[0].fused_score > 2 * passages[1].fused_score. Misura la variazione di P@1 contro la latenza extra.
  3. Soglie per lingua. La soglia di rilevanza è calibrata sull’inglese. Costruisci un set di dieci query in una lingua con tokenizzazione diversa (composizione giapponese o tedesca) e trova la distribuzione dei punteggi per hit rilevanti e irrilevanti. Un min_score globale è difendibile, o serve uno per indice?

L’Esercizio 2 è quello che cambia ciò che spedisci. La cucitura è piccola, e averla significa che il componente costoso diventa una decisione di deployment, non architetturale.

Prossimi passi

L’agente ora può trovare un passaggio e citarlo. Ciò che ancora non può fare è decidere quante ricerche gli servono, né in quale ordine — il loop emette una chiamata allo strumento alla volta, e una domanda come compare the chunking trade-offs with the reranker latency budget richiede un piano.

La Parte 6, Task decomposition, aggiunge un Planner che trasforma un obiettivo in un grafo di compiti con dipendenze esplicite, un executor che esegue in parallelo i compiti pronti e un passaggio di replanning limitato che scatta quando un compito fallisce. Lo strumento search che hai appena costruito diventa il primitivo che il planner compone — e le citazioni che restituisce diventano l’evidenza che la Parte 7 verifica.

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.

Leggi in inglese? Cambia lingua dal menu.