Back to all articlesAI र एजेन्टहरू

स्वयं-भ्रम बिनाको प्रतिबिम्बन: रोक्किने प्रमाणीकरण लुपहरू (Part 7)

Verification before reflection

Decidable checkscitation, number, quote
Rubric criticscore drives arithmetic
Score penalty0.15 per open verdict
Three stop conditionsrounds, delta, oscillation

One reflection round

The program checks are a veto the critic cannot outvote.

One reflection round — flow diagramOne reflection round. Flow diagram with 6 steps. Shapes: pill = input, rounded rect = process, diamond = decision, double border = output, dashed = loop. Steps in order: Step 1, draft answer (input), from AgentLoop trace; Step 2, extract claims (process), sentence + [doc#n] citations; Step 3, programmatic checks (decision), no_citation / number_mismatch; Step 4, rubric critique (decision), score - 0.15 x errors; Step 5, revise from issues (process), clean citations kept; Step 6, labelled answer (output), stopped_by records why. Then loops back to step 3: ↺ repeat until accepted, no_progress, oscillation or max_rounds.draft answerfrom AgentLoop traceextract claimssentence + [doc#n] citationsprogrammaticchecksno_citation / number_mismatchrubric critiquescore - 0.15 x errorsrevise from issuesclean citations keptlabelled answerstopped_by records why
  • input
  • process
  • decision
  • output

प्रतिबिम्बनको सबैभन्दा सामान्य कार्यान्वयन एउटै प्रम्प्ट हो: Review your answer for errors and improve it. यसले विश्वसनीय रूपमा लामो उत्तर दिन्छ। यसले राम्रो उत्तर दिन्छ कि दिँदैन भन्ने अर्को प्रश्न हो, किनकि आफ्नो ड्राफ्ट समीक्षा गर्ने मोडेलसँग ड्राफ्टमा पहिले नै नभएको कुनै सूचना हुँदैन। आलोचनाले थप आत्मविश्वासी शब्दहरूसह उत्तरलाई पुनरावृत्ति गर्छ, संशोधनले आलोचनालाई पुनरावृत्ति गर्छ, र तपाईंले टोकन संख्या बढाउन मात्र दुई मोडेल कलको मूल्य चुकाउनुहुन्छ।

प्रतिबिम्बन ठ्याक्कै दुई अवस्थामा मात्र उपयोगी हुन्छ: आलोचना पहिलो पटक प्रयोग नगरेको प्रमाणमा आधारित हुनुपर्छ, वा प्रोग्रामले मोडेलले वादविवाद गर्न नसक्ने कुनै कुरा जाँच्नुपर्छ। यो भागले दुवै निर्माण गर्छ — र त्यसपछि सबैले छोड्ने भाग, रोक्ने सर्तहरू, पनि निर्माण गर्छ, किनकि सीमारहित प्रतिबिम्बन लुप त्यही उत्तरका दुई संस्करणबीच फेरबदल गर्दै स्टेप बजेट सकिनेसम्म बस्छ।

अघिल्ला तीन भागको फल यहाँ ठोस रूपमा देखिन्छ। Part 5 ले हरेक खोज परिणामलाई साइटेसन id दियो; Part 6 ले हरेक कार्यलाई सीमित परिणाम दियो। साइटेसन id ले प्रमाणीकरणलाई निर्णययोग्य बनाउँछ: उद्धृत अंश अस्तित्वमा छ र त्यो नम्बर समावेश छ, वा छैन। तिनीहरू बिना प्रमाणीकरण मत मात्र हो, र मतहरूले लुपहरू रोक्दैनन्।

तपाईंले निर्माण गर्ने

चार भागसहितको reflect.py मोड्युल:

  • extract_claims + EvidenceStore — उत्तरलाई वाक्यहरूमा विभाजन गर्छ, र हरेकलाई रनले साँच्चै सङ्कलन गरेको प्रमाणसँग जाँच्छ: साइटेसनको अस्तित्व, नम्बर मिलान, शब्दशः उद्धरणहरू।
  • RubricCritic — चार-बुँदे रुब्रिकसहित, संरचित आउटपुटसहित हरेक चरणमा एक मोडेल कल, र कडा नियम: विकृत आलोचना स्वीकृति हो, संशोधन कहिल्यै होइन।
  • ReflectionLoop — आलोचना, संशोधन, तीन रोक्ने सर्तसहित: चरण सीमा, न्यूनतम स्कोर सुधार, आलोचनाको फिंगरप्रिन्टद्वारा दोलन पहिचान।
  • ReflectiveAgent — ड्राफ्टका लागि AgentLoop चलाउँछ, ट्रेसबाट प्रमाण सेट पुनर्निर्माण गर्छ, त्यसपछि प्रमाणित गर्छ।

contracts.py मा एउटा सानो परिवर्तनले यी सबै सम्भव बनाउँछ, र अरू कुनै कुरा भन्नु अघि त्यो उठाउनु उपयुक्त छ:

# Part 2's AgentLoop recorded the decision and the outcome; Part 7 needs the payload too.
record.update({"tool": name, "ok": result.ok, "attempts": result.attempts,
"error_code": result.error_code, "from_cache": result.from_cache,
"data": result.data})

data: result.data एउटै लाइन हो, र त्यो मात्र पढ्न सकिने ट्रेस र प्रमाणित गर्न सकिने ट्रेसबीचको फरक हो। त्यो नभए प्रमाण सेट मोडेलले के पढ्यो भन्ने आफ्नै स्मृतिबाट पुनर्निर्माण गर्नुपर्ने हुन्थ्यो — जुन प्रतिबिम्बनले पक्रनुपर्ने असफलता नै हो।

पूर्वआवश्यकताहरू

  • Part 1–6. reflect.py ले AgentLoop, LLMClient, Message, Tool लाई contracts.py बाट इम्पोर्ट गर्छ।
  • Python 3.10+, प्रमाणिक लाइब्रेरी मात्र (re, json, hashlib).
  • डेमोले दुई तयार प्यासेज भएको स्टब search टूल प्रयोग गर्ने भएकाले अफलाइन चल्छ; साँचो प्रोजेक्टमा Part 5 को make_search_tool(retriever) जोड्नुहोस् — प्रतिबिम्बन लेयरलाई कुन छ भन्ने कुनै फरक पर्दैन।

“तपाईंको उत्तरमा प्रतिबिम्बन गर्नुहोस्” ले कुरा अझ बिगार्ने किन

अमूर्त आत्म-आलोचना एउटा संरचनात्मक कारणले असफल हुन्छ, प्रम्प्ट-इन्जिनियरिङको कारणले होइन। आलोचना स्टेप दोस्रो मोडेल कल हो जसको एकमात्र इनपुट पहिलो कलले उत्पादन गरेको पाठ हो। नयनो सूचना छैन, त्यसैले सम्भव उत्तम आलोचना पहिले नै भएको कुराको पुनःव्युत्पादन हो — र वाक्य उत्पादन गर्ने तै वेटहरूले वाक्यको निर्णय गर्ने भएकाले मोडेलहरू आफ्नै आत्मविश्वासी त्रुटिहरू चिन्हित गर्नमा विशेष रूपमा कमजोर हुन्छन्।

प्रतिबिम्बनले प्रयोग गर्न सक्ने कुरा, र यो भागले जोड्ने कुरा, भिन्नात्मक सूचना हो:

  • प्रमाण सेट — टूलहरूले साँच्चै के फिर्ता गरे, जसको ड्राफ्टले उपेक्षा गरेको हुनसक्छ वा उल्टो बुझेको हुनसक्छ।
  • निर्णययोग्य जाँचहरू — साइटेसनको अस्तित्व, नम्बर मिलान, उद्धरणको उपस्थिति, जसलाई मोडेलको कुनै आवश्यकता पर्दैन।
  • स्केलसहितको रुब्रिक — त्यसैले score ले वाइब्सको सट्टा अंकगणित चलाउन सक्छ।

क्रम महत्त्वपूर्ण छ, र यही मूल डिजाइन हो: पहिले प्रोग्रामेटिक जाँचहरू, दोस्रो मोडेल निर्णय। सजिलैसँग छुट्ने एउटा जवाफदेहिताको असमानता पनि छ। मोडेल-आधारित आलोचना गलत भएमा, प्रणालीभित्र त्यो भन्न सक्ने कोही छैन — आलोचना एउटा निर्णय हो, र निर्णयहरूले अडिट ट्रेल छोड्दैनन्। EvidenceStore.check ले number_mismatch चिन्हित गर्दा, निर्णयले दाबी, कोड, र नमूद साइटेसनमा नभएको ठ्याक्कै नम्बर नमूद गर्छ। open_verdicts पढ्ने डेभलपरले खण्डनयोग्य वक्तव्य देख्छ, जसको अर्थ गलत पोजिटिभ डिबग गर्न सकिन्छ: प्यासेज हेर्नुहोस्, regex हेर्नुहोस्, नियम सुधार्नुहोस्। जाँच्न सकिने लेयर पहिले निर्माण गर्नुहोस्, र आलोचक र जाँचबीचको हरेक पछिल्लो मतभेदका लागि निवेदन गर्न सकिने ग्राउन्ड ट्रुथ हुन्छ। ४० माइक्रोसेकेन्डमा चल्ने जाँच पास हुन्छ वा त्रुटि नमूद गर्छ; आलोचक त्यसपछि प्रोग्रामले गर्न नसक्ने कुराको निर्णय गर्छ — दाबी लक्ष्यसँग सम्बन्धित छ कि छैन, तर्कसुसंगति गुँजिएको छ कि छैन। आलोचकलाई गद्य मात्र दिएर दुवै काम गराउनु भनेको दुवैबाट सबैभन्दा नराम्रो पाउनु हो: ऊ नम्बरहरू विश्वसनीय रूपमा प्रमाणित गर्न सक्दैन, र आफ्नो ध्यान व्याकरणमा खर्च गर्छ।

प्रोग्रामले चलाउन सक्ने जाँचहरू: साइटेसनहरू, नम्बरहरू, उद्धरणहरू

दाबी भनेको शून्य वा त्यो भन्दा बढी साइटेसन id भएको वाक्य हो। जाँचहरू जानाजान यान्त्रिक छन्:

from __future__ import annotations
from dataclasses import dataclass, field
import hashlib
import json
import re
from contracts import AgentLoop, LLMClient, Message, Tool
CITATION = re.compile(r"\[([a-z][a-z0-9_-]{1,40}#\d+)\]")
NUMBER = re.compile(r"\d+(?:\.\d+)?")
QUOTE = re.compile(r'"([^"]{8,160})"')
SENTENCE = re.compile(r"(?<=[.!?])\s+")
@dataclass
class Evidence:
id: str
text: str
@dataclass
class Claim:
text: str
citations: tuple[str, ...]
@dataclass(frozen=True)
class Verdict:
claim: str
code: str # ok | no_citation | unknown_citation | number_mismatch | quote_missing
detail: str = ""
@property
def failed(self) -> bool:
return self.code != "ok"
def extract_claims(answer: str) -> list[Claim]:
return [
Claim(sentence, tuple(CITATION.findall(sentence)))
for sentence in (s.strip() for s in SENTENCE.split(answer.strip()))
if sentence
]
class EvidenceStore:
"""The evidence the run actually retrieved. Claims are checked against this, not against belief."""
def __init__(self, evidence: list[Evidence]) -> None:
self.items = {e.id: e for e in evidence}
def check(self, claim: Claim) -> list[Verdict]:
if not claim.citations:
return [Verdict(claim.text, "no_citation", "claim cites no evidence")]
verdicts: list[Verdict] = []
for citation in claim.citations:
item = self.items.get(citation)
if item is None:
verdicts.append(Verdict(claim.text, "unknown_citation",
citation + " was never retrieved"))
continue
missing_numbers = [n for n in NUMBER.findall(claim.text)
if n not in item.text]
if missing_numbers:
verdicts.append(Verdict(
claim.text, "number_mismatch",
",".join(missing_numbers) + " absent from " + citation))
missing_quotes = [q for q in QUOTE.findall(claim.text)
if not any(q in item.text for item in self.items.values())]
for quote in missing_quotes:
verdicts.append(Verdict(claim.text, "quote_missing", quote[:60]))
if not verdicts:
verdicts.append(Verdict(claim.text, "ok", ""))
return verdicts
def check_claims(self, claims: list[Claim]) -> list[Verdict]:
out: list[Verdict] = []
for claim in claims:
out.extend(self.check(claim))
return out
def block(self, max_chars: int = 1400) -> str:
lines: list[str] = []
for item in self.items.values():
lines.append("[%s] %s" % (item.id, item.text[:200]))
return "\n".join(lines)[:max_chars]

चार जाँचहरू, हरेकमा डिजाइनले लुकाउनुको सट्टा स्वीकार गर्ने एउटा ज्ञात अन्ध बिन्दु।

no_citation सबैभन्दा सस्तो र सबैभन्दा मूल्यवान छ। साइटेसन नभएको दाबी गलत नहुनसक्छ, तर प्रमाणित गर्न नसकिने हुन्छ, र अनुसन्धान एजेन्टमा प्रमाणित नगर्न सकिने दाबी त्रुटि हो: Part 5 को साइटेसन ढाँचाको पूरै उद्देश्य नै दाबीहरू जाँच्न सकिने बनाउनु थियो। अनुपस्थितिलाई असफलता माने मोडेलले साइट गर्न सिक्छ — प्रम्प्ट-पक्षको निर्देशन (cite as [doc#n]) र यो जाँच मिलेर एउटा बन्द लुप बनाउँछन्।

unknown_citation काल्पनिक साइटेसनहरू पक्रन्छ — त्यो दस्तावेजमा दुई चंक्स हुँदा [retrieval-design#7]। यो जाँच भेक्टर-डेटाबेस-RAG प्रणालीहरूले छोड्छन्, र यो निःशुल्क छ।

number_mismatch वेडेपनको टुप्पोसम्म कडा छ: दाबीको हरेक नम्बर उद्धृत पाठमा शब्दशः देखिनुपर्छ। त्यसको अर्थ वैध पुनर्कथन — प्रमाणले 180 to 240 milliseconds भन्छ, दाबीले about 200 ms भन्छ — चिन्हित हुन्छ। यो जानाजान हो। पुनर्कथित नम्बर नै सही सङ्कलन गलत उत्तर हुने सबैभन्दा सामान्य बाटो हो, चिन्हित पुनर्कथनको मूल्य एक संशोधन चरण हो, तर चिन्हित नभएको बनावटी नम्बरको मूल्य गलत उत्पादनयोग्य सामग्री हो। 200 ms को केस नै तलको डेमोले देखाउँछ।

quote_missing ८–१६० अक्षरका उद्धरण क्षेत्रहरूमा मात्र चल्छ। छोटा क्षेत्र शोर हुन्; लामा सामान्यतया मोडेलले आफ्नै सारांश उद्धृत गरेका हुन्। जाँचले उद्धरण प्रमाणमा कतै छ कि छैन मात्र प्रमाणित गर्छ — सही साइटेसनमा जोडिएको छ कि छैन भन्ने होइन, जसलाई स्प्यान मिलान चाहिन्छ र यो चरणमा त्यो जटिलता लाभदायक छैन।

रुब्रिकसहितको आलोचक, र एउटा विटो

आलोचक रुब्रिक, स्केल र संरचित आउटपुटसहित एक मोडेल कल हो। लुपले त्यसमा अंकगणित गर्न सक्नुपर्ने भएकाले स्केल छ।

CRITIC_SYSTEM = (
"You are a critic. Score the draft answer against the evidence. Rubric: "
"(1) every factual claim cites evidence; (2) numbers match the cited text exactly; "
"(3) no claim goes beyond what the evidence supports; (4) the answer responds to the goal. "
"Reply with JSON: {\"type\": \"critique\", \"score\": 0.0-1.0, \"verdict\": \"accept|revise\", "
"\"issues\": [{\"claim\": \"...\", \"problem\": \"...\", \"fix\": \"...\"}]}. "
"Score below 0.80 means revise."
)
@dataclass
class Critique:
score: float
verdict: str
issues: list[dict] = field(default_factory=list)
fingerprint: str = ""
class RubricCritic:
"""One model call per round. A malformed critique is an accept, never a revision."""
def __init__(self, llm: LLMClient) -> None:
self.llm = llm
def review(self, goal: str, draft: str, evidence_block: str) -> Critique:
decision = self.llm.complete(
[Message("system", CRITIC_SYSTEM),
Message("user", "Goal: %s\n\nEVIDENCE:\n%s\n\nDRAFT:\n%s" % (goal, evidence_block, draft))],
[],
)
try:
if decision.get("type") != "critique":
raise ValueError("expected a critique decision")
score = float(decision.get("score", 1.0))
verdict = str(decision.get("verdict", "accept"))
issues = decision.get("issues") or []
if verdict not in ("accept", "revise") or not 0.0 <= score <= 1.0:
raise ValueError("malformed critique")
except (TypeError, ValueError):
return Critique(1.0, "accept", [], "unparseable")
fingerprint = hashlib.sha256(
json.dumps([str(i.get("claim", i))[:120] for i in issues], sort_keys=True)
.encode("utf-8")).hexdigest()[:10]
return Critique(min(1.0, max(0.0, score)), verdict, issues, fingerprint)

त्यो क्लासमा दुई नीतिहरूलाई आफ्नै छुट्टा वाक्यहरू मिल्ने छन्।

विकृत आलोचना स्वीकृति हो। यो उल्टो देखिन्छ — बिग्रेको आलोचक भनेको “फेरि प्रयास गर्नुहोस्” हुनुपर्ने त हो? होइन, किनकि लुपभित्र आलोचकको पुनःप्रयास गर्दा सीमारहित असफलता मार्ग बन्छ: आलोचक असफल हुन्छ, तपाईं पुनःप्रयास गर्नुहुन्छ, ऊ अर्को तरिकाले असफल हुन्छ, तपाईं फेरि प्रयास गर्नुहुन्छ। पार्स गर्न नसकिने आलोचनाको सुरक्षित अर्थ त्यसमाथि कार्य गर्न नसकिने हो, र कार्य नगर्नु भनेको हालको ड्राफ्ट स्वीकार गर्नु हो, जो पहिले नै प्रोग्रामेटिक जाँचहरू पार गरिसकेको छ। लुपले critic_unparseable लाई रोक्ने कारणका रूपमा दर्ता गर्छ, त्यसैले रन लुकाइएको नभई लेबल गरिएको हुन्छ।

फिंगरप्रिन्ट नै दोलन पहिचानकर्ता हो। समस्या दाबीहरूको ह्यास गर्दा “आलोचक त्यही कुरा भन्दै जान्छ” भन्ने कुरा समता परीक्षणमा बदलिन्छ। त्यो नभए claim one is thin चिन्हित गर्दै जाने आलोचकले अनन्त संशोधन लुप उत्पादन गर्छ — र फिंगरप्रिन्ट समता स्कोर समताभन्दा बलियो संकेत हो, किनकि स्कोरहरू सर्छन् तर अडेको समस्या सर्दैन।

तीन रोक्ने सर्तहरू

लुपले जाँचहरू, आलोचक र संशोधनलाई जोड्छ। त्यसको पूरै व्यवहार तीन निर्गमन सर्तहरूको क्रममा छ:

@dataclass
class ReflectionConfig:
max_rounds: int = 2
min_delta: float = 0.08
accept_score: float = 0.8
@dataclass
class ReflectionRun:
final_answer: str
rounds: int
stopped_by: str # accepted | no_progress | oscillation | max_rounds | critic_unparseable
history: list[dict] = field(default_factory=list)
@property
def open_verdicts(self) -> list[Verdict]:
last = self.history[-1] if self.history else {}
return [v for v in last.get("verdicts", []) if v.failed]
class ReflectionLoop:
"""Critique, then revise, with three stop conditions. Never revises on a hunch."""
def __init__(self, llm: LLMClient, critic: RubricCritic, store: EvidenceStore,
config: ReflectionConfig | None = None) -> None:
self.llm = llm
self.critic = critic
self.store = store
self.config = config or ReflectionConfig()
def run(self, goal: str, draft: str) -> ReflectionRun:
current = draft
last_score: float | None = None
last_fingerprint: str | None = None
history: list[dict] = []
stopped_by = "max_rounds"
for round_index in range(self.config.max_rounds):
verdicts = self.store.check_claims(extract_claims(current))
errors = sum(1 for v in verdicts if v.failed)
critique = self.critic.review(goal, current, self.store.block())
if critique.fingerprint == "unparseable":
history.append({"round": round_index, "score": None, "verdicts": verdicts,
"stopped_by": "critic_unparseable"})
return ReflectionRun(current, round_index + 1, "critic_unparseable", history)
score = max(0.0, min(1.0, critique.score - 0.15 * errors))
entry = {"round": round_index, "score": round(score, 2),
"programmatic_errors": errors, "critique": critique,
"verdicts": verdicts}
history.append(entry)
if errors == 0 and critique.verdict == "accept" and score >= self.config.accept_score:
stopped_by = "accepted"
break
if last_score is not None and score - last_score < self.config.min_delta:
stopped_by = "no_progress"
break
if critique.fingerprint == last_fingerprint and critique.issues:
stopped_by = "oscillation"
break
last_score = score
last_fingerprint = critique.fingerprint
current = self.revise(goal, current, critique.issues)
return ReflectionRun(current, len(history), stopped_by, history)
def revise(self, goal: str, draft: str, issues: list[dict]) -> str:
bullets = []
for issue in issues[:5]:
bullets.append("- claim: %s\n problem: %s\n fix: %s"
% (issue.get("claim", ""), issue.get("problem", ""),
issue.get("fix", "")))
decision = self.llm.complete(
[Message("system", "Rewrite the answer to fix every issue. Keep citations that "
"verified clean. Change nothing else."),
Message("user", "Goal: %s\n\nDRAFT:\n%s\n\nISSUES:\n%s" % (goal, draft, "\n".join(bullets)))],
[],
)
return str(decision.get("content", "")) or draft

जरिवाना नै विटो हो। score - 0.15 * errors सिधै घटाइन्छ, त्यसैले साइटेसन नभएको, नम्बर बनावट गरेको ड्राफ्टलाई 0.9 दिने आलोचक पनि 0.6 मा पुग्छ — accept_score को तल, र संशोधन हुन्छ। स्वीकृति सर्तमा errors == 0 पनि चाहिन्छ, त्यसैले खुला निर्णय भएको रनलाई कुनै अंकगणितले बचाउन सक्दैन। आलोचकलाई इमानदार राख्ने यही हो: प्रोग्राम जाँचहरू सल्लाह मात्र होइनन्, ती आलोचकले ओभरभोट गर्न नसक्ने विटो हुन्।

min_delta=0.08 व्यर्थ-फर्काइ रोक्ने सर्त हो। संशोधनको लागत दुई कल हो (आलोचना + संशोधन, थप संशोधनको निर्णय गर्न एक आलोचना)। अन्तिम संशोधनले स्कोरलाई 0.08 भन्दा कम सारेमा, अर्कोले राम्रो गर्दैन, र इमानदार उत्तर रोक्नु र लेबल गर्नु हो: no_progress। तलका टेस्टहरूमा 0.55 → 0.60 चरणले ठ्याक्कै यही ट्रिगर गर्छ।

दोलन सुधारपछि जाँचिन्छ, जानाजान। त्यही फिंगरप्रिन्टसहितको ठूलो स्कोर फड्को सन्दिग्ध छ — आलोचकलाई रिराइट मन पर्‍यो र त्यही गुनासो दोहोऱ्यायो। त्यहाँ रोक्नु तेस्रो चरणभन्दा राम्रो, किनकि तेस्रो चरणले दोस्रोकै पुनरावृत्ति मात्र गर्न सक्छ। तीन जाँचको क्रम: स्वीकृति, त्यसपछि सुधार, त्यसपछि फिंगरप्रिन्ट। क्रम सार्दा फरक असफल रनहरू आउँछन्; टेस्टहरूले क्रम पिन गर्छन्।

max_rounds=2 बजेट हो, र डिफल्ट उत्तर। लुप stopped_by="max_rounds" सहित र हालको ड्राफ्टसहित बाहिरिन्छ, जुन दुई संशोधनपछि accept_score मा नपुगे पनि सामान्यतया मूलभन्दा राम्रो हुन्छ। लेबलसहित वितरण गर्नु फाल्नुभन्दा राम्रो — कलर (Part 8 को चेकपोइन्ट लेयर) ले max_rounds उत्तर आफ्नो यूज केसका लागि स्वीकार्य छ कि छैन निर्णय गर्न सक्छ।

रनमा जोड्ने

एजेन्टले ट्रेसबाट प्रमाण पुनर्निर्माण गर्छ, त्यसैले प्रमाणीकरण मोडेलले सम्झेको कुरामा होइन टूलहरूले फिर्ता गरेको कुरामा आधारित हुन्छ:

def evidence_from_trace(trace: list[dict]) -> list[Evidence]:
"""Rebuild the evidence set from a run's search calls. Requires trace records with data."""
items: dict[str, Evidence] = {}
for record in trace:
if record.get("tool") != "search" or not record.get("ok"):
continue
try:
for hit in json.loads(record.get("data", "[]")):
items[hit["citation"]] = Evidence(hit["citation"], hit["text"])
except (ValueError, KeyError, TypeError):
continue
return list(items.values())
class ReflectiveAgent:
"""AgentLoop for the draft, then verification. Evidence comes from the trace, not memory."""
def __init__(self, llm: LLMClient, tools: list[Tool], config: ReflectionConfig | None = None,
max_steps: int = 6, critic: RubricCritic | None = None) -> None:
self.llm = llm
self.tools = tools
self.config = config or ReflectionConfig()
self.max_steps = max_steps
self.critic = critic or RubricCritic(llm)
self.last_trace: list[dict] = []
def run(self, goal: str) -> ReflectionRun:
loop = AgentLoop(self.llm, self.tools, max_steps=self.max_steps)
draft = loop.run(goal)
self.last_trace = loop.trace
store = EvidenceStore(evidence_from_trace(loop.trace))
return ReflectionLoop(self.llm, self.critic, store, self.config).run(goal, draft)

evidence_from_trace ले असफल खोजहरू छोड्छ (not record.get("ok")) — टूलले कहिल्यै उत्पादन नगरेको प्रमाणले कुनै कुरा प्रमाणित गर्न सक्दैन, र असफल खोजको साइटेसन उद्धृत गर्ने ड्राफ्टलाई सट्टा unknown_citation ले पक्रन्छ।

त्यो पुनर्निर्माणका तीन गुणहरू देखिनेभन्दा महत्त्वपूर्ण छन्।

डिडुप्लिकेशन स्वतः हुन्छ। पाँच खोज गर्ने रनले ओभरल्याप भएका प्यासेजहरू सङ्कलन गर्छ — Part 5 को इन्डेक्सले डिजाइनअनुसार चंक्स ओभरल्याप गर्छ, र दुई क्वेरीले प्रायः त्यही साइटेसन सामुन्ने ल्याउँछन्। items साइटेसन id द्वारा कीड हुन्छ, त्यसैले प्रमाण सेट अद्वितीय प्यासेजहरूको संघ हो, त्यही तीन चंक्सका पाँच प्रतिलिपि होइन। प्रमाणीकरणको लागत रनको लम्बाइले होइन कोर्पस विविधताले सीमित हुन्छ।

प्रमाण ब्लक बजेट निर्णय हो। block() १,४०० अक्षरमा सीमा — लगभग ३५० टोकन — हरेक प्यासेज २०० मा ट्रंकेट। चार प्यासेज दिने दुई खोजको लागत त्यसैले हरेक आलोचना कलमा बढीमा ३५० टोकन, र max_rounds=2 सहित पूरै रनका लागि ७०० टोकन आलोचना सन्दर्भ। सीधा विकल्पसँग तुलना गर्नुहोस्, पूरै ट्रेस आलोचकलाई टाँस्नु: ४२० टोकनका पाँच खोज २,१०० टोकन, र आलोचकले ड्राफ्टले कहिल्यै प्रयोग नगरेको टूल आउटपुट पढ्छ।

max_steps=6 ले ड्राफ्टलाई सीमित गर्छ, प्रमाणीकरणलाई होइन। छ लुप स्टेपपछि उत्पादन भएको ड्राफ्टले बढीमा छ खोज पेलोड उद्धृत गर्न सक्छ, त्यसैले प्रमाण सेटमा छ छुट्टा साइटेसन क्लस्टरको कडा सिमा हुन्छ। लुप कन्फिगले कहिल्यै उल्लेख नगरे पनि प्रमाणीकरणको लागत max_steps सँगै बढ्छ — र त्यसैले Part 8 ले त्यो पुनर्गणना नगरी चेकपोइन्टसँगै ट्रेस स्थायी गर्नेछ।

डेमोले यो भाग अस्तित्वमा आएको कारण भएको ठ्याक्कै असफलता पक्रन्छ। ड्राफ्टले 340 ms भन्छ; प्रमाणले about 200 ms भन्छ:

import json
import reflect as rf
from contracts import ScriptedLLM, Tool, ToolResult
EVIDENCE = [
rf.Evidence("latency-budget#0",
"Reranking 20 candidates costs about 200 ms per query at 12 layers. "
"Capping the set at 8 candidates brings the added cost under 100 ms."),
rf.Evidence("chunking#0",
"Chunk sizes between 300 and 500 characters with a fifth of the window "
"as overlap balance precision against index inflation."),
]
DRAFT = ("A cross-encoder reranker costs about 340 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters "
"[chunking#0].")
REVISED = ("A cross-encoder reranker costs about 200 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters "
"[chunking#0].")
def stub_search_tool() -> Tool:
passages = [
{"citation": "latency-budget#0", "doc": "latency-budget", "text": EVIDENCE[0].text, "score": 0.8},
{"citation": "chunking#0", "doc": "chunking", "text": EVIDENCE[1].text, "score": 0.6},
]
def _run(args: dict) -> ToolResult:
return ToolResult(ok=True, data=json.dumps(passages))
return Tool(
name="search",
description="Return two canned passages with citations.",
parameters={
"type": "object",
"properties": {"query": {"type": "string", "minLength": 2}},
"required": ["query"],
"additionalProperties": False,
},
_fn=_run,
)
def critique(score, verdict, claims):
return {"type": "critique", "score": score, "verdict": verdict,
"issues": [{"claim": c, "problem": "unsupported", "fix": "cite evidence"}
for c in claims]}
SCRIPT = [
{"type": "tool", "name": "search", "arguments": {"query": "reranker latency"}},
{"type": "final", "content": DRAFT},
critique(0.62, "revise", ("A cross-encoder reranker costs about 340 ms per query",)),
{"type": "final", "content": REVISED},
critique(0.90, "accept", ()),
]
def demo() -> None:
llm = ScriptedLLM(SCRIPT)
agent = rf.ReflectiveAgent(llm, [stub_search_tool()], max_steps=3)
run = agent.run("What does reranking cost in latency?")
for entry in run.history:
bad = [(v.code, v.detail) for v in entry.get("verdicts", []) if v.failed]
print("round %d score=%s programmatic_errors=%s open=%s"
% (entry["round"], entry.get("score"), entry.get("programmatic_errors", 0), bad))
print("stopped_by:", run.stopped_by, "rounds:", run.rounds, "model calls:", len(llm.calls))
print("final:", run.final_answer)
if __name__ == "__main__":
demo()
round 0 score=0.47 programmatic_errors=1 open=[('number_mismatch', '340 absent from latency-budget#0')]
round 1 score=0.9 programmatic_errors=0 open=[]
stopped_by: accepted rounds: 2 model calls: 5
final: A cross-encoder reranker costs about 200 ms per query for 20 candidates [latency-budget#0]. Chunk windows should sit between 300 and 500 characters [chunking#0].

लागतहरू पढ्नुहोस्, किनकि त्यही नै max_rounds 5 होइन 2 हुनुको कारण हो। आधारभूत रन २ मोडेल कल (खोज, अन्तिम)। प्रतिबिम्बनले ३ थप्छ: एक आलोचना, एक संशोधन, एक आलोचना। त्यो २.५× कल र लगभग २× टोकन हो — आलोचना र संशोधन प्रम्प्ट दुवैले प्रमाण ब्लक (≤१,४०० अक्षर) प्लस ड्राफ्ट बोक्छन्। एक चरणले एक बनावटी नम्बर पक्रियो। त्यो राम्रो सौदा हो। सही उत्तर पाल्नु लगाउन पाँच चरण त्यस्तो होइन, त्यही नै no_progress र oscillation अस्तित्वमा आएको कारण हो।

आलोचकले के गर्नुपर्नेनै थिएन त्यो पनि ध्यान दिनुहोस्: ऊले 340 लाई कहिल्यै अंकगणितको समस्या भनेर हेरेन। प्रोग्रामेटिक जाँचले त्यो भेट्टायो, नमूद गर्यो (340 absent from latency-budget#0), र आलोचकको काम निर्णयमा सीमित भयो — ड्राफ्टको बाँकी भाग स्वीकार्य छ कि छैन? त्यही कामको विभाजन एक संशोधन चरणले पुगेको कारण हो।

असफलता प्रकारहरू र तिनको व्यवस्थापन

असफलता साँच्चै के हुन्छ यहाँको व्यवस्था अझै टुटेको
नम्बरको वैध पुनर्कथन about 200 ms विरुद्ध 180 to 240 milliseconds चिन्हित, एक संशोधन चरण लागत दायरा-सजग नम्बर जाँच छैन
आलोचकले सबैलाई 0.95 दिन्छ प्रतिबिम्बन कहिल्यै ट्रिगर हुँदैन जरिवाना + errors == 0 स्वीकृति सर्त क्यालिब्रेटेड आलोचकलाई साँचो डेटा चाहिन्छ (Part 10)
आलोचकको आउटपुट पार्स नहुने लुप क्र्यास वा घुम्न सक्छ critic_unparseable रोक्ने, ड्राफ्ट फर्ता पुनःप्रयास छैन — लगातार बिग्रेको आलोचक घटना हो
हरेक चरणमा त्यही समस्या अनन्त संशोधन फिंगरप्रिन्ट समता → oscillation संशोधकले सुझावहरू लागू गर्दैन
प्रमाण सेट खाली (खोज चलेन) हरेक दाबी साइटेसन नभएको सबै दाबीमा no_citation “प्रमाण चाहिँदैन” र “प्रमाण छोडियो” बीच भेद छैन
ड्राफ्टले असफल खोजको साइटेसन उद्धृत गर्छ साइटेसन कहिल्यै सङ्कलन भएन unknown_citation मोडेलले खोज पुनःप्रयास गरेर बढ्न सक्छ
संशोधनले सफा दाबी तोड्छ संशोधनपछि स्कोर घट्छ no_progress ले लुप रोक्छ संशोधन प्रम्प्टले साइटेसन राख भन्छ, लागू गर्न सक्दैन

पहिलो पङ्क्ति कडा जाँचहरूको इमानदार लागत हो: number_mismatch पुनर्कथनमा बल्छ। तपाईंको कोर्पस दायरा र अनुमानहरूले भरिएको छ भने, हरेक उत्तरका लागि एक थप संशोधन चरण स्वीकार गर्नुहोस्, वा जाँचलाई संख्या-सहनशीलता तुलनामा खुकुलो बनाउनुहोस् — दुवै नम्बर पार्स गर्नुहोस्, १० प्रतिशतभन्दा बढी फरक भएमा मात्र चिन्हित गर्नुहोस्। दोस्रो विकल्प check मा दस लाइनको परिवर्तन र राम्रो अभ्यास हो, तर ऊ के त्याग्छ ध्यान दिनुहोस्: about 200 लाई 180 to 240 दायरासँग मिलान भनेको निर्णय हो, र जाँचले निर्णय गर्न थालेपछि उसमाथि वादविवाद हुन सक्छ।

ट्रेड-अफहरू

निर्णय विकल्प किन रोज्यौं लागत
प्रोग्रामेटिक जाँचहरू पहिले आलोचकले सबै कुराको निर्णय गर्छ निर्णययोग्य, निःशुल्क, वादविवाद गर्न नसकिने पुनर्कथित नम्बरहरू चिन्हित हुन्छन्
विकृत आलोचना = स्वीकृति आलोचक पुनःप्रयास सीमारहित असफलता मार्ग छैन अस्थिर आलोचकले मौनतः स्वीकार गर्छ
max_rounds=2 5 वा असीमित लागत चरणहरूमा रैखिक कठिन समस्याहरू चाँडो, लेबलसहित रोकिन्छन्
जरिवाना अंकगणित (0.15 × errors) आलोचकले निर्णयहरू पाठका रूपमा हेर्छ आलोचकले जाँचहरू ओभरभोट गर्न सक्दैन तौल Part 10 सम्म जादुई संख्या
समस्या दाबीहरूको फिंगरप्रिन्ट पूरै आलोचनाको ह्यास पुनर्क्रमण र स्कोर सरकाइप्रति दृढ फरक शब्दहरूमा त्यही दाबी चुक्छ
ट्रेसबाट प्रमाण मोडेललाई प्रमाण जोड्न भन्नु ट्रेस नै ग्राउन्ड ट्रुथ ट्रेस रेकर्डमा data चाहिन्छ
समस्याहरूबाट संशोधन, शून्यबाट होइन उत्तर पुनः उत्पादन प्रमाणित दाबीहरू जोगाउँछ ड्राफ्टको संरचना वंशानुगत आउँछ

जरिवानाको पङ्क्तिलाई डेटासँग पुनः हेर्नुपर्छ। 0.15 को अर्थ एक प्रोग्रामेटिक त्रुटिको लागत १५ स्कोर अंक हो, जुन मापन होइन क्यालिब्रेशन अनुमान हो। Part 10 को हार्नेसले त्यो बदल्नेछ: लेबल गरिएको सेटमा एजेन्ट चलाउनुहोस्, खुला निर्णयसहित स्वीकार गरिएका उत्तरहरू गन्नुहोस्, र त्यो संख्या शून्य हुने गरी तौल राख्नुहोस्।

टेस्टिंग

तेह्र टेस्टहरू, नेटवर्क छैन, 7 ms। अपरिवर्तनीयताहरू:

import json
import unittest
import reflect as rf
from contracts import ScriptedLLM, Tool, ToolResult
EVIDENCE = [
rf.Evidence("latency-budget#0",
"Reranking 20 candidates costs about 200 ms per query at 12 layers. "
"Capping the set at 8 candidates brings the added cost under 100 ms."),
rf.Evidence("chunking#0",
"Chunk sizes between 300 and 500 characters with a fifth of the window "
"as overlap balance precision against index inflation."),
]
def store():
return rf.EvidenceStore(EVIDENCE)
def critique(score, verdict, claims):
return {"type": "critique", "score": score, "verdict": verdict,
"issues": [{"claim": c, "problem": "unsupported", "fix": "cite evidence"}
for c in claims]}
class TestChecks(unittest.TestCase):
def test_uncited_claim_is_flagged(self):
verdicts = store().check(rf.Claim("Reranking costs 200 ms per query.", ()))
self.assertEqual(verdicts[0].code, "no_citation")
def test_invented_citation_is_flagged(self):
verdicts = store().check(rf.Claim("Reranking is slow [ghost-doc#0].", ("ghost-doc#0",)))
self.assertEqual(verdicts[0].code, "unknown_citation")
def test_fabricated_number_is_flagged(self):
claim = rf.Claim("Reranking costs about 340 ms per query [latency-budget#0].",
("latency-budget#0",))
verdicts = store().check(claim)
self.assertEqual(verdicts[0].code, "number_mismatch")
self.assertIn("340", verdicts[0].detail)
def test_unsupported_quote_is_flagged(self):
claim = rf.Claim('The guide says "never rerank above twelve candidates" [latency-budget#0].',
("latency-budget#0",))
self.assertEqual(store().check(claim)[0].code, "quote_missing")
def stub_search_tool() -> Tool:
passages = [
{"citation": "latency-budget#0", "doc": "latency-budget", "text": EVIDENCE[0].text, "score": 0.8},
{"citation": "chunking#0", "doc": "chunking", "text": EVIDENCE[1].text, "score": 0.6},
]
def _run(args: dict) -> ToolResult:
return ToolResult(ok=True, data=json.dumps(passages))
return Tool(name="search", description="Canned passages.",
parameters={"type": "object",
"properties": {"query": {"type": "string", "minLength": 2}},
"required": ["query"], "additionalProperties": False},
_fn=_run)
DRAFT = ("A cross-encoder reranker costs about 340 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters [chunking#0].")
REVISED = ("A cross-encoder reranker costs about 200 ms per query for 20 candidates "
"[latency-budget#0]. Chunk windows should sit between 300 and 500 characters [chunking#0].")
class TestLoop(unittest.TestCase):
def test_fabricated_number_survives_one_revision_then_accepts(self):
llm = ScriptedLLM([
{"type": "tool", "name": "search", "arguments": {"query": "reranker latency"}},
{"type": "final", "content": DRAFT},
critique(0.62, "revise", ("A cross-encoder reranker costs about 340 ms",)),
{"type": "final", "content": REVISED},
critique(0.90, "accept", ()),
])
run = rf.ReflectiveAgent(llm, [stub_search_tool()]).run("What does reranking cost?")
self.assertEqual(run.rounds, 2)
self.assertEqual(run.stopped_by, "accepted")
self.assertEqual(run.history[0]["programmatic_errors"], 1)
self.assertIn("340", run.history[0]["verdicts"][0].detail)
def test_same_issue_twice_is_oscillation(self):
llm = ScriptedLLM([
critique(0.55, "revise", ("claim one is thin",)),
{"type": "final", "content": "Claim one, expanded [latency-budget#0]."},
critique(0.75, "revise", ("claim one is thin",)),
])
run = rf.ReflectionLoop(llm, rf.RubricCritic(llm), store(),
rf.ReflectionConfig(max_rounds=4, min_delta=0.01)
).run("goal", "Claim one [latency-budget#0].")
self.assertEqual(run.stopped_by, "oscillation")
def test_no_progress_stops_before_a_second_revision(self):
llm = ScriptedLLM([
critique(0.55, "revise", ("claim one is thin",)),
{"type": "final", "content": "Claim one, expanded [latency-budget#0]."},
critique(0.60, "revise", ("claim one is still thin",)),
])
run = rf.ReflectionLoop(llm, rf.RubricCritic(llm), store(),
rf.ReflectionConfig(max_rounds=4)).run(
"goal", "Claim one [latency-budget#0].")
self.assertEqual(run.stopped_by, "no_progress")
self.assertEqual(len(run.history), 2)
def test_unparseable_critic_never_forces_a_revision(self):
llm = ScriptedLLM([{"type": "critique", "score": "high", "verdict": "maybe"}])
run = rf.ReflectionLoop(llm, rf.RubricCritic(llm), store(),
rf.ReflectionConfig(max_rounds=3)).run("g", "draft")
self.assertEqual(run.stopped_by, "critic_unparseable")
self.assertEqual(run.final_answer, "draft")
def test_reviser_prompt_contains_the_issues(self):
llm = ScriptedLLM([
critique(0.55, "revise", ("claim one is thin",)),
{"type": "final", "content": "Claim one, fixed [latency-budget#0]."},
critique(0.95, "accept", ()),
])
rf.ReflectionLoop(llm, rf.RubricCritic(llm), store()).run("g", "Claim one [latency-budget#0].")
self.assertIn("claim one is thin", llm.calls[1][1].content)
if __name__ == "__main__":
unittest.main()

test_no_progress_stops_before_a_second_revision र test_same_issue_twice_is_oscillation जानाजान लगभग एकै हुन् — त्यही आलोचना आकार, त्यही ड्राफ्ट — किनकि दुई रोक्ने सर्तहरूलाई टेस्ट सेटअपले होइन स्कोर चलाइले छुट्याउन सक्नुपर्छ। रिफ्याक्टरले तिनलाई एक जाँचमा गाभे, यी दुई टेस्टहरू फरक stopped_by मानहरूसँग असफल हुन्छन् र गाभिएको देखिन्छ।

test_unparseable_critic_never_forces_a_revision ले विकृतमा स्वीकृति नीति पिन गर्छ। आकर्षक विकल्प — आलोचक पुनःप्रयास — त्यही नै सीमारहित मार्ग हो, र यो टेस्ट नै गार्डरेल हो।

अभ्यासहरू

  1. सहनशील नम्बर जाँच। number_mismatch लाई दाबी र प्रमाण दुवै नम्बर पार्स गरी १० प्रतिशतभन्दा बढी फरक भएमा मात्र चिन्हित गर्ने बनाउनुहोस्। त्यसपछि विरोधी केस लेख्नुहोस्: प्रमाणले under 100 ms भन्छ, ड्राफ्टले 95 ms दाबी गर्छ। सहनशीलताले गलत सटीक नम्बर जान दिन्छ कि दिँदैन? रेखा कहाँ छ?
  2. हरेक-जाँच जरिवाना। 0.15 * errors लाई कोड प्रति तौलसँग बदल्नुहोस्: unknown_citation को लागत quote_missing भन्दा बढी हुनुपर्छ। हरेक तौल एक वाक्यमा पुष्टि गर्नुहोस्, त्यसपछि दस ड्राफ्टहरू लुपबाट चलाएर स्वीकृति दर बदलियो कि भनेर रिपोर्ट गर्नुहोस्।
  3. कार्यभित्रको प्रतिबिम्बन। PlannedAgent._run_task लाई प्रतिबिम्बन पास दिनुहोस्: हरेक कार्य परिणाम फर्ता गर्नु अघि आफ्नै खोज प्रमाणसँग प्रमाणित गर्नुहोस्। चार-कार्य योजनाका लागि प्रति-कार्य प्रतिबिम्बनसहित र बिना कुल मोडेल कल र वाल टाइम मापन गर्नुहोस्। प्रति-कार्य प्रमाणीकरणले रन-अन्त्य प्रमाणीकरणलाई कहाँ उछिन्छ, र कहाँ खेर जान्छ?

अभ्यास 3 आर्किटेक्चरल हो। कार्य सीमामा प्रमाणीकरणले त्रुटिहरू संश्लेषणमा प्रवेश गर्नु अघि नै पक्र्छ, तर हरेक कार्यमा प्रतिबिम्बनको लागत तिर्छ — मापनले ठान्छ, र यो शृंखलामा पहिलो पटक गुणस्तर यन्त्र कहाँ बस्नुपर्छ भन्ने छनोट गर्नुपर्छ।

अब के

अहिलेसम्म सबै कुरा एक प्रोसेसभित्र चल्छ: ट्रेस, योजना, प्रमाण सेट र प्रतिबिम्बन इतिहास सबै ऊ रोकिँदा हराउँछन्। चार मिनेट लिने रनले डिप्लोय सहन सक्दैन, र 8 मध्ये कार्य 6 मा क्र्यास कार्य 1 बाट पुनःसुरु हुन्छ।

Part 8, Checkpointing and recovery, टिकाउ अवस्था थप्छ: हरेक कार्य र हरेक लुप स्टेपपछि लेखिने चेकपोइन्ट, पुनःसुरु गरिएको रनले कहिल्यै साइड इफेक्ट दोहोऱ्याउन नपरोस् भन्ने आइडेम्पोटेन्ट टूल रिप्ले, र प्लानरका लागि चेकपोइन्ट-बाट-पुनःसुरु व्यवहार। तपाईंले भर्खरै बनाएको प्रतिबिम्बन इतिहास चेकपोइन्टको भाग हुन्छ — पुनःसुरु गरिएको रनले पहिले नै पास भएको उत्तरको पुनः आलोचना गर्नु हुँदैन।

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.