Back to all articlesAI और एजेंट

स्व-मोह के बिना प्रतिबिंब: रुकने वाले सत्यापन-लूप (भाग 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

सबसे सामान्य reflection कार्यान्वयन एक prompt है: Review your answer for errors and improve it. वह भरोसे-योग्य रूप से लंबा उत्तर पैदा करता है. क्या वह बेहतर उत्तर पैदा करता है, यह अलग सवाल है, क्योंकि अपना ड्राफ्ट समीक्षित करने वाले मॉडल के पास कोई ऐसी जानकारी नहीं है जो ड्राफ्ट में पहले से नहीं थी. आलोचना उत्तर को अधिक आत्मविश्वासी शब्दों में दोहराती है, संशोधन आलोचना को दोहराता है, और आपने token-गिनती बढ़ाने के लिए दो मॉडल-कॉल चुकाए.

Reflection ठीक दो परिस्थितियों में मदद करता है: आलोचना पहली पास ने उपयोग न किए सबूतों से लगी हो, या कोई program ऐसी चीज़ जाँचे जिसके साथ मॉडल विवाद नहीं कर सकता. यह भाग दोनों बनाता है — और फिर वह खंड बनाता है जिसे सब छोड़ते हैं, रुकने-की-शर्तें, क्योंकि असीमित reflection loop एक ही उत्तर के दो रूपों के बीच दोलायमान रहता है जब तक चरण-बजट मर नहीं जाता.

पिछले तीन भागों का प्रतिफल यहाँ ठोस है. भाग 5 ने हर खोज-परिणाम को citation id दिया; भाग 6 ने हर task को सीमित परिणाम. Citation ids सत्यापन को निर्णयात्मक बनाते हैं: या तो उद्धृत passage मौजूद है और संख्या रखता है, या नहीं. उनके बिना सत्यापन राय है, और राय loop नहीं रोकतीं.

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

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

  • extract_claims + EvidenceStore — उत्तर को वाक्यों में बाँटता है, और हर एक की जाँच उन सबूतों से करता है जो run वास्तव में लाया: citation की मौजूदगी, संख्या-मिलान, शब्दशः उद्धरण.
  • RubricCritic — प्रति round एक मॉडल-कॉल, चार-बिंदु रूब्रिक, संरचित आउटपुट और कठोर नियम के साथ: विकृत आलोचना स्वीकृति है, कभी भी संशोधन नहीं.
  • ReflectionLoop — आलोचना, संशोधन, तीन रुकने-की-शर्तों के साथ: round limit, न्यूनतम स्कोर सुधार, आलोचना-फ़िंगरप्रिंट से दोलन पहचान.
  • ReflectiveAgent — ड्राफ्ट के लिए AgentLoop चलाता है, trace से सबूत-सेट फिर बनाता है, फिर सत्यापित करता है.

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 एक पंक्ति है, और वह केवल-पठनीय trace और जिसके विरुद्ध सत्यापन हो सके उसके बीच का अंतर है. उसके बिना सबूत-सेट को मॉडल की उस स्मृति से पुनर्निर्मित करना पड़ता कि उसने क्या पढ़ा — और ठीक वही वह विफलता है जिसे reflection पकड़ना चाहिए.

आवश्यकताएँ

  • भाग 1–6. reflect.py AgentLoop, LLMClient, Message और Tool को contracts.py से import करता है.
  • Python 3.10+, केवल standard library (re, json, hashlib).
  • Demo ऑफ़लाइन चलने के लिए दो तैयार passages के साथ एक stub search टूल उपयोग करता है; असली प्रोजेक्ट में भाग 5 का make_search_tool(retriever) लगाएँ — reflection layer को फ़र्क़ नहीं पड़ता कौन-सा.

क्यों अपने उत्तर पर प्रतिबिंब चीज़ों को बदतर बनाता है

अमूर्त आत्म-आलोचना संरचनात्मक कारण से फेल होती है, prompt-इंजीनियरिंग के कारण नहीं. आलोचना-चरण एक दूसरा मॉडल-कॉल है जिसकी एकमात्र इनपुट वह टेक्स्ट है जो पहली कॉल ने पैदा किया. कोई नई जानकारी नहीं, इसलिए सबसे अच्छी संभावित आलोचना उसका पुनः-व्युत्पन्न है जो पहले से वहाँ है — और मॉडल अपने आत्मविश्वासी त्रुटियों को चिह्नित करने में विशेष रूप से बुरे हैं, क्योंकि वही वज़न जिनसे वाक्य पैदा हुआ, वाक्य का न्याय करते हैं.

जो reflection उपयोग कर सकता है, और जिसे यह भाग जोड़ता है, वह अंतरात्मक जानकारी है:

  • सबूत-सेट — tools वास्तव में क्या लौटाए, जिसे ड्राफ्ट नज़रअंदाज़ कर सकता था या उलटा सकता था.
  • निर्णयात्मक जाँचें — citation की मौजूदगी, संख्या-मिलान, उद्धरण-उपस्थिति, जिन्हें मॉडल की बिल्कुल ज़रूरत नहीं.
  • स्केल वाली रूब्रिक — ताकि score संवेदना की बजाय अंकगणित चला सके.

क्रम मायने रखता है, और वही मूल डिज़ाइन है: पहले programmatic जाँचें, मॉडल-निर्णय बाद में. जवाबदेही की एक असमरूपता भी है जिसे चूकना आसान है. जब मॉडल-आधारित आलोचना ग़लत होती है, सिस्टम में कुछ भी ऐसा नहीं कह सकता — आलोचना न्याय है, और न्याय ऑडिट-पदचिह्न नहीं छोड़ते. जब EvidenceStore.check number_mismatch चिह्नित करता है, निर्णय दावा, कोड और ठीक वही संख्या नाम करता है जो नामित citation में अनुपस्थित है. open_verdicts पढ़ने वाला डेवलपर एक खंडन-योग्य कथन देखता है, यानी ग़लत-धनात्मक डिबग-योग्य है: passage देखें, regex देखें, नियम ठीक करें. जाँच-योग्य स्तर पहले बनाएँ, और critic बनाम जाँचों के बाद के हर विवाद के पास सत्य-स्थल होगा. 40 माइक्रोसेकंड में चलने वाली जाँच या तो पास होती है या दोष नाम करती है; critic फिर वह न्याय करता है जो program नहीं कर सकता — क्या दावा लक्ष्य के उत्तर में है, क्या तर्क-शृंखला सुसंगत है. Critic को केवल गद्य देकर दोनों काम करवाना दोनों में सबसे बुरा देता है: वह संख्याएँ भरोसे से जाँच नहीं सकता, और वह अपना ध्यान व्याकरण पर खर्च करेगा.

वे जाँचें जो program चला सकता है: citations, संख्याएँ, उद्धरण

दावा शून्य या अधिक citation ids वाला वाक्य है. जाँचें जानबूझकर यांत्रिक हैं:

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 सबसे सस्ती और सबसे मूल्यवान है. बिना-उद्धरण दावा ज़रूरी तौर पर ग़लत नहीं, पर असत्यापित है, और अनुसंधान agent में असत्यापित ही दोष है: भाग 5 के citation-प्रारूप की पूरी बात दावों को जाँच-योग्य बनाना थी. अनुपस्थिति को विफलता मानने पर मॉडल उद्धरण देना सीखता है — prompt-पक्ष निर्देश (cite as [doc#n]) और यह जाँच मिलकर बंद लूप है.

unknown_citation कल्पित citations पकड़ता है — [retrieval-design#7] जब उस दस्तावेज़ के दो chunks हैं. यह वह जाँच है जिसे vector-database-RAG सिस्टम छोड़ देते हैं, और वह मुफ़्त है.

number_mismatch पंडिताई तक कठोर है: दावे की हर संख्या उद्धृत टेक्स्ट में शब्दशः दिखनी चाहिए. इसका अर्थ है वैध पैराफ़्रेज़ चिह्नित होगा — सबूत कहते हैं 180 to 240 milliseconds, दावा कहता है about 200 ms. यह जानबूझकर है. पैराफ़्रेज़ की संख्या सही खोज को ग़लत उत्तर बनाने का सबसे सामान्य रास्ता है, और चिह्नित पैराफ़्रेज़ की क़ीमत एक संशोधन-round है, जबकि बिना-चिह्न बनाया संख्या की क़ीमत ग़लत वितरण है. 200 ms का मामला ठीक वही है जो नीचे का demo दिखाता है.

quote_missing केवल 8–160 वर्णों के उद्धृत खंडों पर चलता है. छोटे शोर हैं; लंबे प्रायः मॉडल अपना ही सारांश उद्धृत कर रहा होता है. जाँच सत्यापित करती है कि उद्धरण सबूतों में कहीं मौजूद है — न कि वह सही citation का है, जिसे खंड-पंक्तिबद्धन चाहिए और इस स्तर पर जटिलता की लायक़ नहीं.

रूब्रिक और एक veto वाला critic

Critic रूब्रिक, स्केल और संरचित आउटपुट के साथ एक मॉडल-कॉल है. स्केल इसलिए है कि loop उस पर अंकगणित कर सके.

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)

उस class में दो नीतियाँ अपने वाक्य माँगती हैं.

विकृत आलोचना स्वीकृति है. यह उल्टा लगता है — निश्चय टूटा critic “दोबारा कोशिश” का अर्थ नहीं? नहीं, क्योंकि loop के भीतर critic को दोहराना असीमित विफलता-पथ बनाता है: critic फेल हुआ, आप दोहराते हैं, वह दूसरे ढंग से फेल होता है, आप दोहराते हैं. न-पढ़े-जा-सकने वाली आलोचना का सुरक्षित पठन है कि उस पर अमल नहीं किया जा सकता, और अमल-न-करना वर्तमान ड्राफ्ट की स्वीकृति है, जो पहले ही programmatic जाँचों से गुज़र चुका है. Loop critic_unparseable रुकने-का-कारण दर्ज करता है, इसलिए run लेबलित है, मौन नहीं.

फ़िंगरप्रिंट दोलन-संधानक है. प्रश्न-दावों का हैशिंग “critic बार-बार वही कहता है” को समानता-परीक्षण बना देता है. उसके बिना हमेशा claim one is thin चिह्नित करने वाला critic अनंत संशोधन-लूप पैदा करता है — और फ़िंगरप्रिंट समानता स्कोर-समानता से मज़बूत संकेत है, क्योंकि स्कोर खिसकते हैं पर अटका प्रश्न नहीं.

तीन रुकने-की-शर्तें

Loop जाँचें, critic और संशोधन की रचना करता है. उसकी पूरी आचरण तीन निकास-शर्तों के क्रम में है:

@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

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

min_delta=0.08 विरोधी-द्वंद्ववाद शर्त है. संशोधन की क़ीमत दो कॉल (आलोचना + फिर-लिखना, साथ में संशोधन का न्याय करने वाली आलोचना). यदि अंतिम संशोधन ने स्कोर 0.08 से कम बदला, तो अगला शायद बेहतर न करे, और ईमानदार उत्तर रुकना और लेबल करना है: no_progress. नीचे के tests में 0.55 → 0.60 round ठीक यही जन्म देता है.

दोलन की जाँच सुधार के बाद होती है, जानबूझकर. बड़ा स्कोर-छलांग समरूप फ़िंगरप्रिंट के साथ संदिग्ध है — critic को फिर-लिखना पसंद था और उसने वही शिकायत दोहराई. वहाँ रुकना तीसरे round से बेहतर है, क्योंकि तीसरा round दूसरे की ही पुनरावृत्ति कर सकता है. तीन जाँचों का क्रम: स्वीकृति, फिर सुधार, फिर फ़िंगरप्रिंट. क्रम बदलें तो अलग विफलता-run मिलेंगे; tests क्रम पिन करते हैं.

max_rounds=2 बजट है, और डिफ़ॉल्ट उत्तर. Loop stopped_by="max_rounds" और वर्तमान ड्राफ्ट के साथ निकलता है, जो दो संशोधनों के बाद साधारणतः मूल से बेहतर है, भले वह कभी accept_score तक न पहुँचा. लेबल सहित जारी रखना त्यागने से बेहतर है — कॉलर (भाग 8 का checkpoint स्तर) तय कर सकता है कि max_rounds उत्तर उसके उपयोग-मामले के लिए स्वीकार्य है या नहीं.

run में जोड़ना

Agent trace से सबूत फिर बनाता है, इसलिए सत्यापन उससे लगा है जो tools ने लौटाया, न कि जिसे मॉडल याद रखता है:

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")) — सबूत जिसे tool ने कभी पैदा नहीं किया, किसी को सत्यापित नहीं कर सकता, और फेल खोज का citation उद्धृत करने वाला ड्राफ्ट unknown_citation से पकड़ा जाता है.

उस पुनर्निर्माण की तीन विशेषताएँ दिखने से अधिक मायने रखती हैं.

डुप्लिकेशन-निकास स्वचालित है. पाँच खोजें जारी करने वाला run अतिरोधी passages लाएगा — भाग 5 का index डिज़ाइन से chunks पर अतिरोध करता है, और दो queries अक्सर वही citation उगलती हैं. items citation id द्वारा अनुक्रमित है, इसलिए सबूत-सेट अद्वितीय passages का संघ है, उन्हीं तीन chunks की पाँच प्रतियाँ नहीं. सत्यापन लागत इसलिए corpus विविधता द्वारा सीमित है, run की लंबाई द्वारा नहीं.

सबूत-खंड बजट-निर्णय है. block() 1,400 वर्णों पर सीमित है — लगभग 350 tokens — हर passage 200 पर कटा. चार-चार passages लौटाती दो खोजें इसलिए प्रति आलोचना-कॉल अधिकतम 350 tokens लेती हैं, और max_rounds=2 के साथ वह पूरे run के लिए 700 tokens आलोचना-संदर्भ है. निवेदक विकल्प से तुलना करें, पूरा trace critic में चिपकाना: 420-420 tokens की पाँच खोजें 2,100 tokens हैं, और critic वह tool-आउटपुट पढ़ता है जिसे ड्राफ्ट ने कभी उपयोग न किया हो.

max_steps=6 ड्राफ्ट को बाँधता है, सत्यापन को नहीं. छह loop-चरणों के बाद का ड्राफ्ट अधिकतम छह खोज-पैकेज उद्धृत कर सकता है, इसलिए सबूत-सेट की कठोर छत छह अद्वितीय citation-समूह है. इसीलिए सत्यापन लागत max_steps के साथ स्केल होती है भले loop कॉन्फ़िगरेशन उसका कभी उल्लेख न करे — और इसीलिए भाग 8 trace को checkpoint के साथ सहेजेगा, न कि उसे फिर गणेगा.

Demo ठीक वही विफलता पकड़ता है जिसके लिए यह भाग है. ड्राफ्ट कहता है 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 2 है, 5 नहीं. आधार run 2 मॉडल-कॉल है (खोज, अंतिम उत्तर). Reflection 3 जोड़ता है: एक आलोचना, एक संशोधन, एक आलोचना. वह 2.5× कॉल है और लगभग 2× tokens — आलोचना और संशोधन prompts दोनों सबूत-खंड (≤1,400 वर्ण) और ड्राफ्ट ले जाते हैं. एक round ने एक गढ़ी संख्या पकड़ी. वह अच्छा सौदा है. सही उत्तर को परिमार्जित करने के लिए पाँच rounds नहीं — और ठीक वही no_progress और oscillation रोकते हैं.

यह भी गौर करें कि critic को नहीं करना पड़ा: उसने कभी 340 को अंकगणित-समस्या नहीं देखा. Programmatic जाँच ने उसे पाया, नाम दिया (340 absent from latency-budget#0), और critic का कार्य न्याय तक सिमट गया — ड्राफ्ट का बाक़ी हिस्सा स्वीकार्य है क्या? यही कार्य-विभाजन है जिसकी वजह से एक संशोधन-round काफ़ी था.

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

त्रुटि वास्तव में क्या होता है यहाँ का समाधान अब भी टूटा हुआ
वैध संख्या-पैराफ़्रेज़ about 200 ms बनाम 180 to 240 milliseconds चिह्नित, क़ीमत एक संशोधन-round कोई श्रेणी-सजग संख्या-जाँच नहीं
Critic हर चीज़ 0.95 अंकित करता है Reflection कभी चालू नहीं होता दंड + errors == 0 स्वीकृति-शर्त अंशांकित critic को वास्तविक डेटा चाहिए (भाग 10)
Critic आउटपुट अपार्स-योग्य Loop क्रैश या घूम जाता critic_unparseable रुकना, ड्राफ्ट लौटा कोई retry नहीं — लगातार टूटा critic एक घटना है
हर round वही प्रश्न अनंत संशोधन फ़िंगरप्रिंट समानता → oscillation Fix सुझाव reviser लागू नहीं करता
सबूत-सेट खाली (कोई खोज नहीं) हर दावा बिना-उद्धरण सभी दावों पर no_citation “सबूत आवश्यक नहीं” और “सबूत छोड़े” में भेद नहीं
ड्राफ्ट फेल खोज उद्धृत करता है Citation कभी प्राप्त नहीं unknown_citation मॉडल खोज दोहराकर डिग्रेज़ कर सकता है
संशोधन स्वच्छ दावा तोड़ता है संशोधन के बाद स्कोर गिरता है no_progress loop रोकता है संशोधन prompt citations रखने को कहता है, लागू नहीं कर सकता

पहली पंक्ति कठोर जाँचों की ईमानदार क़ीमत है: number_mismatch पैराफ़्रेज़ पर चलता है. यदि आपका corpus श्रेणियों और लगभगों से भरा है, तो या तो प्रति उत्तर एक अतिरिक्त संशोधन-round स्वीकार करें, या जाँच को संख्यात्मक-सहनशीलता तुलना में ढीला दें — दोनों संख्याएँ parse करें, केवल 10 प्रतिशत से अधिक भिन्न होने पर चिह्नित करें. दूसरा विकल्प check के दस-पंक्तियों का बदलाव और अच्छा अभ्यास है, पर ध्यान रखें उसकी क़ुर्बानी: about 200 का 180 to 240 श्रेणी से मेल एक न्याय है, और जैसे ही जाँच न्याय करती है, उससे विवाद किया जा सकता है.

Trade-offs

निर्णय विकल्प हमने यह क्यों चुना क़ीमत
पहले programmatic जाँचें Critic हर चीज़ का न्याय करे निर्णयात्मक, मुफ़्त, विवाद-अपेक्षित नहीं पैराफ़्रेज़ संख्याएँ चिह्नित होती हैं
विकृत आलोचना = स्वीकृति Critic दोहराएँ कोई असीमित विफलता-पथ नहीं अस्थिर critic चुपचाप स्वीकार करता है
max_rounds=2 5 या असीमित लागत rounds में रैखिक कठिन समस्याएँ जल्दी रुकती हैं, लेबल सहित
दंड-अंकगणित (0.15 × errors) Critic निर्णयों को टेक्स्ट के रूप में देखे Critic जाँचों को बहुमत से पलट नहीं सकता भाग 10 तक भार जादुई संख्या
प्रश्न-दावों का फ़िंगरप्रिंट पूरी आलोचना का हैश क्रम-बदलाव और स्कोर-खिसकने के प्रति मज़बूत अलग शब्दों में वही दावा फिसल जाता है
Trace से सबूत मॉडल से सबूत साथ चिपकाने को कहें Trace ही सत्य-स्थल है Trace रिकॉर्ड्स में data चाहिए
प्रश्नों से संशोधन, शून्य से नहीं उत्तर फिर पैदा करें सत्यापित दावे सुरक्षित रहते हैं ड्राफ्ट संरचना विरासत में

दंड पंक्ति वही है जिसे डेटा के साथ दोबारा देखना चाहिए. 0.15 का अर्थ एक programmatic त्रुटि की क़ीमत 15 स्कोर-अंक है, जो अंशांकन-अनुमान है, मापन नहीं. भाग 10 का हार्नेस उसे बदलेगा: लेबलित सेट पर agent चलाएँ, खुले निर्णयों के साथ स्वीकृत उत्तर गिनें, और भार ऐसा तय करें कि वह संख्या शून्य हो.

परीक्षण

तेरह tests, बिना network, 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 जानबूझकर लगभग समरूप हैं — वही आलोचना-आकार, वही ड्राफ्ट — क्योंकि दोनों रुकने-की-शर्तें test-सेटअप से नहीं, स्कोर-गति से भिन्न होनी चाहिए. यदि रिफ़ैक्टर दोनों को एक जाँच में मिला दे, ये दो tests अलग stopped_by मानों से फेल होंगे और मिलना दृश्य होगा.

test_unparseable_critic_never_forces_a_revision विकृत पर स्वीकृति नीति पिन करता है. लुभावना विकल्प — critic दोहराना — ठीक वही असीमित पथ है, और यह test रक्षा-दीवार है.

अभ्यास

  1. सहनशील संख्या-जाँच. number_mismatch को दोनों दावा और सबूत संख्याएँ parse करने और केवल 10 प्रतिशत से ऊपर अंतर चिह्नित करने में बदलें. फिर विरोधी मामला लिखें: सबूत कहते हैं under 100 ms, ड्राफ्ट दावा करता है 95 ms. क्या सहनशीलता ग़लत सटीक संख्या को गुज़रने देती है? सीमा कहाँ है?
  2. प्रति-जाँच दंड. 0.15 * errors को प्रति-कोड भार से बदलें: unknown_citation की क़ीमत quote_missing से अधिक होनी चाहिए. हर भार को एक वाक्य में सिद्ध करें, फिर दस ड्राफ्ट loop से गुज़ारकर रिपोर्ट करें कि स्वीकृति-दर बदली या नहीं.
  3. Task के भीतर reflection. PlannedAgent._run_task को reflection-पास दें: हर task परिणाम को लौटाने से पहले उसकी अपनी खोज-सबूतों के विरुद्ध सत्यापित करें. चार-task प्लान के लिए कुल मॉडल-कॉल और wall time मापें प्रति-task reflection के साथ और बिना. कहाँ task-सीमा पर सत्यापन run-अंत के सत्यापन को मात देता है, और कहाँ वह बर्बाद है?

तीसरा अभ्यास वास्तुकला वाला है. Task-सीमा पर सत्यापन त्रुटियों को संश्लेषण में जाने से पहले पकड़ता है, पर हर task की reflection-क़ीमत चुकाता है — मापन तय करता है, और यह पहली बार है जब इस सीरीज को चुनना पड़ा कि गुणवत्ता-तंत्र कहाँ रहता है.

आगे क्या

अब तक सब एक process में चलता है: trace, प्लान, सबूत-सेट और reflection-history सब process के गायब होने पर गायब हो जाते हैं. चार मिनट लेने वाला run deploy से नहीं बचता, और 8 में से task 6 पर क्रैश 1 से रीस्टार्ट करता है.

अगला भाग, भाग 8 — Checkpointing and recovery — दीर्घस्थ स्थिति जोड़ता है: हर task और हर loop-चरण के बाद लिखा जाने वाला checkpoint, idempotent tool replay ताकि resume हुआ run कोई side effect न दोहराए, और planner के लिए resume-from-checkpoint semantics. आपका बनाया reflection-history checkpoint का हिस्सा बन जाता है — resume हुआ run पहले से पास उत्तर की दोबारा आलोचना नहीं करेगा.

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.