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 paraphrase-ஐக் கண்டறிவதில் உண்மையில் சிறந்தது. ஆனால் அது மூன்று படிநிலைகளில் ஒன்று மட்டுமே, மேலும் மற்ற இரண்டுதான் பெரும்பாலான production RAG அமைப்புகள் மௌனமாகத் தோற்கும் இடம். உயர் cosine மதிப்பெண்ணுடன் தவறான chunk-ஐத் திருப்பித் தரும் retriever, எதுவும் திருப்பித் தராததை விட மோசமானது — agent அதை மேற்கோள் காட்டும்.

இந்தப் பகுதி retriever-ஐ மூன்று பிரிக்கக்கூடிய படிநிலைகளாக உருவாக்குகிறது — chunk, recall, rerank — ஒவ்வொன்றுக்கும் அளக்கக்கூடிய ஒரு பணம் உண்டு, மேலும் எந்தப் படிநிலை உதவுகிறது அல்லது வெறும் latency சேர்க்கிறது என்பதைச் சொல்லும் அளவீட்டு அமைப்பும் உண்டு. பைப்லைன் பகுதி 2-இன் அதே Tool ஒப்பந்தத்துடன் இணைக்கப்பட்டுள்ளது, எனவே மேற்கோள்கள் இறுதி பதில் வரை உயிருடன் இருக்கும், பகுதி 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 பகுதி, எனவே உண்மையான மாதிரியை இணைப்பது இருபது வரிகளின் adapter ஆகும்.
  • HybridRetriever — BM25 மற்றும் dense பட்டியல்கள், reciprocal rank fusion முறையில் இணைக்கப்பட்டவை.
  • CorpusRetriever + make_search_tool — reranking, ஒரு relevance floor, மற்றும் agent ஏற்கனவே அழைக்கத் தெரிந்த அதே search கருவி.

பகுதி 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 hashing சார்பு, பயிற்சி பெற்ற மாதிரி அல்ல. இது மங்கலான விளிம்புகள் கொண்ட lexical: retrieve-ஐ retrieval-உடன் இணைக்கிறது, ஏனெனில் இரண்டிலும் 4-gram உள்ளது, மேலும் உண்மையான இணைச்சொல்லில் இது தோற்கிறது. இந்த வரம்பு வேண்டுமென்றே உள்ளது, மேலும் அளவீட்டுப் பகுதி அதன் விலை எவ்வளவு என்பதை துல்லியமாகக் காட்டுகிறது — அளக்க முடியாத retriever-ஐ முன்னேற்றவும் முடியாது.

ஐந்து-பதிவு அகராதி உண்மையில் எவ்வளவு செலவாகும்

மூன்று தோல்விகள், அனைத்தும் தற்போதைய குறியீட்டில் மீண்டும் உருவாக்கப்பட்டவை.

Miss ஒரு காலி corpus-இலிருந்து வேறுபடுத்த முடியாதது. எந்த key-யும் பொருந்தாம்போது _search ["no matches"] திருப்பித் தருகிறது, இது ok=True. மாதிரி அதை corpus-இல் விஷயம் பற்றி எதுவும் இல்லை என்பதற்கான ஆதாரமாக வாசிக்கிறது. பகுதி 2-இல் timeout சூழலை வகைப்படுத்தப்பட்ட error மூலம் சரிசெய்தோம்; miss சூழல் இன்னும் தரவின் வேடத்தில் அலங்கரிக்கப்பட்ட பொய்யே.

மேற்கோள் இல்லை. கருவி வெறும் சரங்களைத் திருப்பித் தருகிறது. மாதிரி இறுதிப் பதிலை எழுதும்போது, அதில் எதுவும் ஒரு passage-க்குப் பின்னோக்கிச் சுட்டிக்காட்டாது, எனவே பயனர் கூற்றைச் சரிபார்க்க முடியாது, பகுதி 7 அதைச் சரிபார்க்கவும் முடியாது.

