Back to all articlesAI और एजेंट

वह RAG retriever बनाना जो अपनी जगह सचमुच कमाता है (भाग 5)

Retrieval in three stages

Chunkingsentence-aware, 420 chars, 90 overlap
Hybrid recallBM25 + dense, fused by RRF
Rerankingpay latency, buy precision
Relevance floora miss becomes ERROR[not_found]

One search call, three stages

The pool exists for recall; the reranker exists for order.

One search call, three stages — flow diagramOne search call, three stages. Flow diagram with 6 steps. Shapes: pill = input, rounded rect = process, diamond = decision, double border = output, dashed = loop. Steps in order: Step 1, query (input), minLength 2, validated by schema; Step 2, BM25 over postings (process), 0.015 ms on 19 chunks; Step 3, dense cosine (process), hashed n-gram embedder, 0.6 ms; Step 4, RRF fusion (decision), rank position only, k = 60; Step 5, rerank pool (process), coverage + phrase + proximity; Step 6, top-k with citations (output), doc#n or ERROR[not_found]. Then loops back to step 4: ↺ every search tool call goes through all three stages.queryminLength 2, validated by schemaBM25 over postings0.015 ms on 19 chunksdense cosinehashed n-gram embedder, 0.6 msRRF fusionrank position only, k = 60rerank poolcoverage + phrase + proximitytop-k with citationsdoc#n or ERROR[not_found]
  • input
  • process
  • decision
  • output

Measured on 19 chunks, 8 queries

Recall@12 (pool)P@1 (precision)
BM25 alone0.880.62
Dense alone1.000.38
Hybrid (RRF)1.000.50
Verdictfusion earns its keepbuy a real model

भाग 1 का search टूल पाँच प्रविष्टियों का एक शब्दकोश है. इससे agent loop के बारे में पूछिए तो वह एक वाक्य लौटाता है; कुछ और पूछिए तो वह no matches लौटाता है. इसलिए agent का हर कथन या तो उन पाँच वाक्यों में से एक है या मनगढ़ंत, और loop के पास इनमें फ़र्क़ करने का कोई तरीक़ा नहीं है.

पहली झुकाव vector database जोड़ने की होती है. वह झुकाव आधा सही है: dense retrieval पैराफ़्रेज़ पहचानने में सचमुच बेहतर है. लेकिन वह तीन चरणों में से केवल एक है, और बाक़ी दो ही वह जगह हैं जहाँ अधिकांश production RAG सिस्टम चुपचाप फिसलते हैं. ऊँचे cosine स्कोर के साथ ग़लत chunk लौटाने वाला retriever उससे बदतर है जो कुछ नहीं लौटाता, क्योंकि agent उसे उद्धृत करेगा.

यह भाग retriever को तीन अलग-अलग चरणों के रूप में बनाता है — chunk, recall, rerank — प्रत्येक का एक मापनीय कार्य है, साथ में वह मापन-तंत्र भी जो बताता है कि चरण मदद कर रहा है या केवल latency जोड़ रहा है. पाइपलाइन भाग 2 के उसी Tool अनुबंध से जुड़ी है, ताकि citations अंतिम उत्तर तक बची रहें और भाग 7 उन्हें सत्यापित कर सके.

आप क्या बनाएँगे

पाँच हिस्सों वाला एक rag.py मॉड्यूल:

  • chunk_document — कॉन्फ़िगर करने-योग्य overlap के साथ वाक्य-सजग पैकिंग, जो Chunk ऑब्जेक्ट बनाती है जिनका citation doc#n होता है.
  • BM25Index — inverted index पर Okapi BM25, 19 chunks पर प्रति query 0.015 ms, कोई dependency नहीं.
  • HashedEmbedder + VectorIndex — embed(text) -> list[float] interface के पीछे dense पक्ष, ताकि असली मॉडल लगाना बीस लाइनों का एडेप्टर बन जाए.
  • HybridRetriever — BM25 और dense सूचियाँ, reciprocal rank fusion से जोड़ी हुईं.
  • CorpusRetriever + make_search_tool — reranking, एक relevance floor, और वही search टूल जिसे agent कॉल करना पहले से जानता है.

भाग 1–4 के बाद research-agent की मौजूदा स्थिति: सत्यापित tool contracts, context budget और SQLite memory वाला एक loop. search आख़िरी stub है. यह भाग उसे AgentLoop को छुए बिना बदलता है, और यही परीक्षा है कि पहले की अमूर्तताएँ सचमुच असली थीं या नहीं.

