Back to all articlesAI اور ایجنٹس

اپنی جگہ برحق ثابت ہونے والا RAG ریٹریور بنانا (حصہ 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 کی ہر دعویٰ یا انہی پانچ جملوں میں سے ایک ہوتی ہے یا مکمل گھڑی ہوتی ہے — اور دونوں میں فرق کرنے کا کوئی طریقہ لوپ کے پاس نہیں۔

پہلا جواب ویکٹر ڈیٹابیس لگانا ہوتا ہے۔ یہ سوچ آدھی درست ہے: پیرافریز کی پہچان میں dense retrieval واقعی بہتر ہے۔ لیکن وہ تین مراحل میں سے ایک ہے؛ اور باقی دو مراحل میں ہی اکثر پروڈکشن RAG سسٹم خاموشی سے ناکام ہوتے ہیں۔ بلند کوسائن سکور کے ساتھ غلط چنک واپس کرنے والا ریٹریور کچھ نہ واپس کرنے والے ریٹریور سے زیادہ ہلاہل ہے — کیونکہ agent اس کا حوالہ دے دیتا ہے۔

یہ حصہ ریٹریور کو تین جداگانہ مراحل میں بناتا ہے — chunk، recall، rerank — ہر مرحلے کی ناپنے کے قابل ذمہ داری ہوتی ہے؛ اور ساتھ وہ ہارنس جو بتاتا ہے کہ کوئی مرحلہ مدد کر رہا ہے یا صرف لیٹنسی بڑھا رہا ہے۔ پائپ لائن حصہ 2 کے اسی Tool معاہدے سے جڑتی ہے؛ اس طرح حوالے حتمی جواب تک زندہ رہتے ہیں اور حصہ 7 ان کی تصدیق کر سکتا ہے۔

آپ کیا بنائیں گے

پانچ ٹکڑوں کے ساتھ rag.py ماڈیول:

  • chunk_document — قابلِ ترتیب اوورلیپ کے ساتھ جملہ آگاہ پیکینگ؛ Chunk آبجیکٹ دیتی ہے جن کا citation doc#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، تعلق کی حد، اور وہ search ٹول جسے agent کال کرنا پہلے سے جانتی ہے۔

حصہ 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."
),
}

یہاں کا embedدر حروف n-gram ہیشنگ فنکشن ہے؛ تربیت یافتہ ماڈل نہیں۔ یہ فجی کناروں والا لفظی (lexical) میچر ہے: 4-gram مشترک ہونے سے retrieve کو retrieval سے جوڑتا ہے، پر اصل مترادف الفاظ پر ناکام رہتا ہے۔ یہ حد جان بوجھ کر ہے؛ ناپنے کا حصہ اس کی قیمت ٹھیک ٹھاک دکھاتا ہے — کیونکہ جس ریٹریور کو ناپا نہ جا سکے اسے بہتر بھی نہیں کیا جا سکتا۔

پانچ اندراجات کی ڈکشنری سچ مچ کتنی مہنگی

تین ناکامیاں؛ سب موجودہ کوڈ میں ہی دوبارہ بنائی گئیں۔

مِس اور خالی کارپس میں فرق کیا جا سکتا نہیں۔ کوئی کی جڑنہیں تو _search لے ["no matches"] واپس کرتا ہے، جو ok=True ہوتا ہے۔ اس موضوع پر کارپس میں کچھ نہیں یہ ماڈل اسے ثبوت سمجھ لیتا ہے۔ حصہ 2 نے ٹائم آؤٹ کیس کو درجہ بندی شدہ ایrror سے درست کیا؛ پر مِس کیس ابھی بھی ڈیٹا کے بھیس میں جھوٹ ہی ہے۔

حوالہ (citation) نہیں۔ ٹول ننگی سٹرنگ واپس کرتا ہے۔ ماڈل حتمی جواب لکھتا ہے تو اس میں کسی پیسیج کی طرف اشارہ کرنے والا کچھ نہیں ہوتا؛ نتیجتاً صارف دعویٰ جانچ نہیں سکتا، حصہ 7 بھی تصدیق نہیں کر سکتا۔