மீட்டெடுப்பின் அலகு ஒரு ஆவணம். உண்மையான corpus இருந்தாலும் முழு ஆவணங்களைத் திருப்பித் தருவது என்பது ஒரு hit-க்கு 4,000 எழுத்துக்களின் ஒரு தொகுதி. 420 எழுத்துக்களில் நான்கு hits சுமார் 420 tokens-இன் context; நான்கு முழு ஆவணங்கள் 4,000. பிறகு பகுதி 3-இன் budget தன் முயற்சியை retriever அனுப்பக்கூடாத அந்த text-ஐ சுருக்குவதில் செலவழிக்கிறது.

இந்தக் கட்டுரையின் மீதம் மூன்றையும் கட்டமைப்பின் மூலம் சரிசெய்கிறது: chunks அலகைச் சிறியதாக்குகின்றன, மேற்கோள்கள் வெளியீட்டைச் சரிபார்க்கக்கூடியதாக்குகின்றன, relevance floor miss-ஐ வகைப்படுத்தப்பட்ட error ஆக்குகிறது.

Chunking: திரும்பப் பெற முடியாத முடிவு

Chunk எல்லைகள்தான் மீட்டெடுப்பின் மாற்றுவது விலை உயர்ந்த ஒரே முடிவு, ஏனெனில் அவற்றை மாற்றுவது முழு 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)]

முப்பது வரிகளில் நான்கு முடிவுகள், ஒவ்வொன்றிற்கும் அதன் விலை.

வாக்கியங்களில் பிரிக்கவும், எழுத்து-budget-க்குள் பொதிக்கவும். சொல்லின் நடுவில் பிரிப்பது முதல் token ஒரு துண்டாக இருக்கும் chunk-ஐ உறுதி செய்கிறது, அது embedding-ஐயும் quote-ஐயும் விடம் போடுகிறது. regex ., ! அல்லது ?-க்குப் பிறகு வெற்றிடம் இருந்தால் மட்டுமே பிரிகிறது, அது e.g. போன்ற சுருக்கெழுத்துகளைத் தவறான இடத்தில் பிரிகிறது — ஏற்கக்கூடியது, காரணம் இழை ஒரு கூடுதல் எல்லை, உடைந்த சொல் அல்ல.

420 எழுத்துக்கள், 512 tokens அல்ல. ஒரு token-க்கு சுமார் நான்கு எழுத்துக்கள் என்றால் இது ஒரு chunk-க்கு சுமார் 105 tokens. எண்ணைக் காட்டிலும் விகிதம் முக்கியம்: 105-105 tokens-இல் நான்கு மீட்டெடுக்கப்பட்ட chunks மொத்தம் 420 tokens-இன் சான்றுகள், அவை 300-token system prompt-உடன் பகுதி 3-இன் budget-க்குள் சௌகரியமாக இடம் பெறுகின்றன. 1,000-token chunk வரம்பு நான்கு hits-ஐ 4,000 tokens ஆக்கியிருக்கும், budget-ஐ நீங்கள் பெற செலவழித்த அந்த text-ஐயே சுருக்க கட்டாயப்படுத்தியிருக்கும்.

Overlap ஒரு வால்-நகல், sliding window அல்ல. flush கழித்து 90 எழுத்துக்களில் அடங்கும் கடைசி வாக்கியங்கள் புதிய buffer-இல் மீண்டும் திறக்கப்படுகின்றன. விளைவு இந்த அமைப்புகளில் 21 சதவீத index பெருக்கம் (420-இல் 90), மேலும் ஒரு உத்தரவாதம்: எல்லையில் நிற்கும் வாக்கியம் குறைந்தது ஒரு பக்கத்திலாவது மீட்டெடுக்கப்படுகிறது. token-எண்ணிக்கையின் sliding-window chunking அதே உத்தரவாதத்தைத் தருகிறது, ஆனால் வாக்கியத்தின் நடுவில் தொடங்கும் chunks உருவாக்குகிறது — நாம் தவிர்க்கும் அதே விஷயம்.

