不自欺的反思:會停下來的驗證迴圈(第七篇)
Verification before reflection
One reflection round
The program checks are a veto the critic cannot outvote.
- input
- process
- decision
- output
最常見的反思實作就是一句 prompt:Review your answer for errors and improve it. 它確實穩定產出更長的答案。是否產出更好的答案是另一回事,因為審查自己草稿的模型,手上沒有任何草稿之外的新資訊。批評用更篤定的措辭複述答案,修訂再複述批評,而你花了兩次模型呼叫,只換來 token 數的增加。
反思只在恰好兩個條件下有幫助:批評錨定在第一輪沒用過的證據上,或由程式檢查模型無法反駁的東西。本篇兩者都建——然後把人人跳過的那部分也建起來:停止條件,因為沒有邊界的反思迴圈會在同一個答案的兩個版本之間輪流擺盪,直到步數預算耗盡。
前三篇的回報在此具體成形。第五篇讓每次搜尋結果都帶 citation id;第六篇讓每個任務都有有界結果。citation id 使驗證變成可決定的:被引用的段落存在且含該數字,或不存在。沒有它們,驗證只是意見,而意見止不住迴圈。
你將建構什麼
一個 reflect.py 模組,包含四個部分:
extract_claims+EvidenceStore— 把答案拆成句子,逐句對照 run 實際檢索到的證據:citation 是否存在、數字是否相符、引文是否原樣。RubricCritic— 每輪一次模型呼叫,帶四項評分表、結構化輸出,以及一條鐵律:畸形的批評等於接受,永遠不是修訂。ReflectionLoop— 批評、修訂,帶三個停止條件:輪數上限、最低分數改善、以批評指紋做的震盪偵測。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」與「能拿來驗證的 trace」之間的分界。沒有它,證據集就得靠模型對自己讀過什麼的記憶來重建——那正是反思本該抓住的失敗。
前置條件
- 第一至六篇。
reflect.py匯入AgentLoop、LLMClient、Message、Tool,皆來自contracts.py。 - Python 3.10+,只用標準函式庫(
re、json、hashlib)。 - 示範用一個帶兩段現成段落的 stub
search工具,以便離線執行;在真實專案裡,接上第五篇的make_search_tool(retriever)——反思層不在乎用的是哪個。
為什麼「反思你的答案」反而讓事情更糟
抽象的自我批評之所以失敗,是結構性原因,不是 prompt 工程的問題。批評步驟是第二次模型呼叫,唯一輸入是第一次呼叫產生的文字。沒有新資訊,所以最好的批評也只是把已有的東西重新推導一遍——而模型出了名的不善於標記自己充滿自信的錯誤,因為產出那句話的同一組權重,正是評判那句話的權重。
反思能利用的——也是本篇接上的——是差分資訊:
- 證據集 — 工具實際回傳了什麼,草稿可能忽略或顛倒了它。
- 可決定的檢查 — citation 是否存在、數字是否相符、引文是否在場,這些完全不需要模型。
- 有量表的評分表 — 讓
score能驅動運算,而不是憑感覺。
順序很關鍵,這就是設計核心:程式化檢查在前,模型判斷在後。
還有一個容易被忽略的問責不對稱。當基於模型的批評出錯時,系統裡沒有任何東西能指出這一點——批評是判斷,判斷不會留下稽核軌跡。當 EvidenceStore.check 標記 number_mismatch,裁決點名了主張、程式碼,以及所引 citation 中缺席的那個精確數字。讀 open_verdicts 的開發者看到的是一句可被證偽的陳述——這意味著假陽性可除錯:查段落、查 regex、改規則。先把可檢查的層建起來,之後 Critic 與檢查之間的每一場分歧都有真理可供上訴。一個 40 微秒就跑完的檢查,要嘛通過、要嘛指名道姓一個缺陷;Critic 之後再判斷程式做不到的事——主張是否回應了目標、推理是否連貫。只餵散文給 Critic 並要它兼做兩份工作,會讓你拿到兩頭的缺點:它無法可靠地驗證數字,還會把注意力花在文法上。
程式跑得動的檢查:citation、數字、引文
一個主張是帶零個或多個 citation id 的句子。檢查刻意設計得機械化:
from __future__ import annotations
from dataclasses import dataclass, fieldimport hashlibimport jsonimport 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+")
@dataclassclass Evidence: id: str text: str
@dataclassclass 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 來說,無法驗證就是缺陷:第五篇 citation 格式的全部意義,就是讓主張可被查核。把缺席當成失敗,模型就學會引用——prompt 端的指示(cite as [doc#n])加上這項檢查,構成一個閉環。
unknown_citation 抓住幻覺出來的 citation——[retrieval-design#7],而那份文件只有兩個 chunk。這是 vector-database 式 RAG 系統跳過的檢查,而且它免費。
number_mismatch 嚴格到近乎吹毛求疵:主張裡的每個數字都必須原樣出現在所引文字中。這意味著合法的改寫——證據說 180 to 240 milliseconds,主張說 about 200 ms——會被標記。這是故意的。被改寫過的數字是「檢索正確卻得到錯誤答案」最常見的路徑,被標記的改寫只花一輪修訂,而沒被標記的捏造數字賠上整份錯誤的交付物。200 ms 這個案例正是下面 demo 演示的內容。
quote_missing 只對長度 8–160 字元的引文片段觸發。更短的是雜訊;更長的通常是模型在引自己的摘要。該檢查驗證引文在證據某處存在——不驗證它是否歸屬於正確的 citation,那需要片段對齊,在這個階段不值得。
帶評分表的 Critic,與一票否決
Critic 是一次帶評分表、量表與結構化輸出的模型呼叫。量表的存在,是為了讓迴圈能在它上面做運算。
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.")
@dataclassclass 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 會創造出無界的失敗路徑:Critic 失敗、你重試、它換個方式失敗、你再重試。對你無法解析的批評,安全的解讀是你無法依它行動,而不行動就意味著接受當前草稿——它已經通過了程式化檢查。迴圈把 critic_unparseable 記為停止原因,run 因此被標注,而不是無聲無息。
指紋就是震盪偵測器。 把問題的主張做雜湊,把「Critic 反覆說同一件事」變成相等性測試。沒有它,一個不斷標記 claim one is thin 的 Critic 會產出無限的修訂迴圈——而指紋相等是比分數相等更強的訊號,因為分數會漂移,卡住的問題不會。
三個停止條件
迴圈組合了檢查、Critic 與修訂。它的全部行為就在三個退出條件的排序裡:
@dataclassclass ReflectionConfig: max_rounds: int = 2 min_delta: float = 0.08 accept_score: float = 0.8
@dataclassclass 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 直接相減,所以就算 Critic 給一份未引用又捏造數字的草稿打了 0.9,也會落到 0.6——低於 accept_score,修訂照樣發生。接受條件還要求 errors == 0,所以任何運算都救不了仍有未結裁決的 run。這就是 Critic 保持誠實的機制:程式化檢查不是建議,是 Critic 無法推翻的否決權。
min_delta=0.08 是反搖擺條件。 一次修訂要花兩次呼叫(批評+修訂,再加一次批評來評價修訂)。如果上一次修訂只讓分數移動不到 0.08,下一次也很難更好,誠實的答案是停下來並標注:no_progress。在下面的測試裡,一輪 0.55 → 0.60 恰好觸發這個。
震盪檢查刻意排在改善之後。 大幅跳分配上完全相同的指紋很可疑——Critic 既讚賞了改寫又重複了同一句抱怨。在那裡停下勝過第三輪,因為第三輪只能重演第二輪。三項檢查的順序是:先接受,再改善,再指紋。打亂順序會得到不同的失敗 run;測試把這個順序釘死。
max_rounds=2 是預算,也是預設答案。 迴圈以 stopped_by="max_rounds" 和當前草稿退出,即使從未達到 accept_score,兩輪修訂後的草稿通常仍比原稿好。帶著標籤交出去比丟掉好——呼叫者(第八篇的 checkpoint 層)自行決定 max_rounds 的答案在其使用場景是否可接受。
接進 run
agent 從 trace 重建證據,所以驗證錨定在工具回傳的東西上,而不是模型記得的東西上:
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"))——工具從未產出的證據驗證不了任何東西,而引用了失敗搜尋之 citation 的草稿,會被 unknown_citation 抓住。
這次重建有三個特質,重要性超出它們的外表。
去重自動發生。 一個發出五次搜尋的 run 會檢索到重疊的段落——第五篇的索引本來就讓 chunk 重疊,兩條查詢也常翻出同一個 citation。items 以 citation id 為鍵,所以證據集是唯一段落的聯集,不是同三個 chunk 的五份拷貝。因此驗證成本由語料多樣性封頂,與 run 長度無關。
證據區塊是預算決定。 block() 封頂 1,400 字元——約 350 token——每段截在 200。兩次各回傳四段的搜尋,每次批評呼叫至多 350 token,而配合 max_rounds=2,整個 run 的批評 context 只有 700 token。對照天真的替代方案——把整份 trace 貼給 Critic:五次搜尋、每次 420 token,共 2,100 token,而且 Critic 讀的是草稿可能從未用過的工具輸出。
max_steps=6 封住的是草稿,不是驗證。 六步迴圈後產出的草稿至多引用六份搜尋 payload,所以證據集有六個相異 citation 叢集的硬上界。這就是為什麼驗證成本隨 max_steps 縮放,即使迴圈設定從未提到它——也是第八篇會把 trace 與 checkpoint 一併持久化、而不是重算的原因。
demo 抓到的正是本篇為之而生的那種失敗。草稿宣稱 340 ms;證據說 about 200 ms:
import json
import reflect as rffrom 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: 5final: 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 次模型呼叫(搜尋、作答)。反思加上 3 次:一次批評、一次修訂、一次批評。呼叫量是 2.5 倍、token 約 2 倍——批評與修訂的 prompt 都帶著證據區塊(≤1,400 字元)加草稿。一輪抓住一個捏造的數字。這是筆划算的交易。花五輪為一個已經正確的答案拋光則不然——no_progress 與 oscillation 的存在正是為了防止這件事。
也要注意 Critic 不必做什麼:它從未把 340 當成一道算術題。程式化檢查發現了它、點名了它(340 absent from latency-budget#0),Critic 的工作縮減為判斷——草稿其餘部分是否可接受?正是這種分工讓一輪修訂就足夠。
失敗模式與因應方式
| 失敗模式 | 實際會發生什麼 | 此處的處理 | 仍然無解 |
|---|---|---|---|
| 數字的合法改寫 | about 200 ms 對上 180 to 240 milliseconds |
被標記,花一輪修訂 | 尚無認得區間的數字檢查 |
| Critic 一律給 0.95 | 反思永不觸發 | 扣分+errors == 0 的接受條件 |
校準過的 Critic 需要真實資料(第十篇) |
| Critic 輸出無法解析 | 迴圈會 crash 或空轉 | 以 critic_unparseable 停止,回傳草稿 |
不重試——持續損壞的 Critic 是一起事故 |
| 每輪同一個問題 | 無限修訂 | 指紋相等 → oscillation |
修改建議沒有被修訂者採用 |
| 證據集為空(沒有任何搜尋執行) | 所有主張都未引用 | 所有主張都是 no_citation |
無法區分「不需要證據」與「跳過了證據」 |
| 草稿引用了失敗的搜尋 | Citation 從未被檢索 | unknown_citation |
模型可能重試搜尋而偏離 |
| 修訂弄壞了乾淨的主張 | 修訂後分數下跌 | no_progress 停止迴圈 |
修訂 prompt 嘱咐保留 citation,但無法強制 |
第一列是嚴格檢查的誠實代價:number_mismatch 會在改寫上觸發。如果你的語料充滿區間與近似值,要嘛接受每個答案多一輪修訂,要嘛把檢查放寬成數值容差比較——解析兩邊的數字,只在差異超過 10% 時標記。第二種選擇是改 check 十行,也是個好練習,但要記住它放棄了什麼:about 200 對上 180 to 240 的區間是否相符是一個判斷,而檢查一旦開始做判斷,就可以被反駁。
權衡取捨
| 決定 | 替代方案 | 選擇理由 | 代價 |
|---|---|---|---|
| 程式化檢查在前 | Critic 判斷一切 | 可決定、免費、無法反駁 | 改寫過的數字會被標記 |
| 畸形批評=接受 | 重試 Critic | 沒有無界的失敗路徑 | 罷工的 Critic 會默默放行 |
max_rounds=2 |
5 或無上限 | 成本隨輪數線性 | 更難的問題會較早停止,但帶有標注 |
扣分運算(0.15 × errors) |
Critic 以文字閱讀裁決 | Critic 無法推翻檢查 | 權重在第十篇之前是個魔法數字 |
| 問題主張的指紋 | 雜湊整份批評 | 對重排與分數漂移都穩健 | 同一主張換個說法就漏過 |
| 證據取自 trace | 要求模型附上證據 | trace 是真理依據 | trace 記錄需要 data 欄位 |
| 從問題出發修訂,而非從零重寫 | 重新生成答案 | 保留已驗證的主張 | 繼承草稿結構 |
扣分那一列值得用資料重新審視。0.15 意味著一個程式化錯誤扣 15 分,那是校準的猜測,不是量測。第十篇的 harness 會取代它:在有標籤的集合上跑 agent,統計帶著未結裁決被接受的答案數,然後把權重調到那個數字歸零。
測試
十三個測試、不碰網路、7 ms。以下是這些不變量:
import jsonimport unittest
import reflect as rffrom 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 把畸形即接受的政策釘死。那個誘人的替代方案——重試 Critic——正是無界路徑,這個測試就是護欄。
練習
- 容差版數字檢查。 改
number_mismatch使其解析主張與證據兩邊的數字,只在差異超過 10% 時標記。然後寫出對抗案例:證據說under 100 ms,草稿宣稱95 ms。容差會讓一個精確卻錯誤的數字過關嗎?界線該畫在哪? - 按錯誤碼扣分。 把
0.15 * errors換成每個錯誤碼一個權重:unknown_citation應該比quote_missing更貴。用一句話為每個權重辯護,然後讓十份草稿跑過迴圈,回報接受率是否改變。 - 在任務內反思。 給
PlannedAgent._run_task一段反思:在回傳前,用任務自己的搜尋證據驗證任務結果。量測四任務計畫在開啟與關閉逐任務反思時的總模型呼叫數與牆鐘時間。逐任務驗證在何處勝過 run 結束時的驗證,又在何處是浪費?
練習 3 是帶有架構決策的那一題。在任務邊界驗證能在錯誤進入綜合前抓住它,但要為每個任務付出反思成本——由量測決定,而這也是本系列第一次必須選擇讓品質機制住在哪裡。
接下來
目前的一切都在單一 process 內執行:trace、計畫、證據集與反思歷史,都隨 process 一起消失。跑了四分鐘的 run 撐不過一次部署,而八個任務中的第 6 個崩潰,就得從第 1 個任務重來。
第八篇檢查點與復原會加入持久化狀態:每個任務與每個迴圈步驟之後都寫入 checkpoint、工具以冪等方式重放使續跑的 run 永不重複副作用,以及 planner 的從檢查點續跑語義。你剛建好的反思歷史會成為 checkpoint 的一部分——續跑的 run 不該重新批評一個已經通過的答案。
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.