ریٹریول کا یونٹ پورا ڈاکومنٹ ہے۔ اصل کارپس بھی ہو تو پورا ڈاکومنٹ واپس کرنا مطلب ہر ہٹ کے لیے 4,000 حروف کا لٹھ۔ 420 حروف کے چار ہٹ تقریباً 420 token کانٹیکسٹ؛ چار پورے ڈاکومنٹ 4,000۔ پھر حصہ 3 کا بجٹ ریٹریور کو پہنچنے کے لائق ٹیکسٹ کو کچنے میں ہی اپنی طاقت خرچ کرتا ہے۔

اس مضمون کا باقی حصہ یہ تینوں باتیں بنیاد میں ہی درست کر دیتا ہے: چنکس یونٹ چھوٹا بناتے ہیں، حوالے آؤٹ پٹ کی جانچ کے قابل بناتے ہیں، اور تعلق کی حد مِس کو درجہ بندی شدہ ایrror میں بدل دیتی ہے۔

چنکنگ: الٹا نہ پھیر سکنے والا فیصلہ

چنک حدیں ہی وہ واحد ریٹریول فیصلہ ہیں جو الٹانا مہنگا پڑتا ہے — کیونکہ بدلنے پر پورے کارپس کی دوبارہ embedding کرنی پڑتی ہے۔ باقی سب — سکورنگ فنکشن، فیوژن ثابت، ریرینکر — ایک دوپہر میں ٹیون ہو جاتے ہیں۔

حدوں کا جوڑا سادہ ہے۔ بہت بڑے چنکس پتلا ہو جاتے ہیں: تین غیر متعلق نکات والا 900-حرفی چنک تینوں کے لیے رینک ہوتا ہے پر کسی ایک کا درست جواب نہیں دیتا — کیونکہ embedding اندر کے سب کا اوسط ہوتی ہے۔ بہت چھوٹے چنکس اپنی اپنی گرامر گنوا دیتے ہیں: 120-حرفی ٹکڑا اکثر It سے شروع ہوتا ہے، اس کا ماقول نہیں ہوتا — یہ کوئی ریرینکر درست نہیں کر سکتا۔

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)]

تیس لائنوں میں چار فیصلے؛ ہر ایک کی کوئی قیمت۔

جملوں پر توڑنا، حروف کے بجٹ پر پیکنے۔ لفظ کے درمیان توڑ دیں تو پہلا ٹوکن ٹکڑا ہو جاتا ہے — یہ embedding اور اقتباس دونوں کو زہر آلود کرتا ہے۔ ریگولر ایکسپریشن خالی جگہ سے پہلے آنے والے ., ! یا ? کے بعد ہی توڑتا ہے؛ اس لیے e.g. جیسے مخفف غلط طریقے سے ٹوٹتے ہیں — نقصان ایک اضافی حد کا ہوتا ہے اس لیے یہ قابلِ قبول ہے۔

420 حروف، 512 ٹوکن نہیں۔ ٹوکن کے تقریباً چار حروف چوپ سے یہ ایک چنک پر تقریباً 105 ٹوکن بنتا ہے۔ تعداد سے نسب زیادہ اہم: ایک ایک پر 105 ٹوکن والے چار ریٹریو کیے گئے چنکس 420 ٹوکن ثبوت — 300-ٹوکن سسٹم پرامپٹ کے ساتھ بھی حصہ 3 کے بجٹ میں آرام سے بیٹھتا ہے۔ 1,000-ٹوکن چنک کیپ رکھیں تو چار ہٹ کی قیمت 4,000 ٹوکن ہو جاتی ہے؛ آپ نے پیسہ دے کر لایا ہوا ٹیکسٹ ہی کچنے پر بجٹ مجبور ہو جاتا ہے۔