ordinal மேற்கோள் தான், எனவே அது நிலையாக இருக்க வேண்டும். chunking#1 என்பது chunking ஆவணத்தின் இரண்டாவது chunk. வேறு அமைப்புகளுடன் மீண்டும் chunk செய்தால், பழைய பதில்களின் ஒவ்வொரு மேற்கோளும் வேறு இடத்தைச் சுட்டும். எனவே அமைப்புகள் index உருவாக்கத்தில் இருக்கின்றன, corpus பதிப்பின் அடுத்து பதிவாகின்றன, மேலும் மீண்டும் chunking என்பது config மாற்றமல்ல, ஒரு migration.

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 hashing: இது மொழியியல் அமைப்பையும் பொது துணைச்சரங்களையும் கையாளுகிறது, இது உண்மையான — குறுகியதாயினும் — பொதுமைப்படுத்தல் வடிவம், 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 மாற்றியதற்கும் இந்த index-ஐ வைத்திருப்பது மதிப்புள்ளதாக்குகின்றன. Vector அலகு-norm, எனவே cosine ஒரு dot product, மதிப்பெண்கள் chunk நீளங்களில் ஒப்பிடத்தக்கவை. Hashing குறியுடையது, எனவே மோதல்கள் சராசரியாக ரத்து ஆகின்றன, பொய் ஒற்றுமை குவிக்கப்படாது. தேடல் brute force, 19 chunks-இல் 0.6 ms எடுக்கும், 50,000 chunks-இல் சுத்தமான Python-இல் சுமார் 400 ms — கவனிக்கத்தக்க அளவு மந்தம், மேலும் அங்கு வந்தடையும்போது உண்மையான 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 — முழுதாக lexical 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 matchers கூட்டால் 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-ஐ ஒரே forward pass-இல் காண்கிறது, எனவே not மற்றும் only மற்றும் சொல்-வரிசையை வெளிப்படுத்த முடியும் — BM25-ஆலும் n-gram-கூடை embedding-ஆலும் முடியாத விஷயங்கள்.

கீழே உள்ள deterministic இடைக்கால தீர்வு சொல்-மூட்டல், துல்லியமான தொடர்புத்தொடர் இருப்பு, மற்றும் அடுத்தடுத்த query சொற்களின் நெருக்கம் ஆகியவற்றை மதிப்பிடுகிறது. இது cross-encoder அல்ல; இது reranker-வடிவ சார்பு, கட்டுப்பாட்டுத் தொகுதிகள் சில விலை உயர்ந்ததை இணைப்பதற்கு முன்பே பைப்லைன், threshold, test அனைத்தும் இருக்க செய்கிறது.

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 சொற்களின் எண்ணிக்கையால் normalise செய்யப்படுகிறது, எனவே இரு-சொல் 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-இன் மொத்த budget இரு வினாடிகளாகவும் இருந்தால் ஏற்கமுடியாதது. இரண்டு இணைக்கருவிகள் அதை வரம்புக்குள் வைக்கின்றன: rerank தொகுதியை வரம்புக்குள் வைப்பது (8 நல்ல இயல்புநிலை; 9வது candidate முதல் 4-ஐ அரிதாகவே மாற்றும்) மற்றும் fusion வித்தியாசம் பெரிதாக இருக்கும்போது reranking-ஐத் தவிர்ப்பது (முதல் passage இரண்டாவதை 2×-க்கு மேல் முன்னிற்கவிட்டால் வரிசை நெருங்கியதல்ல).

Tool registry-யில் இணைத்தல்

