打造真正有價值的 RAG Retriever(第五篇)
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 |
第一篇的 search 工具只是一本五條詞條的字典。問它 agent loop 的事,它回一句話;問其他任何事,它回 no matches。因此 agent 提出的每個主張,不是這五句話之一,就是憑空捏造,而迴圈無從分辨兩者的差別。
直覺反應是裝上一套向量資料庫。這個直覺對了一半:dense 檢索確實更擅長同義改寫。但它只是三個階段之一,另外兩個階段才是大多數生產環境 RAG 系統悄悄失敗的地方。回傳錯誤 chunk 又附帶高 cosine 分數的 retriever,比什麼都不回傳的更糟,因為 agent 會引用它。
本篇將 retriever 建成三個可分離的階段——chunk、recall、rerank——每個階段都有可衡量的職責,外加能告訴你某個階段是在幫忙還是只添延遲的評測框架。這條 pipeline 接上的是第二篇同一份 Tool 契約,citation 因此能留到最終答案,第七篇才有辦法驗證。
你將建構什麼
一個 rag.py 模組,包含五個部分:
chunk_document— 句子感知的打包,overlap 可設定,產出的Chunk物件citation形如doc#n。BM25Index— 建在倒排索引上的 Okapi BM25,19 個 chunk 上每次查詢 0.015 ms,零依賴。HashedEmbedder+VectorIndex— 藏在embed(text) -> list[float]介面之後的 dense 支線,換成真正的模型只需要二十行的 adapter。HybridRetriever— BM25 與 dense 兩份清單,經倒數排名融合為一。CorpusRetriever+make_search_tool— 重排、相關性門檻,以及 agent 早已學會呼叫的search工具。
第四篇之後 research-agent 的現狀:一個具備已驗證工具契約的迴圈、一份 context 預算,以及 SQLite 記憶。search 是最後一個 stub。本篇在完全不動 AgentLoop 的前提下換掉它——這正是對先前抽象是否真的站得住腳的檢驗。
前置條件
- 第一至四篇。
rag.py匯入Tool、ToolResult與ErrorCode,皆來自contracts.py;示範程式匯入AgentLoop與ScriptedLLM。 - Python 3.10+,只用標準函式庫。不需要 numpy、向量資料庫或 embedding API key。
- 一份以
dict[str, str]表示的語料,把文件 id 映射到文字。下面的 fixture 是十二篇關於 agent 工程的短文件,切塊後成為十九個段落。
fixture 是一個由文件組成的 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,但碰上真正的同義詞就失效。這個限制是刻意的,量測章節會精確展示它的代價——因為無法量測的 retriever,就是無法改進的 retriever。
五條詞條的字典真正的代價
三個失敗點,全部都能在現有程式碼中重現。
沒中與空語料無法區分。 沒有任何 key 匹配時,_search 回傳 ["no matches"],這是 ok=True。模型會把它當成語料對該主題毫無內容的證據。第二篇我們用分類過的錯誤修好了逾時情境;沒中這種情境至今仍是披著資料外衣的謊言。
沒有 citation。 工具回傳裸字串。模型寫最終答案時,裡面沒有任何東西指回某個段落,使用者無從查核主張,第七篇也無從驗證。
檢索的單位是整份文件。 即便語料是真的,回傳整份文件意味著每次命中都是一團 4,000 字元。四次命中、每次 420 字元,約佔 420 token 的 context;四份完整文件則是 4,000。第三篇的預算接著把力氣花在壓縮 retriever 本不該送來的文字。
本文其餘部分從設計上修正這三點:chunk 把單位縮小,citation 讓輸出可查核,相關性門檻把「沒中」變成有分類的錯誤。
Chunking:無法回頭的決定
chunk 邊界是唯一一個翻悔成本高昂的檢索決定,因為改動它代表要對整份語料重新做 embedding。其他一切——評分函式、融合常數、reranker——一個下午就能調完。
約束成對且簡單。chunk 太大會被稀釋:一個 900 字元的 chunk 裝了三個互不相干的論點,三個論點都能被排名命中,卻沒有一個能被精確回答,因為 embedding 是它所有內容的平均值。chunk 太小則失去自己的文法:120 字元的切片常以 It 開頭卻沒有指涉對象,任何 reranker 都救不回來。
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)]三十行程式碼裡的四個決定,每個都有代價。
按句子切分,按字元預算打包。 在詞中間切分,必然產生首 token 是斷片的 chunk,同時毒害 embedding 與引文。regex 只在 ., ! 或 ? 後接空白處切斷,因此會錯切 e.g. 這類縮寫——可以接受,因為損害只是多出一條邊界,而不是切碎一個詞。
420 字元,而不是 512 token。 以每 token 約四字元計,相當於每 chunk 約 105 token。數字本身不如比例重要:四次檢索、每次 105 token,共 420 token 的證據,連同 300 token 的 system prompt,在第三篇的預算內游刃有餘。若把 chunk 上限設成 1,000 token,四次命中就是 4,000 token,預算被迫壓縮的恰好是你花錢檢索來的文字。
overlap 是複製尾部,不是滑動視窗。 每次落盤後,最後幾個能塞進 90 字元的句子會在新 buffer 重新開頭。結果是這組設定下索引膨脹 21%(420 中的 90),並換來一項保證:跨邊界的句子至少從一側可以被檢索到。按 token 數滑動視窗切塊有同樣保證,但產出的 chunk 從句子中間開頭——這正是我們要避免的。
ordinal 就是 citation,所以必須穩定。 chunking#1 指的是 chunking 這份文件的第二個 chunk。若你用不同設定重新切塊,舊答案裡的每條 citation 都會指向別處。這就是為什麼設定屬於索引建構、與語料版本一併記錄,也為什麼重新切塊是遷移作業,而不是改一下 config。
用倒排索引實現 BM25
BM25 是詞彙型評分器,有兩個至今仍勝過天真相加計數的想法。詞頻會飽和:latency 在一個 chunk 裡出現第十次,比起第五次幾乎不再加分,因為這個 chunk 本來就在講 latency。長度正規化不讓長 chunk 光靠體積取勝。
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 平滑下,出現在每個 chunk 的詞會得到 log(1 + 0.5/(n+0.5))——為正但極小;出現在大約八成 chunk 以上的詞幾乎毫無貢獻,不值得多乘一次。把它丟掉,才能避免常用詞的下限在互不相干的 chunk 之間製造平手。
評分迴圈遍歷的是 postings,不是 chunk。這正是它快的原因:一條有四個存活詞的查詢只觸碰四個 posting list 的聯集,在 19 個 chunk 上是幾十次整數遞增,在 50,000 個 chunk 上是幾千次。實測成本在示範語料上是每次查詢 0.015 ms,在 20,000 個 chunk 上約 4 ms——與 postings 數量成線性,與語料規模無關。
調 k1 與 b 之前,有兩個限制值得先知道。BM25 無法匹配它沒見過的詞:查詢 retrieve 對只含 retrieval 的 chunk 得分為零,因為 token 不同。它也無法按語義排名:查詢 point an answer at its source 對解釋 citation id 的 chunk 得分為零,因為每個實義詞都是同義詞。dense 支線的存在,正是為了補上這兩個失敗。
dense 支線,以及融合兩份排名
dense retriever 把文字映射成向量,按 cosine 相似度排名。在生產環境,這個向量來自訓練過的句子 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 之後仍值得保留。向量是 unit-norm,cosine 就只是點積,分數在不同 chunk 長度間可比較。雜湊是帶符號的,碰撞會在平均上相互抵消,不會累積假相似度。搜尋是暴力解,19 個 chunk 花 0.6 ms,50,000 個 chunk 在純 Python 下約 400 ms——慢到你會察覺,也慢到足以在規模到達時替你正當化換上真正的索引。
接著是融合。BM25 分數無上界;cosine 落在 [-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 的 chunk 得分 1/61 = 0.0164;一個在兩份清單都排第 2 的 chunk 得分 1/62 + 1/62 = 0.0323。後者勝出——當一份清單是詞彙的、另一份是語義的時,你要的正是這種行為。把 k 降到 10,會大幅強化單一清單贏家的份量——當某個 retriever 明顯更好、你只想要另一邊提供少量 tie-break 時很有用。
這正是誠實的量測能改變設計的地方。以下是評測框架,跑在十九個 chunk 與八條標註過的查詢上:
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看第二欄,別看第一欄。候選池存在的意義就是 recall,而且池子大小很重要:在 19 個 chunk 上取 pool=12,BM25 的前 12 名對 8 條查詢中的 7 條含正確文件,dense 支線則是 8 條全中,聯集自然是 8 條全中。有一條查詢——combining keyword and embedding rankings——在詞彙層面完全落空,因為它的主題 chunk 不含 keyword、embedding 或 rankings 這些詞;雜湊 embedder 是靠共用的 rank 4-gram 找到它的。這一條查詢就是這個規模下 dense 支線的全部論據:不是排名更準,而是候選池不會悄悄弄丟答案。
看第一欄,圖像就不那麼好看:BM25 在 precision 上獲勝,融合比單獨的 BM25 低了 12 個百分點的 P@1。這不是 RRF 的 bug。是 dense 支線的 bug,而且值得說精確:字元 n-gram embedder 是一套不同加權方式的詞彙匹配器,把它與 BM25 融合,等於融合了同一份證據的兩個視角,分歧處只是雜訊。三個詞彙匹配器加起來湊不出語義。
修法不是調 k。修法是把 HashedEmbedder 換成訓練過的模型,讓分歧的本質從雜訊變成訊號。下游的一切——融合、重排、citation、工具契約——原封不動,因為 pipeline 其餘部分需要的只有 embed(text) -> list[float]。先上線介面、量測這條支線,等量測說它是最弱一環時再買模型。這套評測框架就是讓你知道的方法。
Reranking:付出延遲,買回 precision
融合給你一個 recall 良好、排序平庸的候選池。reranker 修正排序的方式,是把每個查詢—段落對整體評分,而不是各自獨立評分。cross-encoder 在一次 forward pass 中同時看到查詢與段落,因此能表達 not、only 與詞序——這些是 BM25 與 bag-of-ngrams embedding 都做不到的。
下面這個確定性的替身評分項目是:詞項覆蓋率、精確片語是否出現、相鄰查詢詞的鄰近度。它不是 cross-encoder;它是一個 reranker 形狀的函式,讓 pipeline、門檻與測試都先存在,你才有地方插進昂貴的東西。
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)覆蓋率以查詢中相異詞項的數量做正規化,所以兩詞查詢無法碰巧壓過六詞查詢。片語獎勵是二元的、權重四分之一:精確子字串匹配是強證據,但 chunk 不含原句片語也可能是對的。鄰近度以六 token 視窗為上限,因為超出之後兩個詞只是同時出現,而非彼此相關——而且它只在相鄰的查詢詞項上生效,所以 latency ... reranker 不管先後都計分,latency ... chunk 則不計。
reranker 做不到的事,正是上面的量測所顯示的:在示範語料上它什麼都沒改變,因為它只是第三個詞彙匹配器。它的真正價值要等 cross-encoder 到場,而誠實的工程問題是:你養得起嗎?
啟用之前先算帳。12 層 cross-encoder 處理 20 個候選對,CPU 上每對約 10 ms,即每次查詢 200 ms;封頂 8 對則是 80 ms。每次 run 五次搜尋就多 400 ms——約等於一次 LLM 往返,通常可接受;但如果工具 p95 原本是 40 ms、agent 整體預算只有兩秒,就不可接受。兩根槓桿把它約束住:封頂 rerank 集合(8 是好預設;第 9 名候選鮮少撼動前 4 名)與融合差距大時跳過重排(若第一名段落以超過 2× 領先第二名,排序根本沒在拉鋸)。
接進工具註冊表
工具就是接縫。它必須回傳 citation、遵守第二篇的 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 撈回一點微小正 cosine 的碰撞,agent 收到四段不相干內容而非一個錯誤。門檻把這種情況轉成 ERROR[not_found],模型讀到的訊息是這份語料不涵蓋那個主題——而這是真的。
limit=4 同樣是預算決定。四段、每段約 105 token,共 420 token,再加約 30 token 的 citation 支撐結構。兩次命中更省,但常常不夠——答案往往分散在定義 chunk 與範例 chunk 之間。到六個,precision 的下滑速度就開始超過 recall 的上升。
整合只要一行,因為 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。
失敗模式與因應方式
| 失敗模式 | 實際會發生什麼 | 此處的處理 | 仍然無解 |
|---|---|---|---|
| chunk 切斷表格或清單 | 列散落在不同 chunk,兩邊都答不完整 | 標點允許時,句子切分器會讓各列留在同處 | Markdown 表格需要按結構切分的切分器 |
| 查詢與語料用詞不同 | BM25 什麼都回不了;雜湊 embedding 回傳雜訊 | dense 支線 + 融合 | 真正的同義詞需要訓練過的模型 |
| 每次命中都不相干 | 模型引用了不支持主張的段落 | min_score 門檻 → ERROR[not_found] |
門檻依語料而異;每種語言都要重新校準 |
| reranker 太慢 | 工具 p95 從 40 ms 跳到 240 ms | rerank 集合封頂 8,融合差距大時跳過 | 沒有自適應預算 |
| 跨文件的重複 chunk | 同一句被檢索兩次,浪費兩個名額 | overlap 有上限;以文字雜湊去重 | 近似重複的文件仍會灌爆候選池 |
| 重新切塊讓 citation 失效 | 舊答案指向錯誤的 ordinal | ordinal 依建構而穩定;記錄語料版本 | 已儲存的 citation 沒有遷移工具 |
| 更換 embedding 模型 | 分數漂移,門檻失效 | 介面隔離了變更 | 上線前必須重跑評測框架 |
最後一列是生產環境真正會咬人的,而且那是流程失敗,不是程式碼失敗。把 HashedEmbedder 換成真模型會搬動分數分佈,min_score 因此失效,錯誤路徑悄悄變成回傳不相干段落的路徑。任何 embedder 變更之後都必須重跑評測框架,門檻必須按新分佈的低尾設定——不是照抄舊的。
權衡取捨
| 決定 | 替代方案 | 選擇理由 | 代價 |
|---|---|---|---|
| 420 字元的 chunk | 1,000 token 的 chunk | 四次命中花 420 token,不是 4,000 | 答案被邊界切散 |
| 90 字元的 overlap | 不做 overlap | 跨邊界句子仍可檢索 | 索引膨脹 21% |
| BM25 + dense,用 RRF 融合 | 單一 retriever | 示範中候選池 recall 從 0.88 升到 1.00 | 兩個索引要同步維護 |
| 雜湊 embedder | 訓練過的 embedding 模型 | 確定性、離線、可測試 | 撈不到同義詞;precision 輸給 BM25 |
| 確定性 reranker | Cross-encoder | 1 ms 內跑完,不用托管模型 | 幾乎不改變排名 |
min_score=0.05 |
有匹配就回傳 | 把垃圾變成有分類的錯誤 | 真正罕見的查詢會拿到錯誤 |
limit=4 |
limit=10 |
context 成本有上界 | 會漏接 multi-hop 問題 |
reranker 那一列值得一句直白的回答:用這個替身,你付出介面複雜度,卻換不到任何 precision。仍然要把介面建起來的理由是,precision 正是訓練過的模型能賺到十到二十個百分點 P@1 的階段,事後才補這道接縫,等於同時動到工具契約、citation 格式與全部測試。
測試
十一個測試、不碰網路、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 是為「兩條支線都留著」提供正當性的測試。它對同一個 chunk 斷言兩件相反的事:向量索引能為 retrieve 找到它,而 BM25 回傳空清單。日後若有人把 embedder 換成過不了這個測試的東西,dense 支線就退化成第二個詞彙匹配器,融合步驟成了純粹的開銷——正是上面基準測試所量到的狀態。
test_empty_result_is_a_classified_error 是針對 no matches 謊言的回歸防線。ok=False 加 not_found 意味著迴圈記下一個失敗步驟,模型看到 ERROR[not_found]——這是可以行動的。ok=True 配上空清單,則是模型得出語料對該主題沉默的結論——這不成立。
練習
- 量出 overlap 的效果。 把
overlap_chars設為 0、90、180 各重建一次索引,每次都跑評測框架。報告 recall@12、以 chunk 計的索引大小,以及四次命中的 token 成本。overlap 到多少時,recall 的增益就不再能支付重複的代價? - 一道 cross-encoder 接縫。 定義
class Reranker(Protocol),其中score(query, passage) -> float,讓CoverageReranker實作它,再加一個HTTPReranker,把[[query, passage]]對貼到 reranking endpoint。rerank 集合封頂 8,並在passages[0].fused_score > 2 * passages[1].fused_score時跳過重排。量測 P@1 的變化對上多出來的延遲。 - 按語言設定門檻。 相關性門檻是在英文上校準的。用一個 tokenization 不同的語言(日文或德文的複合詞)建立十條查詢的集合,找出相關命中與不相干命中的分數分佈。單一全域
min_score站得住腳嗎,還是必須按索引設定?
練習 2 是改變你出貨內容的那一題。接縫很小,有了它,昂貴的元件就從架構問題降級為部署決定。
接下來
agent 現在找得到段落、也會引用它。它還做不到的,是決定需要多少次搜尋、按什麼順序——迴圈一次只發出一個工具呼叫,而像 compare the chunking trade-offs with the reranker latency budget 這樣的問題需要一份計畫。
第六篇任務分解會加入一個 Planner,把目標轉成帶明確依賴的任務圖、一個平行執行就緒任務的執行器,以及任務失敗時觸發的受限重新規劃步驟。你剛建好的 search 工具成為 planner 組合的原語——它回傳的 citation 則成為第七篇驗證的證據。
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.