真の実力を備えた 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 ツールは 5 項目の辞書です。agent loop について尋ねれば一文を返し、それ以外を尋ねれば no matches を返します。したがってエージェントが述べる主張は、その 5 文のどれかであるか、でっち上げであるかのどちらかであり、ループにはその区別をつける手段がありません。
反射的な対応はベクトルデータベースを追加することです。その直感は半分正しい:密検索は言い換えに対して確かにより優れています。しかし、それは 3 段階のうちの 1 つにすぎず、残りの 2 つこそ本番 RAG システムが静かに失敗する場所です。高いコサイン類似度とともに誤ったチャンクを返すリトリーバーは、何も返さないリトリーバーよりも悪いのです。なぜならエージェントはそれを引用してしまうからです。
このパートでは、リトリーバーをチャンク・リコール・リランクという 3 つの分離可能な段階として構築します。各段階には測定可能な役割があり、さらに段階が役に立っているのか、単にレイテンシを足しているだけなのかを教えてくれるハーネスも用意します。パイプラインはパート 2 と同じ Tool 契約に接続されるので、引用は最終回答まで生き残り、パート 7 がそれを検証できます。
構築するもの
5 つの部品からなる rag.py モジュール:
chunk_document— 設定可能なオーバーラップを持つ文単位のパッキング。Chunkオブジェクトを生成し、そのcitationはdoc#nになります。BM25Index— 転置インデックス上の Okapi BM25。19 チャンクで 1 クエリあたり 0.015 ms、依存関係なし。HashedEmbedder+VectorIndex—embed(text) -> list[float]インターフェースの背後にある密検索の脚。本物のモデルへの差し替えは 20 行のアダプタで済みます。HybridRetriever— 相互ランク融合(RRF)によって BM25 と密検索の 2 つのランキングを融合します。CorpusRetriever+make_search_tool— リランキング、関連性の下限、そしてエージェントがすでに呼び方を知っている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 キーも不要。
- ドキュメント id をテキストに対応させる
dict[str, str]のコーパス。以下のフィクスチャはエージェント工学に関する 12 の短いドキュメントで、チャンク化すると 19 のパッセージになります。
フィクスチャは 12 個のドキュメントからなる dict で、それぞれ数文です。意図的に小さくしています。
小さければ、この記事のすべてのスコアを 1 コアで 1 秒以内に再現できます。その一方で
ナイーブなインデックスを壊す語彙の罠を含む程度には多様です。
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 にマッチさせますが、真の同義語には失敗します。この限界は意図的なもので、その代償を測定のセクションで正確に示します。測定できないリトリーバーは改善できないリトリーバーだからです。
5 項目の辞書が実際に引き起こすもの
3 つの失敗。すべて現在のコードで再現済みです。
ミスが空のコーパスと区別できない。 _search はどのキーもマッチしない場合に ["no matches"] を返し、これは ok=True です。モデルはこれを「コーパスにはこのトピックに関するものが何もない」という証拠として読みます。パート 2 でタイムアウトのケースは分類されたエラーで修正しましたが、ミスのケースはいまだにデータに見せかけた嘘のままです。
引用がない。 ツールは裸の文字列を返します。モデルが最終回答を書くとき、パッセージを指し示すものは何もなく、ユーザーは主張を確認できず、パート 7 も検証できません。
検索の単位がドキュメント全体。 本物のコーパスにしても、ドキュメント全体を返せば 1 ヒットあたり 4,000 文字の塊になります。420 文字のヒット 4 件なら約 420 トークンのコンテキストですが、ドキュメント 4 件なら 4,000 です。パート 3 の予算はその後、リトリーバーがそもそも送るべきでなかったテキストの圧縮に労力を費やすことになります。
この記事の残りの部分では、これら 3 つすべてを構造によって修正します。チャンクが単位を小さくし、引用が出力を検証可能にし、関連性の下限がミスを分類されたエラーに変えます。
チャンキング:取り消せない決定
チャンク境界は、やり直しが高くつく唯一の検索決定です。変更するとコーパス全体の再 embedding が必要になるからです。それ以外のすべて — スコアリング関数、融合定数、リランカー — は午後ひとつで調整できます。
制約は単純な対です。大きすぎるチャンクは希釈されます。無関係な 3 つの論点を含む 900 文字のチャンクは、3 つの論点すべてでランクに入るのに、どれにも正確には答えません。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)]30 行の中の 4 つの決定。それぞれに代償があります。
文で分割し、文字予算にパックする。 単語の途中で分割すると、最初のトークンが断片であるチャンクが必ずでき、embedding と引用の両方を汚します。正規表現は .、!、? の後に空白が続く場合のみ区切るため、e.g. のような略語は誤って分割されます。受け入れ可能です。代償は余分な境界 1 つであって、壊れた単語ではありません。
512 トークンではなく 420 文字。 トークンあたり約 4 文字として、チャンクあたり約 105 トークンです。数字そのものより比率が重要です。105 トークンの検索チャンク 4 つで 420 トークンの証拠となり、300 トークンのシステムプロンプトと合わせてパート 3 の予算に余裕で収まります。チャンク上限を 1,000 トークンにすると 4 ヒットで 4,000 トークンとなり、予算はまさに検索のために払ったテキストを圧縮することを強いられます。
オーバーラップは末尾のコピーであり、スライディングウィンドウではない。 フラッシュの後、90 文字に収まる最後の文が新しいバッファで再度開かれます。結果として、この設定ではインデックスが 21% 膨らみ(420 のうち 90)、境界をまたぐ文は少なくとも片側から検索可能という保証が得られます。トークン数によるスライディングウィンドウでも同じ保証は得られますが、チャンクが文の途中から始まることになり、それこそ避けたいものです。
ordinal が引用なので、安定していなければならない。 chunking#1 は chunking ドキュメントの 2 番目のチャンクを意味します。異なる設定で再チャンクすると、過去の回答のすべての引用が別の場所を指します。だからこそ設定はインデックス構築に属し、コーパスのバージョンとともに記録され、再チャンクは設定変更ではなく移行なのです。
転置インデックスからの BM25
BM25 は、素朴な用語カウントをいまだに上回る 2 つのアイデアを持つ語彙スコアラーです。用語頻度は飽和する:チャンク内の latency の 10 回目の出現は、5 回目と比べてほとんど加点しません。チャンクがすでに 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% 以上に出現する用語はほとんど寄与せず、乗算に入れる価値がありません。これを落とすのは、一般語の下限が無関係なチャンク間で同点を作るのを防ぐためです。
スコアリングのループはチャンクではなくポスティングを反復します。これが速さの正体です。生存した 4 つの用語を持つクエリは 4 つのポスティングリストの和集合に触れるだけで、19 チャンクなら整数インクリメント数十回、50,000 チャンクなら数千回です。実測コストはデモコーパスで 1 クエリあたり 0.015 ms、20,000 チャンクで約 4 ms — コーパスサイズではなくポスティングに対して線形です。
k1 と b を調整する前に知っておくべき 2 つの限界があります。BM25 は一度も見たことのない用語にはマッチできません。クエリ retrieve は retrieval しか含まないチャンクに対してゼロをスコアリングします。トークンが異なるからです。また、意味でランク付けもできません。クエリ point an answer at its source は citation id を説明するチャンクに対してゼロになります。内容語のすべてが同義語だからです。この 2 つの失敗こそ、密検索の脚が存在する理由です。
密検索の脚と 2 つのランキングの融合
密リトリーバーはテキストをベクトルに写し、コサイン類似度でランク付けします。本番ではそのベクトルは訓練済みの文 embedding モデルから来ます。オフラインで依存関係もキーもない状況での正直な代役は文字 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]3 つの性質により、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 のチャンクは 1/61 = 0.0164、両リストでランク 2 のチャンクは 1/62 + 1/62 = 0.0323 です。後者が勝ちます。1 つが語彙で 1 つが意味論であるときに望まれる挙動です。k を 10 に下げると、単一リストの勝者がはるかに強くなります。一方のリトリーバーが明らかに優れていて、もう一方には小さなタイブレークだけ欲しい場合に有用です。
正直な測定が設計を変える場面がここです。以下は 19 チャンクと 8 件のラベル付きクエリで実行したハーネスです:
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最初の列ではなく 2 番目の列を読んでください。リコールこそ候補プールの存在意義であり、プールサイズも重要です。19 チャンクで pool=12 のとき、BM25 の上位 12 は 8 クエリ中 7 件で正しいドキュメントを含み、密検索の脚は 8 件中 8 件、したがって和集合は 8 件中 8 件です。1 件のクエリ — combining keyword and embedding rankings — は完全な語彙ミスであり、そのトピックのチャンクには keyword、embedding、rankings のいずれの語も含まれません。ハッシュ embedder は共有される rank 4-gram を通じてこれを見つけます。この規模における密検索の脚の根拠は、この 1 件のクエリにすべてあります。より良いランキングではなく、答えを静かに失わない候補プールです。
最初の列を読むと、見通しはあまり好ましくありません。BM25 が精度で勝り、融合は BM25 単独に対して P@1 で 12 ポイント負けています。これは RRF のバグではありません。密検索の脚のバグであり、正確に述べる価値があります。文字 n-gram embedder は異なる重み付け方式を持つ語彙マッチャーなので、それを BM25 と融合することは、同じ証拠の 2 つの視点を融合することになり、不一致はノイズです。3 つの語彙マッチャーを足しても意味論にはなりません。
修正は k を調整することではありません。HashedEmbedder を訓練済みモデルに置き換えることで、不一致の性質がノイズからシグナルに変わります。下流のすべて — 融合、リランキング、引用、ツール契約 — は同じままです。パイプラインの残りが必要としているのは embed(text) -> list[float] だけだからです。インターフェースを出荷し、脚を測定し、測定がその脚が弱いと言ったときにモデルを購入する。このハーネスこそ、それを知る方法です。
リランキング:レイテンシを払い、精度を買う
融合はリコールが良く順序が平凡なプールを与えます。リランカーは、クエリ-パッセージの各ペアを独立ではなく共同でスコアリングすることで順序を修正します。クロスエンコーダーは 1 回の順伝播でクエリとパッセージの両方を見るため、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)カバレッジは異なるクエリ用語の数で正規化されるため、2 語のクエリが偶然 6 語のクエリを上回ることはありません。フレーズボーナスは二値で重みは 4 分の 1 です。正確な部分文字列一致は強い証拠ですが、逐語的なフレーズを含まなくてもチャンクは正しいことがあります。近接性は 6 トークンのウィンドウで打ち切られます。それを超えると 2 つの用語は関連しているのではなく共起しているだけです。しかも隣接するクエリ用語でのみ発動するため、latency ... reranker はどちらの順でもカウントされますが、latency ... chunk はされません。
リランカーにできないことは、上の測定が示す通りです。デモコーパスでは何も動かしません。3 つ目の語彙マッチャーだからです。その本当の価値はクロスエンコーダーの登場とともにやってきます。そして正直な工学の問いは、クロスエンコーダーを用意できるかどうかです。
有効化する前に算数をしましょう。12 層のクロスエンコーダーは CPU 上でペアあたり約 10 ms、20 候補ペアで 1 クエリあたり 200 ms、8 ペアに打ち切れば 80 ms です。1 実行あたり 5 回の検索で 400 ms 追加 — LLM 往復 1 回に相当し、通常は許容範囲です。しかしツールの p95 が 40 ms でエージェントの総予算が 2 秒であれば許容できません。これを有界に保つ 2 つのレバーがあります。リランク集合に上限を設ける(8 が良いデフォルトです。9 番目の候補が上位 4 つを変えることはまれです)ことと、融合のマージンが大きい場合はリランキングをスキップする(上位パッセージが 2 位を 2 倍以上上回るなら、順序には余地がありません)ことです。
ツールレジストリへの接続
ツールが継ぎ目です。引用を返し、パート 2 のスキーマを守り、空の結果を 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 の衝突を返し、エージェントはエラーではなく 4 つの無関係なパッセージを受け取ります。下限はそれを ERROR[not_found] に変えます。モデルはこのコーパスはそれをカバーしていないと読み、それは真実です。
limit=4 も予算の決定です。約 105 トークンのパッセージ 4 つで 420 トークン、引用の足場に約 30 トークン。2 ヒットなら安いのですが、しばしば不十分です。答えは定義のチャンクと例のチャンクに分かれていることが多いからです。6 は精度がリコールの上昇より速く落ち始める地点です。
統合は 1 行です。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 という、スキーマに対して検証可能なツールが見えます。
失敗モードとその対処
| 失敗 | 実際に起きること | ここでの対処 | 依然として壊れている点 |
|---|---|---|---|
| チャンクが表やリストを分割する | 行が別々のチャンクに落ち、どちらも答えにならない | 句読点が許す限り文分割器が行をまとめる | Markdown 表には構造的分割器が必要 |
| クエリとコーパスが異なる語を使う | BM25 は何も返さず、ハッシュ embedding はノイズを返す | 密検索の脚 + 融合 | 真の同義語には訓練済みモデルが必要 |
| すべてのヒットが無関係 | モデルが主張を支持しないパッセージを引用する | min_score 下限 → ERROR[not_found] |
下限はコーパスごと。言語ごとに再校正が必要 |
| リランカーが遅すぎる | ツールの p95 が 40 ms から 240 ms に跳ね上がる | リランク集合を 8 に打ち切り、融合マージンが大きい場合はスキップ | 適応的な予算がない |
| ドキュメント間でチャンクが重複する | 同じ文が 2 回検索され、スロットを 2 つ浪費する | オーバーラップは有界。テキストハッシュで重複排除 | 近重複ドキュメントは依然としてプールをあふれさせる |
| 再チャンクで引用が無効化される | 過去の回答が誤った序数を指す | 序数は構築ごとに安定。コーパスのバージョンを記録 | 保存された引用の移行ツールがない |
| embedding モデルの差し替え | スコアがずれ、下限が無効になる | インターフェースが変更を隔離する | デプロイ前にハーネスの再実行が必要 |
最後の行こそ本番で噛みついてくるものであり、コードの失敗ではなくプロセスの失敗です。HashedEmbedder を本物のモデルに替えるとスコア分布が変わり、min_score が無効化され、エラーパスが静かに無関係パッセージのパスに変わります。embedder の変更の後は必ずハーネスを実行し、下限は新しい分布の裾の低い側から設定しなければなりません。古い分布からコピーしてはいけません。
トレードオフ
| 決定 | 代替案 | 選んだ理由 | 代償 |
|---|---|---|---|
| 420 文字のチャンク | 1,000 トークンのチャンク | 4 ヒットで 4,000 ではなく 420 トークン | 答えが境界をまたいで分割される |
| 90 文字のオーバーラップ | オーバーラップなし | 境界の文が検索可能に保たれる | インデックスが 21% 膨らむ |
| BM25 + 密検索、RRF で融合 | 単一リトリーバー | デモでプールのリコールが 0.88 から 1.00 に上昇 | 同期が必要な 2 つのインデックス |
| ハッシュ embedder | 訓練済み embedding モデル | 決定論的、オフライン、テスト可能 | 同義語のリコールなし。精度で BM25 に負ける |
| 決定論的リランカー | クロスエンコーダー | 1 ms で実行、ホストするモデルなし | ランキングをほとんど変えない |
min_score=0.05 |
マッチしたものを何でも返す | ゴミを分類されたエラーに変える | 本当に珍しいクエリはエラーを返す |
limit=4 |
limit=10 |
コンテキストコストが有界 | マルチホップの質問を取りこぼす |
リランカーの行には率直な答えを述べる価値があります。この代役では、精度の利得なしにインターフェースの複雑さを払っているのです。それでもインターフェースを構築する理由は、精度こそ訓練済みモデルが P@1 で 10〜20 ポイントを稼げる段階であり、後から継ぎ目を後付けすると、ツール契約、引用形式、テストを一度にすべて触ることになるからです。
テスト
11 個のテスト、ネットワークなし、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 が両脚を保持する根拠となるテストです。同じチャンクについて逆の 2 つのことを主張します。ベクトルインデックスは retrieve でそれを見つけ、BM25 は空リストを返します。後日、誰かがこのテストに失敗する embedder に差し替えたなら、密検索の脚は 2 つ目の語彙マッチャーに退化し、融合ステップは純粋なオーバーヘッドになります。まさに上のベンチマークが測定している状態です。
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、チャンク数でのインデックスサイズ、4 ヒットのトークンコストを報告します。オーバーラップがいくつで、リコールの利得が重複のコストを上回らなくなりますか? - クロスエンコーダーの継ぎ目。
class Reranker(Protocol)を定義し、score(query, passage) -> floatを持たせ、CoverageRerankerに実装させ、HTTPRerankerが[[query, passage]]ペアをリランキングのエンドポイントに送るようにしてください。リランク集合を 8 に打ち切り、passages[0].fused_score > 2 * passages[1].fused_scoreの場合はリランキングをスキップします。追加のレイテンシに対する P@1 の変化を測定します。 - 言語ごとの下限。 関連性の下限は英語で校正されています。トークン化が異なる言語(日本語やドイツ語の複合語)で 10 クエリのセットを作り、関連ヒットと無関係ヒットのスコア分布を求めてください。単一のグローバルな
min_scoreは正当化できるか、それともインデックスごとに必要か?
演習 2 が出荷するものを変えます。継ぎ目は小さく、それがあることで高価なコンポーネントはアーキテクチャの決定ではなくデプロイの決定になります。
次回
エージェントはパッセージを見つけて引用できるようになりました。まだできないのは、いくつの検索が必要か、どの順序で行うかを決めることです。ループは 1 回に 1 つのツール呼び出ししか発行せず、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.