கருவிதான் தையல். அது மேற்கோள்களைத் திருப்பித் தர வேண்டும், பகுதி 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, மேலும் அது அடித்தளம் போலச் சுமக்கிறது, test-கள் காட்டும் ஒரு காரணத்திற்காக: அது இல்லாதபோது முற்றிலும் அர்த்தமற்ற சொற்களின் query hashed embedder-இலிருந்து மிகச் சிறிய நேர்மறை cosine கொண்ட மோதல்களைத் திருப்பி வருகிறது, agent error-க்கு பதிலாக நான்கு சம்பந்தமற்ற passages பெறுகிறது. Floor அதை ERROR[not_found] ஆக்குகிறது, மாதிரி அதை இந்த corpus அதை உள்ளடக்கவில்லை என வாசிக்கிறது, மேலும் அது உண்மை.

limit=4 ஒரு budget முடிவும் கூட. சுமார் 105-105 tokens-இல் நான்கு passages மொத்தம் 420 tokens, கூடுதலாக சுமார் 30 tokens மேற்கோள் சட்டகம். இரண்டு hits மலிவானதாக இருந்திருக்கும் ஆனால் பெரும்பாலும் போதுமானதல்ல — பதில் பெரும்பாலும் வரைவிலக்கண 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 store தொடப்படாமல் உள்ளன, மாதிரி இன்னும் search என்ற கருவியைக் காண்கிறது, அதற்கு எதிராக சரிபார்க்கக்கூடிய ஒரு schema உடன்.

தோல்வி முறைகள் மற்றும் அவற்றை கையாளுதல்

தோல்வி உண்மையில் என்ன நடக்கிறது இங்கு என்ன செய்யப்படுகிறது இன்னும் உடைந்தது
Chunk அட்டவணை அல்லது பட்டியலை உடைக்கிறது வரிகள் வெவ்வேறு chunks-இல் விழுகின்றன, எதுவும் பதிலளிக்காது வாக்கிய பிரிப்பான் punctuation அனுமித்தால் வரிகளை ஒன்றாக வைக்கிறது Markdown அட்டவணைகளுக்கு கட்டமைப்பு பிரிப்பான் தேவை
Query மற்றும் corpus வேறு சொற்களைப் பயன்படுத்துகின்றன BM25 எதுவும் தராது; hashed embedding இரைச்சல் தருகிறது Dense பகுதி + fusion உண்மையான இணைச்சொல்லுக்கு பயிற்சி பெற்ற மாதிரி தேவை
ஒவ்வொரு hit-உம் சம்பந்தமற்றது மாதிரி கூற்றை ஆதரிக்காத passage-ஐ மேற்கோள் காட்டுகிறது min_score floor → ERROR[not_found] Floor ஒரு corpus-க்கு; ஒவ்வொரு மொழிக்கும் மீள-அளவீடு தேவை
Reranker மிக மந்தம் Tool-இன் p95 40 ms-இலிருந்து 240 ms குதிக்கிறது Rerank தொகுதி 8-இல் வரம்பு, பெரிய வித்தியாசத்தில் தவிர்ப்பது பொருத்தமான budget இல்லை
ஆவணங்களில் இரட்டை chunks அதே வாக்கியம் இருமுறை மீட்கப்படுகிறது, இரு இடங்கள் வீண் Overlap வரம்புறுத்தப்பட்டது; text hash-ஆல் dedupe கிட்டத்தட்ட இரட்டை ஆவணங்கள் இன்னும் pool-ஐ வெள்ளம் எடுக்கின்றன
மீண்டும் chunking மேற்கோள்களை செல்லாததாக்குகிறது பழைய பதில்கள் தவறான ordinal-க்குச் சுட்டுகின்றன Ordinals ஒரு build-க்கு நிலையானவை; corpus பதிப்பு பதிவாகிறது சேமிக்கப்பட்ட மேற்கோள்களுக்கு migration கருவி இல்லை
Embedding மாதிரி மாற்றப்பட்டது மதிப்பெண்கள் நகர்கின்றன, floor இனி செல்லாது Interface மாற்றத்தைப் பிரிக்கிறது Deploy-க்கு முன் அளவீட்டு அமைப்பின் மீள-இயக்கம் தேவை

