สร้าง RAG Retriever ที่ควรค่าแก่ตำแหน่งของมัน (ตอนที่ 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 |
เครื่องมือ search จากตอนที่ 1 เป็นพจนานุกรมห้ารายการ ถามเรื่อง agent loop มันคืนประโยคเดียว ถามอย่างอื่นมันตอบ no matches ดังนั้นทุกข้อกล่าวอ้างของ agent จึงเป็นได้ทั้งหนึ่งในห้าประโยคนั้นหรือสมมติขึ้นมาล้วน ๆ และลูปไม่มีทางแยกแยะความต่างได้เลย
สัญชาตญาณแรกคือติดตั้ง vector database สัญชาตญาณนั้นถูกครึ่งหนึ่ง: dense retrieval ทำได้ดีจริงกับการเรียกชื่ออื่น (paraphrase) แต่มันเป็นเพียงหนึ่งในสามขั้นตอน และอีกสองขั้นตอนที่เหลือคือที่ที่ระบบ RAG ระดับการผลิตส่วนใหญ่ล่มอย่างเงียบ ๆ ตัวดึงข้อมูลที่คืน chunk ผิดพร้อมคะแนน cosine สูงนั้นแย่กว่าตัวที่ไม่คืนอะไรเลย เพราะ agent จะอ้างอิงมัน
ตอนนี้จะสร้างตัวดึงข้อมูลเป็นสามขั้นตอนที่แยกออกจากกันได้ — chunk, recall, rerank — แต่ละขั้นมีหน้าที่วัดได้ พร้อม harness ที่บอกว่าขั้นตอนหนึ่งช่วยได้หรือแค่เพิ่ม latency เท่านั้น ไปป์ไลน์เชื่อมเข้ากับสัญญา Tool ชุดเดียวกับตอนที่ 2 ดังนั้นการอ้างอิงจึงอยู่ถึงคำตอบสุดท้าย และตอนที่ 7 ตรวจสอบมันได้
สิ่งที่คุณจะสร้าง
โมดูล rag.py ที่มีห้าชิ้น:
chunk_document— การบรรจุแบบรู้เรื่องประโยคด้วย overlap ที่ตั้งค่าได้ คืนออบเจ็กต์Chunkที่มีcitationเป็นdoc#nBM25Index— Okapi BM25 บน inverted index คิวรีละ 0.015 ms บน 19 chunks ไม่พึ่งไลบรารีภายนอกHashedEmbedder+VectorIndex— ขา dense ที่อยู่หลังอินเทอร์เฟซembed(text) -> list[float]การเปลี่ยนเป็นโมเดลจริงคือแค่อะแดปเตอร์ยี่สิบบรรทัดHybridRetriever— รวมรายการ BM25 กับ dense ด้วย reciprocal rank fusionCorpusRetriever+make_search_tool— การ rerank ระดับความเกี่ยวข้องขั้นต่ำ และเครื่องมือsearchที่ agent รู้วิธีเรียกอยู่แล้ว
สถานะปัจจุบันของ research-agent หลังตอนที่ 1–4: ลูปที่มีสัญญาเครื่องมือที่ตรวจสอบแล้ว งบคอนเท็กซ์ต และหน่วยความจำ SQLite search เป็นสตั๊บตัวสุดท้าย ตอนนี้จะแทนที่มันโดยไม่แตะ AgentLoop เลย ซึ่งเป็นบททดสอบว่านามธรรมก่อนหน้านี้จริงแค่ไหน
สิ่งที่ต้องมีก่อน
- ตอนที่ 1–4
rag.pyนำเข้าToolToolResultและErrorCodeจากcontracts.pyส่วนดีโมนำเข้าAgentLoopและScriptedLLM - Python 3.10+ ใช้มาตรฐานไลบรารีเท่านั้น ไม่ต้องมี numpy, vector database หรือ embedding API key
- คลังข้อมูลเป็น
dict[str, str]ที่จับคู่ id เอกสารกับข้อความ ฟิกซ์เจอร์ด้านล่างเป็นเอกสารสั้นสิบสองชิ้นเกี่ยวกับการวิศวกรรม agent ซึ่ง chunk ออกเป็นสิบเก้าช่วงข้อความ
ฟิกซ์เจอร์เป็น 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 ที่นี่เป็นฟังก์ชัน hashing แบบ character n-gram ไม่ใช่โมเดลที่เทรนมา มันเป็นตัวจับคู่แบบศัพท์ที่มีขอบเขตคลุมเครือ (fuzzy): จับ retrieve กับ retrieval คู่กันได้เพราะใช้ 4-gram ร่วมกัน แต่ล้มเหลวกับคำพ้องความหมายของจริง ข้อจำกัดนี้ตั้งใจไว้ และส่วนการวัดจะแสดงต้นทุนของมันอย่างแม่นยำ — เพราะตัวดึงข้อมูลที่วัดไม่ได้ คือตัวที่พัฒนาต่อไม่ได้
พจนานุกรมห้ารายการนั้นมีต้นทุนจริงเท่าไร
สามความล้มเหลว ทั้งหมดทำซ้ำได้จากโค้ดปัจจุบัน
การพลาดกับคลังว่างแยกกันไม่ออก เมื่อไม่มี key ใดจับคู่ได้ _search คืน ["no matches"] ซึ่งเป็น ok=True โมเดลจะอ่านว่าเป็นหลักฐานว่าคลังไม่มีเนื้อหาหัวข้อนี้เลย ตอนที่ 2 แก้กรณี timeout ด้วยข้อผิดพลาดแบบจำแนกแล้ว กรณีพลาดก็ยังเป็นเรื่องโกหกที่แต่งตัวเป็นข้อมูล
ไม่มีการอ้างอิง เครื่องมือคืนสตริงเปล่า ๆ เมื่อโมเดลเขียนคำตอบสุดท้าย ไม่มีอะไรชี้กลับไปที่ช่วงข้อความใดเลย ผู้ใช้จึงตรวจสอบข้อกล่าวอ้างไม่ได้ และตอนที่ 7 ก็ตรวจไม่ได้เช่นกัน
หน่วยการดึงคือทั้งเอกสาร แม้มีคลังจริง การคืนทั้งเอกสารหมายความว่าหนึ่งครั้งได้ก้อน 4,000 ตัวอักษรมาสี่ครั้งๆละ 420 ตัวอักษรคือประมาณ 420 token ของคอนเท็กซ์ต สี่เอกสารเต็มคือ 4,000 จากนั้นงบของตอนที่ 3 ก็เผาแรงไปกับการบีบอัดข้อความที่ตัวดึงข้อมูลไม่ควรส่งมาตั้งแต่แรก
ส่วนที่เหลือของบทความนี้แก้ทั้งสามเรื่องในตัวโครงสร้างเลย: chunk ทำให้หน่วยเล็ก การอ้างอิงทำให้ผลลัพธ์ตรวจสอบได้ และระดับความเกี่ยวข้องขั้นต่ำเปลี่ยนการพลาดเป็นข้อผิดพลาดแบบจำแนก
Chunking: การตัดสินใจที่ย้อนกลับไม่ได้
ขอบเขต chunk เป็นการตัดสินใจด้านการดึงข้อมูลเพียงหนึ่งเดียวที่ย้อนกลับได้ยาก เพราะเปลี่ยนเมื่อไรต้อง embedding คลังทั้งหมดใหม่ ที่เหลือทั้งหมด — ฟังก์ชันให้คะแนน ค่าคงที่ฟิวชัน ตัว reranker — ปรับจบได้ในหนึ่งบ่าย
คู่เงื่อนไขง่ายมาก Chunk ใหญ่เกินจะเจือจาง: chunk 900 ตัวอักษรที่มีสามประเด็นไม่เกี่ยวกัน จะถูกจัดอันดับให้ทั้งสามประเด็นแต่ตอบไม่มีประเด็นไหนแม่น เพราะ 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)]สี่การตัดสินใจในสามสิบบรรทัด แต่ละอันมีต้นทุนของตัวเอง
ตัดที่ประโยค บรรจุให้พอดีงบตัวอักษร การตัดกลางคำทำให้ chunk แรกเริ่มด้วยคำที่ขาดครึ่ง ซึ่งเป็นพิษต่อทั้ง embedding และข้อความอ้างอิง รีเจกซ์ตัดเฉพาะหลัง ., ! หรือ ? ที่ตามด้วยช่องว่างเท่านั้น ทำให้คำย่ออย่าง e.g. ถูกตัดผิด — ยอมรับได้ เพราะความเสียหายมีแค่ขอบเขตเพิ่มหนึ่งอัน ไม่ใช่คำที่ขาด
420 ตัวอักษร ไม่ใช่ 512 token เมื่อประมาณสี่ตัวอักษรต่อ token นั่นคือราว 105 token ต่อ chunk ตัวเลขสำคัญน้อยกว่าอัตราส่วน: สี่ chunk ที่ดึงมาละ 105 token คือ 420 token ของหลักฐาน ซึ่งกินพื้นที่สบาย ๆ ในงบของตอนที่ 3 ร่วมกับ system prompt 300 token ถ้าตั้งเพดาน chunk ที่ 1,000 token สี่ครั้งจะกิน 4,000 token และบังคับให้งบไปบีบอัดข้อความที่คุณจ่ายเงินดึงมาพอดี
Overlap คือการคัดลอกหาง ไม่ใช่หน้าต่างเลื่อน หลัง flush ประโยคสุดท้ายที่อยู่ใน 90 ตัวอักษรได้จะถูกเปิดซ้ำในบัฟเฟอร์ใหม่ ผลคือการเตือนดัชนี 21 เปอร์เซ็นต์ที่ค่าตั้งเหล่านี้ (90 จาก 420) และคำมั่นหนึ่งข้อ: ประโยคที่ข้ามขอบเขตจะดึงได้อย่างน้อยหนึ่งฝั่ง Chunking แบบหน้าต่างเลื่อนตามจำนวน token ได้คำมั่นเดียวกันแต่ให้ chunk ที่ขึ้นกลางประโยค ซึ่งเป็นสิ่งที่เราหลบเลี่ยง
ordinal คือการอ้างอิง จึงต้องนิ่ง chunking#1 หมายถึง chunk ที่สองของเอกสาร chunking ถ้าตั้งค่าใหม่แล้ว chunk ซ้ำ การอ้างอิงทุกจุดในคำตอบเก่าจะชี้ไปที่อื่น เพราะฉะนั้นการตั้งค่าจึงควรอยู่ในการ build ดัชนี จดไว้ข้างเวอร์ชันคลัง และการ chunk ใหม่คือการ migration ไม่ใช่แค่เปลี่ยน config
BM25 จาก inverted index
BM25 เป็นตัวให้คะแนนแบบศัพท์ที่มีสองความคิดซึ่งยังเอาชนะการนับคำแบบง่ายได้ ความถี่คำอิ่มตัว: การเจอ latency ครั้งที่สิบใน chunk แทบไม่เพิ่มอะไรเลยจากครั้งที่ห้า เพราะ chunk นั้นก็เกี่ยวกับ latency อยู่แล้ว การปรับตามความยาว (length normalisation) กัน 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)) ซึ่งเป็นบวกแต่จิ๋ว คำที่ปรากฏในเกินราว 80 เปอร์เซ็นต์ของ chunk แทบไม่เพิ่มอะไรเลย ไม่คุ้มที่จะคูณ การตัดทิ้งทำให้ระดับขั้นต่ำของคำทั่วไปไม่ก่อสถานะเสมอกันระหว่าง chunk ที่ไม่เกี่ยวกัน
ลูปให้คะแนนวนตาม postings ไม่ใช่ chunks นั่นแหละที่ทำให้เร็ว: คิวรีที่มีสี่คำรอดจะสัมผัสยูเนียนของสี่ posting list ซึ่งบน 19 chunks เป็นการเพิ่มค่าจำนวนเต็มไม่กี่สิบครั้ง และบน 50,000 chunks เป็นหลักพัน ต้นทุนที่วัดได้คือ 0.015 ms ต่อคิวรีบนคลังดีโม และประมาณ 4 ms ที่ 20,000 chunks — เป็นเชิงเส้นตาม postings ไม่ใช่ตามขนาดคลัง
สองข้อจำกัดที่ควรรู้ก่อนปรับ k1 และ b BM25 จับคู่คำที่ไม่เคยเห็นไม่ได้: คิวรี retrieve ให้ศูนย์กับ chunk ที่มีแต่ retrieval เพราะ token ต่างกัน และจัดอันดับตามความหมายไม่ได้: คิวรี point an answer at its source ให้ศูนย์กับ chunk ที่อธิบาย id การอ้างอิง เพราะทุกคำเนื้อหาเป็นพ้องความหมาย สองความล้มเหลวนี้คือเหตุผลที่ขา dense มีอยู่เพื่อคลุม
ขา dense และการหลอมรวมสองอันดับ
ตัวดึงข้อมูลแบบ dense แปลงข้อความเป็นเวกเตอร์และจัดอันดับด้วยความคล้าย cosine ในการผลิต เวกเตอร์นั้นมาจากโมเดล sentence-embedding ที่เทรนมา ในโหมดออฟไลน์ ไม่พึ่งไลบรารีและไม่มี key ตัวแทนที่ซื่อสัตย์คือ hashing แบบ character n-gram: มันจับ morphology และ substring ที่ใช้ร่วมกัน ซึ่งเป็นรูปการวางนัยทั่วไปที่แคบแต่จริง ซึ่ง 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 คือ dot product และคะแนนเปรียบเทียบกันได้ข้ามความยาว chunk Hashing เป็นแบบ signed ทำให้การชนกันรวมกันเป็นศูนย์โดยเฉลี่ยแทนการสะสมความคล้ายปลอม การค้นหาเป็น brute force ซึ่งที่ 19 chunks กิน 0.6 ms และที่ 50,000 chunks ใน Python ล้วนราว 400 ms — ช้าพอให้คุณสังเกตเห็น และช้าพอเป็นข้ออ้างให้ใช้ดัชนีจริงเมื่อไปถึงจุดนั้น
ต่อไปคือฟิวชัน คะแนน BM25 ไร้เพดาน cosine อยู่ใน [-1, 1] การนำมาบวกกันเป็นข้อผิดพลาดเชิงประเภท และการทำให้เป็นบรรทัดฐานเดียวกันต้องใช้สถิติต่อคิวรีที่เปลี่ยนไปตามคิวรี Reciprocal rank fusion เลี่ยงทั้งคู่ด้วยการให้คะแนนเฉพาะตำแหน่งอันดับ
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 เป็นค่าเริ่มต้นที่เผยแพร่และฝังความเชื่อเฉพาะหนึ่งไว้: ความเห็นพ้องระหว่างรายการสำคัญกว่าความเด่นภายในรายการเดียว chunk ที่อันดับ 1 ในรายการหนึ่งได้ 1/61 = 0.0164 chunk ที่อันดับ 2 ในทั้งสองรายการได้ 1/62 + 1/62 = 0.0323 อันหลังชนะ ซึ่งเป็นพฤติกรรมที่คุณอยากได้เมื่อรายการหนึ่งเป็นแบบศัพท์และอีกรายการเป็นแบบความหมาย ลด k เหลือ 10 ทำให้ผู้ชนะจากรายการเดียวแรงขึ้นมาก — มีประโยชน์เมื่อตัวดึงข้อมูลหนึ่งชัดเจนว่าดีกว่า และคุณแค่อยากได้การตัดสินเสมอเล็กน้อยจากอีกตัว
ตรงนี้แหละที่การวัดอย่างซื่อสัตย์เปลี่ยนการออกแบบ นี่คือ harness ที่รันบนสิบเก้า 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 คือเหตุผลที่มีพูลผู้สมัครอยู่ และขนาดพูลมีผล: ที่ pool=12 บน 19 chunks top 12 ของ BM25 มีเอกสารที่ถูกสำหรับ 7 จาก 8 คิวรี และขา dense ครบ 8 จาก 8 ยูเนียนจึงครบ 8 จาก 8 มีคิวรีหนึ่ง — combining keyword and embedding rankings — เป็นการพลาดเชิงศัพท์หมดจด ที่ chunk ของหัวข้อไม่มีคำว่า keyword embedding หรือ rankings เลย และ embedder แบบ hash หาเจอด้วย 4-gram rank ที่ใช้ร่วมกัน คิวรีเดียวนั้นคือข้อโต้แย้งทั้งหมดให้ขา dense ที่สเกลนี้: ไม่ใช่การจัดอันดับที่ดีกว่า แต่เป็นพูลที่ไม่ทิ้งคำตอบไปเงียบ ๆ
อ่านคอลัมน์แรกแล้วภาพไม่สวยเท่าไร BM25 ชนะด้าน precision และฟิวชันแพ้ 12 แต้มของ P@1 เทียบกับ BM25 เดี่ยว ๆ นั่นไม่ใช่บั๊กของ RRF มันเป็นบั๊กของขา dense และควรพูดให้ชัด: embedder character n-gram คือตัวจับคู่ศัพท์ที่ใช้แผนถ่วงน้ำหนักต่างออกไป การหลอมรวมมันกับ BM25 จึงรวมมุมมองสองอันของหลักฐานชุดเดียวกัน และความไม่ลงรอยคือเสียงรบกวน ตัวจับคู่ศัพท์สามตัวไม่รวมกันเป็นความหมายได้
ทางแก้ไม่ใช่ปรับ k ทางแก้คือเปลี่ยน HashedEmbedder เป็นโมเดลที่เทรนมา ซึ่งเปลี่ยนธรรมชาติของความไม่ลงรอยจากเสียงรบกวนเป็นสัญญาณ ทุกอย่างปลายน้ำ — ฟิวชัน การ rerank การอ้างอิง สัญญาเครื่องมือ — ยังเหมือนเดิม เพราะสิ่งที่ไปป์ไลน์ที่เหลือต้องการมีแค่ embed(text) -> list[float] ปล่อยอินเทอร์เฟซออกไป วัดขา แล้วซื้อโมเดลเมื่อการวัดบอกว่าขาเป็นจุดอ่อน Harness นี่คือวิธีที่คุณรู้
การ rerank: จ่าย latency แลก precision
ฟิวชันให้พูลที่มี recall ดีแต่การจัดอันดับกลาง ๆ ตัว reranker แก้การจัดอันดับด้วยการให้คะแนนคู่ query-passage ร่วมกันแทนที่จะแยกกัน Cross-encoder เห็นคิวรีและช่วงข้อความในหนึ่ง forward pass จึงเข้าใจ not กับ only และลำดับคำ — สิ่งที่ทั้ง BM25 และ embedding แบบ bag-of-ngrams ทำไม่ได้
ตัวแทนแบบกำหนดผลได้ (deterministic) ด้านล่างให้คะแนนจากความครอบคลุมคำ การมีอยู่ของวลีเป๊ะ ๆ และความใกล้กันของคำคิวรีที่อยู่ติดกัน มันไม่ใช่ cross-encoder มันเป็นฟังก์ชันที่มีรูปร่างแบบ reranker เพื่อให้ไปป์ไลน์ เกณฑ์ตัดสิน และการทดสอบ มีอยู่แล้วก่อนคุณจะต่ออะไรที่แพง
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)ความครอบคลุมถูกหารด้วยจำนวนคำคิวรีที่ไม่ซ้ำกัน คิวรีสองคำจึงไม่มีทางได้คะแนนมากกว่าคิวรีหกคำโดยบังเอิญ โบนัสวลีเป็นแบบสองสถานะและหนักหนึ่งในสี่: การจับ substring เป๊ะ ๆ เป็นหลักฐานแข็งแรง แต่ chunk จะถูกได้แม้ไม่มีวลีตรงตัว ความใกล้กันถูกเพดานที่หน้าต่างหก token เพราะเกินนั้นสองคำเป็นแค่เกิดพร้อมกัน ไม่ใช่เกี่ยวข้องกัน — และมันจุดเฉพาะกับคำคิวรีที่ ติดกัน เท่านั้น latency ... reranker ในทิศไหนก็นับ แต่ latency ... chunk ไม่นับ
สิ่งที่ตัว reranker ทำไม่ได้คือสิ่งที่การวัดด้านบนแสดงแล้ว: บนคลังดีโมมันไม่เปลี่ยนอะไรเลย เพราะมันเป็นตัวจับคู่ศัพท์ตัวที่สาม คุณค่าจริงของมันมาพร้อม cross-encoder และคำถามวิศวกรรมที่ซื่อสัตย์คือคุณแบกมันไหวหรือไม่
คิดเลขก่อนเปิดใช้ Cross-encoder 12 เลเยอร์บนคู่ผู้สมัคร 20 คู่กินราว 10 ms ต่อคู่บน CPU คือ 200 ms ต่อคิวรี จำกัด 8 คู่คือ 80 ms ห้าการค้นหาต่อรันเพิ่ม 400 ms — เทียบเท่าการเดินทางกลับ LLM หนึ่งรอบ ซึ่งปกติยอมรับได้ แต่ยอมไม่ได้ถ้า p95 ของเครื่องมือคือ 40 ms และงบรวมของ agent คือสองวินาที สองคันโยงช่วยจำกัดไว้: เพดานชุด rerank (8 เป็นค่าเริ่มต้นที่ดี ตัวที่ 9 แทบไม่เปลี่ยน top 4) และ ข้ามการ rerank เมื่อระยะห่างของฟิวชันมาก (ถ้าช่วงข้อความอันดับหนึ่งเอาชนะอันดับสองเกิน 2× การจัดอันดับไม่ใกล้กันแล้ว)
เชื่อมเข้ารีจิสทรีเครื่องมือ
เครื่องมือคือรอยต่อ มันต้องคืนการอ้างอิง เคารพ schema จากตอนที่ 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 แบบ hash ที่ cosine เป็นบวกจิ๋ว และ agent ได้สี่ช่วงข้อความที่ไม่เกี่ยวแทนข้อผิดพลาด ระดับขั้นต่ำเปลี่ยนสิ่งนั้นเป็น ERROR[not_found] ซึ่งโมเดลอ่านว่า คลังนี้ไม่ครอบคลุมหัวข้อนั้น และมันก็จริง
limit=4 ก็เป็นการตัดสินใจด้านงบด้วย สี่ช่วงข้อความละราว 105 token คือ 420 token บวกโครงอ้างอิงราว 30 token สองครั้งถูกกว่าแต่มักไม่พอ — คำตอบมักถูกแบ่งข้าม 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"] คือการย้ายทั้งหมด ลูป ตัวเรียกทำงาน นโยบายลองซ้ำ และร้าน idempotency ไม่ถูกแตะเลย และโมเดลยังเห็นเครื่องมือชื่อ search ที่มี schema ตรวจสอบได้เหมือนเดิม
รูปแบบความล้มเหลวและวิธีจัดการ
| ความล้มเหลว | เกิดอะไรขึ้นจริง ๆ | การจัดการที่นี่ | ยังเป็นจุดอ่อน |
|---|---|---|---|
| Chunk ตัดทะลุตารางหรือรายการ | แถวกระจายคนละ chunk ไม่มีอันไหนตอบได้ | ตัวแยกประโยคเก็บแถวไว้ด้วยกันเมื่อเครื่องหมายวรรคตอนอนุญาต | ตาราง Markdown ต้องใช้ตัวแยกเชิงโครงสร้าง |
| คิวรีกับคลังใช้คำต่างกัน | BM25 ไม่คืนอะไร embedding แบบ hash คืนเสียงรบกวน | ขา dense + ฟิวชัน | คำพ้องความหมายแท้ต้องใช้โมเดลที่เทรนมา |
| ทุกครั้งที่ได้มาไม่เกี่ยวข้อง | โมเดลอ้างช่วงข้อความที่ไม่สนับสนุนข้อกล่าวอ้าง | ระดับขั้นต่ำ min_score → ERROR[not_found] |
ระดับขั้นต่ำผูกกับคลัง ต้องวัดใหม่ตามภาษา |
| Reranker ช้าเกิน | p95 ของเครื่องมือพุ่งจาก 40 ms เป็น 240 ms | จำกัดชุด rerank ที่ 8 ข้ามเมื่อระยะฟิวชันมาก | ไม่มีงบประมาณแบบปรับตัว |
| Chunk ซ้ำข้ามเอกสาร | ประโยคเดียวถูกดึงสองรอบ เสียสองช่อง | overlap มีขอบเขต ลบซ้ำด้วย hash ข้อความ | เอกสารเกือบซ้ำกันยังท่วมพูลอยู่ |
| การ chunk ใหม่ทำให้การอ้างอิงหมดความหมาย | คำตอบเก่าชี้ไป ordinal ผิด | ordinal นิ่งต่อ build จดเวอร์ชันคลังไว้ | ไม่มีเครื่องมือ migration สำหรับการอ้างอิงที่เก็บไว้ |
| เปลี่ยนโมเดล embedding | คะแนนเลื่อน ระดับขั้นต่ำใช้ไม่ได้ | อินเทอร์เฟซโอบการเปลี่ยนไว้ | ต้องรัน harness ใหม่ก่อน deploy |
แถวสุดท้ายคืออันที่กัดในการผลิต และมันเป็นความล้มเหลวเชิงกระบวนการไม่ใช่เชิงโค้ด การเปลี่ยน HashedEmbedder เป็นโมเดลจริงเปลี่ยนการกระจายคะแนน ซึ่งทำให้ min_score ใช้ไม่ได้ ซึ่งเทียบเท่ากับการเปลี่ยนเส้นทางข้อผิดพลาดเป็นเส้นทางช่วงข้อความที่ไม่เกี่ยวอย่างเงียบ ๆ ทุกการเปลี่ยน embedder ต้องตามด้วยการรัน harness และระดับขั้นต่ำต้องตั้งจากหางล่างของการกระจายใหม่ — ไม่ใช่ก็อปจากของเก่า
การแลกเปลี่ยน
| การตัดสินใจ | ทางเลือก | ทำไมจึงเลือก | ต้นทุน |
|---|---|---|---|
| chunk 420 ตัวอักษร | chunk 1,000 token | สี่ครั้งกิน 420 token ไม่ใช่ 4,000 | คำตอบถูกตัดข้ามขอบเขต |
| overlap 90 ตัวอักษร | ไม่มี overlap | ประโยคที่ขอบเขตยังดึงได้ | ดัชนีบวม 21 เปอร์เซ็นต์ |
| BM25 + dense หลอมด้วย RRF | ตัวดึงข้อมูลเดียว | recall ของพูลขึ้นจาก 0.88 เป็น 1.00 ในดีโม | ดัชนีสองชุดที่ต้องซิงก์กัน |
| embedder แบบ hash | โมเดล embedding ที่เทรนมา | กำหนดผลได้ ออฟไลน์ ทดสอบได้ | ไม่มี recall จากคำพ้อง แพ้ BM25 ด้าน precision |
| reranker กำหนดผลได้ | Cross-encoder | รันใน 1 ms ไม่ต้องโฮสต์โมเดล | แทบไม่เปลี่ยนอันดับ |
min_score=0.05 |
คืนอะไรที่จับคู่ได้ก็พอ | เปลี่ยนขยะเป็นข้อผิดพลาดแบบจำแนก | คิวรีที่หายากจริง ๆ จะได้ข้อผิดพลาด |
limit=4 |
limit=10 |
ต้นทุนคอนเท็กซ์ถูกจำกัด | พลาดคำถามแบบหลายก้าว (multi-hop) |
แถว reranker ควรได้คำตอบตรง ๆ: กับตัวแทนตัวนี้คุณจ่ายความซับซ้อนของอินเทอร์เฟซโดยไม่ได้ precision เพิ่มเลย เหตุผลที่ยังควรสร้างอินเทอร์เฟซคือ precision เป็นขั้นตอนที่โมเดลที่เทรนมาได้เพิ่ม 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 เป็นเทสต์ที่ให้เหตุผลว่าทำไมต้องเก็บทั้งสองขา มันยืนยันสองข้อกล่าวฝืนกันเองเกี่ยวกับ 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 แล้วรัน harness ทุกครั้ง รายงาน recall@12 ขนาดดัชนีเป็น chunks และต้นทุน token ของสี่ครั้ง ที่ค่า overlap เท่าไรที่ความได้เปรียบของ recall ไม่คุ้มต้นทุนการซ้ำอีกแล้ว? - รอยต่อ cross-encoder นิยาม
class Reranker(Protocol)ที่มีscore(query, passage) -> floatให้CoverageRerankerไปใช้ แล้วเพิ่มHTTPRerankerที่ POST คู่[[query, passage]]ไปยัง endpoint การ rerank จำกัดชุด rerank ที่ 8 และข้ามการ rerank เมื่อpassages[0].fused_score > 2 * passages[1].fused_scoreวัดการเปลี่ยนแปลง P@1 เทียบกับ latency เพิ่ม - ระดับขั้นต่ำต่อภาษา ระดับความเกี่ยวข้องขั้นต่ำถูกเทียบบนภาษาอังกฤษ สร้างชุดคิวรีสิบตัวในภาษาที่แบ่ง token ต่างกัน (ภาษาญี่ปุ่นหรือการประสมคำเยอรมัน) แล้วหาการกระจายคะแนนระหว่างครั้งที่เกี่ยวข้องกับไม่เกี่ยวข้อง
min_scoreเดียวรวมทั้งระบบยังป้องกันตัวเองได้หรือต้องเป็นต่อดัชนี?
แบบฝึกหัด 2 คือข้อที่เปลี่ยนสิ่งที่คุณปล่อยออกไป รอยต่อเล็ก และการมีมันหมายความว่าชิ้นส่วนที่แพงกลายเป็นการตัดสินใจเรื่องการ deploy ไม่ใช่การตัดสินใจเชิงสถาปัตยกรรม
ก้าวต่อไป
ตอนนี้ agent หาช่วงข้อความและอ้างอิงมันได้แล้ว สิ่งที่ยังทำไม่ได้คือตัดสินว่าต้องค้น กี่ครั้ง หรือในลำดับไหน — ลูปออกการเรียกเครื่องมือครั้งละหนึ่ง และคำถามอย่าง compare the chunking trade-offs with the reranker latency budget ต้องการแผน
ตอนที่ 6 Task decomposition เพิ่ม Planner ที่เปลี่ยนเป้าหมายเป็นกราฟงานที่มี dependency ชัดเจน ตัวเรียกทำงานที่รันงานพร้อมแล้วขนานกัน และขั้นวางแผนใหม่ที่มีขอบเขตซึ่งทำงานเมื่องานล้มเหลว เครื่องมือ 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.