Back to all articlesAI at mga ahente

Pagbuo ng RAG Retriever na Karapat-dapat sa Lugar Nito (Bahagi 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

Ang search na tool mula sa Bahagi 1 ay limang-entrang diksyonaryo lang. Tanungin mo ito tungkol sa agent loop at magbabalik ito ng isang pangungusap; tanungin mo ng iba pa at magbabalik ito ng no matches. Kaya ang bawat claim ng agent ay isa sa limang pangungusap na iyon o imbento, at walang paraan ang loop para makilala ang pagitan.

Ang unang naiisip ay magdagdag ng vector database. Tama nang bahagya ang ugaling iyon: tunay na mas magaling ang dense retrieval sa paraphrase. Ngunit isa lang ito sa tatlong yugto, at sa dalawang natitira nangyayari ang tahimik na pagkabigo ng karamihan sa mga production RAG system. Mas masahol pa ang retriever na nagbabalik ng maling chunk na may mataas na cosine score kaysa sa wala ang ibinabalik, dahil gagamitin itong citation ng agent.

Sa bahaging ito, binubuo ang retriever bilang tatlong hiwalay na yugto — chunk, recall, rerank — bawat isa may nasusukat na tungkulin, kasama ang harness na nagsasabi kung tumutulong ba ang isang yugto o nagdaragdag lang ng latency. Ang pipeline ay ikokonekta sa mismong Tool contract mula sa Bahagi 2, kaya dala ng citation hanggang sa panghuling sagot at mababago ng Bahagi 7.

Ano ang bubuuin mo

Isang rag.py na module na may limang bahagi:

  • chunk_document — packing na may kamalayan sa hangganan ng pangungusap na may nako-configure na overlap, na lumilikha ng mga Chunk object na ang citation ay anyong doc#n.
  • BM25Index — Okapi BM25 sa ibabaw ng inverted index, 0.015 ms kada query sa 19 chunks, walang dependency.
  • HashedEmbedder + VectorIndex — dense na sangay sa likod ng embed(text) -> list[float] na interface, kaya ang pagpapalit sa totoong model ay dalawampu-linggong adapter lang.
  • HybridRetriever — mga listahan ng BM25 at dense na pinagsasama sa pamamagitan ng reciprocal rank fusion.
  • CorpusRetriever + make_search_tool — reranking, pinakamababang antas ng kaugnayan, at ang search na tool na alam na ng agent kung paano tawagin.

Ang kasalukuyang kalagayan ng research-agent pagkatapos ng Bahagi 1–4: isang loop na may na-valid na tool contracts, context budget, at SQLite memory. Ang search ang huling stub. Pinapalitan ito ng bahaging ito nang hindi ginagalaw ang AgentLoop — iyon ang pagsubok kung totoo nga ang mga naunang abstraction.

Mga kinakailangan

  • Bahagi 1–4. Nag-import ang rag.py ng Tool, ToolResult at ErrorCode mula sa contracts.py; nag-i-import ang demo ng AgentLoop at ScriptedLLM.
  • Python 3.10+, standard library lang. Walang numpy, walang vector database, walang embedding API key.
  • Isang corpus na anyong dict[str, str] na nagmamapa ng document id sa teksto. Ang fixture sa ibaba ay labindalawang maikling dokumento tungkol sa agent engineering, na nagiging siyam na buong dalawampung passages.

Ang fixture ay isang dict ng mga dokumento, labindalawa, bawat isa ilang pangungusap. Maliit ito nang sadya: sapat na liit para ma-reproduce ang bawat score sa artikulong ito sa isang core nang walang isang segundo, at sapat na iba-iba para mayroong mga leksikal na bitag na sumisira sa 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."
),
}

