తన స్థానాన్ని సార్థకం చేసుకునే RAG రిట్రీవర్ను నిర్మించడం (భాగం 5)
Retrieval in three stages
One search call, three stages
The pool exists for recall; the reranker exists for order.
- input
- process
- decision
- output
Measured on 19 chunks, 8 queries
| Recall@12 (pool) | P@1 (precision) | |
|---|---|---|
| BM25 alone | 0.88 | 0.62 |
| Dense alone | 1.00 | 0.38 |
| Hybrid (RRF) | 1.00 | 0.50 |
| Verdict | fusion earns its keep | buy a real model |
భాగం 1 నుంచి వచ్చిన search టూల్ ఐదు ఎంట్రీల డిక్షనరీ. దాన్ని agent loop గురించి అడిగితే ఒక వాక్యం తిరిగి ఇస్తుంది; వేరే దేన్ని అడిగిత్తే no matches అని ఇస్తుంది. అందుకే agent చేసే ప్రతి వాదన ఆ ఐదు వాక్యాల్లో ఒకటో, లేదా పూర్తిగా కల్పితమో — రెండింటినీ వేరు చేసే మార్గం లూప్కి లేదు.
మొదటి ఆలోచన వెక్టర్ డేటాబేస్ అమర్చడం. ఆ ఆలోచన సగం సరైంది: పారాఫ్రేజ్లను గుర్తించడంలో dense retrieval నిజంగానే మెరుగైనది. కానీ అది మూడు దశల్లో ఒకటి మాత్రమే; మిగతా రెండు దశల్లోనే చాలా ప్రొడక్షన్ RAG సిస్టమ్లు నిశ్శబ్దంగా విఫలమవుతాయి. అధిక కోసైన్ స్కోరుతో తప్పు చంక్ను తిరిగిచ్చే రిట్రీవర్, ఏమీ తిరిగివ్వని రిట్రీవర్ కంటే ఘోర — ఎందుకంటే agent దాన్ని సైట్ చేస్తుంది.
ఈ భాగం రిట్రీవర్ను మూడు వేరుచేయగల దశలుగా నిర్మిస్తుంది — chunk, recall, rerank — ప్రతి దశకూ కొలవగల బాధ్యత ఉంటుంది; అంతేకాక ఏ దశ నిజంగా పనిచేస్తోందో లేదో లేదా కేవలం లేటెన్సీ మాత్రమే చేరుస్తోందో చెప్పే హార్నెస్ కూడా ఉంటుంది. పైప్లైన్ భాగం 2 లోని అదే Tool ఒప్పందానికి అనుసంధానమవుతుంది; దీనివల్ల సైటేషన్లు తుది సమాధానం వరకు నిలిచి, భాగం 7 వాటిని ధృవీకరించగలదు.
మీరు నిర్మించేది
ఐదు భాగాలు కలిగిన rag.py మాడ్యూల్:
chunk_document— కాన్ఫిగర్ చేయదగిన ఓవర్ల్యాప్తో వాక్య-స్పృహ కలిగిన ప్యాకింగ్;Chunkఆబ్జెక్టులను ఇస్తుంది, వాటిcitationdoc#nగా ఉంటుంది.BM25Index— ఇన్వర్టెడ ఇండెక్స్ మీద Okapi BM25; 19 చంక్లపై ఒక్క క్వెరీకి 0.015 ms, డిపెండెన్సీ లేదు.HashedEmbedder+VectorIndex—embed(text) -> list[float]ఇంటర్ఫేస్ వెనుక దాగిన dense శాఖ; నిజమైన మోడల్ను మార్చడం ఇరవై లైన్ల అడాప్టర్ పని మాత్రమే.HybridRetriever— BM25, dense జాబితాలను reciprocal rank fusion తో మేళవించేది.CorpusRetriever+make_search_tool— reranking, ప్రాసంగత్య ఫ్లోర్, agent ఇప్పటికే ఎలా పిలవాలో తెలిసినsearchటూల్.
భాగాల 1–4 తర్వాత research-agent ప్రస్తుత స్థితి: ధృవీకరించిన టూల్ ఒప్పందాలు, కాంటెక్స్ట్ బడ్జెట్, SQLite మెమరీ ఉన్న ఒక లూప్. search చివరి స్టబ్. ఈ భాగం AgentLoop ని తాకకుండానే దాన్ని భర్తీ చేస్తుంది — గత అబ్స్ట్రాక్షన్లు నిజంగానే పనిచేస్తాయో లేదో పరీక్షించేది ఇదే.
ముందస్తు అవసరాలు
- భాగాల 1–4.
rag.py,Tool,ToolResult,ErrorCodeలనుcontracts.pyనుంచి ఇంపోర్ట్ చేస్తుంది; డెమోAgentLoop,ScriptedLLMలను ఇంపోర్ట్ చేస్తుంది. - Python 3.10+, స్టాండర్డ్ లైబ్రరీ మాత్రమే. numpy అవసరం లేదు, వెక్టర్ డేటాబేస్ లేదు, embedding API key కూడా లేదు.
- డాక్యుమెంట్ id ని టెక్స్టుకు మ్యాప్ చేసే
dict[str, str]రూపంలో కార్పస్. కింది ఫిక్స్చర్ agent ఇంజినీరింగ్ గురించిన పన్నెండు చిన్న డాక్యుమెంట్లు; అవి పందొమ్మిది పేసేజీలుగా చంక్ అవుతాయి.
ఫిక్స్చర్ అంటే డాక్యుమెంట్ల dict; పన్నెండు డాక్యుమెంట్లు, ప్రతి దానిలో కొన్ని వాక్యాలే. ఇది ఉద్దేశపూర్వకంగా చిన్నదిగా ఉంచారు:
ఈ వ్యాసంలోని ప్రతి స్కోరు ఒకే కోర్పై ఒక సెకన్లోపలి వ్యవధిలో పునఃసృష్టించగలిగేంత చిన్నది; అదే సమయంలో
సరళమైన ఇండెక్స్ను చుక్కరించే పదాల ఉచ్చులను కలిగి ఉండేంత వైవిధ్యమైనది.
DOCUMENTS = { "chunking": ( "Chunk size sets the ceiling on retrieval precision. A 900-character chunk that " "contains three unrelated points will rank for all three and answer none of them " "cleanly. A 120-character chunk loses the pronoun and the subject of its own " "sentence. The band that survives contact with real corpora is 300 to 500 " "characters with an overlap of roughly one fifth of the window. Overlap exists so " "a sentence split across a boundary is still retrievable from one side; it also " "duplicates text, so a 20 percent overlap inflates the index by 20 percent. Split " "on sentence boundaries, never mid-word. Then measure: recall at five on a " "labelled query set is the only number that tells you whether the window is right." ), "retrieval-design": ( "A retrieval pipeline has three stages and they fail differently. Recall stage: " "fetch a candidate pool of twenty to fifty passages. Lexical scoring with BM25 " "catches exact identifiers, error codes and product names; dense retrieval catches " "paraphrase such as retrieve versus retrieval. Fuse the two ranked lists by " "reciprocal rank fusion rather than by adding raw scores, because BM25 scores are " "unbounded while cosine similarity lives in a fixed range. Rerank stage: a " "cross-encoder scores each query and passage pair jointly and is far more accurate " "than either first stage, at roughly ten milliseconds per pair. Generation stage: " "the model receives four passages with citation ids and must cite one per claim." ), "latency-budget": ( "Search latency is a budget, not a property. On a single CPU core, BM25 over " "twenty thousand chunks answers in about 4 milliseconds because it touches only " "the postings of query terms. Brute-force cosine over the same set costs 38 " "milliseconds in pure Python and 3 milliseconds with a matrix multiply. A " "cross-encoder reranker over twenty candidates costs 180 to 240 milliseconds per " "query at 12 layers. If the agent issues five searches per run, reranking adds " "more than a second to the run and the p95 latency of the tool dominates the p95 " "of the answer. Cap the rerank set at eight candidates and the added cost falls " "under 100 milliseconds." ), "planner": ( "A planner turns one goal into a graph of tasks with explicit dependencies. The " "graph, not the prose plan, is what the executor runs: a task becomes ready only " "when every task it depends on has completed. Two invariants matter. The graph " "must be acyclic, checked before execution rather than discovered by a stack " "overflow, and every dependency must name a task that exists. When a task fails, " "the planner is invoked again with the failure as input; the cheapest replan adds " "remediation tasks in front of the remaining work instead of rebuilding the whole " "plan, which is why replans are bounded to two per run." ), "reflection": ( "Reflection is a second pass that critiques the first answer and, if the critique " "finds a defect, produces a revision. It improves answers when the critique is " "anchored to evidence and degrades them when the model is asked to judge itself in " "the abstract. A loop needs three stop conditions: a hard round limit, a minimum " "score improvement below which another round is waste, and an oscillation check " "that fires when the same critique returns twice. Without the second condition " "the loop spends tokens rewriting a correct answer; without the third it " "alternates between two versions forever." ), "citations": ( "A citation id is a pointer from a claim to a passage, and it is the only cheap " "way to verify an answer mechanically. Format the id as document plus chunk " "ordinal, for example latency-budget#1, so a checker can reload the exact text. " "Verification then becomes decidable: does the cited chunk exist, does it contain " "the number in the claim, does the quote appear verbatim. An answer with no " "citation is not automatically wrong, but it is unverifiable, and the difference " "matters when a downstream step trusts the number." ),"cdn-transfer": ( "Chunked transfer encoding splits an HTTP response into chunks of up to 64 KB so " "a proxy can forward bytes before the origin finishes writing. The chunk size is a " "transport decision, unrelated to how much text a reader can absorb at once, and " "changing it never changes answer quality. A CDN that buffers whole responses " "defeats the purpose: the first byte arrives only after the last chunk." ), "cache-latency": ( "A read-through cache in front of the index drops p95 latency from 240 ms to 9 ms " "for repeated queries, but the hit rate on a research workload is 31 percent " "because every run asks new questions. Cache the embedding of a query, not the " "result of a search, and the hit rate rises to 68 percent without returning stale " "passages." ), "document-store": ( "A document database stores JSON documents and indexes their fields. Retrieving a " "document by primary key is a hash lookup and takes microseconds; retrieving by an " "unindexed field is a full collection scan. Documents in this sense are rows, not " "prose, and no amount of chunk size tuning changes that." ), "self-critique": ( "Asking a model to reflect on its answer in the abstract produces longer answers " "with the same errors. The model has no new information, so the critique restates " "the answer with more confident wording. Reflection helps only when the critique is " "given evidence the first pass did not have, or a checker it cannot argue with." ), "ide-plan-mode": ( "Plan mode in an editor writes a plan file, waits for approval, then executes. When " "a step fails the developer edits the plan by hand and reruns; there is no automatic " "replan and no dependency graph, which is fine because a human is the scheduler." ), "prompt-caching": ( "Prompt caching bills the unchanged prefix at a tenth of the input price. The " "saving depends on prefix stability: an agent that injects a timestamp into the " "system message invalidates the cache on every call and pays full price for a " "prefix it just sent." ),}ఇక్కడి embedder అక్షర n-gram హ్యాషింగ్ ఫంక్షన్; ట్రైన్ చేసిన మోడల్ కాదు. ఇది ఫజ్జీ అంచులున్న పదాభాస మ్యాచర్: 4-gram లు పంచుకున్నందుకు retrieve ని retrieval తో జోడిస్తుంది, కానీ నిజమైన సమానార్థక పదాలపై విఫలమవుతుంది. ఈ పరిమితి ఉద్దేశపూర్వకమే; కొలతల విభాగం దాని ఖరీదు ఎంతో ఖచ్చితంగా చూపుతుంది — ఎందుకంటే కొలవలేని రిట్రీవర్ను మెరుగుపరచలేం.
ఐదు ఎంట్రీల డిక్షనరీ నిజానికి ఏమి ఖరీదు
మూడు వైఫల్యాలు; అన్నీ ప్రస్తుత కోడ్లోనే పునఃసృష్టించినవి.
మిస్ అయినట్టు, ఖాళీ కార్పస్ అయినట్టు ఒకదానికొకటి తేల్చలేం. ఏ కీ కూడా సరిపోకపోతే _search ["no matches"] తిరిగిస్తుంది, అది ok=True అవుతుంది. ఈ అంశం గురించి కార్పస్లో ఏమీ లేదని మోడల్ దీన్ని సాక్ష్యంగా చదువుతుంది. భాగం 2 టైమౌట్ కేసును వర్గీకృత ఎర్రర్తో సరిచేసింది; కానీ మిస్ కేసు ఇప్పటికీ డేటా వేషంలో అబద్ధమే.
సైటేషన్ లేదు. టూల్ సాదా స్ట్రింగ్లను తిరిగిస్తుంది. మోడల్ తుది సమాధానం రాసేటప్పుడు, అందులో ఒక పేసేజీని చూపించే లింకు ఏమీ ఉండదు; ఫలితంగా వినియోగదారు వాదనను సరిచూడలేడు, భాగం 7 కూడా ధృవీకరించలేదు.
రిట్రీవల్ యూనిట్ ఒత్తు డాక్యుమెంట్. నిజమైన కార్పస్ ఉన్నా సరే, పూర్తి డాక్యుమెంట్లను తిరిగివ్వడం అంటే ఒక్క హిట్కి 4,000 అక్షరాల ముద్ద. 420 అక్షరాల నాలుగు హిట్లు సుమారు 420 token ల కాంటెక్స్ట్; నాలుగు పూర్తి డాక్యుమెంట్లు 4,000. అప్పుడు భాగం 3 బడ్జెట్ రిట్రీవర్ పంపనూడని టెక్స్టును కుదించడంలోనే తన శక్తిని ఖర్చు చేస్తుంది.
ఈ వ్యాసంలోని మిగతా భాగం ఈ మూడింటినీ నిర్మాణంలోనే సరిచేస్తుంది: చంక్లు యూనిట్ను చిన్నది చేస్తాయి, సైటేషన్లు అవుట్పుట్ను సరిచూచగలిగించాయి, ప్రాసంగత్య ఫ్లోర్ మిస్ను వర్గీకృత ఎర్రర్గా మారుస్తుంది.
చంకింగ్: వెనక్కి తిరగలేని నిర్ణయం
చంక్ సరిహద్దులే మార్చడానికి ఖరీదైన ఏకైక రిట్రీవల్ నిర్ణయం — ఎందుకంటే వాటిని మార్చాలంటే మొత్తం కార్పస్కు మళ్లీ embedding చేయాలి. మిగతావన్నీ — స్కోరింగ్ ఫంక్షన్, ఫ్యూజన్ స్థిరాంకం, రీర్యాంకర్ — ఒక మధ్యాహ్నంలో ట్యూన్ చేయగలం.
పరిమితుల జోడీ సరళం. మరీ పెద్ద చంక్లు పలుచబడతాయి: మూడు సంబంధం లేని అంశాలున్న 900-అక్షరాల చంక్ మూడింటికీ ర్యాంక్ అవుతుంది గానీ ఏ దానికీ ఖచ్చితంగా సమాధానం ఇవ్వదు — ఎందుకంటే embedding అంతా లోపలివాటి సగటు. మరీ చిన్న చంక్లు తమ సొంత వ్యాకరణాన్ని కోల్పోతాయి: 120-అక్షరాల ముక్క తరచుగా It తో మొదలవుతుంది, దానికి పూర్వసూచకం (antecedent) ఉండదు — దీన్ని ఎటువంటి రీర్యాంకర్ కూడా సరిచేయలేదు.
from __future__ import annotations
from dataclasses import dataclassimport hashlibimport jsonimport mathimport refrom collections import Counter
from contracts import ErrorCode, Tool, ToolResult
CHUNK_CHARS = 420OVERLAP_CHARS = 90SENTENCE = re.compile(r"(?<=[.!?])\s+")WORD = re.compile(r"[a-z0-9]+")STOP = frozenset( "the and for with that this from are was were what when how why into than then " "does did can could should would your you our its it is of to in on by as at be".split())
def words(text: str) -> list[str]: return [w for w in WORD.findall(text.lower()) if len(w) > 2 and w not in STOP]
@dataclass(frozen=True)class Chunk: id: str doc_id: str text: str ordinal: int = 0
@property def citation(self) -> str: return "%s#%d" % (self.doc_id, self.ordinal)
def chunk_document(doc_id: str, text: str, max_chars: int = CHUNK_CHARS, overlap_chars: int = OVERLAP_CHARS) -> list[Chunk]: """Split on sentence boundaries, pack to max_chars, carry a tail overlap.""" sentences = [s.strip() for s in SENTENCE.split(text.strip()) if s.strip()] packs: list[str] = [] buf: list[str] = [] size = 0 for sentence in sentences: if buf and size + len(sentence) + 1 > max_chars: packs.append(" ".join(buf)) tail: list[str] = [] tail_size = 0 for prev in reversed(buf): if tail_size + len(prev) > overlap_chars: break tail.insert(0, prev) tail_size += len(prev) + 1 buf, size = tail, tail_size buf.append(sentence) size += len(sentence) + 1 if buf: packs.append(" ".join(buf)) return [Chunk("%s#%d" % (doc_id, i), doc_id, body, i) for i, body in enumerate(packs)]ముప్పై లైన్లలో నాలుగు నిర్ణయాలు; ప్రతి దానికీ ఒక ఖరీదు.
వాక్యాల వద్ద విభజించి, అక్షర బడ్జెట్కు ప్యాక్ చేయాలి. పదం మధ్యలో విభజిస్తే మొదటి టోకెన్ ముక్కలావుతుంది — ఇది embedding ని కూడా కోట్ను కూడా విషపూరితం చేస్తుంది. రెగ్యులర్ ఎక్స్ప్రెషన్ స్పేస్ వెంట వచ్చే ., ! లేదా ? తర్వాత మాత్రమే విడుస్తుంది; అందువల్ల e.g. లాంటి సంక్షిప్త రూపాలు తప్పుగా విడిపోతాయి — నష్టం ఒక అదనపు సరిహద్దు మాత్రమే కావడంతో ఇది ఓకే.
420 అక్షరాలు, 512 token లు కాదు. టోకెన్కి సుమారు నాలుగు అక్షరాల చొప్పున ఇది ఒక్కో చంక్కి సుమారు 105 token లవుతుంది. సంఖ్య కంటే నిష్పత్తి ముఖ్యం: ఒక్కోదానికి 105 token లున్న నాలుగు రిట్రీవ్ చేసిన చంక్లు 420 token ల సాక్ష్యం — 300-token సిస్టమ్ ప్రాంప్ట్తో కలిపి కూడా భాగం 3 బడ్జెట్లో సౌకర్యంగా కుదురుతుంది. 1,000-token చంక్ క్యాప్ పెడితే నాలుగు హిట్ల ఖరీదు 4,000 token లవుతుంది; మీరు ఖర్చు చేసి తెచ్చుకున్న టెక్స్టునే కుదించమని బడ్జెట్ను బలవంతం చేస్తుంది.
ఓవర్ల్యాప్ అంటే టెయిల్ కాపీ, స్లైడింగ్ విండో కాదు. ఫ్లష్ తర్వాత 90 అక్షరాల్లో కుదిరే చివరి వాక్యాలు కొత్త బఫర్లో మళ్లీ తెరుచుకుంటాయి. ఈ సెట్టింగ్లలో ఫలితం 21 శాతం ఇండెక్స్ ద్రోణిక (420 లో 90) — పైగా ఒక హామీ: సరిహద్దు మీద పడిన వాక్యం అయినా ఒక వైపు నుంచైనా రిట్రీవ్ చేయగలం. టోకెన్ లెక్కతో స్లైడింగ్-విండో చంకింగ్ అదే హామీ ఇస్తుంది గానీ వాక్యం మధ్యలో మొదలయ్యే చంక్లను ఇస్తుంది — మేము తప్పించుకోబోయేది అదే.
ordinal అంటే సైటేషన్; అందుకే అది స్థిరంగా ఉండాలి. chunking#1 అంటే chunking డాక్యుమెంట్లోని రెండో చంక్. వేరే సెట్టింగ్లతో మళ్లీ చంక్ చేస్తే పాత సమాధానాల్లోని ప్రతి సైటేషన్ వేరే చోటు చూపిస్తుంది. అందుకే సెట్టింగ్లు ఇండెక్స్ బిల్డ్లో భాగంగా కార్పస్ వెర్షన్ పక్కనే రికార్డవుతాయి; మళ్లీ చంక్ చేయడం కాన్ఫిగ్ మార్పు కాదు, మైగ్రేషన్.
ఇన్వర్టెడ ఇండెక్స్ నుంచి BM25
BM25 అనేది పదాభాస స్కోరర్; సరళమైన పద లెక్కలను ఇప్పటికీ దాటిపోయే రెండు ఆలోచనలు ఉన్నాయి. పద పౌనఃపున్యం సంతృప్తం అవుతుంది: ఒక చంక్లో latency పదం పదవిసారి వచ్చినా ఐదోసారితో పోలిస్తే దాదాపు ఏమీ చేరదు — ఎందుకంటే చంక్ ఇప్పటికే లేటెన్సీ గురించే ఉంది. పొడవు సామాన్యీకరణ (length normalisation) పొడవాటి చంక్లు కేవలం పరిమాణంతో గెలవకుండా ఆపుతుంది.
class BM25Index: """Okapi BM25 over an inverted index. No dependency, no service."""
def __init__(self, k1: float = 1.2, b: float = 0.75) -> None: self.k1 = k1 self.b = b self.chunks: dict[str, Chunk] = {} self.postings: dict[str, dict[str, int]] = {} self.lengths: dict[str, int] = {} self.avg_len = 0.0
def add(self, chunks: list[Chunk]) -> None: for chunk in chunks: tokens = words(chunk.text) self.chunks[chunk.id] = chunk self.lengths[chunk.id] = len(tokens) for term, count in Counter(tokens).items(): self.postings.setdefault(term, {})[chunk.id] = count total = sum(self.lengths.values()) self.avg_len = total / len(self.lengths) if self.lengths else 0.0
def idf(self, term: str) -> float: n = len(self.chunks) df = len(self.postings.get(term, {})) return math.log(1.0 + (n - df + 0.5) / (df + 0.5))
def search(self, query: str, k: int = 20) -> list[tuple[str, float]]: scores: Counter[str] = Counter() for term in words(query): idf = self.idf(term) if idf <= 0: continue for chunk_id, tf in self.postings.get(term, {}).items(): norm = tf + self.k1 * ( 1 - self.b + self.b * self.lengths[chunk_id] / max(self.avg_len, 1e-9) ) scores[chunk_id] += idf * tf * (self.k1 + 1) / norm return [(cid, round(score, 4)) for cid, score in scores.most_common(k)]idf <= 0 గార్డ్ రక్షక చప్పుడు కాదు. +0.5 స్మూదింగ్తో, ప్రతి చంక్లోనూ కనిపించే పదం log(1 + 0.5/(n+0.5)) పొందుతుంది — అది పాజిటివ్ అయినా అతి చిన్నది; దాదాపు 80 శాతం చంక్లలో కనిపించే పదం దాదాపు ఏమీ చేర్చదు, గుణకారానికి విలువ లేదు. దాన్ని వదిలేయడం వల్ల సామాన్య పదాల ఫ్లోర్ సంబంధం లేని చంక్ల మధ్య సమాన స్కోర్లను సృష్టించకుండా ఉంటుంది.
స్కోరింగ్ లూప్ చంక్లపై కాదు, పోస్టింగ్స్ పై నడుస్తుంది. అదే వేగం ఇచ్చేది: నాలుగు మిగిలిన పదాలున్న క్వెరీ నాలుగు పోస్టింగ్ జాబితాల సమ్మేళనాన్ని తాకుతుంది — 19 చంక్లపై ఇది కొన్ని పదహారు ఇంటిజర్ పెంపుదలలే, 50,000 చంక్లపై కొన్ని వేలు. కొలిచిన ఖరీదు డెమో కార్పస్పై క్వెరీకి 0.015 ms; 20,000 చంక్లపై సుమారు 4 ms — ఇది కార్పస్ పరిమాణంలో కాదు, పోస్టింగ్స్లో రేఖీయం.
k1, b లను ట్యూన్ చేసే ముందు తెలుసుకోవాల్సిన రెండు పరిమితులు. BM25 ఎన్నడూ చూడని పదాన్ని సరిపోల్చలేదు: retrieve క్వెరీ, retrieval మాత్రమే కలిగిన చంక్పై సున్నా స్కోరు వస్తుంది — ఎందుకంటే టోకెన్లు భిన్నం. అర్థం ప్రకారం ర్యాంక్ చేయలేదు: point an answer at its source క్వెరీ, సైటేషన్ id లను వివరించే చంక్పై సున్నా — ఎందుకంటే ప్రతి కంటెంట్ పదం సమానార్థకం. dense శాఖ ఉనికికి కారణమైన ఈ రెండు వైఫల్యాలను ఆవరించడమే.
dense శాఖ, రెండు ర్యాంకింగ్ల మేళవింపు
dense రిట్రీవర్ టెక్స్టును వెక్టర్కు మ్యాప్ చేసి కోసైన్ సారూప్యంతో ర్యాంక్ చేస్తుంది. ప్రొడక్షన్లో ఆ వెక్టర్ ట్రైన్ చేసిన sentence-embedding మోడల్ నుంచి వస్తుంది. ఆఫ్లైన్లో, డిపెండెన్సీ లేకుండా, key లేకుండా, నిజాయితీ ప్రతినిధి అక్షర n-gram హ్యాషింగ్: ఇది రూపవిజ్ఞానాన్ని (morphology), పంచుకున్న సబ్స్ట్రింగ్లను పట్టుకుంటుంది — BM25 లేని, సంకుచితమైనా నిజమైన సామాన్యీకరణ రూపం ఇది.
class HashedEmbedder: """Character n-gram hashing embedder: deterministic, offline, morphology-tolerant.
Swap this class for a sentence-embedding model behind the same embed() contract; everything downstream only needs a unit-norm vector. """
def __init__(self, dim: int = 512, n: int = 4) -> None: self.dim = dim self.n = n
def _grams(self, text: str) -> list[str]: cleaned = re.sub(r"[^a-z0-9]+", " ", text.lower()) out: list[str] = [] for word in cleaned.split(): padded = "#" + word + "#" for i in range(max(1, len(padded) - self.n + 1)): out.append(padded[i:i + self.n]) return out
def embed(self, text: str) -> list[float]: vec = [0.0] * self.dim for gram in self._grams(text): digest = hashlib.blake2b(gram.encode("utf-8"), digest_size=8).digest() index = int.from_bytes(digest[:4], "big") % self.dim sign = 1.0 if digest[4] & 1 else -1.0 vec[index] += sign norm = math.sqrt(sum(v * v for v in vec)) or 1.0 return [v / norm for v in vec]
def cosine(a: list[float], b: list[float]) -> float: return sum(x * y for x, y in zip(a, b))
class VectorIndex: """Brute-force cosine search. Fast enough to 50k chunks; swap for FAISS later."""
def __init__(self, embedder: HashedEmbedder | None = None) -> None: self.embedder = embedder or HashedEmbedder() self.chunks: dict[str, Chunk] = {} self.matrix: dict[str, list[float]] = {}
def add(self, chunks: list[Chunk]) -> None: for chunk in chunks: self.chunks[chunk.id] = chunk self.matrix[chunk.id] = self.embedder.embed(chunk.text)
def search(self, query: str, k: int = 20) -> list[tuple[str, float]]: probe = self.embedder.embed(query) scored = [(cid, cosine(probe, vec)) for cid, vec in self.matrix.items()] scored.sort(key=lambda pair: (-pair[1], pair[0])) return [(cid, round(score, 4)) for cid, score in scored[:k] if score > 0]embedder ను మార్చినా ఈ ఇండెక్స్ను ఉంచుకోవడం విలువైనది చేసే మూడు లక్షణాలు. వెక్టర్ unit-norm; కావున కోసైన్ అంటే డాట్ ప్రొడక్ట్, చంక్ పొడవుల అంతటా స్కోర్లు పోల్చదగినవి. హ్యాషింగ్ signed; కొలైజన్లు సగటున రద్దవుతాయి తప్ప తప్పుడు సారూప్యత పేరుకోదు. శోధన brute force; 19 చంక్లపై ఇది 0.6 ms, 50,000 చంక్లపై స్వచ్ఛమైన Python లో సుమారు 400 ms — గమనించేంత నెమ్మది; అంత దూరం చేరుకున్నప్పుడు నిజమైన ఇండెక్స్ పెట్టడానికి సమర్థన ఇచ్చేంత నెమ్మది.
ఇప్పుడు ఫ్యూజన్. BM25 స్కోర్లు అనంతంగా వెళ్తాయి; కోసైన్ [-1, 1] లో ఉంటుంది. వీటిని కూడగట్టడం వర్గ దోషం; సామాన్యీకరించాలంటే క్వెరీతో మారే ప్రతి-క్వెరీ గణాంకాలు కావాలి. Reciprocal rank fusion ర్యాంక్ స్థానాన్ని మాత్రమే స్కోర్ చేసి రెండింటినీ దాటవేస్తుంది.
def reciprocal_rank_fusion(rankings: list[list[tuple[str, float]]], k: int = 60) -> list[tuple[str, float]]: """RRF: score by rank position, not by raw score. Immune to scale mismatch.""" fused: dict[str, float] = {} for ranking in rankings: for rank, (chunk_id, _score) in enumerate(ranking, start=1): fused[chunk_id] = fused.get(chunk_id, 0.0) + 1.0 / (k + rank) return sorted(fused.items(), key=lambda pair: (-pair[1], pair[0]))
@dataclassclass Passage: chunk: Chunk fused_score: float bm25_rank: int | None = None vector_rank: int | None = None rerank_score: float = 0.0
class HybridRetriever: """BM25 + vector, fused by RRF. Named Hybrid because Part 4's Retriever is the memory scorer."""
def __init__(self, chunks: list[Chunk], embedder: HashedEmbedder | None = None, pool: int = 20, rrf_k: int = 60) -> None: self.bm25 = BM25Index() self.bm25.add(chunks) self.vectors = VectorIndex(embedder) self.vectors.add(chunks) self.chunks = {c.id: c for c in chunks} self.pool = pool self.rrf_k = rrf_k
def retrieve(self, query: str, k: int = 5) -> list[Passage]: lexical = self.bm25.search(query, k=self.pool) dense = self.vectors.search(query, k=self.pool) rank_bm25 = {cid: i for i, (cid, _) in enumerate(lexical, start=1)} rank_vector = {cid: i for i, (cid, _) in enumerate(dense, start=1)} fused = reciprocal_rank_fusion([lexical, dense], k=self.rrf_k) return [ Passage(self.chunks[cid], score, rank_bm25.get(cid), rank_vector.get(cid)) for cid, score in fused[:k] ]k=60 ప్రచురించిన డీఫాల్ట్; ఇది ఒక ప్రత్యేక నమ్మకాన్ని కుదిపేర్చుకుంది: జాబితాల మధ్య ఏకముఖత్వం, ఒక్క జాబితా లోపలి ఆధిపత్యం కంటే ముఖ్యం. ఒక జాబితాలో ర్యాంక్ 1 లున్న చంక్ 1/61 = 0.0164 స్కోరు చేస్తుంది; రెండు జాబితాలలోనూ ర్యాంక్ 2 లున్న చంక్ 1/62 + 1/62 = 0.0323. రెండోది గెలుస్తుంది — ఒక జాబితా పదాభాసమై, మరొకటి సెమాంటిక్ అయినప్పుడు కావాల్సిందే ప్రవర్తన ఇది. k ని 10 కు తగ్గిస్తే ఒకే జాబితా విజేత చాలా బలంగా మారుతుంది — ఒక రిట్రీవర్ స్పష్టంగా మెరుగైనది, మరొకదాన్ని నుంచి చిన్న టై-బ్రేక్ మాత్రమే కావాలంటే ఉపయోగకరం.
నిజాయితీ కొలత డిజైన్ను మార్చే చోటది. ఇదిగో హార్నెస్ — పందొమ్మిది చంక్లపై, లేబుల్ చేసిన ఎనిమిది క్వెరీలపై నడిచింది:
import corpusimport rag
QUERIES = [ ("what window size should a passage have", "chunking"), ("combining keyword and embedding rankings", "retrieval-design"), ("tail latency after adding a reranker", "latency-budget"), ("the plan changes after a step fails", "planner"), ("critique loops that never terminate", "reflection"), ("point an answer at its source", "citations"), ("does overlap inflate the index size", "chunking"), ("cheapest way to cut repeated prefix cost", "prompt-caching"),]
def evaluate(name: str, rank_fn, k: int = 3) -> None: p1 = recall = mrr = 0.0 for query, expected in QUERIES: docs = rank_fn(query, k) p1 += 1.0 if docs[:1] == [expected] else 0.0 recall += 1.0 if expected in docs else 0.0 mrr += 1.0 / (docs.index(expected) + 1) if expected in docs else 0.0 n = len(QUERIES) print("%-14s P@1=%.2f Recall@%d=%.2f MRR=%.3f" % (name, p1 / n, k, recall / n, mrr / n))
def main() -> None: r = rag.CorpusRetriever(corpus.DOCUMENTS) r.hybrid.pool = 12 evaluate("bm25", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.bm25.search(q, k=n)]) evaluate("vector", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.vectors.search(q, k=n)]) evaluate("hybrid", lambda q, n: [p.chunk.doc_id for p in r.hybrid.retrieve(q, k=n)]) evaluate("hybrid+rerank", lambda q, n: [p.chunk.doc_id for p in r.search(q, limit=n)])
if __name__ == "__main__": main()bm25 P@1=0.62 Recall@3=0.88 MRR=0.750vector P@1=0.38 Recall@3=0.88 MRR=0.604hybrid P@1=0.50 Recall@3=0.88 MRR=0.667hybrid+rerank P@1=0.50 Recall@3=0.88 MRR=0.667మొదటి కాలమ్ కాదు, రెండో కాలమ్ చదవాలి. Recall అంటే కాండిడేట్ పూల్ ఉనికికి కారణమే; పూల్ పరిమాణం ముఖ్యం: 19 చంక్లపై pool=12 వద్ద BM25 టాప్ 12 లో 8 క్వెరీలలో 7 దానికి సరైన డాక్యుమెంట్ ఉంది; dense శాఖకు 8 లో 8; కావున సమ్మేళనం 8 లో 8. ఒక క్వెరీ — combining keyword and embedding rankings — పూర్తి పదాభాస మిస్; దాని అంశ చంక్లో keyword, embedding లేదా rankings పదాలు లేవు; హ్యాష్డ్ embedder పంచుకున్న rank 4-gram ల ద్వారా దాన్ని కనుగొంటుంది. ఈ స్కేల్లో dense శాఖకు మద్దతు ఇచ్చే మొత్తం వాదన ఆ ఒక్క క్వెరీ: మెరుగైన ర్యాంకింగ్ కాదు, సమాధానాన్ని నిశ్శబ్దంగా పోగొట్టని పూల్.
మొదటి కాలమ్ చదివితే చిత్రం అంత వర్ణనీయం కాదు: precision లో BM25 గెలుస్తుంది; ఫ్యూజన్ BM25 ఒంటరితో పోలిస్తే P@1 లో 12 పాయింట్లు కోల్పోతుంది. ఇది RRF లోని బగ్ కాదు. ఇది dense శాఖలోని బగ్; ఖచ్చితంగా చెప్పాలి: అక్షర n-gram embedder అంటే వేరే వెయిటింగ్ స్కీమ్తో కూడిన పదాభాస మ్యాచర్; BM25 తో దీన్ని కలిపితే అదే సాక్ష్యానికి రెండు దృష్టులు కలియగా, విభేదాలు నాయిస్ మాత్రమే. మూడు పదాభాస మ్యాచర్లు సెమాంటిక్స్గా కూడవు.
పరిష్కారం k ను ట్యూన్ చేయడం కాదు. పరిష్కారం HashedEmbedder స్థానంలో ట్రైన్ చేసిన మోడల్ పెట్టడం — దీనితో విభేదాల స్వభావం నాయిస్ నుంచి సిగ్నల్కు మారుతుంది. దిగువన ఉన్నదంతా — ఫ్యూజన్, reranking, సైటేషన్, టూల్ ఒప్పందం — అలాగే ఉంటుంది; ఎందుకంటే పైప్లైన్లో మిగతా భాగానికి కావాల్సిందల్లా embed(text) -> list[float] మాత్రమే. ఇంటర్ఫేస్ను షిప్ చేయాలి, శాఖను కొలవాలి; శాఖ బలహీనమని కొలత చెబితేనే మోడల్ కొనాలి. దీన్ని తెలుసుకోవడానికి ఈ హార్నెసే మార్గం.
రీర్యాంకింగ్: లేటెన్సీ చెల్లించి, precision కొనడం
ఫ్యూజన్ మంచి recall గల, సాధారణ క్రమాన్నిచ్చే పూల్ ఇస్తుంది. రీర్యాంకర్ ప్రతి క్వెరీ-పేసేజీ జోడీని స్వతంత్రంగా కాకుండా కలిపి స్కోర్ చేసి క్రమాన్ని సరిచేస్తుంది. cross-encoder క్వెరీనీ, పేసేజీనీ ఒకే ఫార్వర్డ్ పాస్లో చూస్తుంది; కావున not, only పదాలు, పద క్రమం — BM25 తోనూ, bag-of-ngrams embedding తోనూ పట్టలేనివి — దీనికి అర్థమవుతాయి.
కింది నిర్ధారక ప్రతినిధి పద కవరేజీని, ఖచ్చిత పదబంధం ఉనికిని, పొసగిన క్వెరీ పదాల సాన్నిహిత్యాన్ని స్కోర్ చేస్తుంది. ఇది cross-encoder కాదు; ఇది రీర్యాంకర్ ఆకారపు ఫంక్షన్ — ఖరీదైనదేదైనా అమర్చే ముందే పైప్లైన్, థ్రెషోల్డ్, టెస్ట్లన్నీ ఉండేలా చేసేది.
class CoverageReranker: """Deterministic stand-in for a cross-encoder: term coverage, phrase hit, proximity."""
def __init__(self, phrase_weight: float = 0.25, proximity_weight: float = 0.15) -> None: self.phrase_weight = phrase_weight self.proximity_weight = proximity_weight
@staticmethod def _proximity(query_terms: list[str], passage_terms: list[str]) -> float: positions: dict[str, list[int]] = {} for i, term in enumerate(passage_terms): positions.setdefault(term, []).append(i) best = 0.0 for left, right in zip(query_terms, query_terms[1:]): for i in positions.get(left, []): for j in positions.get(right, []): gap = abs(i - j) if 0 < gap <= 6: best = max(best, 1.0 - (gap - 1) / 6.0) return best
def score(self, query: str, passage: Passage) -> float: query_terms = words(query) if not query_terms: return 0.0 passage_terms = words(passage.chunk.text) covered = len(set(query_terms) & set(passage_terms)) / len(set(query_terms)) phrase = 1.0 if query.strip().lower() in passage.chunk.text.lower() else 0.0 proximity = self._proximity(query_terms, passage_terms) return (covered + self.phrase_weight * phrase + self.proximity_weight * proximity)కవరేజీని ప్రత్యేక క్వెరీ పదాల సంఖ్యతో సామాన్యీకరిస్తారు; అందువల్ల రెండు-పదాల క్వెరీ అయిష్టంగా ఆరు-పదాల క్వెరీ కంటే ఎక్కువ స్కోరు చేయలేదు. పదబంధ బోనస్ బైనరీ, ఒక పావు బరువు తోస్తుంది: ఖచ్చిత సబ్స్ట్రింగ్ మ్యాచ్ బలమైన సాక్ష్యం; అయినా పదబంధం అక్షరాలా లేకుండానే చంక్ సరైనది కావచ్చు. సాన్నిహిత్యం ఆరు-టోకెన్ విండోకు పరిమితం — దాటితే రెండు పదాలు సంబంధితం కాదు, ఒకేసారి వచ్చినవి మాత్రమే — పైగా ఇది పొసగిన క్వెరీ పదాలపై మాత్రమే పనిచేస్తుంది: latency ... reranker ఏ క్రమంలోనైనా లెక్కవుతుంది గానీ latency ... chunk లెక్కవదు.
రీర్యాంకర్ చేయలేనిది ఎంతో పైన కొలత చూపింది: డెమో కార్పస్పై అది ఏమీ మార్చదు — ఎందుకంటే ఇది మూడో పదాభాస మ్యాచర్. దాని నిజమైన విలువ cross-encoder వచ్చాక వస్తుంది; నిజాయితీ ఇంజినీరింగ్ ప్రశ్న: దాన్ని మీరు భరించగలరా అనేది.
దీన్ని ప్రారంభించే ముందు లెక్క వేయాలి. 12-లేయర్ cross-encoder 20 కాండిడేట్ జోడీలపై CPU లో ఒక్కో జోడీకి సుమారు 10 ms — క్వెరీకి 200 ms; 8 జోడీలకు పరిమితితే 80 ms. ఒక్క రన్లో ఐదు శోధనలు 400 ms చేరుస్తాయి — ఒక LLM రౌండ్ ట్రిప్తో సమానం; ఇది సామాన్యంగా ఓకే, గానీ టూల్ p95 40 ms ఉండి agent మొత్తం బడ్జెట్ రెండు సెకన్లు అయితే అంగీకరించరానిది. దీన్ని పరిమితంగా ఉంచే రెండు లీవర్లు: రీర్యాంక్ సెట్కు క్యాప్ (8 మంచి డీఫాల్ట్; 9వ కాండిడేట్ టాప్ 4 ని అరుదుగా మారుస్తాడు) మరియు ఫ్యూజన్ మార్జిన్ పెద్దగా ఉంటే రీర్యాంకింగ్ దాటవేయడం (టాప్ పేసేజీ రెండోదాన్ని 2× కంటే ఎక్కువ తేడాతో దాటి వెళ్తే క్రమం దగ్గరగా లేదు).
టూల్ రిజిస్ట్రీలో అమర్చడం
టూలే కుట్టు పట్టీ. అది సైటేషన్లను తిరిగివ్వాలి, భాగం 2 స్కీమాకు లోబడాలి, ఖాళీ ఫలితాన్ని no matches కాకుండా వర్గీకృత ఎర్రర్గా మార్చాలి.
class CorpusRetriever: """Chunk once, then serve top-k passages through hybrid recall plus reranking."""
def __init__(self, documents: dict[str, str], embedder: HashedEmbedder | None = None, reranker: CoverageReranker | None = None, max_chars: int = CHUNK_CHARS, overlap_chars: int = OVERLAP_CHARS, min_score: float = 0.05) -> None: chunks: list[Chunk] = [] for doc_id, text in documents.items(): chunks.extend(chunk_document(doc_id, text, max_chars, overlap_chars)) self.chunks = chunks self.hybrid = HybridRetriever(chunks, embedder) self.reranker = reranker or CoverageReranker() self.min_score = min_score
def search(self, query: str, limit: int = 4) -> list[Passage]: pool = self.hybrid.retrieve(query, k=max(limit * 4, 12)) for passage in pool: passage.rerank_score = self.reranker.score(query, passage) pool.sort(key=lambda p: (-p.rerank_score, -p.fused_score, p.chunk.id)) return [p for p in pool[:limit] if p.rerank_score >= self.min_score]
def passage_block(self, query: str, limit: int = 4, max_chars: int = 1800) -> str: hits = self.search(query, limit) if not hits: return "" lines = ["EVIDENCE (cite as [doc#n]; do not paraphrase numbers):"] for passage in hits: lines.append("[%s] %s" % (passage.chunk.citation, passage.chunk.text)) return "\n".join(lines)[:max_chars]
def make_search_tool(retriever: CorpusRetriever) -> Tool: """Replaces the five-entry dictionary in Part 1 with a real corpus backend."""
def _run(args: dict) -> ToolResult: query = str(args.get("query", "")) limit = int(args.get("limit", 4)) hits = retriever.search(query, limit) if not hits: return ToolResult(ok=False, data="", error="no passage scored above zero for: " + query, error_code=ErrorCode.NOT_FOUND.value) payload = [ { "citation": p.chunk.citation, "doc": p.chunk.doc_id, "text": p.chunk.text, "score": round(p.rerank_score, 3), } for p in hits ] return ToolResult(ok=True, data=json.dumps(payload, ensure_ascii=False))
return Tool( name="search", description=( "Search the local research corpus. Returns JSON passages, each with a " "citation id of the form doc#n. Cite these ids in your final answer." ), parameters={ "type": "object", "properties": { "query": {"type": "string", "minLength": 2, "maxLength": 200}, "limit": {"type": "integer", "minimum": 1, "maximum": 10}, }, "required": ["query"], "additionalProperties": False, }, _fn=_run, )min_score=0.05 అంటే ప్రాసంగత్య ఫ్లోర్; టెస్ట్లు చూపించే కారణంతో ఇది బోనులా ముఖ్యం: ఇది లేకపోతే పిచ్చి క్వెరీలకు హ్యాష్డ్ embedder చిన్న పాజిటివ్ కోసైన్ల కొలైజన్లను తిరిగిస్తుంది; ఎర్రర్ బదులు agent నాలుగు సంబంధం లేని పేసేజీలను పొందుతుంది. ఫ్లోర్ దీన్ని ERROR[not_found] గా మారుస్తుంది — మోడల్ దీన్ని ఈ కార్పస్ ఆ అంశాన్ని కవర్ చేయదు అంటూ చదువుతుంది; అది నిజమే.
limit=4 కూడా బడ్జెట్ నిర్ణయమే. ఒక్కోదానికి 105 token లున్న నాలుగు పేసేజీలు 420 token లు; పైగా సైటేషన్ బోను సుమారు 30 token లు. రెండు హిట్లు చవక అయినా తరచుగా సరిపోవు — సమాధానం తరచుగా నిర్వచన చంక్, ఉదాహరణ చంక్ల మధ్య పగిలి ఉంటుంది. ఆరు వద్ద precision, recall పెరుగుదల కంటే వేగంగా పడిపోవడం మొదలవుతుంది.
ఇంటిగ్రేషన్ ఒక్క లైన్ — AgentLoop ఇప్పటికే టూల్ జాబితాను అంగీకరిస్తుంది:
import corpusimport ragfrom contracts import AgentLoop, ScriptedLLM, build_tools
retriever = rag.CorpusRetriever(corpus.DOCUMENTS)tools = [rag.make_search_tool(retriever)] + [t for t in build_tools() if t.name != "search"]
script = [ {"type": "tool", "name": "search", "arguments": {"query": "tail latency after adding a reranker", "limit": 2}}, {"type": "final", "content": "A cross-encoder reranker over 20 candidates costs about 200 ms per " "query; capping at 8 candidates brings it under 100 ms [latency-budget#0]."},]agent = AgentLoop(ScriptedLLM(script), tools, max_steps=3)print(agent.run("What does reranking cost in latency?"))print("tool ok:", agent.trace[0]["ok"], "attempts:", agent.trace[0]["attempts"])A cross-encoder reranker over 20 candidates costs about 200 ms per query; capping at 8 candidates brings it under 100 ms [latency-budget#0].tool ok: True attempts: 1[t for t in build_tools() if t.name != "search"] ఫిల్టరే మొత్తం మైగ్రేషన్. లూప్, ఎగ్జిక్యూటర్, రీట్రై పాలసీ, ఐడెంపోటెన్సీ స్టోర్ ఏవీ తాకబడలేదు; మోడల్ ఇప్పటికీ స్కీమా ఉన్న search అనే టూల్నే చూస్తుంది.
వైఫల్య రీతులు, వాటిని ఎలా నిర్వహించాలి
| వైఫల్యం | నిజానికి ఏం జరుగుతుంది | ఇక్కడ నిర్వహణ | ఇంకా పగిలి ఉన్నది |
|---|---|---|---|
| చంక్ ఒక టేబుల్ను లేదా జాబితాను పగలగొడతాయి | వరుసలు వేరే చంక్లలో పడతాయి; ఏ దానితోనూ సమాధానమవదు | యత్ర వీలమైతే వాక్య విభజన వరుసలను కలిపి ఉంచుతుంది | Markdown టేబుల్లకు నిర్మాణ విభజన కావాలి |
| క్వెరీ, కార్పస్ వేరే పదాలు వాడతాయి | BM25 ఏమీ ఇవ్వదు; హ్యాష్డ్ embedding చప్పుడు ఇస్తుంది | dense శాఖ + ఫ్యూజన్ | నిజమైన సమానార్థకాలకు ట్రైన్ చేసిన మోడల్ కావాలి |
| ప్రతి హిట్ సంబంధం లేనిది | వాదనకు ఆధారం ఇవ్వని పేసేజీను మోడల్ సైట్ చేస్తుంది | min_score ఫ్లోర్ → ERROR[not_found] |
ఫ్లోర్ కార్పస్ను బట్టి ఉంటుంది; భాషకు భాషా పునఃక్రమాంకనం కావాలి |
| రీర్యాంకర్ మరీ నెమ్మది | టూల్ p95 40 ms నుంచి 240 ms కు దూకుతుంది | రీర్యాంక్ సెట్ను 8 కు పరిమితించడం; పెద్ద ఫ్యూజన్ మార్జిన్పై దాటవేయడం | ఏ అనుకూల బడ్జెట్ లేదు |
| డాక్యుమెంట్ల అంతటా నకిలీ చంక్లు | ఒకే వాక్యం రెండుసార్లు రిట్రీవ్ అవుతుంది; రెండు స్లాట్లు వృథా | ఓవర్ల్యాప్ పరిమితం; టెక్స్ట్ హ్యాష్ ద్వారా నకిలీ తొలగింపు | దాదాపు నకిలీ డాక్యుమెంట్లు ఇంకా పూల్ను ముంచుతాయి |
| మళ్లీ చంక్ చేయడం సైటేషన్లను అంతర్వేధం చేస్తుంది | పాత సమాధానాలు తప్పు ordinal ను చూపుతాయి | ordinal లు ప్రతి బిల్డ్కు స్థిరం; కార్పస్ వెర్షన్ రికార్డవుతుంది | సేవ్ చేసిన సైటేషన్లకు మైగ్రేషన్ టూల్ లేదు |
| Embedding మోడల్ మార్పు | స్కోర్లు మారతాయి; ఫ్లోర్ చెల్లదు | ఇంటర్ఫేస్ మార్పును ఒంటరిగా వేస్తుంది | డిప్లాయ్కు ముందు హార్నెస్ను మళ్లీ నడపాలి |
చివరి వరుసే ప్రొడక్షన్లో కుట్టేది; అది కోడ్ వైఫల్యం కాదు, ప్రక్రియ వైఫల్యం. HashedEmbedder ను నిజమైన మోడల్తో మార్చడం స్కోర్ పంపిణీని మారుస్తుంది; అది min_score ను చెల్లనిది చేస్తుంది; అదే ఎర్రర్ మార్గాలను నిశ్శబ్దంగా సంబంధం లేని-పేసేజీ మార్గాలుగా మారుస్తుంది. ఏ embedder మార్పు అయినా వెంటనే హార్నెస్ రన్ జరగాలి; ఫ్లోర్ను కొత్త పంపిణీ అంచులోని తక్కువ భాగం నుంచి పెట్టాలి — పాతదాని నుంచి కాపీ చేయకూడదు.
ట్రేడ్-ఆఫ్ లు
| నిర్ణయం | ప్రత్యామ్నాయం | ఎందుకు ఎంచుకున్నాము | ఖరీదు |
|---|---|---|---|
| 420-అక్షరాల చంక్లు | 1,000-token చంక్లు | నాలుగు హిట్ల ఖరీదు 420 token లు, 4,000 కాదు | సమాధానాలు సరిహద్దుల వద్ద పగులుతాయి |
| 90-అక్షరాల ఓవర్ల్యాప్ | ఓవర్ల్యాప్ లేనిది | సరిహద్దు వాక్యాలు రిట్రీవ్ అవుతూనే ఉంటాయి | 21 శాతం ఇండెక్స్ ద్రోణిక |
| BM25 + dense, RRF తో మేళవింపు | ఒకే రిట్రీవర్ | డెమోలో పూల్ recall 0.88 నుంచి 1.00 కు | సమకాలీకరించాల్సిన రెండు ఇండెక్స్లు |
| హ్యాష్డ్ embedder | ట్రైన్ చేసిన embedding మోడల్ | నిర్ధారక, ఆఫ్లైన్, టెస్ట్ చేయదగినది | సమానార్థక recall లేదు; precision లో BM25 కి తీరిక |
| నిర్ధారక రీర్యాంకర్ | Cross-encoder | 1 ms లో నడుస్తుంది; హోస్ట్ చేయాల్సిన మోడల్ లేదు | ర్యాంకింగ్ను కాదగించినంత మార్చదు |
min_score=0.05 |
సరిపోయినదేదైనా తిరిగివ్వడం | చతిపులను వర్గీకృత ఎర్రర్గా మారుస్తుంది | నిజంగా అరుదైన క్వెరీ ఎర్రర్ ఇస్తుంది |
limit=4 |
limit=10 |
కాంటెక్స్ట్ ఖరీదు పరిమితం | బహుళ-అంచు (multi-hop) ప్రశ్నలు తప్పుపోతాయి |
రీర్యాంకర్ వరుసకు నేరుగా సమాధానం దర్కారు: ఈ ప్రతినిధితో ఏ precision లాభం లేకుండా ఇంటర్ఫేస్ సంకీర్ణతకు రుసుము చెల్లిస్తున్నారు. అయినా ఇంటర్ఫేస్ను నిర్మించడానికి కారణం: precision అనేది ట్రైన్ చేసిన మోడల్ P@1 లో పది నుంచి ఇరవై పాయింట్లు సంపాదించే దశ; ఆ కుట్టుపట్టీని తర్వాత జోడించాలంటే టూల్ ఒప్పందం, సైటేషన్ ఫార్మాట్, టెస్ట్లను ఒకేసారి తాకాలి.
దీన్ని పరీక్షించడం
పదకొండు టెస్ట్లు; నెట్వర్క్ లేదు; 50 ms లోపల. ఇవే అచలనాలు:
import jsonimport unittest
import corpusimport ragfrom contracts import ToolExecutor, build_tools
class TestRecall(unittest.TestCase): def test_bm25_ranks_exact_identifier_first(self): r = rag.CorpusRetriever(corpus.DOCUMENTS) hits = r.hybrid.bm25.search("chunked transfer encoding 64 KB", k=3) self.assertEqual(hits[0][0].split("#")[0], "cdn-transfer")
def test_vector_bridges_morphology_that_bm25_misses(self): chunks = rag.chunk_document( "morph", "Retrieval quality depends on the candidate pool, not on the prompt.") index = rag.VectorIndex() index.add(chunks) self.assertTrue(index.search("retrieve", k=1)) bm25 = rag.BM25Index() bm25.add(chunks) self.assertEqual(bm25.search("retrieve", k=1), [])
def test_rrf_prefers_agreement_over_a_single_winner(self): fused = rag.reciprocal_rank_fusion([[("a", 9.0), ("b", 8.0)], [("b", 0.9), ("a", 0.8)]]) self.assertEqual(fused[0][0], "a")
class TestChunking(unittest.TestCase): def test_overlap_carries_the_boundary_sentence(self): text = ("Alpha sentence about chunk one. " * 12 + "Boundary sentence that must survive. " + "Beta sentence two. " * 12) chunks = rag.chunk_document("doc", text, max_chars=200, overlap_chars=60) self.assertGreater(len(chunks), 2) self.assertTrue(any("Boundary sentence" in c.text for c in chunks)) self.assertTrue(all(len(c.text) <= 260 for c in chunks))
class TestTool(unittest.TestCase): def test_tool_returns_citations_the_agent_can_reuse(self): r = rag.CorpusRetriever(corpus.DOCUMENTS) tools = {t.name: t for t in build_tools()} tools["search"] = rag.make_search_tool(r) result = ToolExecutor(tools).execute("search", {"query": "reranker latency", "limit": 2}) self.assertTrue(result.ok) payload = json.loads(result.data) self.assertEqual(len(payload), 2) self.assertRegex(payload[0]["citation"], r"^[a-z-]+#\d+$")
def test_short_query_is_rejected_before_the_index(self): r = rag.CorpusRetriever(corpus.DOCUMENTS) result = ToolExecutor({"search": rag.make_search_tool(r)}).execute( "search", {"query": "a"}) self.assertFalse(result.ok) self.assertEqual(result.error_code, "invalid_arguments")
def test_empty_result_is_a_classified_error(self): tiny = rag.CorpusRetriever({"only": corpus.DOCUMENTS["chunking"]}) result = rag.make_search_tool(tiny).run({"query": "zzz qqq", "limit": 2}) self.assertFalse(result.ok) self.assertEqual(result.error_code, "not_found")
if __name__ == "__main__": unittest.main()test_vector_bridges_morphology_that_bm25_misses రెండు శాఖలను ఉంచడానికి సమర్థన ఇచ్చేది. ఇది ఒకే చంక్ గురించి భిన్నమైన రెండు విషయాలను నిర్ధారిస్తుంది: వెక్టర్ ఇండెక్స్ retrieve కోసం దాన్ని కనుగొంటుంది, BM25 ఖాళీ జాబితా ఇస్తుంది. ఈ టెస్ట్ విఫలమయ్యేలా ఎవరైనా తర్వాత embedder ను మార్చితే, dense శాఖ రెండో పదాభాస మ్యాచర్ అవుతుంది; ఫ్యూజన్ దశ ఇప్పుడు స్వచ్ఛమైన అదనపు భారం — పై బెంచ్మార్క్ కొలిచే స్థితి అదే.
test_empty_result_is_a_classified_error అంటే no matches అబద్ధానికి రిగ్రెషన్ కాపురం. ok=False + not_found అంటే లూప్ విఫల దశను రికార్డ్ చేస్తుంది; మోడల్కు ERROR[not_found] కనిపిస్తుంది — దీనిపై నడవగలం. ok=True అయి ఖాళీ జాబితా వచ్చారంటే మోడల్ కార్పస్ ఆ అంశంపై మౌనం అని నిర్ణయిస్తుంది — అది నిజం కాదు.
అభ్యాసాలు
- ఓవర్ల్యాప్ను కొలవండి.
overlap_charsను 0, 90, 180 వద్ద పెట్టి ఇండెక్స్ను మళ్లీ బిల్డ్ చేసి, ప్రతిసారీ హార్నెస్ నడపండి. recall@12, చంక్లలో ఇండెక్స్ పరిమాణం, నాలుగు హిట్ల టోకెన్ ఖరీదు నివేదించండి. ఏ ఓవర్ల్యాప్ వద్ద recall లాభం నకిలీ ఖరీదును చెల్లించడం ఆపేస్తుంది? - Cross-encoder కుట్టుపట్టీ.
class Reranker(Protocol)నిscore(query, passage) -> floatతో నిర్వచించి,CoverageRerankerదీన్ని అమలు చేయనివ్వండి;HTTPRerankerఅనేది జోడించండి — అది రీర్యాంకింగ్ ఎండ్పాయింట్కు[[query, passage]]జోడీలను POST చేస్తుంది. రీర్యాంక్ సెట్ను 8 కు పరిమితించి,passages[0].fused_score > 2 * passages[1].fused_scoreఉంటే రీర్యాంకింగ్ దాటవేయండి. అదనపు లేటెన్సీకి వ్యతిరేకంగా P@1 మార్పును కొలవండి. - భాషా ప్రాతిపదిక ఫ్లోర్లు. ప్రాసంగత్య ఫ్లోర్ ఇంగ్లీష్పై క్రమాంకనం అయింది. వేరే టోకెనైజేషన్ (జపనీస్ లేదా జర్మన్ సంయుక్త పదాలు) ఉన్న భాషలో పది-క్వెరీ సెట్ నిర్మించి, సంబంధిత మరియు సంబంధం లేని హిట్ల స్కోర్ పంపిణీని తేల్చండి. ఒకే సార్వత్రిక
min_scoreసమర్థించదగినదా, లేదా ఇండెక్స్కు ఇండెక్సుగా ఉండాలా?
అభ్యాసం 2 మీరు షిప్ చేసే దాన్ని మార్చేది. కుట్టుపట్టీ చిన్నది; అది ఉండటం అంటే ఖరీదైన భాగం నిర్మాణ నిర్ణయం కాకుండా డిప్లాయ్మెంట్ నిర్ణయం అవుతుంది.
తర్వాత ఏమిటి
agent ఇప్పుడు పేసేజీను కనుగొని సైట్ చేయగలదు. ఇంకా చేయలేనిది: తనకు ఎన్ని శోధనలు కావాలో, ఏ క్రమంలోనో నిర్ణయించడం — లూప్ ఒకేసారి ఒక టూల్ కాల్ ఇస్తుంది; compare the chunking trade-offs with the reranker latency budget లాంటి ప్రశ్నకు ప్లాన్ కావాలి.
భాగం 6, Task decomposition, గోల్ను స్పష్ట డిపెండెన్సీలతో టాస్క్ గ్రాఫ్గా మార్చే Planner ను, రెడీ టాస్క్లను సమాంతరంగా నడిపే ఎగ్జిక్యూటర్ను, టాస్క్ విఫలమైనప్పుడు పనిచేసే పరిమిత రీప్లానింగ్ దశను జోడిస్తుంది. మీరు ఇప్పుడు నిర్మించిన search టూల్ planner కుదిపేర్చే ప్రిమిటివ్ అవుతుంది — అది తిరిగిచ్చే సైటేషన్లు భాగం 7 ధృవీకరించే సాక్ష్యం.
Everything above, running in Ball — no code, no install. Try it in your browser.
Only used to send Ball resources. No spam.
You're in. Open the resource list below. Open the resource list
Try Ball in your browser — no install, no signup needed.
Try Ball in your browser — no install, no signup needed.