आवश्यकताएँ

  • भाग 1–4. rag.py Tool, ToolResult और ErrorCode को contracts.py से import करता है; demo AgentLoop और ScriptedLLM import करता है.
  • Python 3.10+, केवल standard library. न numpy, न vector database, न कोई embedding API key.
  • एक corpus, dict[str, str] के रूप में, जो document id को text पर मैप करता है. नीचे दिया fixture agent engineering पर बारह छोटे दस्तावेज़ हैं, जो उन्नीस passages में बँटते हैं.

Fixture दस्तावेज़ों का एक dict है, बारह गिनती के, प्रत्येक कुछ वाक्यों का. यह जानबूझकर छोटा है: इतना छोटा कि इस लेख का हर स्कोर एक कोर पर एक सेकंड से कम में दोबारा पैदा किया जा सके, और इतना विविध कि उसमें वे शब्दात्मक जाल हों जो naive index को तोड़ देते हैं.

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 है: यह retrieve को retrieval से मिलाता है क्योंकि दोनों में 4-gram साझा हैं, और यह सच्चे पर्यायवाचियों पर फिसल जाता है. यह सीमा जानबूझकर है, और मापन-खंड दिखाता है कि इसकी क़ीमत ठीक कितनी है, क्योंकि जिसे मापा न जा सके उसे सुधारा भी नहीं जा सकता.

पाँच-प्रविष्टि शब्दकोश वास्तव में कितना महँगा है

तीन त्रुटियाँ, सभी मौजूदा कोड में दोबारा पैदा की गईं.

Miss खाली corpus से अलग नहीं की जा सकती. जब कोई key मेल नहीं खाती तो _search ["no matches"] लौटाता है, जो ok=True है. मॉडल उसे इस बात के सबूत की तरह पढ़ता है कि corpus में विषय पर कुछ नहीं है. भाग 2 में हमने timeout के मामले को वर्गीकृत error से ठीक किया था; miss का मामला अब भी डेटा के वेश में सजा झूठ है.

कोई citation नहीं है. टूल केवल सादी स्ट्रिंग लौटाता है. जब मॉडल अंतिम उत्तर लिखता है, उसमें कुछ भी किसी passage की ओर वापस इशारा नहीं करता, इसलिए उपयोगकर्ता कथन की जाँच नहीं कर सकता और भाग 7 उसे सत्यापित नहीं कर सकता.

retrieval की इकाई दस्तावेज़ है. असली corpus के साथ भी पूरे दस्तावेज़ लौटाने का अर्थ है प्रति हिट 4,000 वर्णों का एक ब्लॉक. 420 वर्णों पर चार हिट लगभग 420 tokens का context है; चार पूरे दस्तावेज़ 4,000 हैं. फिर भाग 3 का बजट अपनी ऊर्जा ठीक उस text को संपीड़ित करने में खर्च करता है जिसे retriever को कभी भेजना ही नहीं चाहिए था.

इस लेख का शेष भाग तीनों को रचना से ठीक करता है: chunks इकाई को छोटा बनाते हैं, citations आउटपुट को जाँच-योग्य बनाते हैं, और relevance floor miss को वर्गीकृत error बना देता है.

Chunking: वह निर्णय जिसे वापस नहीं लिया जा सकता

Chunk की सीमाएँ एकमात्र retrieval निर्णय हैं जिन्हें बदलना महँगा है, क्योंकि उन्हें बदलने का अर्थ है पूरे corpus का पुनः-embedding. बाक़ी सब — scoring फ़ंक्शन, fusion स्थिरांक, reranker — एक दोपहर में tune किए जा सकते हैं.

बाधाओं की जोड़ी सरल है. बहुत बड़े chunks पतले कर देते हैं: तीन असंबंधित बिंदुओं वाला 900-वर्ण का chunk तीनों के लिए रैंक होता है और किसी का सटीक उत्तर नहीं देता, क्योंकि embedding उसके भीतर की हर चीज़ का औसत है. बहुत छोटे chunks अपनी व्याकरणिक ढाँचा खो देते हैं: 120-वर्ण का टुकड़ा अक्सर It से शुरू होता है, बिना किसी पूर्व-संदर्भ के, जिसे कोई reranker नहीं सुधार सकता.