Ang embedder dito ay character n-gram hashing function, hindi natripan na model. Leksikal ito na may malabo ang gilid: ipinapares nito ang retrieve sa retrieval dahil nagbabahagi sila ng 4-grams, at nabibigo ito sa tunay na mga kasingkahulugan. Sinasadya ang limitasyong iyon, at ipinapakita ng bahagi ng pagsukat ang eksaktong halaga nito — dahil ang retriever na hindi masukat ay retriever na hindi mapapabuti.

Ang tunay na halaga ng limang-entrang diksyonaryo

Tatlong pagkabigo, lahat na-reproduce sa kasalukuyang code.

Ang isang miss ay hindi maiiba sa walang-lamang corpus. Nagbabalik ang _search ng ["no matches"] kapag walang key na tumugma, na siyang ok=True. Binabasa ito ng model bilang ebidensya na walang laman ang corpus tungkol sa paksa. Sa Bahagi 2 inayos natin ang timeout case gamit ang classified error; ang miss case ay maling impormasyon pa rin na nakadamit na datos.

Walang citation. Baseng string ang ibinabalik ng tool. Kapag nagsulat ang model ng panghuling sagot, walang anuman dito na tumuturo sa isang passage, kaya hindi makatsek ang user ng claim at hindi mababago ng Bahagi 7.

Ang yunit ng retrieval ay buong dokumento. Kahit na may tunay na corpus, ang pagbabalik ng buong dokumento ay nangangahulugang 4,000-character na hulma kada hit. Apat na hit sa 420 characters ay mga 420 tokens ng context; apat na buong dokumento ay 4,000. Pagkatapos ay gagamitin ng budget ng Bahagi 3 ang lakas nito sa pag-compress ng eksaktong teksto na hindi dapat naipadala ng retriever.

Inaayos ng natitirang bahagi ng artikulo ang tatlong ito sa mismong disenyo: ang chunks ay pumapaliit sa yunit, ang citations ay ginagawang tsekeable ang output, at ang relevance floor ay ginagawang classified error ang isang miss.

Chunking: ang desisyon na hindi na maibabalik

Ang mga hangganan ng chunk ang tanging desisyon sa retrieval na magastos baligtarin, dahil ang pagbabago nila ay nangangahulugang muling pag-e-embed ng buong corpus. Ang lahat ng iba pa — scoring function, fusion constant, reranker — ay pwedeng i-tune sa isang hapon.

Simpleng pares ang mga constraint. Ang mga chunk na masyadong malaki ay dumidilusyon: ang 900-character na chunk na may tatlong magkakaugnay na punto ay naka-rank sa tatlong lahat at walang tinatugunan nang tumpak, dahil ang embedding ay average ng lahat ng nasa loob nito. Ang mga chunk na masyadong maliit ay nawawalan ng sariling gramatika: ang 120-character na piraso ay kadalasang nagsisimula sa It na walang antecedent, at walang reranker na makakabawi nito.

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

Apat na desisyon sa tatlumpung linya, bawat isa may halaga.

Hatiin ayon sa pangungusap, ipack ayon sa character budget. Ang paghahati sa gitna ng salita ay nagsisiguro ng chunk na ang unang token ay piraso, na nilalason ang embedding at ang quote. Ang regex ay humahati lang pagkatapos ng ., ! o ? na sinusundan ng whitespace, kaya mali ang paghahati ng mga abbreviation na katulad ng e.g. — katanggap-tanggap, dahil ang pinsala ay isang karagdagang hangganan lamang, hindi isang naputol na salita.

420 characters, hindi 512 tokens. Sa humigit-kumulang apat na character kada token, iyon ay mga 105 tokens kada chunk. Mas mahalaga ang ratio kaysa sa numero: apat na na-retrieve na chunks na 105 tokens bawat isa ay 420 tokens ng ebidensya, na kasyang-kasya sa loob ng budget ng Bahagi 3 kasama ang 300-token na system prompt. Ang 1,000-token na chunk cap ay gagawing 4,000 tokens ang apat na hit at pipilitin ang budget na i-compress ang eksaktong teksto na binayaran mo para makuha.