اوورلیپ یعنی دم کی کاپی، سلائیڈنگ ونڈو نہیں۔ فلس کے بعد 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]

embedدر بدل جانے پر بھی یہ انڈیکس رکھنے کے قابل بنانے والے تین خواص۔ ویکٹر 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]))
@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 والا چنک 1/61 = 0.0164 سکور کرتا ہے؛ دونوں فہرستوں میں رینک 2 والا چنک 1/62 + 1/62 = 0.0323۔ دوسرا جیتتا ہے — ایک فہرست لفظی اور ایک سی مینٹک ہو تو ہی یہی برتاؤ چاہیے۔ k کو 10 تک گھٹائیں تو ایک فہرست کا جیتنے والا بہت مضبوط ہو جاتا ہے — ایک ریٹریور صاف طور پر بہتر ہو دوسرے سے چھوٹا ٹائی بریک ہی مانگنا ہو تو مفید۔

ایماندار ناپ ڈیزائن بدلنے والا جگہ یہی ہے۔ یہاں ہارنس — انیس چنکس پر، لیبل شدہ آٹھ کوئریوں پر چلا:

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 ہی کینڈیڈیٹ پول کے وجود کا سبب ہے؛ پول سائز اہم: 19 چنکس پر pool=12 پر BM25 کے ٹاپ 12 میں 8 کوئریوں میں سے 7 کے لیے درست ڈاکومنٹ ہے؛ dense بازو کے لیے 8 میں سے 8؛ اس لیے اجتماع 8 میں سے 8۔ ایک کوئری — combining keyword and embedding rankings — مکمل لفظی مِس؛ اس کے موضوع چنک میں keyword، embedding یا rankings الفاظ نہیں؛ ہیشڈ embedدر مشترک 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 کی بجائے درجہ بندی شدہ ایrror میں بدلنا چاہیے۔

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در چھوٹے مثبت کوسائن والی ٹکرائیں واپس کرتا ہے؛ ایrror کی بجائے agent چار غیر متعلق پیسیج پاتا ہے۔ حد اسے ERROR[not_found] میں بدل دیتی ہے — ماڈل اسے یہ کارپس وہ موضوع کور نہیں کرتا پڑتا ہے؛ اور وہ سچ ہے۔

limit=4 بھی بجٹ فیصلہ ہی ہے۔ ایک ایک پر 105 ٹوکن والے چار پیسیج 420 ٹوکن؛ اوپر حوالہ پائیا تقریباً 30 ٹوکن۔ دو ہٹ سستا ہوتا ہے پر اکثر ناکافی — جواب اکثر تعریف چنک اور مثال چنک کے بیچ ٹوٹا ہوتا ہے۔ چھ کے مقام پر precision، recall اضافے سے تیز گرنا شروع کرتا ہے۔

انٹیگریشن ایک لائن — AgentLoop پہلے سے ٹول فہرست قبول کرتا ہے:

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"] فلٹر ہی پورا مائیگریشن ہے۔ لوپ، ایگزیکیوٹر، رےٹرائی پالیسی، آئیڈیمپوٹینسی اسٹور کچھ بھی چھونا نہیں گیا؛ ماڈل ابھی بھی اسکیمہ والا search نام کا ٹول ہی دیکھتا ہے۔

ناکامی کی صورتیں اور ان کی دیکھ بھال