from __future__ import annotations
from dataclasses import dataclass
import hashlib
import json
import math
import re
from collections import Counter
from contracts import ErrorCode, Tool, ToolResult
CHUNK_CHARS = 420
OVERLAP_CHARS = 90
SENTENCE = 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 गारंटी देता है जिसका पहला token एक टुकड़ा है, जो embedding और quote दोनों को ज़हर देता है. regex केवल ., ! या ? के बाद तोड़ता है जब उनके बाद खाली स्थान हो, जो e.g. जैसे संक्षेपों को ग़लत जगह तोड़ देता है — स्वीकार्य, क्योंकि नुक़सान एक अतिरिक्त सीमा है, टूटा हुआ शब्द नहीं.

420 वर्ण, 512 tokens नहीं. प्रति token लगभग चार वर्णों पर यह प्रति chunk लगभग 105 tokens है. संख्या से अनुपात अधिक मायने रखता है: 105-105 tokens के चार retrieved chunks मिलकर 420 tokens के सबूत हैं, जो 300-token system prompt के साथ भाग 3 के बजट में आराम से समा जाते हैं. 1,000-token की chunk-सीमा चार हिटों को 4,000 tokens कर देती और बजट को ठीक उसी text को संपीड़ित करने पर मजबूर करती जिसे पाने के लिए आपने मेहनत की.

Overlap एक पूँछ-प्रति है, sliding window नहीं. flush के बाद अंतिम वे वाक्य जो 90 वर्णों में समा जाते हैं, नए buffer में फिर से खोले जाते हैं. नतीजा इन सेटिंग्स पर 21 प्रतिशत index मुद्रास्फीति है (420 में से 90), और एक गारंटी: सीमा पर अड़ा वाक्य कम से कम एक ओर से पुनः-प्राप्त है. token-गिनती वाला sliding-window chunking वही गारंटी देता है लेकिन ऐसे chunks बनाता है जो वाक्य के बीच से शुरू होते हैं — और यही वह बात है जिससे हम बच रहे हैं.

ordinal ही citation है, इसलिए इसे स्थिर रहना ही चाहिए. chunking#1 का अर्थ है chunking दस्तावेज़ का दूसरा chunk. यदि आप अलग सेटिंग्स से फिर से chunk करते हैं, तो पुराने उत्तरों की हर citation कहीं और इशारा करने लगती है. इसीलिए सेटिंग्स index-निर्माण में रहती हैं, corpus संस्करण के साथ दर्ज होती हैं, और इसीलिए फिर से chunking एक migration है, config बदलना नहीं.

Inverted index से BM25

BM25 एक lexical scorer है जिसके दो विचार आज भी naive शब्द-गिनती को मात देते हैं. Term frequency संतृप्त होता है: chunk में latency की दसवीं उपस्थिति पाँचवीं पर लगभग कुछ नहीं जोड़ती, क्योंकि chunk पहले से latency के बारे में है. Length normalisation लंबे chunks को केवल आकार से जीतने से रोकती है.

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 smoothing के साथ हर chunk में मिलने वाला शब्द log(1 + 0.5/(n+0.5)) पाता है, जो धनात्मक पर अत्यंत छोटा है; लगभग 80 प्रतिशत से अधिक chunks में मिलने वाला शब्द लगभग कुछ नहीं जोड़ता और उसका गुणा व्यर्थ है. उसे छोड़ देना इसलिए है ताकि साझा शब्दों की तली असंबंधित chunks के बीच बराबरियाँ न बना दे.

Scoring loop postings पर चलता है, chunks पर नहीं. यही उसे तेज़ बनाता है: चार बचे हुए शब्दों वाली query चार posting सूचियों के संघ को छूती है, जो 19 chunks पर कुछ दर्जन पूर्णांक-वृद्धियाँ हैं और 50,000 chunks पर कुछ हज़ार. मापी गई लागत demo corpus पर प्रति query 0.015 ms है और 20,000 chunks पर लगभग 4 ms — postings में रैखिक, corpus आकार में नहीं.