Ang overlap ay tail copy, hindi sliding window. Pagkatapos ng flush, muling binubuksan ang mga huling pangungusap na kasya sa 90 characters sa bagong buffer. Ang resulta ay 21 percent na index inflation sa mga setting na ito (90 sa 420), at isang garantiya: ang pangungusap na sumasaklaw sa hangganan ay nakukuha mula kahit sa isang panig. Ang sliding-window chunking ayon sa bilang ng token ay may parehong garantiya ngunit gumagawa ng mga chunk na nagsisimula sa gitna ng pangungusap — ang bagay na iniiwasan natin.

Ang ordinal ang citation, kaya dapat ito matatag. Ang chunking#1 ay nangangahulugang ikalawang chunk ng chunking na dokumento. Kapag nag-re-chunk ka gamit ang iba pang setting, ituturo ng bawat citation sa mga lumang sagot ang ibang lugar. Kaya naroon ang mga setting sa index build, naitatala katabi ang bersyon ng corpus, at ang re-chunking ay migrasyon, hindi pagbabago ng config.

BM25 mula sa inverted index

Ang BM25 ay leksikal na scorer na may dalawang ideyang nananalo pa rin sa naive term counting. Nagsasaturate ang term frequency: ang ikasampung paglitaw ng latency sa isang chunk ay halos walang idinaragdag sa ika- lima, dahil tungkol sa latency na ang chunk. Hinihila ng length normalisation ang mahahabang chunk na manalo dahil lang sa dami.

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

Ang idf <= 0 na guard ay hindi magulong depensiba. Sa +0.5 na smoothing, ang terminong lumilitaw sa bawat chunk ay nakakakuha ng log(1 + 0.5/(n+0.5)) — positibo ngunit napakaliit; ang terminong lumilitaw sa higit kaysa mga 80 percent ng mga chunk ay halos walang ambag at hindi sulit ang multiply. Ang pag-alis nito ay pumipigil sa common-word floor na gumawa ng mga tie sa mga chunk na walang kaugnayan.

Ang scoring loop ay umiinog sa mga posting, hindi sa mga chunk. Iyon ang nagpapabilis dito: ang query na may apat na natitirang termino ay sumasagi lamang sa union ng apat na posting list, na sa 19 chunks ay ilang dosenang integer increment at sa 50,000 chunks ay ilang libo. Ang nasukat na halaga ay 0.015 ms kada query sa demo corpus at mga 4 ms sa 20,000 chunks — linear sa postings, hindi sa laki ng corpus.

Dalawang limitasyon na dapat malaman bago mo i-tune ang k1 at b. Hindi kayang tugunan ng BM25 ang terminong hindi pa nito nakita: ang query na retrieve ay naka-zero sa chunk na naglalaman lang ng retrieval, dahil magkaiba ang mga token. At hindi ito kayang mag-rank ayon sa kahulugan: ang query na point an answer at its source ay naka-zero sa chunk na nagpapaliwanag ng citation ids, dahil lahat ng content word ay kasingkahulugan. Iyon ang dalawang pagkabigong tinatambunan ng dense na sangay.

Ang dense na sangay, at ang pagbubuklod ng dalawang ranking

Ang dense retriever ay nagmamapa ng teksto sa vector at nagra-rank ayon sa cosine similarity. Sa production, ang vector na iyon ay mula sa natripan na sentence-embedding model. Sa offline, walang dependency at walang key, ang tapat na kapalit ay character n-gram hashing: hinahawakan nito ang morpolohiya at mga shared substring — totoong anyo ng generalisation, kahit makitid, na wala ang 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]

