การสะท้อนโดยไร้การหลอกตัวเอง: วงตรวจสอบที่รู้จุดหยุด (Part 7)
Verification before reflection
One reflection round
The program checks are a veto the critic cannot outvote.
- input
- process
- decision
- output
การใช้งาน reflection ที่พบบ่อยที่สุดคือ prompt เดียว: Review your answer for errors and improve it. มันให้คำตอบที่ยาวขึ้นอย่างแน่นอน แต่มันให้คำตอบที่ดีขึ้นหรือไม่เป็นอีกคำถามหนึ่ง เพราะโมเดลที่ทบทวนฉบับร่างของตัวเองไม่มีข้อมูลใดที่ฉบับร่างไม่มีอยู่แล้ว คำวิจารณ์พูดซ้ำคำตอบด้วยถ้อยคำที่มั่นใจกว่า การแก้ไขพูดซ้ำคำวิจารณ์ และคุณจ่ายการเรียกโมเดลสองครั้งไปเพื่อเพิ่มจำนวน token เท่านั้น
reflection ช่วยได้เพียงสองเงื่อนไขเท่านั้น: คำวิจารณ์ต้องยึดกับหลักฐานที่รอบแรกไม่ได้ใช้ หรือมีโปรแกรมตรวจสิ่งที่โมเดลโต้แย้งไม่ได้ ส่วนนี้สร้างทั้งสองอย่าง — แล้วสร้างอีกส่วนที่ทุกคนข้ามคือเงื่อนไขหยุด เพราะ reflection loop ที่ไร้ขอบเขตจะสลับกลับไปมาระหว่างสองเวอร์ชันของคำตอบเดียวกันจนงบขั้นตอนหมด
ผลตอบแทนของสามส่วนก่อนหน้ามาถึงจุดนี้อย่างเป็นรูปธรรม Part 5 ให้ผลลัพธ์ค้นหาทุกชิ้นมี citation id; Part 6 ให้ทุกงานมีผลลัพธ์ที่มีขอบเขต citation id ทำให้การตรวจสอบเป็นเรื่อง ตัดสินได้: หรือทั้งข้อความที่อ้างมีอยู่และมีตัวเลขนั้น หรือไม่มี หากไร้สิ่งเหล่านี้ การตรวจสอบคือความเห็น และความเห็นไม่หยุดลูป
สิ่งที่คุณจะสร้าง
โมดูล reflect.py ที่มีสี่ส่วน:
extract_claims+EvidenceStore— แยกคำตอบเป็นประโยค แล้วตรวจแต่ละประโยคกับหลักฐานที่รันค้นมาจริง: การมีอยู่ของ citation, การจับคู่ตัวเลข, คำพูดอ้างอิงแบบคำต่อคำRubricCritic— การเรียกโมเดลหนึ่งครั้งต่อรอบด้วย rubric สี่ข้อ ผลลัพธ์แบบมีโครงสร้าง และกฎแข็ง: คำวิจารณ์ที่ผิดรูปแบบคือการยอมรับ ไม่ใช่การแก้ไข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 ที่ตรวจสอบได้ หากไร้มัน ชุดหลักฐานต้องถูกสร้างขึ้นจากความจำของโมเดลว่ามันอ่านอะไร — ซึ่งเป็นความล้มเหลวแบบเดียวกับที่ reflection ต้องจับให้ได้
สิ่งที่ต้องมีก่อน
- Part 1–6.
reflect.pyimportAgentLoop,LLMClient,Message,Toolจากcontracts.py - Python 3.10+ ขึ้นไป ใช้แต่ standard library เท่านั้น (
re,json,hashlib) - เดโมใช้เครื่องมือ
searchแบบ stub ที่มีข้อความสำเร็จรูปสองชุด จึงรันออฟไลน์ได้; ในโปรเจกต์จริงให้ต่อmake_search_tool(retriever)จาก Part 5 — ชั้น reflection ไม่สนว่าตัวไหน
ทำไม “สะท้อนคำตอบของคุณ” ถึงทำให้ทุกอย่างแย่ลง
การวิจารณ์ตัวเองแบบนามธรรมล้มเหลวด้วยเหตุผลเชิงโครงสร้าง ไม่ใช่เชิง prompt engineering ขั้นวิจารณ์คือการเรียกโมเดลครั้งที่สองซึ่งมีอินพุตเดียวคือข้อความที่การเรียกครั้งแรกผลิตขึ้น ไม่มีข้อมูลใหม่ ดังนั้นคำวิจารณ์ที่ดีที่สุดเท่าที่จะเป็นได้คือการสร้างซ้ำสิ่งที่มีอยู่แล้ว — และโมเดลแย่อย่างโจ่งแจ้งในการชี้ข้อผิดพลาดที่มั่นใจของตัวเอง เพราะน้ำหนักชุดเดียวกับที่ผลิตประโยคตัดสินประโยคนั้นเอง
สิ่งที่ reflection ใช้ได้ และสิ่งที่ส่วนนี้ต่อให้ คือข้อมูลแบบ *เปรียบเทียบต่าง
- ชุดหลักฐาน — สิ่งที่เครื่องมือคืนมาจริง ๆ ซึ่งฉบับร่างอาจละเลยหรือเข้าใจผิดขึ้น
- การตรวจที่ตัดสินได้ — การมีอยู่ของ citation, การจับคู่ตัวเลข, การมีของคำพูดอ้างอิง ซึ่งไม่ต้องใช้โมเดลเลย
- rubric ที่มีมาตรวัด — เพื่อให้
scoreขับเคลื่อนเลขคณิตได้ ไม่ใช่ความรู้สึก
ลำดับสำคัญ และเป็นแกนของดีไซน์: ตรวจเชิงโปรแกรมก่อน ตัดสินด้วยโมเดลทีหลัง
ยังมีความไม่สมดุลเรื่องความรับผิดชอบที่มองข้ามง่ายด้วย เมื่อคำวิจารณ์ที่อิงโมเดลผิด ไม่มีอะไรในระบบบอกได้ — คำวิจารณ์คือการตัดสิน และการตัดสินไม่ทิ้งร่องรอยตรวจสอบ เมื่อ EvidenceStore.check ชี้ number_mismatch คำตัดสินระบุทั้งข้อกล่าวอ้าง โค้ด และตัวเลขเป๊ะที่ไม่อยู่ใน citation ที่ระบุ นักพัฒนาที่อ่าน open_verdicts เห็นคำกล่าวที่หักล้างได้ หมายความว่า false positive แก้บั๊กได้: ดูข้อความ ดู regex แก้กฎ สร้างชั้นที่ตรวจได้ไว้ก่อน แล้วทุกความเห็นต่างระหว่างตัววิจารณ์กับการตรวจย่อมมีความจริงอ้างอิงให้ต่อรอง การตรวจที่รันใน 40 ไมโครวินาทีจะผ่านหรือระบุข้อบกพร่อง ตัววิจารณ์จึงตัดสินสิ่งที่โปรแกรมทำไม่ได้ — ข้อกล่าวอ้างตอบโจทย์หรือไม่ เหตุผลมีเหตุมีผลหรือไม่ ให้ตัววิจารณ์มีแต่โสตทัศน์แล้วให้ทำสองหน้าที่ คุณจะได้แย่ที่สุดจากทั้งสอง: มันตรวจตัวเลขได้ไม่น่าเชื่อถือ และเทความสนใจไปกับไวยากรณ์
การตรวจที่โปรแกรมรันได้: citations, ตัวเลข, คำพูดอ้างอิง
ข้อกล่าวอ้างคือประโยคที่มี 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 ถูกที่สุดและมีค่าที่สุด ข้อกล่าวอ้างที่ไร้ citation ไม่จำเป็นต้องผิด แต่ตรวจไม่ได้ และใน research agent สิ่งที่ตรวจไม่ได้คือข้อบกพร่อง: จุดประสงค์ทั้งหมดของรูปแบบ citation ของ Part 5 คือทำให้ข้อกล่าวอ้างตรวจได้ ถือว่าการขาดนั้นเป็นความล้มเหลวแล้วโมเดลจะเรียนรู้ที่จะอ้างอิง — คำสั่งฝั่ง prompt (cite as [doc#n]) คู่กับการตรวจนี้เป็นวงปิด
unknown_citation จับ citation ปลอม — เมื่อเอกสารนั้นมีเพียงสองชังก์แต่มันอ้าง [retrieval-design#7] นี่คือการตรวจที่ระบบ RAG บน vector database มักข้าม และมันฟรี
number_mismatch เข้มงวดถึงขั้นพิถีพิถัน: ตัวเลขทุกตัวในข้อกล่าวอ้างต้องปรากฏคำต่อคำในข้อความที่อ้าง หมายความว่าการเรียบเรียงใหม่อย่างถูกต้อง — หลักฐานบอก 180 to 240 milliseconds แต่ข้อกล่าวอ้างบอก about 200 ms — ถูกชี้ว่า นี่คือเจตนา การเรียบเรียงตัวเลขใหม่คือเส้นทางที่พบบ่อยที่สุดที่การค้นที่ถูกกลายเป็นคำตอบผิด การเรียบเรียงที่ถูกชี้แพ้การแก้ไขหนึ่งรอบ แต่ตัวเลขปลอมที่ไม่ถูกชี้แพ้ผลงานผิด 200 ms คือกรณีที่เดโมด้านล่างแสดงพอดี
quote_missing ทำงานเฉพาะคำพูดอ้างอิงยาว 8–160 อักษร ส่วนสั้นกว่าคือเสียงรบกวน ส่วนยาวกว่ามักเป็นโมเดลอ้างสรุปของตัวเอง การตรวจเช็กว่าคำพูดอ้างอิงมีอยู่ที่ใดที่หนึ่งในหลักฐาน — ไม่ใช่ว่าถูกอ้างถึง citation ที่ถูกต้อง ซึ่งต้องการการจับคู่ช่วงข้อความและไม่คุ้มความซับซ้อนในขั้นนี้
ตัววิจารณ์ที่มี rubric และหนึ่งสิทธิยับยั้ง
ตัววิจารณ์คือการเรียกโมเดลหนึ่งครั้งพร้อม rubric มาตรวัด และผลลัพธ์แบบมีโครงสร้าง มาตรวัดมีไว้เพื่อให้ลูปคำนวณเลขจากมันได้
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_unparseable เป็นเหตุผลการหยุด ทำให้รันถูกติดป้าย ไม่ใช่เงียบเฉย
ลายนิ้วมือคือตัวตรวจจับการแกว่ง การแฮชข้อกล่าวอ้างที่มีปัญหาเปลี่ยน “ตัววิจารณ์พูดสิ่งเดียวกันซ้ำ” ให้เป็นการทดสอบความเท่ากัน หากไร้มัน ตัววิจารณ์ที่ชี้ claim one is thin ตลอดไปจะสร้างวงแก้ไขไม่รู้จบ — และความเท่ากันของลายนิ้วมือเป็นสัญญาณที่ แข็งแรงกว่า ความเท่ากันของคะแนน เพราะคะแนนลอยได้แต่ปัญหาที่ติดค้างไม่ลอย
สามเงื่อนไขหยุด
ลูปประกอบการตรวจ ตัววิจารณ์ และการแก้ไขเข้าด้วยกัน พฤติกรรมทั้งหมดของมันอยู่ในลำดับของเงื่อนไขออกสามข้อ:
@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 หักตรง ๆ ดังนั้นตัววิจารณ์ที่ให้ฉบับร่างไร้ citation และกุตัวเลข 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 ส่งต่อพร้อมป้ายดีกว่าทิ้ง — ผู้เรียก (ชั้น checkpoint ของ Part 8) ตัดสินได้ว่าคำตอบแบบ max_rounds ยอมรับได้สำหรับกรณีใช้งานของตนหรือไม่
ต่อเข้ากับการรัน
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 แทน
สามคุณสมบัติของการสร้างขึ้นใหม่นั้นสำคัญกว่าที่เห็น
การรวมกลุ่มข้อมูลซ้ำเกิดขึ้นอัตโนมัติ รันที่ส่งค้นหาห้าครั้งจะได้ข้อความที่ซ้อนทับกัน — ดัชนีของ Part 5 ซ้อนทับชังก์ตามดีไซน์ และสอง query มักดึง citation เดียวกันออกมา items ถูกเขียนด้วยคีย์ citation id ชุดหลักฐานจึงเป็น ยูเนียนของข้อความไม่ซ้ำ ไม่ใช่สำเนาห้าชุดของชังก์เดิมสามชิ้น ต้นทุนการตรวจสอบจึงถูกผูกด้วยความหลากหลายของ corpus ไม่ใช่ความยาวของรัน
บล็อกหลักฐานคือการตัดสินใจเรื่องงบ block() จำกัดที่ 1,400 อักษร — ราว 350 token — ข้อความแต่ละชิ้นถูกตัดที่ 200 การค้นสองครั้งที่ให้ข้อความสี่ชิ้นจึงใช้ไม่เกิน 350 token ต่อการเรียกวิจารณ์หนึ่งครั้ง และด้วย max_rounds=2 คือ 700 token ของบริบทวิจารณ์ตลอดรัน เทียบกับทางเลือกตรง ๆ คือแปะ trace เต็มให้ตัววิจารณ์: ค้นหาห้าครั้งคนละ 420 token คือ 2,100 token และตัววิจารณ์ต้องอ่านผลลัพธ์เครื่องมือที่ฉบับร่างอาจไม่เคยใช้เลย
max_steps=6 จำกัดฉบับร่าง ไม่ใช่การตรวจสอบ ฉบับร่างที่ทำหลังผ่านหกขั้นลูปอ้างถึง payload การค้นได้ไม่เกินหกชุด ชุดหลักฐานจึงมีเพดานแข็งหกกลุ่ม citation ที่ต่างกัน ด้วยเหตุนี้ต้นทุนการตรวจสอบจึงขยายตาม max_steps ทั้งที่การตั้งค่าลูปไม่เคยพูดถึงมันเลย — และเพราะเหตุนี้ Part 8 จะบันทึก trace ไว้กับ checkpoint ถาวร ไม่ใช่คำนวณซ้ำ
เดโมจับความล้มเหลวพอดีที่ส่วนนี้ถูกสร้างขึ้นเพื่อมัน ฉบับร่างบอก 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 รันพื้นฐานใช้ 2 การเรียกโมเดล (ค้นหา สรุป) reflection เพิ่ม 3: วิจารณ์หนึ่ง แก้ไขหนึ่ง วิจารณ์หนึ่ง นั่นคือ 2.5 เท่าของการเรียกและราว 2 เท่าของ token — ทั้ง prompt วิจารณ์และแก้ไขแบกบล็อกหลักฐาน (≤1,400 อักษร) บวกฉบับร่าง หนึ่งรอบจับตัวเลขปลอมหนึ่งตัว นั่นคือการแลกที่ดี ห้ารอบเพื่อขัดเกลาคำตอบที่ถูกอยู่แล้วไม่ใช่ ซึ่งเป็นสิ่งที่ no_progress และ oscillation ถูกสร้างขึ้นมากัน
สังเกตด้วยว่าสิ่งที่ตัววิจารณ์ ไม่ต้อง ทำคืออะไร: มันไม่เคยเห็น 340 เป็นปัญหาเรื่องเลขเลย การตรวจเชิงโปรแกรมค้นพบและระบุมัน (340 absent from latency-budget#0) งานของตัววิจารณ์จึงเหลือแค่การตัดสิน — ส่วนที่เหลือของฉบับร่างยอมรับได้หรือไม่? การแบ่งงานแบบนี้เองที่ทำให้รอบแก้ไขหนึ่งรอบพอ
โหมดล้มเหลวและวิธีจัดการ
| ความล้มเหลว | สิ่งที่เกิดขึ้นจริง | วิธีจัดการที่นี่ | ยังเปราะบาง |
|---|---|---|---|
| การเรียบเรียงตัวเลขใหม่อย่างถูกต้อง | about 200 ms เทียบกับ 180 to 240 milliseconds |
ถูกชี้ แพ้การแก้ไขหนึ่งรอบ | ยังไม่มีการตรวจตัวเลขแบบรู้ช่วง |
| ตัววิจารณ์ให้ทุกอย่าง 0.95 | reflection ไม่เคยถูกกระตุ้นเลย | บทลงโทษ + เงื่อนไขยอมรับ errors == 0 |
ตัววิจารณ์ที่ปรับเทียบแล้วต้องมีข้อมูลจริง (Part 10) |
| ผลวิจารณ์แยกวิเคราะห์ไม่ได้ | ลูปอาจค้างหรือแตก | หยุดด้วย critic_unparseable ส่งฉบับร่างคืน |
ไม่มีการลองใหม่ — วิจารณ์ที่เสียถาวรถือเป็นเหตุฉุกเฉิน |
| ปัญหาเดิมทุกรอบ | แก้ไขไม่รู้จบ | ลายนิ้วมือเท่ากัน → oscillation |
ผู้แก้ไขไม่นำข้อเสนอแนะไปใช้ |
| ชุดหลักฐานว่าง (ไม่มีการค้น) | ทุกข้อกล่าวอ้างไร้ citation | no_citation กับทุกข้อกล่าว |
ยังไม่แยก “ไม่ต้องมีหลักฐาน” กับ “ละเลยหลักฐาน” |
| ฉบับร่างอ้างการค้นที่ล้ม | citation ไม่เคยถูกดึงมาเลย | unknown_citation |
โมเดลอาจลองค้นใหม่แล้วเบี่ยงเบน |
| การแก้ไขทำลายข้อกล่าวที่เคยถูกต้อง | คะแนนดิ่งหลังแก้ไข | no_progress หยุดลูป |
prompt แก้ไขบอกให้คง citation ไว้แต่บังคับไม่ได้ |
แถวแรกคือต้นทุนตรงไปตรงมาของการตรวจที่เข้มงวด: number_mismatch ติดการเรียบเรียงใหม่ ถ้า corpus ของคุณเต็มไปด้วยช่วงค่าและค่าโดยประมาณ ให้ยอมรับการแก้ไขเพิ่มหนึ่งรอบต่อคำตอบ หรือคลายการตรวจเป็นการเทียบแบบยอมรับความคลาด — แยกตัวเลขทั้งสองออกแล้วชี้เฉพาะเมื่อต่างกันเกิน 10 เปอร์เซ็นต์ ทางเลือกที่สองคือการแก้ check สิบบรรทัดและเป็นแบบฝึกหัดที่ดี แต่สังเกตว่าต้องแลกอะไร: about 200 ตรงกับช่วง 180 to 240 คือการตัดสิน เมื่อการตรวจเริ่มตัดสิน มันก็โต้แย้งได้
ข้อแลกเปลี่ยน
| การตัดสินใจ | ทางเลือก | เหตุผลที่เลือก | ต้นทุน |
|---|---|---|---|
| ตรวจเชิงโปรแกรมมาก่อน | ตัววิจารณ์ตัดสินทุกอย่าง | ตัดสินได้ ฟรี โต้แย้งไม่ได้ | ตัวเลขที่เรียบเรียงใหม่ถูกชี้ |
| วิจารณ์ผิดรูปแบบ = ยอมรับ | ลองใหม่ตัววิจารณ์ | ไม่มีเส้นทางล้มไม่รู้จบ | วิจารณ์ที่สั่นโอกาสยอมรับเงียบ ๆ |
max_rounds=2 |
5 หรือไม่จำกัด | ต้นทุนเป็นเชิงเส้นตามจำนวนรอบ | ปัญหายากหยุดเร็วพร้อมป้าย |
เลขคณิตบทลงโทษ (0.15 × errors) |
ตัววิจารณ์เห็นคำตัดสินเป็นข้อความ | ตัววิจารณ์โหวตข้ามการตรวจไม่ได้ | น้ำหนักยังเป็นเลขวิเศษจนถึง Part 10 |
| ลายนิ้วมือของข้อกล่าวที่มีปัญหา | แฮชคำวิจารณ์ทั้งหมด | ทนต่อการเรียงใหม่และคะแนนที่ลอย | ข้อกล่าวเดิมพร้อมถ้อยคำใหม่หลุดผ่านได้ |
| หลักฐานจาก trace | ให้โมเดลแนบหลักฐานมาเอง | trace คือความจริงอ้างอิง | ต้องมี data ในระเบียน trace |
| แก้จากประเด็น ไม่ใช่แต่งใหม่ | สร้างคำตอบขึ้นใหม่ทั้งหมด | เก็บข้อกล่าวที่ตรวจแล้วไว้ | สืบทอดโครงสร้างฉบับร่างมาด้วย |
แถวบทลงโทษคือแถวที่ควรกลับมาดูอีกด้วยข้อมูลจริง 0.15 แปลว่าข้อผิดพลาดเชิงโปรแกรมหนึ่งข้อมีราคา 15 คะแนน ซึ่งเป็นการเดาจากการปรับเทียบ ไม่ใช่การวัด Part 10 จะแทนที่ด้วย 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 ถูกออกแบบให้เหมือนกันเกือบสมบูรณ์ — รูปแบบวิจารณ์เดียวกัน ฉบับร่างเดียวกัน — เพราะสองเงื่อนไขหยุดต้องแยกจากกันด้วย การขยับของคะแนน ไม่ใช่การตั้งค่าเทสต์ ถ้า refactor รวมสองอันเป็นการตรวจเดียว เทสต์สองอันนี้จะล้มพร้อมค่า stopped_by ต่างกัน ทำให้เห็นการรวม
test_unparseable_critic_never_forces_a_revision ตรึงนโยบายยอมรับเมื่อผิดรูปแบบไว้ ทางเลือกที่ล่อใจ — ลองใหม่ตัววิจารณ์ — คือเส้นทางไร้ขอบเขตพอดี และเทสต์นี้คือราวกันตก
แบบฝึกหัด
- การตรวจตัวเลขแบบยืดหยุ่น เปลี่ยน
number_mismatchให้แยกตัวเลขทั้งจากข้อกล่าวและหลักฐาน แล้วชี้เฉพาะเมื่อต่างกันเกิน 10 เปอร์เซ็นต์ แล้วเขียนกรณีต่อต้าน: หลักฐานบอกunder 100 msฉบับร่างอ้าง95 msความยืดหยุ่นทำให้ตัวเลขเป๊ะที่ผิดหลุดผ่านไหม? เส้นอยู่ตรงไหน? - บทลงโทษต่อรหัส เปลี่ยน
0.15 * errorsเป็นน้ำหนักต่อรหัส:unknown_citationควรแพงกว่าquote_missingอธิบายน้ำหนักแต่ละอันในหนึ่งประโยค แล้วรันฉบับร่างสิบอันผ่านลูป รายงานว่าอัตรายอมรับเปลี่ยนไหม - สะท้อนภายในงาน ให้
PlannedAgent._run_taskมีช่วง reflection: ตรวจผลลัพธ์ของแต่ละงานกับหลักฐานการค้นของงานนั้นก่อนส่งกลับ วัดจำนวนการเรียกโมเดลรวมและเวลาทั้งหมดของแผนสี่งาน เมื่อมีและไม่มี reflection ต่องาน การตรวจต่องานชนะการตรวจปลายรันตรงไหน และเสียเปล่าตรงไหน?
แบบฝึกหัดข้อ 3 คือข้อเชิงสถาปัตยกรรม การตรวจที่ขอบงานจับข้อผิดพลาดก่อนเข้าสู่การสังเคราะห์ แต่แลกด้วยต้นทุน reflection ต่อทุกงาน — การวัดตัดสิน และเป็นครั้งแรกที่ซีรีส์นี้ต้องเลือกว่ากลไกคุณภาพควร อยู่ที่ไหน
ก้าวต่อไป
จนถึงตอนนี้ทุกอย่างรันอยู่ภายในโปรเซสเดียว: trace แผน ชุดหลักฐาน และประวัติการสะท้อนหายไปทั้งหมดเมื่อโปรเซสจบ รันที่ใช้เวลาสี่นาทีรอดการ deploy ไม่ได้ และการแตกที่งานที่ 6 จาก 8 ทำให้เริ่มใหม่จากงานที่ 1
Part 8, Checkpointing and recovery, เพิ่มสถานะถาวร: checkpoint ที่เขียนหลังทุกงานและทุกขั้นลูป การเล่นซ้ำเครื่องมือแบบ idempotent เพื่อให้รันที่กลับมาไม่ซ้ำผลข้างเคียงใด และพฤติกรรมกลับมาจาก checkpoint สำหรับ planner ประวัติการสะท้อนที่คุณเพิ่งสร้างกลายเป็นส่วนหนึ่งของ checkpoint — รันที่กลับมาไม่ควรวิจารณ์คำตอบที่ผ่านไปแล้วซ้ำอีก
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.