k1 और b tune करने से पहले जानने लायक़ दो सीमाएँ. BM25 वह शब्द नहीं मिला सकती जो उसने कभी देखा ही नहीं: retrieve query केवल retrieval वाले chunk के सामने शून्य अंक पाती है, क्योंकि tokens अलग हैं. और वह अर्थ से रैंक नहीं कर सकती: point an answer at its source query citation-id समझाने वाले chunk के सामने शून्य पाती है, क्योंकि हर सार्थक शब्द एक पर्यायवाची है. ठीक यही दोनों त्रुटियाँ dense पक्ष कवर करने के लिए है.

Dense पक्ष, और दो रैंकिंगों का जोड़

Dense retriever text को vector पर मैप करता है और cosine समानता से रैंक करता है. Production में वह vector एक प्रशिक्षित sentence-embedding मॉडल से आता है. ऑफ़लाइन, बिना dependency और बिना key, ईमानदार कामचलाऊ विकल्प वर्ण n-gram हैशिंग है: यह रूप-विज्ञान और साझा अंश-स्ट्रिंग पकड़ती है, जो वास्तविक — यदि संकीर्ण ही सही — सामान्यीकरण का रूप है जो BM25 में नहीं है.

class HashedEmbedder:
"""Character n-gram hashing embedder: deterministic, offline, morphology-tolerant.
Swap this class for a sentence-embedding model behind the same embed() contract;
everything downstream only needs a unit-norm vector.
"""
def __init__(self, dim: int = 512, n: int = 4) -> None:
self.dim = dim
self.n = n
def _grams(self, text: str) -> list[str]:
cleaned = re.sub(r"[^a-z0-9]+", " ", text.lower())
out: list[str] = []
for word in cleaned.split():
padded = "#" + word + "#"
for i in range(max(1, len(padded) - self.n + 1)):
out.append(padded[i:i + self.n])
return out
def embed(self, text: str) -> list[float]:
vec = [0.0] * self.dim
for gram in self._grams(text):
digest = hashlib.blake2b(gram.encode("utf-8"), digest_size=8).digest()
index = int.from_bytes(digest[:4], "big") % self.dim
sign = 1.0 if digest[4] & 1 else -1.0
vec[index] += sign
norm = math.sqrt(sum(v * v for v in vec)) or 1.0
return [v / norm for v in vec]
def cosine(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b))
class VectorIndex:
"""Brute-force cosine search. Fast enough to 50k chunks; swap for FAISS later."""
def __init__(self, embedder: HashedEmbedder | None = None) -> None:
self.embedder = embedder or HashedEmbedder()
self.chunks: dict[str, Chunk] = {}
self.matrix: dict[str, list[float]] = {}
def add(self, chunks: list[Chunk]) -> None:
for chunk in chunks:
self.chunks[chunk.id] = chunk
self.matrix[chunk.id] = self.embedder.embed(chunk.text)
def search(self, query: str, k: int = 20) -> list[tuple[str, float]]:
probe = self.embedder.embed(query)
scored = [(cid, cosine(probe, vec)) for cid, vec in self.matrix.items()]
scored.sort(key=lambda pair: (-pair[1], pair[0]))
return [(cid, round(score, 4)) for cid, score in scored[:k] if score > 0]

तीन गुण इस index को embedder बदलने पर भी रखने लायक़ बनाते हैं. Vector इकाई-norm का है, इसलिए cosine एक dot product है और स्कोर chunk-लंबाइयों में तुलनीय हैं. हैशिंग चिह्नित है, इसलिए टकराव औसतन रद्द होते हैं, झूठी समानता जमा नहीं करते. खोज brute force है, जो 19 chunks पर 0.6 ms और 50,000 chunks पर लगभग 400 ms शुद्ध Python में लेती है — इतनी धीमी कि आप गौर करेंगे, और इतनी धीमी कि वहाँ पहुँचने पर असली index का पैरोकार बनता है.