Tatlong katangian ang nagpapatibay sa index na ito kahit palitan mo ang embedder. Ang vector ay unit-norm, kaya ang cosine ay dot product lamang at ang mga score ay maihahambing sa mga haba ng chunk. Ang hashing ay signed, kaya ang mga collision ay nagkakansela sa average sa halip na mag-ipon ng maling pagkakatulad. Ang search ay brute force, na sa 19 chunks ay 0.6 ms at sa 50,000 chunks ay mga 400 ms sa purong Python — mabagal sapat para mapansin mo, at sapat ding mabagal para bigyang-katwiran ang totoong index kapag dumating ka na doon.

Ngayon naman ang fusion. Walang takda ang mga score ng BM25; ang cosine ay nasa [-1, 1]. Ang pagdaragdag sa kanila ay maling kategorya, at ang pag-normalize ay nangangailangan ng per-query na estadistika na gumagalaw ayon sa query. Nilalaktawan ng reciprocal rank fusion ang dalawa sa pamamagitan ng pagmamarka lang sa 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]
]

Ang k=60 ang nailathalang default at nagsasando ito ng partikular na paniniwala: mas mahalaga ang pagkakasundo ng mga listahan kaysa paghahari sa loob ng isa. Ang chunk sa rank 1 sa isang listahan ay naka-1/61 = 0.0164; ang chunk sa rank 2 sa dalawa ay naka-1/62 + 1/62 = 0.0323. Ang pangalawa ang panalo — ang gawi na gusto mo kapag leksikal ang isang listahan at semantik ang isa. Ang pagpapababa ng k sa 10 ay gagawing mas malakas ang panalo ng isang listahan — kapaki-pakinabang kapag halatang mas magaling ang isang retriever at maliit na tie-break lang ang gusto mo mula sa kabila.

Ito ang lugar kung saan nagbabago ang disenyo dahil sa tapat na pagsukat. Narito ang harness, na tumatakbo sa labinsiyam na chunks at walong may-label na query:

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

Basahin ang ikalawang haligi, hindi ang una. Ang recall ang dahilan ng pag-iral ng candidate pool, at mahalaga ang laki nito: sa pool=12 sa ibabaw ng 19 chunks, ang top 12 ng BM25 ay naglalaman ng tamang dokumento sa 7 sa 8 na query at ang dense na sangay sa 8 sa 8, kaya ang union ay 8 sa 8. Isang query — combining keyword and embedding rankings — ay ganap na leksikal na miss na ang topic chunk ay walang mga salitang keyword, embedding o rankings; natagpuan ito ng hashed embedder sa pamamagitan ng mga shared na 4-gram ng rank. Ang iisang query na iyon ang buong argumento para sa dense na sangay sa scale na ito: hindi mas magandang ranking, kundi pool na hindi tahimik na nawawala ang sagot.

Basahin ang unang haligi at hindi na kapani-paniwa ang larawan: nananalo ang BM25 sa precision, at nawawalan ang fusion ng 12 puntos ng P@1 kumpara sa BM25 lang. Hindi bug ng RRF iyon. Bug ng dense na sangay iyon, at sulit sabihin nang eksakto: leksikal na matcher na may ibang weighting scheme ang character n-gram embedder, kaya ang pagfu-fuse nito sa BM25 ay pagbubuklod ng dalawang pananaw sa parehong ebidensya, at ang mga hindi pagkakasundo ay ingay. Walang kabuluhan ang tatlong leksikal na matcher na pinagsama sa semantika.

Ang solusyon ay hindi ang pag-tune ng k. Ang solusyon ay ang pagpapalit ng HashedEmbedder sa natripan na model, na nagbabago ang uri ng mga hindi pagkakasundo mula ingay patungong signal. Hindi magbabago ang lahat ng nasa ibaba — fusion, reranking, citation, tool contract — dahil tanging embed(text) -> list[float] lang ang kailangan ng natitirang pipeline. I-release ang interface, sukatin ang sangay, bumili ng model kapag sinabi ng pagsukat na iyon ang mahinang sangay. Sa harness na ito mo ito nalalaman.

Reranking: magbayad ng latency, bumili ng precision

