자기기만 없는 반성: 멈추는 검증 루프(7부)
Verification before reflection
One reflection round
The program checks are a veto the critic cannot outvote.
- input
- process
- decision
- output
가장 흔한 반성 구현은 프롬프트 하나입니다: Review your answer for errors and improve it. 그것은 확실히 더 긴 답변을 만듭니다. 더 나은 답변을 만드는지는 별개의 문제입니다. 자기 초고를 검토하는 모델은 초고에 이미 담기지 않은 정보를 아무것도 갖고 있지 않기 때문입니다. 비평은 더 자신만만한 문구로 답변을 다시 진술하고, 수정은 비평을 다시 진술하며, 당신은 토큰 수를 늘리기 위해 두 번의 모델 호출을 지불한 셈입니다.
반성이 도움이 되는 조건은 정확히 둘입니다: 비평이 첫 패스가 쓰지 않은 증거에 고정되어 있거나, 프로그램이 모델이 반박할 수 없는 것을 검사하거나. 이번 편은 둘 다 만들고 — 모두가 건너뛰는 부분인 정지 조건까지 만듭니다. 무한한 반성 루프는 같은 답변의 두 버전 사이를 오가다가 단계 예산이 죽기 때문입니다.
지난 세 부의 보상이 여기서 구체적으로 나타납니다. 5부는 모든 검색 결과에 인용 id를 주었고, 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는 한 줄이지만, 읽기만 가능한 트레이스와 대조 검증 가능한 트레이스의 차이입니다. 이것이 없으면 증거 집합을 모델이 읽었던 것에 대한 기억으로 재구축해야 하는데 — 그것이 바로 반성이 잡아야 할 실패입니다.
사전 준비
- 1~6부.
reflect.py는AgentLoop,LLMClient,Message,Tool을contracts.py에서 임포트합니다. - Python 3.10+, 표준 라이브러리만 사용(
re,json,hashlib). - 데모는 두 개의 미리 담아둔 패시지를 가진 스텁
search도구를 사용해 오프라인에서 돌아갑니다. 실제 프로젝트에서는 5부의make_search_tool(retriever)을 연결하세요 — 반성 계층은 어느 쪽이든 상관하지 않습니다.
왜 「자기 답변을 반성하라」는 일을 더 나쁘게 만드는가
추상적인 자기 비평이 실패하는 데는 프롬프트 엔지니어링이 아니라 구조적 이유가 있습니다. 비평 단계는 입력이 첫 호출이 산출한 텍스트뿐인 두 번째 모델 호출입니다. 새 정보가 없으므로 최선의 비평은 이미 있는 것의 재유도일 뿐입니다. 그리고 모델은 자기 확신에 찬 오류를 지적하는 데 특히 서툽니다. 그 문장을 만든 바로 그 가중치가 그 문장을 심판하기 때문입니다.
반성이 쓸 수 있는 것, 그리고 이번 편이 연결하는 것은 차등 정보입니다:
- 증거 집합 — 도구가 실제로 반환한 것. 초고가 무시했거나 뒤집었을 수 있습니다.
- 결정 가능한 검사 — 인용 존재, 숫자 일치, 인용문 존재. 모델을 전혀 필요로 하지 않습니다.
- 척도를 갖춘 루브릭 — 그래서
score가 감이 아니라 산술을 구동합니다.
순서가 중요하며, 그것이 핵심 설계입니다: 프로그램적 검사가 먼저, 모델 판단이 다음.
놓치기 쉬운 책임 비대칭도 있습니다. 모델 기반 비평이 틀렸을 때 시스템 안의 그 무엇도 그렇다고 말할 수 없습니다 — 비평은 판단이고, 판단은 감사 흔적을 남기지 않습니다. 반면 EvidenceStore.check가 number_mismatch를 표시하면, 판정은 주장과 코드와, 지목된 인용에 없는 정확한 숫자를 이름으로 지칭합니다. open_verdicts를 읽는 개발자는 반증 가능한 서술을 봅니다. 즉 오탐은 디버깅 가능합니다: 패시지를 확인하고, 정규식을 확인하고, 규칙을 고칩니다. 검사 가능한 계층을 먼저 만들면, 그 뒤 크리틱과 검사 사이의 모든 불일치에 호소할 사실 기준이 생깁니다. 40마이크로초에 도는 검사는 통과하거나 결함을 지목하거나 둘 중 하나입니다. 크리틱은 그다음 프로그램이 못하는 것을 판단합니다 — 주장이 목표에 응답하는지, 추론이 일관되는지. 산문만 먹이고 두 직업을 모두 맡기면 두 세상의 최악을 얻습니다: 숫자를 신뢰성 있게 검증하지 못하고, 주의를 문법에 씁니다.
프로그램이 돌릴 수 있는 검사: 인용, 숫자, 인용문
주장이란 인용 id를 0개 이상 가진 문장입니다. 검사는 의도적으로 기계적입니다:
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**이 가장 싸고 가장 가치 있습니다. 인용 없는 주장이 꼭 틀린 것은 아니지만 검증 불가능하고, 리서치 에이전트에서 검증 불가능은 결함입니다. 5부 인용 형식의 존재 이유가 바로 주장을 검사 가능하게 만드는 것이었습니다. 부재를 실패로 다루면 모델은 인용을 배웁니다 — 프롬프트 측 지시(cite as [doc#n])와 이 검사는 닫힌 루프입니다.
**unknown_citation**은 환각 인용을 잡습니다 — 그 문서에 청크가 두 개뿐인데 [retrieval-design#7]이 나오는 경우. 이것은 벡터 데이터베이스 RAG 시스템이 건너뛰는 검사이며, 공짜입니다.
**number_mismatch**는 학문적 지루함 수준으로 엄격합니다: 주장의 모든 숫자는 인용된 텍스트에 축자로 나타나야 합니다. 즉 정당한 바꿔 말하기 — 증거는 180 to 240 milliseconds, 주장은 about 200 ms — 도 표시됩니다. 의도된 것입니다. 바꿔 말한 숫자는 올바른 검색이 틀린 답변이 되는 가장 흔한 경로이고, 표시된 바꿔말하기는 수정 라운드 한 번이면 되지만, 표시되지 않은 조작 숫자는 틀린 납품물을 산출합니다. 200 ms 사례가 바로 아래 데모가 보여주는 것입니다.
**quote_missing**은 8~160자의 인용 구간에서만 발동합니다. 더 짧은 구간은 노이즈이고, 더 긴 것은 보통 모델이 자기 요약을 인용하는 것입니다. 이 검사는 인용문이 증거 어딘가에 존재하는지만 검증합니다 — 올바른 인용에 귀속되는지는 아니며, 귀속에는 구간 정렬이 필요하고 이 단계에서는 복잡성을 치를 가치가 없습니다.
루브릭을 가진 크리틱과 단 하나의 거부권
크리틱은 루브릭과 척도와 구조화된 출력을 갖춘 한 번의 모델 호출입니다. 척도가 존재하는 이유는 루프가 그 위에서 산술을 할 수 있게 하기 위함입니다.
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는 직접 감산되므로, 인용 없고 숫자를 조작한 초고에 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에 도달하지 못했더라도 보통 원본보다 낫습니다. 라벨을 달고 출하하는 것이 버리는 것보다 낫습니다 — 호출자(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에게 잡힙니다.
이 재구축에는 보기보다 중요한 세 성질이 있습니다.
중복 제거는 자동입니다. 다섯 검색을 내는 실행은 겹치는 패시지를 검색합니다 — 5부 인덱스는 설계상 청크를 겹치고, 두 쿼리가 같은 인용을 띄우는 일이 잦습니다. items는 인용 id를 키로 하므로, 증거 집합은 유일 패시지의 합집합이지 같은 세 청크의 다섯 복사본이 아닙니다. 검증 비용은 따라서 실행 길이가 아니라 코퍼스 다양성으로 유계됩니다.
증거 블록은 예산 결정입니다. block()은 1,400자로 상한 — 약 350토큰 — 패시지마다 200으로 잘립니다. 패시지 네 개씩 돌려주는 두 검색은 따라서 비평 호출당 최대 350토큰이고, max_rounds=2이면 전체 실행의 비평 컨텍스트는 700토큰입니다. 순진한 대안 — 트레이스 전체를 크리틱에 붙이기 — 와 비교하면: 420토큰짜리 검색 다섯 번은 2,100토큰이고, 크리틱은 초고가 한 번도 쓰지 않았을지 모르는 도구 출력을 읽습니다.
max_steps=6은 초고를 유계하고, 검증이 아닙니다. 여섯 루프 단계 후 생산된 초고는 최대 여섯 검색 페이로드를 인용할 수 있으므로, 증거 집합의 강한 천장은 여섯 개의 서로 다른 인용 클러스터입니다. 검증 비용이 max_steps에 따라 스케일하는데 루프 설정은 그것을 언급하지 않는 이유가 이것입니다 — 그리고 8부가 재계산 대신 체크포인트와 함께 트레이스를 영속화할 이유이기도 합니다.
데모는 이번 편이 존재하는 이유인 정확히 그 실패를 잡습니다. 초고는 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가 5가 아니라 2인 이유이기 때문입니다. 기선 실행은 2번의 모델 호출(검색, 마무리). 반성은 3번을 더합니다: 비평 하나, 수정 하나, 비평 하나. 즉 호출은 2.5배, 토큰은 약 2배 — 비평과 수정 프롬프트는 모두 증거 블록(≤1,400자)과 초고를 싣습니다. 한 라운드가 조작된 숫자 하나를 잡았습니다. 좋은 거래입니다. 옳은 답변을 다듬는 데 다섯 라운드는 아닌데, 그것이 정확히 no_progress와 oscillation이 막기 위해 존재하는 것입니다.
크리틱이 하지 않아도 됐던 일도 주목하세요: 그것은 340을 산술 문제로 한 번도 보지 않았습니다. 프로그램적 검사가 발견하고 이름 붙였고(340 absent from latency-budget#0), 크리틱의 일은 판단으로 축소됐습니다 — 초고의 나머지는 수용할 만한가? 이 분업이 한 번의 수정 라운드로 충분했던 이유입니다.
실패 모드와 대응
| 실패 | 실제로 일어나는 일 | 여기서의 대응 | 여전히 깨져 있는 점 |
|---|---|---|---|
| 숫자의 정당한 바꿔 말하기 | about 200 ms vs 180 to 240 milliseconds |
표시됨, 수정 라운드 한 번의 비용 | 범위를 이해하는 숫자 검사 없음 |
| 크리틱이 모든 것에 0.95를 준다 | 반성이 발동되지 않는다 | 페널티 + errors == 0 수용 조건 |
보정된 크리틱에는 실데이터가 필요(10부) |
| 크리틱 출력을 파싱 불가 | 루프가 크래시하거나 헛돈다 | critic_unparseable 정지, 초고 반환 |
재시도 없음 — 지속적으로 부서진 크리틱은 사고 |
| 매 라운드 같은 논점 | 무한 수정 | 지문 등가 → oscillation |
수정자가 수정 제안을 적용하지 않음 |
| 증거 집합이 비어 있음(검색 없이 실행) | 모든 주장이 무인용 | 모든 주장에 no_citation |
「증거 불필요」와 「증거 건너뜀」의 구분 없음 |
| 초고가 실패한 검색을 인용한다 | 인용이 한 번도 검색되지 않음 | unknown_citation |
모델이 검색을 재시도하고 표류할 수 있음 |
| 수정이 깨끗한 주장을 망친다 | 수정 후 점수 하락 | no_progress가 루프를 멈춘다 |
수정 프롬프트는 인용 유지를 요구하지만 강제할 수 없음 |
첫 행은 엄격한 검사의 정직한 비용입니다: number_mismatch는 바꿔말하기에 발동합니다. 코퍼스가 범위와 근사로 가득하면, 답변마다 한 번의 추가 수정 라운드를 받아들이거나 검사를 수치 허용 비교로 완화하십시오 — 양쪽 숫자를 파싱하고 10% 초과 차이에만 표시. 후자는 check에 대한 열 줄 변경이자 좋은 연습이지만, 무엇을 포기하는지 주목하세요: about 200이 180 to 240 범위에 맞는지는 판단이고, 검사가 판단을 시작하는 순간 반박 가능해집니다.
트레이드오프
| 결정 | 대안 | 선택한 이유 | 대가 |
|---|---|---|---|
| 프로그램적 검사가 먼저 | 크리틱이 모든 것을 판단 | 결정 가능, 공짜, 반박 불가 | 바꿔 말한 숫자가 표시됨 |
| 변형된 비평 = 수용 | 크리틱 재시도 | 유계 없는 실패 경로 없음 | 불안정한 크리틱이 조용히 수용한다 |
max_rounds=2 |
5 또는 무제한 | 비용은 라운드에 선형 | 더 어려운 문제는 일찍 멈추지만 라벨이 붙음 |
페널티 산술(0.15 × errors) |
크리틱이 판정을 텍스트로 봄 | 크리틱이 검사를 뒤집을 수 없음 | 10부까지 가중치는 마법의 수 |
| 논점 주장의 지문 | 전체 비평을 해싱 | 재정렬과 점수 표류에 강건 | 같은 주장도 표현을 바꾸면 통과 |
| 트레이스에서 증거 | 모델에 증거 첨부를 요청 | 트레이스가 사실 기준 | 트레이스 기록에 data 필요 |
| 백지가 아니라 논점에서 수정 | 답변 재생성 | 검증된 주장을 보존 | 초고 구조를 상속 |
페널티 행은 데이터와 함께 다시 봐야 할 것입니다. 0.15는 프로그램적 오류 하나가 15점을 먹는다는 뜻인데, 이는 측정이 아니라 보정 추측입니다. 10부의 하네스가 교체할 것입니다: 라벨 붙은 집합에서 에이전트를 돌리고, 미결 판정과 함께 수용된 답변 수를 세고, 그 수가 0이 되도록 가중치를 정합니다.
테스트
열세 개 테스트, 네트워크 없음, 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은 변형 시 수용 정책을 못 박습니다. 유혹적인 대안 — 크리틱 재시도 — 이 바로 유계 없는 경로이고, 이 테스트가 가드레일입니다.
연습 문제
- 관용적인 숫자 검사.
number_mismatch를 주장과 증거 양쪽 숫자를 파싱하고 10% 초과 차이에만 표시하도록 바꿔라. 그다음 적대적 사례를 작성하라: 증거는under 100 ms, 초고는95 ms라고 주장. 관용이 틀린 정확한 숫자를 통과시키는가? 선은 어디에 있는가? - 검사별 페널티.
0.15 * errors를 코드별 가중치로 교체하라:unknown_citation은quote_missing보다 비싸야 한다. 각 가중치를 한 문장으로 정당화하고, 열 개 초고를 루프에 통과시켜 수용률이 변했는지 보고하라. - 작업 내부의 반성.
PlannedAgent._run_task에 반성 패스를 부여하라: 반환 전에 작업 자신의 검색 증거에 대해 결과를 검증한다. 작업별 반성 켬/끔의 네 작업 계획 총 모델 호출 수와 벽시계 시간을 측정하라. 작업별 검증이 실행 말미 검증을 이기는 곳은 어디이고, 낭비되는 곳은 어디인가?
연습 3이 아키텍처적 것입니다. 작업 경계의 검증은 오류가 종합에 들어가기 전 잡지만, 모든 작업에 반성 비용을 지불합니다 — 측정이 결정하고, 이 시리즈가 품질 메커니즘의 거처를 어디에 둘지 선택해야 하는 것은 처음입니다.
다음 편
지금까지의 모든 것은 하나의 프로세스 안에서 돌아갑니다: 트레이스, 계획, 증거 집합, 반성 이력은 프로세스와 함께 사라집니다. 4분 걸리는 실행은 배포를 못 견디고, 8개 작업 중 6에서 크래시하면 작업 1부터 다시 시작합니다.
8부인 **체크포인트와 복구(Checkpointing and recovery)**는 영속 상태를 추가합니다: 모든 작업과 모든 루프 단계 뒤에 기록되는 체크포인트, 재개된 실행이 부작용을 반복하지 않게 하는 멱등 도구 재생, 플래너의 체크포인트에서 재개 의미론. 방금 만든 반성 이력은 체크포인트의 일부가 됩니다 — 재개된 실행은 이미 통과한 답변을 다시 비평해서는 안 됩니다.
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.