搭建一个名副其实的 RAG 检索器(第 5 部分)
Retrieval in three stages
One search call, three stages
The pool exists for recall; the reranker exists for order.
- input
- process
- decision
- output
Measured on 19 chunks, 8 queries
| Recall@12 (pool) | P@1 (precision) | |
|---|---|---|
| BM25 alone | 0.88 | 0.62 |
| Dense alone | 1.00 | 0.38 |
| Hybrid (RRF) | 1.00 | 0.50 |
| Verdict | fusion earns its keep | buy a real model |
第 1 部分的 search 工具是一个五键字典。问它 agent loop 相关的内容,它返回一句话;问其它任何东西,它返回 no matches。因此 agent 做出的每个论断要么是那五句话之一,要么就是编造,而循环没有任何办法区分二者。
直觉做法是装一个向量数据库。这个直觉对了一半:稠密检索在处理转述时确实更好。但它只是三个阶段之一,而另外两个阶段正是大多数生产级 RAG 系统悄悄出问题的地方。一个用高余弦分数返回错误片段的检索器,比什么都不返回的检索器更糟,因为 agent 会引用它。
本篇把检索器构建为三个可分离的阶段——分块、召回、重排——每个都有可度量的职责,外加一套基架,告诉你某个阶段是在帮忙还是只增加延迟。整条流水线接入与第 2 部分相同的 Tool 契约,因此引用会保留到最终答案里,第 7 部分可以据此验证。
你将构建什么
一个包含五个组件的 rag.py 模块:
chunk_document— 具有可配置重叠的句子感知打包,产出Chunk对象,其citation为doc#n。BM25Index— 建立在倒排索引之上的 Okapi BM25,在 19 个片段上单次查询耗时 0.015 ms,零依赖。HashedEmbedder+VectorIndex— 藏在embed(text) -> list[float]接口之后的稠密支路,换上真实模型只需一个二十行的适配器。HybridRetriever— 通过倒数排名融合(RRF)将 BM25 与稠密两路排名合并。CorpusRetriever+make_search_tool— 重排序、相关性下限,以及 agent 已经知道如何调用的search工具。
第 1–4 部分之后 research-agent 的现状:一个带经过验证的工具契约、上下文预算和 SQLite 记忆的循环。search 是最后一个桩。本篇在不触动 AgentLoop 的前提下替换它——这正是对前面抽象是否真实的检验。
前置条件
- 第 1–4 部分。
rag.py导入Tool、ToolResult与ErrorCode(来自contracts.py);演示代码导入AgentLoop与ScriptedLLM。 - Python 3.10+,仅用标准库。不需要 numpy、向量数据库,也不需要 embedding API key。
- 语料库是一个把文档 id 映射到文本的
dict[str, str]。下文的测试语料是十二篇关于 agent 工程的短文档,切分后得到十九个片段。
测试语料是一个 dict,包含十二篇文档,每篇只有几句话。它刻意保持小,
小到本文中的每个分数都能在单核上一秒内复现,同时又足够多样,
足以包含能让朴素索引翻车的词汇陷阱。
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." ),}这里的 embedder 是一个字符 n-gram 哈希函数,不是训练出来的模型。它是带模糊边缘的词法匹配:因为共享 4-gram,它能把 retrieve 匹配到 retrieval;但对真正的同义词无能为力。这个局限是刻意的,度量一节会精确展示它的代价——因为一个无法度量的检索器,就是一个无法改进的检索器。
五键字典的实际代价
三个失败,全部在现有代码中复现。
未命中与空语料无法区分。 _search 在没有任何 key 匹配时返回 ["no matches"],也就是 ok=True。模型会把这当作语料库中不存在该主题的证据。第 2 部分已经用分类错误修好了超时场景;而未命中场景仍然是披着数据外衣的谎言。
没有引用。 工具返回裸字符串。模型写最终答案时,答案里没有任何东西指回某个片段,用户无法核查论断,第 7 部分也无法验证它。
检索单元是整篇文档。 即使换成真实语料,返回整篇文档意味着每次命中都是一个 4,000 字符的大块。四次命中、每块 420 字符大约是 420 token 的上下文;四篇整文档则是 4,000。第 3 部分的预算随后要把力气花在压缩检索器本不该送来的文本上。
本文余下部分从构造上修复这三个问题:分块让单元变小,引用让输出可核查,相关性下限把未命中变成分类错误。
分块:一个无法反悔的决定
片段边界是唯一一个推翻起来代价高昂的检索决策,因为改变它意味着对整个语料库重新做 embedding。其余一切——打分函数、融合常数、重排器——都可以在一个下午调完。
约束是一对矛盾。片段太大就会稀释:一个 900 字符、包含三个不相关要点的片段会同时为三个要点排上名,却无法精确回答其中任何一个,因为它的 embedding 是里面所有内容的平均。片段太小就会失去自身语法:一个 120 字符的切片往往以 It 开头却没有先行词,任何重排器都救不回来。
from __future__ import annotations
from dataclasses import dataclassimport hashlibimport jsonimport mathimport refrom collections import Counter
from contracts import ErrorCode, Tool, ToolResult
CHUNK_CHARS = 420OVERLAP_CHARS = 90SENTENCE = 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)]三十行代码里的四个决定,每个都有代价。
按句子切分,按字符预算打包。 在词中间切分必然造出以残句开头的片段,同时毒化 embedding 和引用原文。正则只在 .、! 或 ? 后跟空白处断开,这会把 e.g. 这类缩写切错——可以接受,因为代价只是多出一个边界,而不是切碎一个词。
420 字符,而不是 512 token。 按每 token 约四字符计算,大约每片段 105 token。具体数字不如比例重要:四个检索片段各 105 token,共 420 token 的证据,配合 300 token 的系统提示词,可以轻松装进第 3 部分的预算。若片段上限是 1,000 token,四次命中就要 4,000 token,预算被迫去压缩你花成本检索来的文本。
重叠是尾部复制,不是滑动窗口。 每次落盘之后,能塞进 90 字符的最后几句话会在新缓冲区里重新开启。结果是这些设置下索引膨胀 21%(420 中的 90),换来一个保证:跨界的句子至少能从一侧被检索到。按 token 数滑动窗口也能得到同样保证,但产生的片段会从句中开始——这正是我们要避免的。
ordinal 就是引用,所以必须稳定。 chunking#1 表示 chunking 文档的第二个片段。如果你用不同设置重新分块,旧答案里的每个引用都会指向别处。这就是为什么分块设置要放进索引构建过程、与语料库版本一起记录,也是为什么重新分块是一次迁移而不是一次配置修改。
从倒排索引到 BM25
BM25 是一个词法打分器,带着两个至今仍胜过朴素词频统计的想法。词频会饱和:latency 在片段里出现第十次相比第五次几乎不加分,因为这个片段本来就在讲 latency。长度归一化阻止长片段靠堆量取胜。
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)]idf <= 0 的守卫不是防御性噪音。在 +0.5 平滑下,出现在每个片段中的词得到 log(1 + 0.5/(n+0.5)),为正但极小;出现在约 80% 以上片段中的词贡献趋近于零,不值得参与乘法。把它丢掉是为了防止常见词的下限在无关片段之间制造并列。
打分循环遍历的是倒排表(postings),不是片段。这正是它快的原因:一个有四个存活词的查询只触及四个倒排列表的并集,在 19 个片段上是几十次整数自增,在 50,000 个片段上是几千次。实测成本在演示语料上是每查询 0.015 ms,在 20,000 片段上约 4 ms——与倒排表规模成线性,而不是与语料库大小。
在调 k1 和 b 之前值得知道两个局限。BM25 无法匹配从未见过的词:查询 retrieve 对只含 retrieval 的片段打分为零,因为 token 不同。它也无法按语义排序:查询 point an answer at its source 对解释 citation id 的那个片段打分为零,因为每个实义词都是同义词。这两个失败正是稠密支路存在的意义。
稠密支路与两路排名的融合
稠密检索器把文本映射为向量并按余弦相似度排序。生产环境中该向量来自训练好的句子 embedding 模型;离线、无依赖、无 key 的情况下,诚实的替身是字符 n-gram 哈希:它捕捉形态学和共享子串,这是一种真实(虽然狭窄)的泛化能力,而 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]三个性质让这个索引即使在替换 embedder 之后也值得保留。向量是单位范数的,因此余弦就是点积,不同长度的片段分数可比。哈希是带符号的,冲突平均下来会相互抵消,而不是累积虚假相似。检索是暴力遍历的,在 19 个片段上耗时 0.6 ms,在 50,000 片段上纯 Python 约 400 ms——慢到你能察觉,也慢到足以证明将来值得换真正的索引。
接下来是融合。BM25 分数无界;余弦落在 [-1, 1]。把它们相加是范畴错误,而归一化又需要随查询变化的每查询统计量。倒数排名融合只按排名位置打分,绕开了这两个坑。
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]))
@dataclassclass 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 是已发表的默认值,它编码了一个明确的信念:两个列表之间的一致性,比单个列表内部的支配性更重要。一个在某列表排第 1 的片段得 1/61 = 0.0164;在两个列表都排第 2 的片段得 1/62 + 1/62 = 0.0323。后者胜出,这正是当一路是词法、一路是语义时你想要的行为。把 k 降到 10 会让单列表赢家强得多——当某一路明显更好、你只想从另一路拿一点打破平局的信号时很有用。
诚实的度量就在这里改变设计。下面是基架,跑在十九个片段和八条带标注的查询上:
import corpusimport 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.750vector P@1=0.38 Recall@3=0.88 MRR=0.604hybrid P@1=0.50 Recall@3=0.88 MRR=0.667hybrid+rerank P@1=0.50 Recall@3=0.88 MRR=0.667请读第二列,而不是第一列。召回才是候选池存在的意义,池的大小也很关键:在 19 个片段上取 pool=12,BM25 的前 12 个对 8 条查询中的 7 条包含正确文档,稠密支路则是 8/8,因此并集是 8/8。有一条查询——combining keyword and embedding rankings——是彻底的词法未命中,其主题片段里不含 keyword、embedding 或 rankings 任何一个词;哈希 embedder 借助共享的 rank 4-gram 找到了它。在这个规模下,稠密支路的全部论证就在这一条查询上:不是更好的排序,而是一个不会悄悄丢掉答案的候选池。
再看第一列,画面就没那么好看了:BM25 在精确率上胜出,融合比 BM25 单独使用低了 12 个点的 P@1。这不是 RRF 的 bug。这是稠密支路的 bug,值得精确地说出来:字符 n-gram embedder 是一种换了权重方案的词法匹配器,把它和 BM25 融合,等于融合对同一证据的两个视角,分歧全是噪音。三个词法匹配器加不出语义。
修复方法不是调 k,而是把 HashedEmbedder 换成训练好的模型,这会把分歧的性质从噪音变成信号。下游的一切——融合、重排、引用、工具契约——保持不变,因为流水线其余部分需要的只是 embed(text) -> list[float]。先把接口发布出去,度量这条支路,等度量说明它是短板时再买模型。这个基架就是让你知道这一点的工具。
重排序:用延迟换精确率
融合给你的是一个召回好、排序平庸的候选池。重排器通过把每个查询-片段对放在一起联合打分(而非独立打分)来修正排序。交叉编码器在一次前向传播中同时看到查询与片段,因此它能表达 not、only 和词序——这些是 BM25 和 n-gram 词袋 embedding 都做不到的。
下面的确定性替身对词项覆盖率、精确短语出现和相邻查询词的接近度打分。它不是交叉编码器;它是一个重排器形状的函数,好让你在接入昂贵组件之前,流水线、阈值和测试都已就位。
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)覆盖率按不同查询词的数量归一化,所以两词查询不会偶然胜过六词查询。短语加分是二值的、权重为四分之一:精确子串匹配是强证据,但一个片段即使不含逐字短语也可能是对的。接近度封顶在六 token 窗口,超过这个范围两个词就只是共现而非相关——而且它只对相邻查询词生效,latency ... reranker 无论顺序都算,latency ... chunk 则不算。
重排器做不到的事,正是上面的度量所展示的:在演示语料上它什么都没改变,因为它是第三个词法匹配器。它的真正价值要等交叉编码器到来,而诚实的工程问题是:你负担得起吗?
启用之前先算笔账。12 层交叉编码器在 20 个候选对上 CPU 每对约 10 ms,即每查询 200 ms;封顶 8 对则是 80 ms。每次运行五次搜索共增加 400 ms——与一次 LLM 往返相当,通常可以接受;但如果工具 p95 本来是 40 ms、而 agent 的总预算是两秒,这就不可接受了。两个手段让它有界:封顶重排集合(8 是个好默认值;第 9 个候选很少会改变前 4 名)和融合差距大时跳过重排(如果第一名片段比第二名高出一倍以上,排序就没什么悬念)。
接入工具注册表
工具就是接缝。它必须返回引用、遵守第 2 部分的 schema,并把空结果变成分类错误而不是 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 是相关性下限,测试演示了它为什么承重:没有它,一条纯胡话查询会返回哈希 embedder 带着微小正余弦的碰撞结果,agent 收到的是四段无关片段而不是错误。下限把它转换成 ERROR[not_found],模型读到的含义是本语料不覆盖该主题,而这句话是真的。
limit=4 同样是预算决策。四个片段各约 105 token 共 420 token,外加约 30 token 的引用脚手架。两次命中更便宜但常常不够——答案经常分散在一个定义片段和一个示例片段之间。六条则开始出现精确率下降快于召回率上升的拐点。
集成只需一行,因为 AgentLoop 本来就接受工具列表:
import corpusimport ragfrom 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[t for t in build_tools() if t.name != "search"] 这个过滤器就是整个迁移。循环、执行器、重试策略和幂等存储都原封不动,模型看到的仍是名为 search、schema 可校验的工具。
失败模式与处理方式
| 失败 | 实际发生什么 | 本文如何处理 | 仍然存在的问题 |
|---|---|---|---|
| 片段切分了表格或列表 | 行落在不同片段中,两者都无法回答 | 标点允许时句子切分器让行保持在一起 | Markdown 表格需要结构性切分器 |
| 查询与语料用词不同 | BM25 返回空;哈希 embedding 返回噪音 | 稠密支路 + 融合 | 真同义词需要训练好的模型 |
| 每个命中都不相关 | 模型引用了不支持论断的片段 | min_score 下限 → ERROR[not_found] |
下限是按语料库调的;换语言需要重新校准 |
| 重排器太慢 | 工具 p95 从 40 ms 跳到 240 ms | 重排集合封顶 8;融合差距大时跳过 | 无自适应预算 |
| 不同文档中出现重复片段 | 同一句话被检索两次,浪费两个名额 | 重叠有界;按文本哈希去重 | 近重复文档仍会淹没候选池 |
| 重新分块使引用失效 | 旧答案指向错误的序号 | 序号在每次构建内稳定;记录语料库版本 | 已存储的引用没有迁移工具 |
| 替换 embedding 模型 | 分数分布变化,下限失效 | 接口隔离了变化 | 部署前需要重跑基架 |
最后一行才是生产中真正咬人的,而且是流程失败而非代码失败。把 HashedEmbedder 换成真实模型会改变分数分布,进而让 min_score 失效,悄悄把错误路径变成无关片段路径。任何 embedder 变更之后必须重跑基架,且下限必须按新分布的低尾来设定——而不是照抄旧分布。
权衡
| 决策 | 替代方案 | 选择理由 | 代价 |
|---|---|---|---|
| 420 字符片段 | 1,000 token 片段 | 四次命中花费 420 token 而非 4,000 | 答案可能被切在边界两侧 |
| 90 字符重叠 | 无重叠 | 边界句保持可检索 | 索引膨胀 21% |
| BM25 + 稠密,RRF 融合 | 单一检索器 | 演示中候选池召回率从 0.88 升至 1.00 | 需要同步两个索引 |
| 哈希 embedder | 训练好的 embedding 模型 | 确定性、离线、可测试 | 无同义词召回;精确率不敌 BM25 |
| 确定性重排器 | 交叉编码器 | 1 ms 内完成,无需托管模型 | 几乎不改变排序 |
min_score=0.05 |
有匹配就返回 | 把垃圾变成分类错误 | 真正罕见的查询会返回错误 |
limit=4 |
limit=10 |
上下文成本有界 | 会漏掉多跳问题 |
重排器这一行值得一个直白的回答:用这个替身,你是在付出接口复杂度却换不到精确率。仍然要建这个接口的理由是:精确率正是训练模型能挣到十到二十个 P@1 点的阶段,而日后补装接缝意味着同时改动工具契约、引用格式和测试。
测试
十一个测试,无网络,50 ms 内完成。这些是不变量:
import jsonimport unittest
import corpusimport ragfrom 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 是证明保留两条支路合理性的测试。它对同一个片段断言两件相反的事:向量索引能靠 retrieve 找到它,而 BM25 返回空列表。如果日后有人把 embedder 换成过不了这条测试的东西,稠密支路就退化成了第二个词法匹配器,融合步骤沦为纯粹的开销——这正是上面基准所度量的状态。
test_empty_result_is_a_classified_error 是针对 no matches 谎言的回归守卫。ok=False 加 not_found 意味着循环记录一次失败步骤,模型看到 ERROR[not_found],这是可行动的信息。ok=True 加空列表意味着模型得出语料库对该话题无话可说的结论——而这并非事实。
练习
- 度量重叠。 用
overlap_chars取 0、90 和 180 重建索引,每次都跑基架。报告 recall@12、以片段数计的索引大小,以及四次命中的 token 成本。重叠加到多少时,召回收益不再能抵消重复带来的代价? - 交叉编码器接缝。 定义
class Reranker(Protocol),带score(query, passage) -> float,让CoverageReranker实现它,再加一个HTTPReranker把[[query, passage]]对发送到重排端点。重排集合封顶 8,并在passages[0].fused_score > 2 * passages[1].fused_score时跳过重排。对照新增延迟度量 P@1 的变化。 - 按语言设定下限。 相关性下限是在英文上校准的。用一门分词方式不同的语言(日语或德语的复合词)构造十条查询,找出相关命中与无关命中的分数分布。一个全局
min_score站得住脚吗,还是需要按索引设定?
练习 2 会改变你交付的东西。接缝很小,有了它,昂贵组件就成为一个部署决策,而不是架构决策。
下一步
agent 现在能找到片段并引用它。它还做不到的是决定需要几次搜索、按什么顺序——循环一次只发一个工具调用,而像 compare the chunking trade-offs with the reranker latency budget 这样的问题需要一个计划。
第 6 部分,任务分解(Task decomposition),将加入一个 Planner,把目标变成带显式依赖的任务图,一个并行执行就绪任务的执行器,以及在任务失败时触发的有界重规划。你刚建好的 search 工具将成为 planner 组合的原语——它返回的引用则成为第 7 部分要验证的证据。
Everything above, running in Ball — no code, no install. Try it in your browser.
Only used to send Ball resources. No spam.
You're in. Open the resource list below. Open the resource list
Try Ball in your browser — no install, no signup needed.
Try Ball in your browser — no install, no signup needed.