ناکامی سچ مچ کیا ہوتا ہے یہاں دیکھ بھال ابھی بھی ٹوٹا ہوا
چنک جدول یا فہرست توڑ دیتا ہے قطاریں الگ چنکس میں گرتے ہیں؛ کسی سے جواب نہیں ملتا جہاں وقفہ نشان اجازت دے وہاں جملہ توڑنے والا قطاریں ساتھ رکھتا ہے Markdown جدول کو ساختی توڑنے والا چاہیے
کوئری اور کارپس الگ الفاظ استعمال کرتے ہیں BM25 کچھ نہیں دیتا؛ ہیشڈ embedding شور دیتی ہے dense بازو + فیوژن اصل مترادفوں کے لیے تربیت یافتہ ماڈل چاہیے
ہر ہٹ غیر متعلق ماڈل دعویٰ کو مدد نہ دینے والا پیسیج حوالہ دیتا ہے min_score حد → ERROR[not_found] حد کارپس کے مطابق ہے؛ فی-زبان پھر سے ماپنے چاہیے
ریرینکر بہت سست ٹول p95 40 ms سے 240 ms پر اچھلتا ہے ریرینک سیٹ 8 پر محدود؛ بڑا فیوژن مارجن ہو تو چھوڑنا کوئی موزون بجٹ نہیں
ڈاکومنٹوں پر نقل چنکس ایک ہی جملہ دو بار ریٹریو ہوتا ہے؛ دو سلٹ بیکار اوورلیپ محدود؛ ٹیکسٹ ہیش سے نقل نکالنا تقریباً نقل ڈاکومنٹ ابھی بھی پول بھرتے ہیں
دوبارہ چنک کرنے حوالے اضافی کر دیتے ہیں پرانے جواب غلط ordinal اشارہ کرتے ہیں ordinal ہر بلڈ کے لیے مستحکم؛ کارپس ورژن درج ہوتا ہے محفوظ حوالوں کے لیے مائیگریشن ٹول نہیں
Embedding ماڈل بدل گیا سکور سر جاتے ہیں؛ حد بے اعتبار انٹرفیس تبدیلی کو اکیلے رکھتا ہے ڈیپلائے سے پہلے ہارنس پھر چلانا چاہیے

آخری قطار ہی پروڈکشن میں کاٹنے والی ہے؛ وہ کوڈ ناکامی نہیں، عمل ناکامی ہے۔ HashedEmbedder کو اصل ماڈل سے بدلنا سکور تقسیم بدلتا ہے؛ وہ min_score کو بے اعتبار کرتا ہے؛ وہی ایrror راستے خاموشی سے غیر متعلق-پیسیج راستے بنا دیتے ہیں۔ کسی بھی embedدر تبدیلی کے بعد فوراً ہارنس رن ہونا چاہیے؛ حد نئی تقسیم کے نیچے کے دم سے سیٹ ہو — پرانے سے کاپی نہیں۔

ٹریڈ-آف

فیصلہ متبادل ہم نے کیوں چنا قیمت
420-حرفی چنکس 1,000-ٹوکن چنکس چار ہٹ کی قیمت 420 ٹوکن، 4,000 نہیں جواب حدوں پر ٹوٹتے ہیں
90-حرفی اوورلیپ اوورلیپ نہیں حد جملے ریٹریو ہوتے رہتے ہیں 21 فیصد انڈیکس پھولنا
BM25 + dense، RRF سے امتزاج ایک ہی ریٹریور ڈیمو میں پول recall 0.88 سے 1.00 سینک میں رکھنے والے دو انڈیکس
ہیشڈ embedدر تربیت یافتہ embedding ماڈل معینہ، آف لائن، ٹیسٹ کے قابل مترادف recall نہیں؛ precision میں BM25 سے ہارتا ہے
معینہ ریرینکر Cross-encoder 1 ms میں چلتا ہے؛ ہوسٹ کرنے والا ماڈل نہیں رینکنگ بہت کم بدلتا ہے
min_score=0.05 جوڑنے والا کچھ بھی واپس کرنا کچرا درجہ بندی شدہ ایrror بناتا ہے سچ مچ نایاب کوئری ایrror دیتی ہے
limit=4 limit=10 کانٹیکسٹ قیمت محدود کثیر-علاقہ (multi-hop) سوالات چھوٹ جاتے ہیں

