तन स्थान निर्माण करून घेणारा 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 embedder म्हणजे वेगळ्या वेटिंग स्कीमसह असलेला शब्दकीय मॅचर; 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 म्हणजे संदर्भात्मक फ्लोअर; टेस्ट दाखवणाऱ्या कारणामुळे हे ओझे तसे महत्त्वाचे: नसेल तर फटाटिक क्वेरीला हॅश्ड embedder लहान सकारात्मक कोसाइनच्या टक्करी परत करते; त्रुटी ऐवजी 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 अवैध करते; तेच त्रुटी मार्ग शांतपणे असंबद्ध-पॅसेज मार्ग बनवते. कोणत्याही embedder बदलानंतर हार्नेस रन लगेच होणे आवश्यक; फ्लोअर नवीन वितरणाच्या खालच्या शेपटीतून सेट करावा — जुन्यातून कॉपी नको.
ट्रेड-ऑफ
| निर्णय | पर्याय | आपण का निवडले | किंमत |
|---|---|---|---|
| 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 रिकामी यादी देतो. या टेस्ट अपयशी होईल असा एखाद्याने नंतर embedder बदलला तर dense शाखा दुसरा शब्दकीय मॅचर बनतो; फ्यूजन पायरी आता शुद्ध अतिरिक्त भार — वरील बेंचमार्क मोजणारी स्थिती तीच.
test_empty_result_is_a_classified_error म्हणजे no matches खोट्याचे रिग्रेशन कापूर. ok=False + not_found म्हणजे लूप अपयशी पायरी नोंदवते; मॉडेलला ERROR[not_found] दिसते — त्यावर चालता येते. ok=True रिकामी यादीसह आल्यास मॉडेल कॉर्पस विषयावर मौन आहे असा निर्धार करते — ते खरे नाही.
व्यायाम
- ओव्हरलॅप मोजा.
overlap_chars0, 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.