अब fusion. BM25 स्कोर असीमित हैं; cosine [-1, 1] में है. उन्हें जोड़ना श्रेणी-भूल है, और उन्हें normalize करने के लिए प्रति-query आँकड़े चाहिए जो query के साथ ही बदलते हैं. 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]))
@dataclass
class Passage:
chunk: Chunk
fused_score: float
bm25_rank: int | None = None
vector_rank: int | None = None
rerank_score: float = 0.0
class HybridRetriever:
"""BM25 + vector, fused by RRF. Named Hybrid because Part 4's Retriever is the memory scorer."""
def __init__(self, chunks: list[Chunk], embedder: HashedEmbedder | None = None,
pool: int = 20, rrf_k: int = 60) -> None:
self.bm25 = BM25Index()
self.bm25.add(chunks)
self.vectors = VectorIndex(embedder)
self.vectors.add(chunks)
self.chunks = {c.id: c for c in chunks}
self.pool = pool
self.rrf_k = rrf_k
def retrieve(self, query: str, k: int = 5) -> list[Passage]:
lexical = self.bm25.search(query, k=self.pool)
dense = self.vectors.search(query, k=self.pool)
rank_bm25 = {cid: i for i, (cid, _) in enumerate(lexical, start=1)}
rank_vector = {cid: i for i, (cid, _) in enumerate(dense, start=1)}
fused = reciprocal_rank_fusion([lexical, dense], k=self.rrf_k)
return [
Passage(self.chunks[cid], score, rank_bm25.get(cid), rank_vector.get(cid))
for cid, score in fused[:k]
]

k=60 प्रकाशित डिफ़ॉल्ट है और यह एक ठोस मान्यता व्यक्त करता है: सूचियों के बीच मेल एक ही सूची के भीतर की प्रभुत्ता से अधिक मायने रखता है. एक सूची में रैंक 1 पर chunk को 1/61 = 0.0164 मिलता है; दोनों सूचियों में रैंक 2 पर chunk को 1/62 + 1/62 = 0.0323. दूसरा जीतता है — यही वह व्यवहार है जो चाहिए जब एक सूची lexical हो और दूसरी semantic. k घटाकर 10 करने से एक-सूची विजेता काफ़ी मज़बूत हो जाता है — उपयोगी जब एक retriever साफ़ बेहतर हो और आप दूसरे से केवल छोटा टाई-ब्रेक चाहते हों.

यहीं एक ईमानदार मापन डिज़ाइन बदल देता है. यह रहा मापन-तंत्र, उन्नीस chunks और आठ लेबल वाली queries पर चलाया हुआ:

import corpus
import 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.750
vector P@1=0.38 Recall@3=0.88 MRR=0.604
hybrid P@1=0.50 Recall@3=0.88 MRR=0.667
hybrid+rerank P@1=0.50 Recall@3=0.88 MRR=0.667

पहला कॉलम नहीं, दूसरा पढ़ें. Recall के लिए ही candidate pool होता है, और pool का आकार मायने रखता है: 19 chunks पर pool=12 के साथ BM25 के शीर्ष 12 में 8 में से 7 queries के लिए सही दस्तावेज़ है, dense पक्ष के लिए 8 में से 8, इसलिए संघ 8 में से 8 है. एक query — combining keyword and embedding rankings — पूरी तरह शब्दात्मक miss है जिसके विषय-chunk में keyword, embedding या rankings शब्द नहीं हैं; hashed embedder उसे साझे rank 4-gramों से ढूँढ़ लेता है. यह अकेली query इस पैमाने पर dense पक्ष का पूरा तर्क है: बेहतर रैंकिंग नहीं, बल्कि वह pool जो उत्तर को चुपचाप नहीं खोता.

पहला कॉलम पढ़ें और तस्वीर उतनी चमकदार नहीं: precision पर BM25 जीतता है, और fusion अकेले BM25 की तुलना में 12 अंक P@1 खोता है. वह RRF का bug नहीं है. वह dense पक्ष का bug है, और उसे सटीक कहना उचित है: वर्ण n-gram embedder एक अलग भार-योजना वाला lexical matcher है, इसलिए उसे BM25 के साथ जोड़ने का अर्थ है उन्हीं सबूतों के दो दृष्टिकोण जोड़ना, और उनके मतभेद शोर हैं. तीन lexical matcher मिलकर semantics नहीं बनते.

समाधान k tune करना नहीं है. समाधान HashedEmbedder को प्रशिक्षित मॉडल से बदलना है, जो मतभेदों का स्वभाव शोर से संकेत में बदल देता है. नीचे की सब कुछ — fusion, reranking, citation, tool contract — अपरिवर्तित रहता है, क्योंकि पाइपलाइन के बाक़ी हिस्से को केवल embed(text) -> list[float] चाहिए. Interface जारी करें, पक्ष मापें, मॉडल तब ख़रीदें जब मापन कहे कि पक्ष ही कमज़ोर कड़ी है. यह मापन-तंत्र यह जानने का तरीक़ा है.