Nakakakuha ka ng pool na maganda ang recall ngunit karaniwang ayos lang. Inaayos ng reranker ang ayos sa pamamagitan ng pagmamarka sa bawat query-passage na pares nang magkakasama sa halip na hiwalay. Nakikita ng cross-encoder ang query at passage sa iisang forward pass, kaya kayang ipakita ang not, only at word order — mga bagay na hindi kayang gawin ng BM25 o ng bag-of-ngrams na embedding.

Ang deterministikong kapalit sa ibaba ay nagmamarka ng term coverage, presensya ng eksaktong parirala, at kalapitan ng magkasunod na query terms. Hindi ito cross-encoder; reranker-shaped na function ito para may pipeline, threshold, at mga test bago mo pa isaksak ang mahal na bagay.

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)

Inino-normalize ang coverage ayon sa bilang ng mga natatanging query term, kaya hindi basta-basta makalampas sa score ang dalawang-salitang query sa anim-na-salitang query. Binaray ang phrase bonus at isang-kaapat ang timbang: malakas na ebidensya ang eksaktong substring match, ngunit pwedeng tama ang isang chunk kahit walang verbatim na parirala. Nakatakda sa anim-token na bintana ang proximity, dahil lampas doon ay magkasama lang ang dalawang termino, hindi magkaugnay — at nag-aaktibo ito lang sa mga magkasunod na query term, kaya binibilang ang latency ... reranker kahit anong order habang hindi binibilang ang latency ... chunk.

Ang hindi kayang gawin ng reranker ang ipinapakita ng pagsukat sa itaas: sa demo corpus, walang binabago ito dahil ito ang pangatlong leksikal na matcher. Dumarating ang tunay nitong halaga kasama ng cross-encoder, at ang tapat na tanong sa engineering ay kung may kaya kang bumili nito.

Magsagawa ng kalkulasyon bago mo ito i-enable. Ang 12-layer na cross-encoder sa 20 candidate pairs ay mga 10 ms kada pares sa CPU, kaya 200 ms kada query; sa 8 na pares na takda, 80 ms. Ang limang search kada run ay nagdaragdag ng 400 ms — katumbas ng isang LLM round trip, na karaniwang katanggap-tanggap, at hindi katanggap-tanggap kung ang tool p95 ay 40 ms at ang kabuuang budget ng agent ay dalawang segundo. Dalawang manibela ang nagpapanatili nito sa hangganan: takdaan ang rerank set (maganda ang 8 bilang default; bihirang baguhin ng ikasiyam na kandidato ang top 4) at laktawan ang reranking kapag malaki ang fusion margin (kung lampasan ng top passage ang pangalawa nang lampas 2×, hindi malapit ang ayos).

Pagkabit dito sa tool registry

Ang tool ang tahi. Kailangang magbalik ito ng citations, igungalang ang schema mula sa Bahagi 2, at gawing classified error ang walang-lamang resulta sa halip na 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,
)

Ang min_score=0.05 ang relevance floor, at ito ang may dalang bigat dahil sa dahilang ipinapakita ng mga test: wala nito, ang query na puro kaululan ay nagbabalik ng mga collision mula sa hashed embedder na may napakaliit na positibong cosine, at tatanggap ang agent ng apat na walang kaugnayang passage sa halip na error. Ginagawa nitong ERROR[not_found] ang iyon, na binabasa ng model bilang hindi sinasaklaw ng corpus na ito iyon — at totoo nga.

Ang limit=4 ay desisyon ding budget. Apat na passage na mga 105 tokens bawat isa ay 420 tokens, kasama ang mga 30 tokens ng citation scaffolding. Mas mura ang dalawang hit ngunit kadalasang kulang — kadalasang nahahati ang sagot sa definition chunk at example chunk. Sa anim nagsisimulang bumagsak ang precision nang mas mabilis kaysa tumaas ang recall.