கடைசி வரிதான் production-இல் கடிக்கும் ஒன்று, அது குறியீட்டின் தோல்வி அல்ல, செயல்முறையின் தோல்வி. HashedEmbedder-ஐ உண்மையான மாதிரியால் மாற்றுவது மதிப்பெண் பரவலை மாற்றுகிறது, அது min_score-ஐ செல்லாததாக்குகிறது, அது மௌனமாக error பாதைகளை சம்பந்தமற்ற passage பாதைகளாக மாற்றுகிறது. எந்த embedder மாற்றத்தையும் அளவீட்டு அமைப்பின் இயக்கம் பின்தொடர வேண்டும், floor புதிய பரவலின் கீழ்-வாலிலிருந்து தீர்மானிக்கப்பட வேண்டும் — பழையதிலிருந்து நகலெடுக்காமல்.

Trade-off-கள்

முடிவு மாற்று ஏன் இதைத் தேர்ந்தெடுத்தோம் விலை
420-எழுத்து chunks 1,000-token chunks நான்கு hits 420 tokens, 4,000 அல்ல பதில்கள் எல்லைகளில் பிரிகின்றன
90-எழுத்து overlap Overlap இல்லை எல்லை வாக்கியங்கள் மீட்கத்தக்கவையாக இருக்கின்றன 21 சதவீத index பெருக்கம்
BM25 + dense, RRF மூலம் இணைந்தவை ஒரே ஒரு retriever Demo-இல் pool-இன் recall 0.88-இலிருந்து 1.00 ஆகிறது இரண்டு indexes sync-இல் வைக்கப்பட வேண்டும்
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 வடிவம் மற்றும் test-கள் மூன்றையும் ஒரே நேரத்தில் தொடுவதாகும்.

சோதித்தல்

பதினொரு test-கள், 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 அளவு மற்றும் நான்கு hits-இன் 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. மொழி-வாரியான floor-கள். Relevance floor ஆங்கிலத்தில் அளவீடு செய்யப்பட்டது. வேறு tokenisation கொண்ட ஒரு மொழியில் (ஜப்பானிய அல்லது ஜெர்மன் கூட்டுச்சொற்கள்) பத்து-query தொகுதி உருவாக்கி, சம்பந்தமுள்ள மற்றும் சம்பந்தமற்ற hits-இன் மதிப்பெண் பரவலைக் கண்டுபிடியுங்கள். ஒரு உலகளாவிய min_score ஆதரிக்கத்தக்கதா, அல்லது அது ஒரு index-க்கு இருக்க வேண்டுமா?

இரண்டாவது பயிற்சிதான் நீங்கள் வெளியிடுவதை மாற்றுவது. தையல் சிறியது, அது இருப்பது விலை உயர்ந்த component deployment முடிவாக மாறுகிறது என்று பொருள், கட்டமைப்பு முடிவாக அல்ல.

அடுத்து என்ன

Agent இப்போது ஒரு passage-ஐக் கண்டுபிடித்து மேற்கோள் காட்ட முடிகிறது. இன்னும் செய்ய முடியாதது என்பது தனக்கு எத்தனை தேடல்கள் தேவை மற்றும் எந்த வரிசையில் என்பதை முடிவெடுப்பது — loop ஒரே நேரத்தில் ஒரு tool call மட்டுமே வழங்குகிறது, மேலும் compare the chunking trade-offs with the reranker latency budget போன்ற கேள்விக்கு ஒரு திட்டம் தேவை.

அடுத்த பகுதி, பகுதி 6 — Task decomposition — ஒரு இலக்கை வெளிப்படையான சார்புகள் கொண்ட task graph ஆக்கும் ஒரு Planner, தயாரான பணிகளை இணைந்து இயக்கும் ஒரு executor, மற்றும் ஒரு பணி தோல்வியுறும்போது துரத்தும் வரம்புறுத்தப்பட்ட மீள்-திட்டமிடல் படிநிலை ஆகியவற்றைச் சேர்க்கிறது. நீங்கள் சற்றுமுன் உருவாக்கிய 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.