आफ्नो ठाउँ कमाउने RAG रिट्रिभर बनाउने (भाग 5)
Retrieval in three stages
One search call, three stages
The pool exists for recall; the reranker exists for order.
- input
- process
- decision
- output
Measured on 19 chunks, 8 queries
| Recall@12 (pool) | P@1 (precision) | |
|---|---|---|
| BM25 alone | 0.88 | 0.62 |
| Dense alone | 1.00 | 0.38 |
| Hybrid (RRF) | 1.00 | 0.50 |
| Verdict | fusion earns its keep | buy a real model |
भाग 1 को search टुल पाँच प्रविष्टिको डिक्सनरी हो. यसलाई agent loop बारे सोध्यो भने एक वाक्य फर्काउँछ; अरू कुनै पनि कुरा सोध्यो भने no matches भन्छ. त्यसैले agent ले गर्ने हरेक दाबी ती पाँच वाक्यमध्ये एक हुन्छ या सम्पूर्ण कपोली — दुवैबीच भेद गर्ने उपाय लुपसँग छैन.
पहिलो प्रतिक्रिया भेक्टर डेटाबेस जोड्ने हुन्छ. त्यो प्रतिक्रिया आधा सही हो: प्याराफ्रेज पहिचानमा dense retrieval साँच्चै राम्रो. तर त्यो तीन चरणमध्ये एक मात्र हो; बाँकी दुई चरणमै धेरैजसो प्रोडक्सन RAG सिस्टम मौनतः असफल हुन्छन्. उच्च कोसाइन स्कोरसँग गलत चंक फर्काउने रिट्रिभर केही पनि नफर्काउने रिट्रिभरभन्दा अझै नरक — किनकि agent ले त्यसको संदर्भ दिन्छ.
यो भाग रिट्रिभरलाई तीन छुट्टाछुट्टै चरणमा खडा गर्छ — chunk, recall, rerank — हरेक चरणको नाप्नसकिने जिम्मेवारी हुन्छ; साथै कुन चरण मद्दत गरिरहेको छ कि केवल लेटेन्सी थपिरहेको छ भन्ने हार्नेस पनि. पाइपलाइन भाग 2 कै Tool सम्झौतासँग जोडिन्छ; त्यसैले संदर्भहरू अन्तिम उत्तरसम्म टिक्छन् र भाग 7 ले तिनीहरू प्रमाणित गर्न सक्छ.
तपाईं बनाउने कुरा
पाँच टुक्रासहित rag.py मोड्युल:
chunk_document— मिलाउनसकिने ओभरल्यापसहित वाक्य-सचेत प्याकिङ;Chunkवस्तुहरू दिन्छ, जसकोcitationdoc#nहुन्छ.BM25Index— इन्भर्टेड इन्डेक्समाथि Okapi BM25; 19 चंक्समा प्रति क्वेरी 0.015 ms, डिपेन्डेन्सी छैन.HashedEmbedder+VectorIndex—embed(text) -> list[float]इन्टरफेस पछाडि बसेको dense शाखा; साँचो मोडेल साट्नु बीस लाइनको अड्याप्टर काम मात्र हो.HybridRetriever— BM25 र dense सूचीहरूलाई reciprocal rank fusion ले जोड्ने.CorpusRetriever+make_search_tool— reranking, प्रासंगिकता फ्लोर, र agent ले अगाइ नै कसरी कल गर्ने जानेकोsearchटुल.
भाग 1–4 पछि research-agent को वर्तमान स्थिति: प्रमाणित टुल सम्झौता, कन्टेक्स्ट बजेट, र SQLite मेमोरी भएको एउटा लुप. search अन्तिम स्टब हो. यो भाग AgentLoop लाई छुनै नदिई त्यसलाई बदल्छ — अगाडिका अब्स्ट्रयाक्सन साँच्चै खडे छन् कि छैनन् भन्ने परीक्षा यही हो.
आवश्यक पूर्वतयारी
- भाग 1–4.
rag.pyलेTool,ToolResultरErrorCodeलाईcontracts.pyबाट इम्पोर्ट गर्छ; डेमोलेAgentLoopरScriptedLLMइम्पोर्ट गर्छ. - Python 3.10+, स्ट्यान्डर्ड लाइब्रेरी मात्र. numpy चाहिँदैन, भेक्टर डेटाबेस छैन, embedding API key पनि छैन.
- डकुमेन्ट id लाई टेक्स्टमा म्याप गर्ने
dict[str, str]स्वरूपको कोर्पस. तलको फिक्स्चर agent इन्जिनियरिङबारे बाह्र छोटा डकुमेन्ट हो; तिनीहरू उन्नाइस प्यासेजमा चंक हुन्छन्.
फिक्स्चर भनेको डकुमेन्टहरूको dict; बाह्र डकुमेन्ट, हरेकमा थोरै वाक्यहरू. यसलाई जानाजान सानो राखिएको हो:
यस लेखका हरेक स्कोर एउटै कोरमा एक सेकेन्डभित्र पुनःसृजना गर्नसकिने गरी सानो; अनि त्यही बेला
सरल इन्डेक्सलाई निल्ने शब्दकीय झोलहरू राख्नसक्ने गरी विविधतापूर्ण.
DOCUMENTS = { "chunking": ( "Chunk size sets the ceiling on retrieval precision. A 900-character chunk that " "contains three unrelated points will rank for all three and answer none of them " "cleanly. A 120-character chunk loses the pronoun and the subject of its own " "sentence. The band that survives contact with real corpora is 300 to 500 " "characters with an overlap of roughly one fifth of the window. Overlap exists so " "a sentence split across a boundary is still retrievable from one side; it also " "duplicates text, so a 20 percent overlap inflates the index by 20 percent. Split " "on sentence boundaries, never mid-word. Then measure: recall at five on a " "labelled query set is the only number that tells you whether the window is right." ), "retrieval-design": ( "A retrieval pipeline has three stages and they fail differently. Recall stage: " "fetch a candidate pool of twenty to fifty passages. Lexical scoring with BM25 " "catches exact identifiers, error codes and product names; dense retrieval catches " "paraphrase such as retrieve versus retrieval. Fuse the two ranked lists by " "reciprocal rank fusion rather than by adding raw scores, because BM25 scores are " "unbounded while cosine similarity lives in a fixed range. Rerank stage: a " "cross-encoder scores each query and passage pair jointly and is far more accurate " "than either first stage, at roughly ten milliseconds per pair. Generation stage: " "the model receives four passages with citation ids and must cite one per claim." ), "latency-budget": ( "Search latency is a budget, not a property. On a single CPU core, BM25 over " "twenty thousand chunks answers in about 4 milliseconds because it touches only " "the postings of query terms. Brute-force cosine over the same set costs 38 " "milliseconds in pure Python and 3 milliseconds with a matrix multiply. A " "cross-encoder reranker over twenty candidates costs 180 to 240 milliseconds per " "query at 12 layers. If the agent issues five searches per run, reranking adds " "more than a second to the run and the p95 latency of the tool dominates the p95 " "of the answer. Cap the rerank set at eight candidates and the added cost falls " "under 100 milliseconds." ), "planner": ( "A planner turns one goal into a graph of tasks with explicit dependencies. The " "graph, not the prose plan, is what the executor runs: a task becomes ready only " "when every task it depends on has completed. Two invariants matter. The graph " "must be acyclic, checked before execution rather than discovered by a stack " "overflow, and every dependency must name a task that exists. When a task fails, " "the planner is invoked again with the failure as input; the cheapest replan adds " "remediation tasks in front of the remaining work instead of rebuilding the whole " "plan, which is why replans are bounded to two per run." ), "reflection": ( "Reflection is a second pass that critiques the first answer and, if the critique " "finds a defect, produces a revision. It improves answers when the critique is " "anchored to evidence and degrades them when the model is asked to judge itself in " "the abstract. A loop needs three stop conditions: a hard round limit, a minimum " "score improvement below which another round is waste, and an oscillation check " "that fires when the same critique returns twice. Without the second condition " "the loop spends tokens rewriting a correct answer; without the third it " "alternates between two versions forever." ), "citations": ( "A citation id is a pointer from a claim to a passage, and it is the only cheap " "way to verify an answer mechanically. Format the id as document plus chunk " "ordinal, for example latency-budget#1, so a checker can reload the exact text. " "Verification then becomes decidable: does the cited chunk exist, does it contain " "the number in the claim, does the quote appear verbatim. An answer with no " "citation is not automatically wrong, but it is unverifiable, and the difference " "matters when a downstream step trusts the number." ),"cdn-transfer": ( "Chunked transfer encoding splits an HTTP response into chunks of up to 64 KB so " "a proxy can forward bytes before the origin finishes writing. The chunk size is a " "transport decision, unrelated to how much text a reader can absorb at once, and " "changing it never changes answer quality. A CDN that buffers whole responses " "defeats the purpose: the first byte arrives only after the last chunk." ), "cache-latency": ( "A read-through cache in front of the index drops p95 latency from 240 ms to 9 ms " "for repeated queries, but the hit rate on a research workload is 31 percent " "because every run asks new questions. Cache the embedding of a query, not the " "result of a search, and the hit rate rises to 68 percent without returning stale " "passages." ), "document-store": ( "A document database stores JSON documents and indexes their fields. Retrieving a " "document by primary key is a hash lookup and takes microseconds; retrieving by an " "unindexed field is a full collection scan. Documents in this sense are rows, not " "prose, and no amount of chunk size tuning changes that." ), "self-critique": ( "Asking a model to reflect on its answer in the abstract produces longer answers " "with the same errors. The model has no new information, so the critique restates " "the answer with more confident wording. Reflection helps only when the critique is " "given evidence the first pass did not have, or a checker it cannot argue with." ), "ide-plan-mode": ( "Plan mode in an editor writes a plan file, waits for approval, then executes. When " "a step fails the developer edits the plan by hand and reruns; there is no automatic " "replan and no dependency graph, which is fine because a human is the scheduler." ), "prompt-caching": ( "Prompt caching bills the unchanged prefix at a tenth of the input price. The " "saving depends on prefix stability: an agent that injects a timestamp into the " "system message invalidates the cache on every call and pays full price for a " "prefix it just sent." ),}यहाँको embedder अक्षर n-gram ह्यासिङ फङ्सन हो; तालिम दिइएको मोडेल होइन. यो फजी किनारा भएको शब्दकीय (lexical) म्याचर हो: 4-gram साझा भएकाले retrieve लाई retrieval सँग जोड्छ, तर साँचो पर्यायवाची शब्दमा असफल हुन्छ. यो सीमा जानाजान राखिएको हो; नाप्ने खण्डले यसको मूल्य कति हो त्यो ठीक-ठाक देखाउँछ — किनकि नाप्न नसकिने रिट्रिभर सुधार्न पनि सकिँदैन.
पाँच प्रविष्टिको डिक्सनरी साँच्चै कति महँगो
तीन असफलता; सबै वर्तमान कोडमै पुनःसृजना गरिएका.
मिस भएको र खाली कोर्पस भएको बीच भेद गर्न सकिँदैन. कुनै की जुड्दैन भने _search ले ["no matches"] फर्काउँछ, जुन ok=True हुन्छ. यो विषयमा कोर्पसमा केही छैन भनी मोडेलले यसलाई प्रमाण मान्छे. भाग 2 ले टाइमआउट केसलाई वर्गीकृत त्रुटिले मिलायो; तर मिस केस अझै डेटाको बेशभूषामा भएको झुटो नै छ.
संदर्भ (citation) छैन. टुलले नाङ्गा स्ट्रिङ फर्काउँछ. मोडेलले अन्तिम उत्तर लेख्दा त्यसभित्र कुनै प्यासेजको औंला देखाउने केही हुँदैन; परिणाममा प्रयोगकर्ता दाबी जाँच्न सक्दैन, भाग 7 ले पनि प्रमाणित गर्न सक्दैन.
रिट्रिभल युनिट पूरै डकुमेन्ट हो. साँचो कोर्पस भए पनि पूरै डकुमेन्ट फर्काउनु भनेको एक हिटको लागि 4,000 अक्षरको लठ्ठा हो. 420 अक्षरका चार हिट करिब 420 token कन्टेक्स्ट; चार पूरा डकुमेन्ट 4,000. अनि भाग 3 को बजेटले रिट्रिभरले पठाउनै नहुने टेक्स्ट कुचिङमै आफ्नो शक्ति खर्च गर्छ.
यस लेखको बाँकी भागले यी तीनवटै कुरा निर्माणमै मिलाउँछ: चंक्सले युनिट सानो बनाउँछन्, संदर्भहरूले आउटपुट जाँच्नसकिने बनाउँछन्, र प्रासंगिकता फ्लोरले मिसलाई वर्गीकृत त्रुटिमा बदल्छ.
चंकिङ: उल्ट्याउन नसकिने निर्णय
चंक सीमा नै फर्काउन महँगो पर्ने एक मात्र रिट्रिभल निर्णय हो — किनकि बदल्नु परे पूरै कोर्पसलाई फेरि embedding गर्नुपर्छ. बाँकी सबै — स्कोरिङ फङ्सन, फ्यूजन स्थिरांक, रीर्यान्कर — एक दिउँसैमा ट्युन गर्नसकिन्छन्.
सीमाहरूको जोडी सरल छ. धेरै ठूला चंक्स पातलिन्छन्: तीन असम्बन्धित बुँदा भएको 900-अक्षरको चंक तीनैमा र्यान्क हुन्छ तर कसैको पनि ठीक उत्तर दिँदैन — किनकि embedding भित्रका सबैको औसत हुन्छ. धेरै साना चंक्स आफ्नै व्याकरण गुमाउँछन्: 120-अक्षरको टुक्रा बर्सेनि It बाट सुरु हुन्छ, त्यसको पूर्वसूचक हुँदैन — त्यो कुनै रीर्यान्करले पनि मिलाउन सक्दैन.
from __future__ import annotations
from dataclasses import dataclassimport hashlibimport jsonimport mathimport refrom collections import Counter
from contracts import ErrorCode, Tool, ToolResult
CHUNK_CHARS = 420OVERLAP_CHARS = 90SENTENCE = re.compile(r"(?<=[.!?])\s+")WORD = re.compile(r"[a-z0-9]+")STOP = frozenset( "the and for with that this from are was were what when how why into than then " "does did can could should would your you our its it is of to in on by as at be".split())
def words(text: str) -> list[str]: return [w for w in WORD.findall(text.lower()) if len(w) > 2 and w not in STOP]
@dataclass(frozen=True)class Chunk: id: str doc_id: str text: str ordinal: int = 0
@property def citation(self) -> str: return "%s#%d" % (self.doc_id, self.ordinal)
def chunk_document(doc_id: str, text: str, max_chars: int = CHUNK_CHARS, overlap_chars: int = OVERLAP_CHARS) -> list[Chunk]: """Split on sentence boundaries, pack to max_chars, carry a tail overlap.""" sentences = [s.strip() for s in SENTENCE.split(text.strip()) if s.strip()] packs: list[str] = [] buf: list[str] = [] size = 0 for sentence in sentences: if buf and size + len(sentence) + 1 > max_chars: packs.append(" ".join(buf)) tail: list[str] = [] tail_size = 0 for prev in reversed(buf): if tail_size + len(prev) > overlap_chars: break tail.insert(0, prev) tail_size += len(prev) + 1 buf, size = tail, tail_size buf.append(sentence) size += len(sentence) + 1 if buf: packs.append(" ".join(buf)) return [Chunk("%s#%d" % (doc_id, i), doc_id, body, i) for i, body in enumerate(packs)]तीस लाइनमा चार निर्णय; हरेकको कुनै मूल्य.
वाक्यमा तोडेर, अक्षर बजेटमा प्याक गर्ने. शब्दको बीचमा तोडियो भने पहिलो टोकन टुक्रा हुन्छ — त्यसले embedding लाई पनि उद्धरणलाई पनि विषाक्त बनाउँछ. रेगुलर एक्सप्रेसनले स्पेस अगाडि आएका ., ! वा ? पछि मात्र तोड्छ; त्यसैले e.g. जस्ता संक्षेप गलत तरिकाले टुट्छन् — क्षति एक थप सीमा मात्र हुने भएकाले यो स्वीकार्य छ.
420 अक्षर, 512 token होइन. टोकनको करिब चार अक्षर चोपबाट यो एक चंकमा करिब 105 token हुन्छ. संख्याभन्दा अनुपात महत्त्वपूर्ण: एक-एकमा 105 token भएका चार रिट्रिभ गरिएका चंक्स 420 token प्रमाण — 300-token सिस्टम प्रोम्प्टसँगै भाग 3 को बजेटभित्र सजिलै बस्छ. 1,000-token चंक क्याप राखे चार हिटको मूल्य 4,000 token हुन्छ; तपाईंले पैसा तिरेर ल्याएको टेक्स्टलाई नै कुच्न बजेटलाई बाध्य बनाउँछ.
ओभरल्याप भनेको पुच्छर कपी हो, स्लाइडिङ विन्डो होइन. फ्लस पछि 90 अक्षरमा अटाउने अन्तिम वाक्यहरू नयाँ बफरमा फेरि खुल्छन्. यो सेटिङमा परिणाम 21 प्रतिशत इन्डेक्स फुलाउने (420 मध्ये 90) — र एक आश्वासन: सीमा माथि बस्ने वाक्य कम्तीमा एक तर्फबाट रिट्रिभ हुन्छ. टोकन गणनामा स्लाइडिङ-विन्डो चंकिङले त्यही आश्वासन दिन्छ तर वाक्यको बीचमा सुरु हुने चंक्स दिन्छ — हामी जोगिन खोजेको त्यही.
ordinal नै संदर्भ हो; त्यसैले यो स्थिर हुनैपर्छ. chunking#1 भनेको chunking डकुमेन्टको दोस्रो चंक हो. फरक सेटिङले पुनः चंक गरे जुना उत्तरहरूका हरेक संदर्भ अर्को ठाउँ औंला देखाउँछन्. त्यसैले सेटिङहरू इन्डेक्स बिल्डको भाग भएर कोर्पस संस्करणको छेउमा दर्ता हुन्छन्; पुनः चंक गर्नु कन्फिग परिवर्तन होइन, माइग्रेसन हो.
इन्भर्टेड इन्डेक्सबाट BM25
BM25 शब्दकीय स्कोरर हो; सरल पद गणनालाई अझै उछिन्ने दुई विचार छन्. पद आवृत्ति सन्तुष्ट हुन्छ: एक चंकमा latency शब्द दसौँ पटक आए पनि पाचौँसँग तुलना गर्दा निकै केही थपिँदैन — किनकि चंक अगाइ नै लेटेन्सीबारे नै छ. लम्बाइ सामान्यीकरण (length normalisation) लामा चंक्स केवल आकारले जित्न रोक्छ.
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 प्रतिशतभन्दा बढी चंक्समा देखिने पदले निकै केही थप्दैन, गुणनको लायक छैन. त्यसलाई छोड्दा सामान्य शब्दको फ्लोरले असम्बन्धित चंक्सबीच बराबरीका स्कोर बनाउन पाउँदैन.
स्कोरिङ लुप चंक्समा होइन, पोस्टिङमा हिँड्छ. त्यही नै गति दिने हो: चार बाँकी रहेका पदको क्वेरी चार पोस्टिङ सूचीको संगमलाई छुन्छ — 19 चंक्समा यो केही सोह्र इन्टिजर वृद्धि मात्र हो, 50,000 चंक्समा केही हजार. नापिएको मूल्य डेमो कोर्पसमा प्रति क्वेरी 0.015 ms; 20,000 चंक्समा करिब 4 ms — यो कोर्पस आकारमा होइन, पोस्टिङमा रेखीय हो.
k1, b ट्युन गर्नु अघि जान्नैपर्ने दुई सीमा. BM25 ले कहिल्यै नदेखेको पद जुराउन सक्दैन: retrieve क्वेरीले retrieval मात्र भएको चंकविरुद्ध शून्य स्कोर ल्याउँछ — किनकि टोकन फरक छन्. र अर्थअनुसार र्यान्क गर्न सक्दैन: point an answer at its source क्वेरीले संदर्भ id बुझाउने चंकविरुद्ध शून्य — किनकि हरेक कन्टेन्ट पद पर्यायवाची हो. dense शाखाको अस्तित्वको कारण भएका यी दुई असफलता ढाक्न नै हो.
dense शाखा र दुई र्यान्किङको संगम
dense रिट्रिभरले टेक्स्टलाई भेक्टरमा म्याप गरेर कोसाइन समानताले र्यान्क गर्छ. प्रोडक्सनमा त्यो भेक्टर तालिम दिइएको sentence-embedding मोडेलबाट आउँछ. अफलाइनमा, डिपेन्डेन्सी नलिई, key नलिई, इमानदार प्रतिनिधि अक्षर n-gram ह्यासिङ: यसले रूपविज्ञान (morphology) र साझा सबस्ट्रिङ पक्रन्छ — 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; त्यसैले कोसाइन डट प्रोडक्ट हुन्छ र चंक लम्बाइहरूमा स्कोर तुलनीय रहन्छन्. ह्यासिङ signed; टक्करहरू औसतमा रद्द हुन्छन्, खोटो समानता जम्दैन. खोजी brute force; 19 चंक्समा यो 0.6 ms, 50,000 चंक्समा शुद्ध Python मा करिब 400 ms — ख्याल गरिने गरी मन्द; त्यो दूरी पुगेपछि साँचो इन्डेक्स ल्याउन समर्थन दिने गरी मन्द.
अब फ्यूजन. BM25 स्कोर असीमित जान्छन्; कोसाइन [-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 प्रकाशित डिफल्ट हो; यसले एक विशेष विश्वास कुचिमा कुची राखेको छ: सूचीहरूबीचको एकमुखी एउटै सूचीभित्रको प्राबल्यभन्दा महत्त्वपूर्ण. एउटा सूचीमा र्यान्क 1 भएको चंकले 1/61 = 0.0164 स्कोर गर्छ; दुवै सूचीमा र्यान्क 2 भएको चंकले 1/62 + 1/62 = 0.0323. दोस्रोले जित्छ — एक सूची शब्दकीय र एक सिमान्टिक हुँदा चाहिने नै यस्तो व्यवहार. k लाई 10 मा घटाए एउटै सूचीको विजेता धेरै बलियो हुन्छ — एक रिट्रिभर स्पष्ट रूपमा राम्रो हुँदा अर्कोबाट सानो टाइ-ब्रेक मात्र चाहिए उपयोगी.
इमानदार नापले डिजाइन बदल्ने ठाउँ यही हो. यहाँ हार्नेस — उन्नाइस चंक्समा, लेबल गरिएका आठ क्वेरीमा चलेको:
import corpusimport rag
QUERIES = [ ("what window size should a passage have", "chunking"), ("combining keyword and embedding rankings", "retrieval-design"), ("tail latency after adding a reranker", "latency-budget"), ("the plan changes after a step fails", "planner"), ("critique loops that never terminate", "reflection"), ("point an answer at its source", "citations"), ("does overlap inflate the index size", "chunking"), ("cheapest way to cut repeated prefix cost", "prompt-caching"),]
def evaluate(name: str, rank_fn, k: int = 3) -> None: p1 = recall = mrr = 0.0 for query, expected in QUERIES: docs = rank_fn(query, k) p1 += 1.0 if docs[:1] == [expected] else 0.0 recall += 1.0 if expected in docs else 0.0 mrr += 1.0 / (docs.index(expected) + 1) if expected in docs else 0.0 n = len(QUERIES) print("%-14s P@1=%.2f Recall@%d=%.2f MRR=%.3f" % (name, p1 / n, k, recall / n, mrr / n))
def main() -> None: r = rag.CorpusRetriever(corpus.DOCUMENTS) r.hybrid.pool = 12 evaluate("bm25", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.bm25.search(q, k=n)]) evaluate("vector", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.vectors.search(q, k=n)]) evaluate("hybrid", lambda q, n: [p.chunk.doc_id for p in r.hybrid.retrieve(q, k=n)]) evaluate("hybrid+rerank", lambda q, n: [p.chunk.doc_id for p in r.search(q, limit=n)])
if __name__ == "__main__": main()bm25 P@1=0.62 Recall@3=0.88 MRR=0.750vector P@1=0.38 Recall@3=0.88 MRR=0.604hybrid P@1=0.50 Recall@3=0.88 MRR=0.667hybrid+rerank P@1=0.50 Recall@3=0.88 MRR=0.667पहिलो स्तम्भ होइन, दोस्रो स्तम्भ पढ्ने. Recall भनेकै क्यान्डिडेट पूल अस्तित्वको कारण हो; पूल आकार महत्त्वपूर्ण: 19 चंक्समा pool=12 मा BM25 को टप 12 भित्र 8 क्वेरीमध्ये 7 का लागि ठीक डकुमेन्ट छ; dense शाखाका लागि 8 मध्ये 8; त्यसैले संगम 8 मध्ये 8. एक क्वेरी — combining keyword and embedding rankings — सम्पूर्ण शब्दकीय मिस; त्यसको विषय चंकमा keyword, embedding वा rankings शब्द छैनन्; ह्यास्ड embedder ले साझा rank 4-gram बाट त्यसलाई भेट्छ. यो स्केलमा dense शाखालाई पक्ष दिने सम्पूर्ण तर्क त्यही एक क्वेरी हो: राम्रो र्यान्किङ होइन, उत्तरलाई मौनतः नगुमाउने पूल.
पहिलो स्तम्भ पढे चित्र त्यति चम्किलो छैन: precision मा BM25 जित्छ; फ्यूजनले BM25 एक्लैसँग तुलना गर्दा P@1 मा 12 अङ्क गुमाउँछ. यो RRF को बग होइन. यो dense शाखाको बग हो; ठीक-ठाक भन्नैपर्छ: अक्षर n-gram embedर भनेको फरक वेटिङ स्किमसहितको शब्दकीय म्याचर हो; BM25 सँग त्यसलाई मिलाउँदा त्यही प्रमाणका दुई दृष्टिकोण मिल्छन्, र मतभेद केवल नॉइज हुन्छन्. तीन शब्दकीय म्याचर सिमान्टिक्स हुँदैनन्.
समाधान k ट्युन गर्ने होइन. समाधान HashedEmbedder को सट्टा तालिम दिइएको मोडेल राख्ने हो — त्यसले मतभेदको स्वभाव नॉइजबाट सिग्नलमा बदल्छ. तलका सबै — फ्यूजन, reranking, संदर्भ, टुल सम्झौता — त्यही रहन्छन्; किनकि पाइपलाइनको बाँकी भागलाई चाहिने एउटै कुरा embed(text) -> list[float] मात्र हो. इन्टरफेस शिप गर्ने, शाखा नाप्ने; शाखा कमजोर छ भनेर नापले भने त मोडेल किन्ने. त्यो जान्ने मार्ग यही हार्नेस.
रीर्यान्किङ: लेटेन्सी तिरेर, precision किन्ने
फ्यूजनले राम्रो recall भएको, सामान्य क्रम दिने पूल दिन्छ. रीर्यान्करले हरेक क्वेरी-प्यासेज जोडी स्वतन्त्र रूपमा नभई सँगै स्कोर गरेर क्रम सुधार्छ. cross-encoder ले क्वेरी र प्यासेज एउटै फरवार्ड पासमा हेर्छ; त्यसैले not, only शब्द, शब्द क्रम — BM25 र bag-of-ngrams embedding दुवैले पक्रन नसक्ने कुरा — यसलाई बुझ्छ.
तलको निर्धारक (deterministic) प्रतिनिधिले पद कभरेज, सटीक वाक्यरचना उपस्थिति, र जुर्ने क्वेरी पदको निकटता स्कोर गर्छ. यो cross-encoder होइन; यो रीर्यान्कर-आकारको फङ्सन हो — महँगो कुरा जडान गर्नु अगाडि नै पाइपलाइन, थ्रेसोल्ड, र टेस्ट सबै अस्तित्वमा आउने बनाउने.
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)कभरेजलाई फरक क्वेरी पदको संख्याले सामान्यीकरण गरिन्छ; त्यसैले दुई-शब्दको क्वेरीले आकस्मिक रूपमा छ-शब्दको क्वेरीभन्दा बढी स्कोर गर्न पाउँदैन. वाक्यरचना बोनस बाइनरी, एक चौथाइ तौल दिन्छ: सटीक सबस्ट्रिङ म्याच बलियो प्रमाण; तै पनि वाक्यरचना अक्षरशः नभएका बेला पनि चंक सही हुनसक्छ. निकटता छ-टोकन विन्डोमा सीमित — त्यो नाघेपछि दुई पद सम्बन्धित नभई एकैसाथ आएका मात्र हुन्छन् — र यो जुर्ने क्वेरी पदमा मात्र प्रज्वलित हुन्छ: latency ... reranker कुनै क्रममा पनि गनिन्छ तर latency ... chunk गनिँदैन.
रीर्यान्करले गर्न नसक्ने कुरा माथिको नापले देखाएको छ: डेमो कोर्पसमा त्यसले केही बदल्दैन — किनकि यो तेस्रो शब्दकीय म्याचर हो. यसको साँचो मूल्य cross-encoder आएपछि आउँछ; इमानदार इन्जिनियरिङ प्रश्न: त्यो बहन हुन्छ कि हुँदैन.
सक्रिय गर्नु अघि हिसाब गर्नैपर्छ. 12-लेयर cross-encoder ले 20 क्यान्डिडेट जोडीमा CPU मा प्रति जोडी करिब 10 ms — प्रति क्वेरी 200 ms; 8 जोडीमा सीमित गरे 80 ms. एक रनका पाँच खोजीले 400 ms थप्छन् — एउटै LLM राउन्ड ट्रिप एवढो; त्यो सामान्यतः ठीक, तर टुल p95 40 ms हुँदा agent को कुल बजेट दुई सेकेन्ड भए स्वीकार्य छैन. यसलाई बाँधेर राख्ने दुई लिभर: रीर्यान्क सेटलाई क्याप (8 राम्रो डिफल्ट; 9 औँ क्यान्डिडेटले टप 4 लाई दुर्लभै बदल्छ) र फ्यूजन मार्जिन ठूलो हुँदा रीर्यान्किङ छोड्ने (टप प्यासेजले दोस्रोलाई 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 प्रासंगिकता फ्लोर हो; टेस्टले देखाउने कारणले यो बोझ यति गम्भीर: यो नभए फाल्टी क्वेरीलाई ह्यास्ड embedर ले साना सकारात्मक कोसाइनका टक्करहरू फर्काउँछ; त्रुटिको सट्टा agent ले चार असम्बन्धित प्यासेज पाउँछ. फ्लोरले त्यसलाई ERROR[not_found] मा बदल्छ — मोडेलले त्यसलाई यो कोर्पस त्यो विषय कभर गर्दैन भनी पढ्छ; र त्यो साँचो हो.
limit=4 पनि बजेट निर्णय नै हो. एक-एकमा 105 token भएका चार प्यासेज 420 token; माथि संदर्भ पाया करिब 30 token. दुई हिट सस्तो हुन्छ तर बर्सेनि अपुग — उत्तर बर्सेनि परिभाषा चंक र उदाहरण चंकबीच टुटेको हुन्छ. छ भएको ठाउँमा 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 नामको टुल नै देख्छ.
असफलता ढाँचा र सम्हालन
| असफलता | साँच्चै के हुन्छ | यहाँ सम्हालन | अझै टुटेको |
|---|---|---|---|
| चंकले टेबल वा सूची तोड्छ | पङ्क्तिहरू फरक चंक्समा पर्छन्; दुवैबाट उत्तर मिल्दैन | विरामचिन्हले अनुमति दिए वाक्य विभाजकले पङ्क्तिहरू सँगै राख्छ | Markdown टेबललाई संरचनात्मक विभाजक चाहिन्छ |
| क्वेरी र कोर्पसले फरक शब्द प्रयोग गर्छन् | BM25 ले केही दिँदैन; ह्यास्ड embedding ले हल्ला दिन्छ | dense शाखा + फ्यूजन | साँचा पर्यायवाचीका लागि तालिम दिइएको मोडेल चाहिन्छ |
| हरेक हिट असम्बन्धित | मोडेलले दाबीलाई आधार नदिने प्यासेज संदर्भित गर्छ | min_score फ्लोर → ERROR[not_found] |
फ्लोर कोर्पसअनुसार हुन्छ; प्रति-भाषा पुनःमापन चाहिन्छ |
| रीर्यान्कर अत्यन्त मन्द | टुल p95 40 ms बाट 240 ms मा उछिन्छ | रीर्यान्क सेट 8 मा सीमित; ठूलो फ्यूजन मार्जिनमा छोड्ने | कुनै अनुकूल बजेट छैन |
| डकुमेन्टहरूभर प्रतिलिपि चंक्स | एउटै वाक्य दुई पटक रिट्रिभ हुन्छ; दुई स्लट बर्बाद | ओभरल्याप सीमित; टेक्स्ट ह्यासद्वारा प्रतिलिपि हटाइने | लगभग प्रतिलिपि डकुमेन्टहरूले अझै पूल भर्छन् |
| पुनः चंक गर्दा संदर्भहरू अतिरिक्त हुन्छन् | पुराना उत्तरहरूले गलत ordinal औंला देखाउँछन् | ordinal प्रत्येक बिल्डका लागि स्थिर; कोर्पस संस्करण दर्ता हुन्छ | भण्डारण गरिएका संदर्भका लागि माइग्रेसन टुल छैन |
| Embedding मोडेल साटियो | स्कोरहरू सर्छन्; फ्लोर अमान्य हुन्छ | इन्टरफेसले परिवर्तनलाई एकान्त राख्छ | डिप्लोय अघि हार्नेस फेरि चलाउनैपर्छ |
अन्तिम पङ्क्ति नै प्रोडक्सनमा टोक्ने हो; त्यो कोड असफल नभई प्रक्रिया असफल हो. HashedEmbedder लाई साँचो मोडेलले साट्दा स्कोर वितरण बदलिन्छ; त्यसले min_score लाई अमान्य बनाउँछ; त्यही त्रुटि मार्गहरूलाई मौनतः असम्बन्धित-प्यासेज मार्ग बनाउँछ. कुनै पनि embedर परिवर्तन पछि तुरुन्तै हार्नेस रन हुनैपर्छ; फ्लोर नयाँ वितरणको तलको पुच्छरबाट सेट गर्नैपर्छ — पुरानोबाट कपी गर्न हुँदैन.
ट्रेड-अफ
| निर्णय | विकल्प | किन रोजियो | मूल्य |
|---|---|---|---|
| 420-अक्षरका चंक्स | 1,000-token चंक्स | चार हिटको मूल्य 420 token, 4,000 होइन | उत्तरहरू सीमामा टुट्छन् |
| 90-अक्षरको ओभरल्याप | ओभरल्याप नभएको | सीमा वाक्यहरू रिट्रिभ भइरहन्छन् | 21 प्रतिशत इन्डेक्स फुलाउने |
| BM25 + dense, RRF ले मिलाउने | एउटै रिट्रिभर | डेमोमा पूल recall 0.88 बाट 1.00 | सिन्कमा राख्नुपर्ने दुई इन्डेक्स |
| ह्यास्ड embedder | तालिम दिइएको embedding मोडेल | निर्धारक, अफलाइन, टेस्ट गर्नसकिने | पर्यायवाची recall छैन; precision मा BM25 लाई हराउँछ |
| निर्धारक रीर्यान्कर | Cross-encoder | 1 ms मा चल्छ; होस्ट गर्नुपर्ने मोडेल छैन | र्यान्किङ ज्यादै थोरै बदल्छ |
min_score=0.05 |
जुरेको कुनै पनि फर्काउने | फाल्टीलाई वर्गीकृत त्रुटि बनाउँछ | साँच्चै दुर्लभ क्वेरीले त्रुटि दिन्छ |
limit=4 |
limit=10 |
कन्टेक्स्ट मूल्य सीमित | बहु-अञ्चल (multi-hop) प्रश्नहरू छुट्छन् |
रीर्यान्कर पङ्क्तिलाई सिधै उत्तर दिने हक छ: यो प्रतिनिधिसँग तपाईं कुनै 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 दुवै शाखा राख्न समर्थन दिने टेस्ट हो. यसले एउटै चंकबारे विपरीत दुई दाबी ठहराउँछ: भेक्टर इन्डेक्सले retrieve का लागि त्यसलाई भेट्छ, र BM25 ले खाली सूची दिन्छ. यो टेस्ट असफल हुने गरी कसैले पछि embedर साटे dense शाखा दोस्रो शब्दकीय म्याचर बन्छ; फ्यूजन चरण अब शुद्ध थप भार — माथिको बेन्चमार्कले नाप्ने स्थिति त्यही.
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, चंक्समा इन्डेक्स आकार, र चार हिटको टोकन मूल्य प्रतिवेदन दिनुहोस्. कुन ओभरल्यापमा recall लाभले प्रतिलिपि मूल्य तिर्न छोड्छ? - Cross-encoder सिउन पट्टी.
class Reranker(Protocol)लाईscore(query, passage) -> floatसँग परिभाषित गर्नुहोस्,CoverageRerankerले यसलाई लागू गरी दिनुहोस्;HTTPRerankerथप्नुहोस् — त्यसले रीर्यान्किङ एन्डपोइन्टमा[[query, passage]]जोडी POST गर्छ. रीर्यान्क सेटलाई 8 मा सीमित गरेर,passages[0].fused_score > 2 * passages[1].fused_scoreभए रीर्यान्किङ छोड्नुहोस्. थप लेटेन्सीको सामना P@1 परिवर्तन नाप्नुहोस्. - प्रति-भाषा फ्लोर. प्रासंगिकता फ्लोर अंग्रेजीमा मापन गरिएको छ. फरक टोकनाइजेसन (जापानी वा जर्मन संयुक्त शब्द) भएको भाषामा दस-क्वेरी सेट बनाएर, सम्बन्धित र असम्बन्धित हिटको स्कोर वितरण तुल्यौँला. एउटै सार्वभौमिक
min_scoreसमर्थनीय छ, या इन्डेक्स अनुसार हुनैपर्छ?
अभ्यास 2 ले तपाईंले शिप गर्ने कुरा बदल्छ. सिउन पट्टी सानो छ; त्यो भएको अर्थ महँगो घटक स्थापत्य निर्णयबाट डिप्लोयमेन्ट निर्णय बन्छ.
अब के
agent ले अब प्यासेज खोजी संदर्भ दिन सक्छ. अझै गर्न नसक्ने कुरा: आफूलाई कति खोजी चाहिन्छ, कुन क्रममा — लुपले एकैसाथ एक टुल कल मात्र दिन्छ; compare the chunking trade-offs with the reranker latency budget जस्तो प्रश्नका लागि योजना चाहिन्छ.
भाग 6, Task decomposition, लक्ष्यलाई स्पष्ट डिपेन्डेन्सीसहित टास्क ग्राफमा बदल्ने Planner, तयार टास्कहरू समानान्तर चलाउने एक्जिक्युटर, र टास्क असफल हुँदा पेट्ने सीमित रिप्लानिङ चरण थप्छ. तपाईंले अब बनाएको search टुल planner ले कुचिमा कुची राख्ने प्रिमिटिभ बन्छ — त्यसले फर्काउने संदर्भहरू भाग 7 ले प्रमाणित गर्ने प्रमाण बन्छन्.
Everything above, running in Ball — no code, no install. Try it in your browser.
Only used to send Ball resources. No spam.
You're in. Open the resource list below. Open the resource list
Try Ball in your browser — no install, no signup needed.
Try Ball in your browser — no install, no signup needed.