Isang linya lang ang integration, dahil tumatanggap na ng tool list ang AgentLoop:

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

Ang [t for t in build_tools() if t.name != "search"] na filter ang buong migrasyon. Hindi ginagalaw ang loop, executor, retry policy, at idempotency store, at nakikita pa rin ng model ang tool na tinatawag na search na may schema na puwede nitong baliktarin.

Mga mode ng pagkabigo at kung paano haharapin

Pagkabigo Ano talaga ang nangyayari Pagharap dito Sira pa rin
Humahati ang chunk sa table o listahan Napupunta ang mga hilera sa iba-ibang chunk, walang sumasagot Pinananatili ng sentence splitter ang mga hilera nang magkakasama kung papayag ang punctuation Kailangan ng structural splitter ang mga Markdown table
Iba ang mga salita ng query at corpus Walang ibinabalik ang BM25; nagbabalik ng ingay ang hashed embedding Dense na sangay + fusion Kailangan ng natripan na model ang tunay na mga kasingkahulugan
Walang kaugnayan ang lahat ng hit Nagcicite ang model ng passage na hindi sumusuporta sa claim min_score floor → ERROR[not_found] Per-corpus ang floor; kailangang i-recalibrate kada wika
Masyadong mabagal ang reranker Lumulukso ang tool p95 mula 40 ms sa 240 ms Takdaan ng 8 ang rerank set, laktawan kapag malaki ang fusion margin Walang adaptive budget
Mga duplicate na chunk sa iba-ibang dokumento Dalawang beses nakuha ang parehong pangungusap, nasasayang ang dalawang slot May takda ang overlap; dedupe sa pamamagitan ng text hash Bumabaha pa rin ang pool sa mga halos duplicate na dokumento
Binabawi ng re-chunking ang mga citation Itinuturo ng mga lumang sagot ang maling ordinal Matatag ang ordinals kada build; itinatala ang bersyon ng corpus Walang migration tool para sa mga naka-stored na citation
Napalitan ang embedding model Gumagalaw ang mga score, hindi na balido ang floor Iniiwalay ng interface ang pagbabago Kailangang muling patakbuhin ang harness bago mag-deploy

Ang huling hilera ang tunay na kumakagat sa production, at pagkabigo ng proseso ito, hindi ng code. Ang pagpapalit ng HashedEmbedder sa totoong model ay gumagalaw sa score distribution, na nagpawawalang-bisa sa min_score, na tahimik na ginagawang irrelevant-passage ang mga error path. Ang bawat pagbabago ng embedder ay dapat sundan ng pagtakbo ng harness, at dapat itakda ang floor mula sa mababang buntot ng bagong distribution — hindi kinokopya mula sa luma.

Mga trade-off

Desisyon Alternatibo Bakit namin pinili Halaga
420-character na chunks 1,000-token na chunks 420 tokens lang ang apat na hit, hindi 4,000 Nahahati ang sagot sa mga hangganan
90-character na overlap Walang overlap Nanatiling nakukuha ang mga pangungusap sa hangganan 21 percent na index inflation
BM25 + dense, binuklod ng RRF Isang retriever lang Tumaas ang pool recall mula 0.88 sa 1.00 sa demo Dalawang index na kailangang i-sync
Hashed embedder Natripan na embedding model Deterministic, offline, nasusubok Walang synonym recall; natatalo sa BM25 sa precision
Deterministikong reranker Cross-encoder Tumatakbo sa 1 ms, walang model na iho-host Halos hindi nagbabago ang ranking
min_score=0.05 Ibalik ang anumang tumugma Ginagawang classified error ang basura Ang tunay na bihirang query ay nagbabalik ng error
limit=4 limit=10 May hangganan ang context cost Namimiss ang mga multi-hop na tanong