ریرینکر قطار کو سیدھا جواب دینے کا حق ہے: اس نمائندے سے آپ کوئی precision لاب کے بغیر انٹرفیس پیچیدگی کی قیمت ادا کر رہے ہیں۔ تہہ بھی انٹرفیس کھڑا کرنے کا سبب: precision وہ مرحلہ ہے جہاں تربیت یافتہ ماڈل P@1 میں دس سے بیس پوائنٹ کماتا ہے؛ سیو کی پٹی بعد میں لگانے پر ٹول معاہدہ، حوالہ فارمیٹ، اور ٹیسٹ سب ایک ساتھ چھونے پڑتے ہیں۔

جانچ

گیارہ ٹیسٹ؛ نیٹ ورک نہیں؛ 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 دونوں بازو رکھنے کا جواز دینے والا ٹیسٹ ہے۔ یہ ایک ہی چنک پر وہم مخالف دو دعوے ٹہراتا ہے: ویکٹر انڈیکس retrieve کے لیے اسے ڈھونڈتا ہے، اور BM25 خالی فہرست دیتا ہے۔ یہ ٹیسٹ ناکام ہونے کے قابل کوئی بعد میں embedدر بدل دے تو dense بازو دوسرا لفظی میچر بن جاتا ہے؛ فیوژن مرحلہ اب خالص اضافی بوجھ — اوپر کا بینچمارک ناپنے والی صورت حال وہی۔

test_empty_result_is_a_classified_error یعنی no matches جھوٹے کا ریگریشن کاپور۔ ok=False + not_found مطلب لوپ ناکام قدم درج کرتا ہے؛ ماڈل کو ERROR[not_found] دکھتا ہے — اس پر چل سکتا ہے۔ ok=True خالی فہرست کے ساتھ آئے تو ماڈل کارپس موضوع پر خاموش ہے یہ نتیجہ نکالتا ہے — وہ سچ نہیں۔

مشق

  1. اوورلیپ ناپیں۔ overlap_chars کو 0، 90، 180 پر رکھ کر انڈیکس دوبارہ بلڈ کریں، ہر بار ہارنس چلائیں۔ recall@12، چنکس میں انڈیکس سائز، اور چار ہٹ کی ٹوکن قیمت رپورٹ کریں۔ کس اوورلیپ پر recall لاب نقل کی قیمت ادا کرنا چھوڑ دیتا ہے؟
  2. 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 تبدیلی ناپیں۔
  3. فی-زبان حدیں۔ تعلق کی حد انگریزی پر ناپی گئی ہے۔ الگ ٹوکنائزیشن (جاپانی یا جرمن ملے ہوئے الفاظ) والی زبان میں دس-کوئری سیٹ بنا کر، متعلق اور غیر متعلق ہٹ کا سکور تقسیم تولیں۔ ایک ہی عالمگیر min_score قابلِ دفاع ہے، یا انڈیکس انڈیکس کے مطابق ہونا چاہیے؟

مشق 2 آپ جو شپ کریں گے وہ بدل دیتی ہے۔ سیو پٹی چھوٹی ہے؛ وہ ہو تو مہنگا حصہ ساختی فیصلے سے ڈیپلائے منٹ فیصلہ بن جاتا ہے۔

اب کیا

agent اب پیسیج ڈھونڈ کر حوالہ دے سکتی ہے۔ ابھی نہیں کر سکتی: اپنے لیے کتنی تلاشیں چاہئیں، کس ترتیب میں — لوپ ایک وقت میں ایک ٹول کال دیتی ہے؛ compare the chunking trade-offs with the reranker latency budget جیسے سوال کے لیے منصوبہ چاہیے۔

حصہ 6، Task decomposition، ہدف کو صاف ڈیپینڈنسیوں والے ٹاسک گراف میں بدلنے والا Planner، تیار ٹاسک متوازی چلانے والا ایگزیکیوٹر، اور ٹاسک ناکام ہونے پر پھٹنے والا بندھا ہوا رپلاننگ مرحلہ جوڑتا ہے۔ آپ نے ابھی بنایا search ٹول planner کا گھونپا ہوا پریمیٹیو بنتا ہے — اس کے واپس کیے حوالے حصہ 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.