Reranking: latency दें, precision ख़रीदें

Fusion आपको अच्छे recall और औसत क्रम वाला pool देता है. Reranker क्रम को ठीक करता है — प्रत्येक query-passage जोड़े को संयुक्त रूप से अंकित करके, अलग-अलग नहीं. Cross-encoder query और passage को एक ही आगे-चाल में देखता है, इसलिए वह not और only और शब्द-क्रम को व्यक्त कर सकता है — बातें जो न BM25, न n-gram-थैला embedding कर सकता.

नीचे का deterministic कामचलाऊ विकल्प शब्द-कवरेज, सटीक वाक्यांश की उपस्थिति और आस-पास के query शब्दों की निकटता अंकित करता है. वह cross-encoder नहीं है; वह reranker-आकार का फ़ंक्शन है ताकि कुछ महँगा लगाने से पहले पाइपलाइन, threshold और tests सभी मौजूद हों.

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)

कवरेज को भिन्न query शब्दों की संख्या से normalize किया जाता है, इसलिए दो-शब्द query दुर्घटना से छह-शब्द query को मात नहीं दे सकती. वाक्यांश-बोनस द्विआधारी है और एक चौथाई वज़न रखता है: सटीक अंश-स्ट्रिंग मेल मज़बूत सबूत है, पर बिना शब्दशः वाक्यांश के भी chunk सही हो सकता है. निकटता छह-token खिड़की पर सीमित है, क्योंकि उससे आगे दो शब्द साथ पाए जाते हैं, संबंधित नहीं — और वह केवल आस-पास के query शब्दों पर चलता है, इसलिए latency ... reranker किसी भी क्रम में गिनती में आता है पर latency ... chunk नहीं.

Reranker जो नहीं कर सकता, वही ऊपर का मापन दिखाता है: demo corpus पर वह कुछ नहीं हिलाता, क्योंकि वह तीसरा lexical matcher है. उसकी असली क़ीमत cross-encoder के साथ आती है, और ईमानदार इंजीनियरिंग प्रश्न यह है कि आप उसे जुटा सकते हैं या नहीं.

सक्रिय करने से पहले हिसाब करें. 20 candidate जोड़ों पर 12-परत का cross-encoder CPU पर प्रति जोड़ा लगभग 10 ms लेता है, यानी प्रति query 200 ms; 8 जोड़ों पर सीमित — 80 ms. एक run में पाँच खोजें 400 ms जोड़ती हैं — एक LLM राउंड-ट्रिप जितना, जो साधारणतः स्वीकार्य है, और अस्वीकार्य यदि tool का p95 40 ms था और agent का कुल बजट दो सेकंड है. दो लीवर इसे सीमित रखते हैं: rerank सेट पर सीमा (8 अच्छा डिफ़ॉल्ट है; 9वाँ candidate ऊपर के 4 को कभी-कभार ही बदलता है) और fusion की बढ़त बड़ी होने पर reranking छोड़ देना (यदि शीर्ष passage दूसरे से 2× से अधिक आगे है, तो क्रम निकट नहीं है).

Tool registry में जोड़ना

टूल ही जोड़ है. उसे citations लौटाने हैं, भाग 2 की schema का सम्मान करना है, और खाली परिणाम को no matches की बजाय वर्गीकृत error बनाना है.

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 relevance floor है, और वह नींव जैसी है एक ऐसी वजह से जो tests दिखाते हैं: उसके बिना शुद्ध बेतुके शब्दों की query hashed embedder से बहुत छोटे धनात्मक cosine वाले टकराव लौटाती है, और agent को error की जगह चार असंबंधित passages मिलते हैं. Floor उसे ERROR[not_found] में बदलता है, जिसे मॉडल यह corpus उसे नहीं कवर करता पढ़ता है, और जो सच है.

limit=4 भी एक बजट-निर्णय है. लगभग 105-105 tokens के चार passages मिलकर 420 tokens हैं, साथ में लगभग 30 tokens citation-ढाँचे के. दो हिट सस्ते होते, पर अक्सर अपर्याप्त — उत्तर अक्सर परिभाषा-chunk और उदाहरण-chunk में बँटा होता है. छह वह जगह है जहाँ precision recall की वृद्धि से तेज़ गिरने लगता है.