Lugas na sagot ang dapat sa reranker row: sa kapalit na ito, nagbabayad ka ng karumihan ng interface nang walang napapanalong precision. Ang dahilan para itayo pa rin ang interface ay ang precision ang yugto kung saan kumikita ang natripan na model ng sampu hanggang dalawampung puntos ng P@1, at ang pagkakabit ng tahi sa huli ay nangangahulugang pagsabay na paggalaw sa tool contract, citation format, at mga test.

Pagsubok nito

Labing-isang test, walang network, mababa sa 50 ms. Narito ang mga invariant:

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

Ang test_vector_bridges_morphology_that_bm25_misses ang test na nagpapabigat sa pagpapanatili ng parehong sangay. Dalawang magkasalungat na bagay ang ipinapahayag nito tungkol sa parehong chunk: nahahanap ng vector index ito para sa retrieve, at nagbabalik ang BM25 ng walang-lamang listahan. Kapag kinalaunaan palitan ng iba ang embedder ng bagay na nabibigo sa test na ito, naging pangalawang leksikal na matcher ang dense na sangay at puro overhead na ngayon ang hakbang ng fusion — eksaktong kalagayan na sinusukat ng benchmark sa itaas.

Ang test_empty_result_is_a_classified_error ang regression guard para sa kasinungalingang no matches. Ang ok=False plus not_found ay nangangahulugang nagtatala ang loop ng nabigong hakbang at nakikita ng model ang ERROR[not_found], na puwedeng gawan ng hakbang. Ang ok=True na may walang-lamang listahan ay nangangahulugang nagkakonklusyon ang model na tahimik ang corpus sa paksa — hindi totoo iyon.

Mga ehersisyo

  1. Sukatin ang overlap. Muling buuin ang index na ang overlap_chars ay 0, 90 at 180, at patakbuhin ang harness sa bawat beses. Mag-ulat ng recall@12, laki ng index sa chunks, at token cost ng apat na hit. Sa anong overlap tumitigil ang pagbayad ng napapanalong recall sa halaga ng duplication?
  2. Isang cross-encoder na tahi. Tukuyin ang class Reranker(Protocol) na may score(query, passage) -> float, gawing nagpapatupad ito ang CoverageReranker, at magdagdag ng HTTPReranker na nagpapadala ng mga [[query, passage]] na pares sa reranking endpoint. Takdaan ng 8 ang rerank set at laktawan ang reranking kapag passages[0].fused_score > 2 * passages[1].fused_score. Sukatin ang pagbabago ng P@1 laban sa dagdag na latency.
  3. Mga floor kada wika. Naka-calibrate sa Ingles ang relevance floor. Bumuo ng sampung-query na set sa wikang may ibang tokenisation (Hapones o German compounding) at hanapin ang score distribution ng mga kaugnay na hit laban sa mga walang kaugnayan. Mapapatibay ba ang isang global na min_score, o per-index ito dapat?

Ang Ehersisyo 2 ang nagbabago ng iyong ni-rerelease. Maliit ang tahi, at ang pagkakaroon nito ay nangangahulugang desisyon sa deployment, hindi sa arkitektura, ang mamahaling komponent.

Ano ang susunod

Kaya na ngayon ng agent na hanapin ang passage at gawing citation ito. Hindi pa nito kayang gawin ay magdesisyon kung gaano karami ang kailangang search, o sa anong order — isang tool call kada beses ang ibinibigay ng loop, at ang tanong na katulad ng compare the chunking trade-offs with the reranker latency budget ay nangangailangan ng plano.

Magdaragdag ang Bahagi 6, Task decomposition, ng Planner na gumagawa ng task graph na may malinaw na dependencies mula sa goal, executor na nagpapatakbo nang sabay-sabay sa mga handang task, at may hangganang replanning na hakbang na nag-aactivate kapag nabigo ang isang task. Ang search na tool na binuo mo lang ay nagiging primitive na binubuo ng planner — at ang mga citation na ibinabalik nito ay nagiging ebidensyang buburugin ng Bahagi 7.

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.