इकलौती लाइन में एकीकरण, क्योंकि AgentLoop tool सूची पहले से स्वीकार करता है:

import corpus
import rag
from 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"] फ़िल्टर ही पूरा migration है. Loop, executor, retry नीति और idempotency स्टोर अछूते हैं, और मॉडल अब भी search नाम का टूल देखता है, एक ऐसी schema के साथ जिसके विरुद्ध वह सत्यापन कर सकता है.

त्रुटि-प्रकार और उन्हें कैसे सँभालें

त्रुटि वास्तव में क्या होता है यहाँ का समाधान अब भी टूटा हुआ
Chunk तालिका या सूची को तोड़ता है पंक्तियाँ अलग-अलग chunks में जाती हैं, कोई उत्तर नहीं देता वाक्य-विभाजक punctuation अनुमति पर पंक्तियाँ साथ रखता है Markdown तालिकाओं को संरचनात्मक विभाजक चाहिए
Query और corpus अलग शब्द बोलते हैं BM25 कुछ नहीं लौटाती; hashed embedding शोर लौटाता है Dense पक्ष + fusion सच्चे पर्यायवाचियों को प्रशिक्षित मॉडल चाहिए
हर हिट असंबंधित मॉडल ऐसा passage उद्धृत करता है जो कथन को समर्थन नहीं देता min_score floor → ERROR[not_found] Floor प्रति-corpus है; प्रति-भाषा पुनः-अंशांकन चाहिए
Reranker बहुत धीमा Tool का p95 40 ms से 240 ms तक कूदता है Rerank सेट 8 पर सीमित, बड़ी बढ़त पर छोड़ें कोई अनुकूली बजट नहीं
दस्तावेज़ों में डुप्लिकेट chunks वही वाक्य दो बार मिलता है, दो स्लॉट बर्बाद Overlap सीमित; text hash से dedupe लगभग-डुप्लिकेट दस्तावेज़ अब भी pool भर देते हैं
दुबारा chunking citations बेकार करता है पुराने उत्तर ग़लत ordinal की ओर इशारा करते हैं Ordinals प्रति build स्थिर; corpus संस्करण दर्ज दर्ज citations के लिए कोई migration टूल नहीं
Embedding मॉडल बदला स्कोर खिसकते हैं, floor अब मान्य नहीं Interface परिवर्तन को पृथक करता है Deploy से पहले मापन-तंत्र का पुनः-रन चाहिए

आख़िरी पंक्ति वही है जो production में काटती है, और वह कोड की नहीं, प्रक्रिया की त्रुटि है. HashedEmbedder को असली मॉडल से बदलना स्कोर-वितरण बदल देता है, जो min_score को अमान्य कर देता है, जो चुपचाप error-पथों को असंबंधित passage-पथों में बदल देता है. किसी भी embedder-बदलाव के बाद मापन-तंत्र का रन अनिवार्य है, और floor नए वितरण की निचली पूँछ से तय करें — पुराने से कॉपी नहीं.

Trade-offs

निर्णय विकल्प हमने यह क्यों चुना क़ीमत
420-वर्ण के chunks 1,000-token के chunks चार हिट 420 tokens के हैं, 4,000 नहीं उत्तर सीमाओं पर बँट जाते हैं
90-वर्ण overlap बिना overlap सीमा-वाक्य खोजे जा सकते रहते हैं 21 प्रतिशत index मुद्रास्फीति
BM25 + dense, RRF से जोड़े अकेला retriever Demo में pool का recall 0.88 से 1.00 तक चढ़ता है दो indexes सिंक में रखने होंगे
Hashed embedder प्रशिक्षित embedding मॉडल Deterministic, ऑफ़लाइन, परीक्षण-योग्य पर्यायवाची recall नहीं; precision में BM25 से हार
Deterministic reranker Cross-encoder 1 ms में चलता है, कोई मॉडल होस्ट नहीं रैंकिंग में मुश्किल से बदलाव
min_score=0.05 जो मिले वही लौटाना कचरे को वर्गीकृत error बनाता है सचमुच दुर्लभ query एक error लौटाती है
limit=4 limit=10 Context लागत सीमित Multi-hop प्रश्न छूट जाते हैं

Reranker पंक्ति का सीधा उत्तर: इस कामचलाऊ विकल्प के साथ आप किसी precision-लाभ के बिना interface की जटिलता की क़ीमत चुका रहे हैं. फिर भी interface बनाने की वजह यह है कि precision ही वह चरण है जहाँ प्रशिक्षित मॉडल दस से बीस P@1 अंक कमाता है, और जोड़ को बाद में फिट करने का अर्थ है tool contract, citation प्रारूप और tests तीनों एक साथ छुना.

परीक्षण

ग्यारह tests, बिना network, 50 ms से कम. ये अपरिवर्तनीय बातें हैं:

import json
import unittest
import corpus
import rag
from 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 पर दो विपरीत बातें कहता है: vector index उसे retrieve के लिए ढूँढ़ लेता है, और BM25 खाली सूची लौटाती है. अगर कोई बाद में embedder को ऐसे किसी चीज़ से बदले जो यह test फेल करे, तो dense पक्ष दूसरा lexical matcher बन गया है और fusion चरण अब शुद्ध अतिरिक्त-खर्च है — ठीक वही अवस्था जिसे ऊपर का benchmark मापता है.

test_empty_result_is_a_classified_error no matches झूठ के ख़िलाफ़ regression रक्षक है. ok=False और not_found का अर्थ है loop असफल चरण दर्ज करता है और मॉडल ERROR[not_found] देखता है, जो कार्य-योग्य है. ok=True खाली सूची के साथ इसका अर्थ है मॉडल यह निष्कर्ष निकालता है कि corpus विषय पर मौन है, जो सच नहीं है.

अभ्यास

  1. Overlap मापें. Index को overlap_chars को 0, 90 और 180 करके दोबारा बनाएँ और हर बार मापन-तंत्र चलाएँ. recall@12, chunks में index आकार और चार हिटों की token लागत रिपोर्ट करें. कितने overlap पर recall-लाभ डुप्लिकेशन की क़ीमत चुकाना बंद कर देता है?
  2. Cross-encoder की जोड़. class Reranker(Protocol) को score(query, passage) -> float के साथ परिभाषित करें, CoverageReranker से उसे लागू कराएँ, और एक HTTPReranker जोड़ें जो [[query, passage]] जोड़े reranking endpoint को भेजता है. Rerank सेट 8 पर सीमित करें और passages[0].fused_score > 2 * passages[1].fused_score होने पर reranking छोड़ दें. अतिरिक्त latency के मुक़ाबले P@1 का बदलाव मापें.
  3. प्रति-भाषा floors. Relevance floor अंग्रेज़ी पर अंशांकित है. अलग tokenization वाली किसी भाषा (जापानी या जर्मन संयुक्त-शब्द) में दस-query का सेट बनाएँ और संबंधित बनाम असंबंधित हिटों का स्कोर-वितरण निकालें. क्या एक वैश्विक min_score बचाया जा सकता है, या उसे प्रति-index होना चाहिए?

दूसरा अभ्यास ही वह है जो आपकी जारी-की-जाने-वाली चीज़ बदल देता है. जोड़ छोटी है, और उसका होना इसका अर्थ है कि महँगी component deployment का निर्णय बन जाती है, वास्तुकला का नहीं.

आगे क्या

Agent अब passage ढूँढ़कर उद्धृत कर सकता है. जो वह अब भी नहीं कर सकता, वह है तय करना कि उसे कितनी खोजें चाहिए और किस क्रम में — loop एक बार में एक ही tool call जारी करता है, और compare the chunking trade-offs with the reranker latency budget जैसे प्रश्न को एक योजना चाहिए.

अगला भाग, भाग 6 — Task decomposition — एक Planner जोड़ता है जो लक्ष्य को स्पष्ट निर्भरताओं वाले task graph में बदलता है, एक executor जो तैयार कार्य समानांतर चलाता है, और एक सीमित replanning चरण जो किसी कार्य के असफल होने पर चलता है. आपका बनाया हुआ search टूल वही प्राथमिक इकाई बन जाता है जिससे planner रचता है — और उसकी लौटाई citations वही सबूत बनते हैं जिन्हें भाग 7 सत्यापित करेगा.

Connect your agents without writing code

Everything above, running in Ball — no code, no install. Try it in your browser.

Try Ball free
Get the free AI agent kit

Only used to send Ball resources. No spam.

Try Ball in your browser — no install, no signup needed.

Try Ball in your browser — no install, no signup needed.

Reading in English? Switch language in the menu.