記事一覧に戻るAIとエージェント

自欺なきリフレクション:止まる検証ループ(パート 7)

On this page

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

最もよく見るリフレクションの実装は 1 つのプロンプトです:Review your answer for errors and improve it. それは確実により長い答えを生みます。より良い答えを生むかは別の問題です。自分の草稿を見直すモデルは、草稿に含まれない情報を何も持っていないからです。批評はより自信ありげな言い回しで答えを言い直し、改訂は批評を言い直し、あなたはトークン数を増やすためだけに 2 回のモデル呼び出しを支払ったことになります。

リフレクションが助けになるのは、正確に 2 つの条件の下です:批評が最初のパスで使わなかった証拠に根ざしているか、プログラムがモデルが反論できないものをチェックしているか。このパートは両方を構築します — そして誰もが飛ばす部分も構築します。停止条件です。というのも、無限界のリフレクションループは同じ答えの 2 つのバージョンを行き来してステップ予算が尽きるまで続くからです。

直近 3 パートの見返りは、ここで具体的に現れます。パート 5 はすべての検索結果に引用 id を与え、パート 6 はすべてのタスクに有界な結果を与えました。引用 id は検証を決定可能にします:引用されたパッセージが存在してその数を含むか、しないか。それらがなければ、検証は意見にすぎず、意見はループを止めません。

構築するもの

4 つの部品からなる reflect.py モジュール:

  • extract_claims + EvidenceStore — 答えを文に分割し、各文を実際に取得された証拠と照合します:引用の存在、数値の一致、逐語引用。
  • RubricCritic — ルーブリック、構造化出力、そしてハードルール付きのラウンドごと 1 回のモデル呼び出し。整形不良の批評は受理であり、決して改訂ではありません。
  • ReflectionLoop — 批評、改訂。3 つの停止条件付き:ラウンド上限、最小スコア改善、批評のフィンガープリントによる振動検出。
  • ReflectiveAgent — 草稿のために AgentLoop を実行し、トレースから証拠集合を再構築し、それから検証します。

contracts.py への小さな変更の 1 つが、このすべてを可能にします。何よりも先に指摘する価値があります:

# 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 行ですが、読めるだけのトレースと照合検証できるトレースの違いです。これがなければ、証拠集合はモデルが読んだものの記憶から再構築するしかありません — それはまさにリフレクションが捉えるはずの失敗です。

前提条件

  • パート 1〜6。reflect.py は AgentLoop、LLMClient、Message、Tool を contracts.py からインポートします。
  • Python 3.10+、標準ライブラリのみ(re、json、hashlib)。
  • デモは 2 つの固定パッセージを持つスタブの search ツールを使い、オフラインで動きます。本物のプロジェクトでは、パート 5 の make_search_tool(retriever) を配線してください — リフレクション層はどちらかを気にしません。

なぜ「自分の答えを振り返れ」は事態を悪くするのか

抽象的な自己批評が失敗するのは構造的な理由からで、プロンプトエンジニアリングの問題ではありません。批評ステップは、入力が最初の呼び出しが生んだテキストだけである第 2 のモデル呼び出しです。新しい情報はないので、最善の批評はすでにそこにあるものの再導出にすぎません。そしてモデルは、自分の自信のある誤りを指摘するのが顕著に苦手です。その文を生んだのと同じ重みが、その文を審判しているからです。

リフレクションが使えるもの、そしてこのパートが配線するものは、差分の情報です:

  • 証拠集合 — ツールが実際に返したもの。草稿がそれを無視したり、反転したりしたかもしれません。
  • 決定可能なチェック — 引用の存在、数値の一致、引用文の存在。モデルをまったく必要としません。
  • 尺度付きのルーブリック — これにより score が勘ではなく算術を駆動できます。

順序が重要であり、それがコアの設計です:まずプログラム的チェック、次にモデルの判断。 見落としやすい説明責任の非対称もあります。モデルベースの批評が間違っていても、システム内の何もそれを指摘できません — 批評は判断であり、判断は監査の痕跡を残しません。一方、EvidenceStore.check が number_mismatch をフラグするとき、判定は主張とコードと、指名された引用に存在しない正確な数を名指しします。open_verdicts を読む開発者は反証可能な述明を見ます。つまり誤検知はデバッグ可能です:パッセージを確認し、正規表現を確認し、ルールを直す。チェック可能な層を先に作れば、その後のクリティックとチェックのどの不一致にも、上訴できる事実の基準が生まれます。40 マイクロ秒で走るチェックは、通るか欠陥を名指しするかのどちらかです。クリティックはその後に、プログラムにできないことを判断します — 主張がゴールに応答しているか、推論が一貫しているか。散文だけを与えて両方の仕事を頼むと、両方の悪い面を取ることになります:数値を確実に検証できず、注意を文法に費やします。

プログラムが走らせられるチェック:引用、数値、引用文

主張とは、引用 id を 0 個以上持つ文です。チェックは意図的に機械的です:

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]

4 つのチェック。それぞれに、設計が隠すのではなく受け入れる既知の盲点があります。

no_citation が最も安く、最も価値があります。引用のない主張は必ずしも間違いではありませんが、検証不能であり、リサーチエージェントにおいて検証不能は欠陥です。パート 5 の引用形式の要点は、主張をチェック可能にすることでした。不在を失敗として扱えば、モデルは引用を学びます — プロンプト側の指示(cite as [doc#n])とこのチェックは閉ループです。

unknown_citation は幻覚引用を捉えます — その文書にチャンクが 2 つしかないのに [retrieval-design#7] が出る場合。これはベクトルデータベース RAG システムが飛ばすチェックであり、しかも無料です。

number_mismatch は几帳面なまでに厳密です:主張内のすべての数は、引用されたテキストに逐語的に現れなければなりません。つまり正当な言い換え — 証拠は 180 to 240 milliseconds、主張は about 200 ms — もフラグされます。これは意図的です。言い換えられた数は、正しい検索が間違った答えになる最も一般的な経路であり、フラグされた言い換えは改訂ラウンド 1 回で済むのに対し、フラグされなかった捏造数は間違った成果物を生みます。200 ms のケースはまさに下のデモが示すものです。

quote_missing は 8〜160 文字の引用スパンにのみ発火します。より短いスパンはノイズであり、より長いものはたいていモデルが自分の要約を引用しているものです。このチェックは、引用文が証拠のどこかに存在することを検証します — 正しい引用に帰属していることではありません。帰属にはスパン整列が必要で、この段階では複雑化に見合いません。

ルーブリックを持つクリティックと、1 つの拒否権

クリティックは、ルーブリックと尺度と構造化出力を備えた 1 回のモデル呼び出しです。尺度が存在するのは、ループがそれに対して算術を行えるようにするためです。

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)

そのクラスの 2 つのポリシーには、それぞれ一言を割く価値があります。

整形不良の批評は受理。 これは逆に見えます — 壊れたクリティックは「再試行」を意味するのでは?いいえ、そうではありません。ループ内でクリティックを再試行すると、無限界の失敗経路が生まれます:クリティックが失敗し、再試行し、別の形で失敗し、また再試行する。パースできない批評の安全な読み方は、それに対して行動できない、ということです。行動しないことは現在の草稿の受理を意味し、草稿はすでにプログラム的チェックを通過しています。ループは critic_unparseable を停止理由として記録するので、実行は沈黙ではなくラベル付きです。

フィンガープリントが振動検出器です。 問題の主張をハッシュ化することで、「クリティックが同じことを言い続ける」は等価性テストになります。これがなければ、claim one is thin を永久にフラグするクリティックは無限の改訂ループを生みます。そしてフィンガープリントの等価性はスコアの等価性より強いシグナルです。スコアはドリフトしますが、スタックした論点はしないからです。

3 つの停止条件

ループはチェックとクリティックと改訂を組み合わせます。その振る舞いのすべては、3 つの終了条件の順序にあります:

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

ペナルティが拒否権です。 score - 0.15 * errors は直接減算されるので、引用なし・数値捏造の草稿に 0.9 をつけるクリティックでも最終的には 0.6 に着地します — accept_score を下回り、改訂は起こります。受理条件はさらに errors == 0 を要求するので、どんな算術も未決判定のある実行を救えません。これがクリティックを正直に保つ仕組みです:プログラム的チェックは助言ではなく、クリティックが多数決で覆せない拒否権です。

min_delta=0.08 は、ためらわせない条件です。 改訂には 2 回の呼び出しがかかります(批評 + 改訂、さらに改訂を判断する批評)。直近の改訂がスコアを 0.08 未動かしたのなら、次も同じことは起こりにくく、正直な答えは停止してラベルを付けることです:no_progress。下のテストでは、0.55 → 0.60 のラウンドがまさにこれを引き起こします。

振動チェックは意図的に改善チェックの後です。 同一フィンガープリントでの大きなスコアジャンプは疑わしい — クリティックは書き直しを気に入りかつ同じ不満を繰り返しました。そこで止まる方が第 3 ラウンドに勝ります。第 3 ラウンドは第 2 ラウンドを再生することしかできないからです。3 つのチェックの順序は:受理、次に改善、次にフィンガープリント。並べ替えると別の失敗実行になります。テストがその順序を固定しています。

max_rounds=2 が予算であり、既定の答えです。 ループは stopped_by="max_rounds" と現在の草稿で終了します。2 回の改訂の後なら、たとえ 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 で捉えられます。

この再構築には、見た目以上に重要な 3 つの性質があります。

重複排除は自動です。 5 つの検索を発する実行は重なるパッセージを取得します — パート 5 のインデックスは設計上チャンクを重ねており、2 つのクエリはしばしば同じ引用を浮上させます。items は引用 id をキーとするので、証拠集合は一意なパッセージの和集合であり、同じ 3 チャンクの 5 部ではありません。検証コストはしたがって実行長ではなくコーパスの多様性で上限がつきます。

証拠ブロックは予算の決定です。 block() は 1,400 文字で上限 — 約 350 トークン — パッセージごとに 200 で切り詰めます。4 パッセージずつ返す 2 つの検索では、批評呼び出しごとに最大 350 トークン、max_rounds=2 なら実行全体で 700 トークンの批評コンテキストです。素朴な代替 — トレース全体をクリティックに貼る — と比べると:420 トークンの検索 5 回は 2,100 トークンで、しかもクリティックは草稿が一度も使わなかったかもしれないツール出力を読みます。

max_steps=6 は草稿を束縛し、検証ではありません。 6 つのループステップの後に生まれた草稿は最大 6 つの検索ペイロードしか引用できず、証拠集合の硬い天井は 6 つの異なる引用クラスタです。だからこそ検証コストは max_steps とともにスケールするのに、ループ設定はそれに触れないのです — そしてパート 8 が再計算ではなくチェックポイントとともにトレースを永続化する理由でもあります。

デモは、このパートが存在するためにある失敗を正確に捉えます。草稿は 340 ms と述べ、証拠は about 200 ms と言います:

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

コストを読んでください。それが max_rounds が 5 ではなく 2 である理由だからです。基線の実行は 2 回のモデル呼び出し(検索、最終)。リフレクションは 3 回追加します:批評 1、改訂 1、批評 1。つまり呼び出しは 2.5 倍、トークンは約 2 倍です — 批評と改訂のプロンプトはどちらも証拠ブロック(≤1,400 文字)と草稿を運びます。1 ラウンドで 1 つの捏造数を捉えました。良い取引です。正しい答えを磨くのに 5 ラウンドは違います — まさに no_progress と oscillation が防ぐために存在するものです。

クリティックがする必要がなかったことにも注目してください:それは 340 を算術の問題として一度も見ませんでした。プログラム的チェックがそれを見つけ、名指しし(340 absent from latency-budget#0)、クリティックの仕事は判断へと縮みました — 草稿の残りは受理できるか。この分業こそが、改訂ラウンド 1 回で足りた理由です。

失敗モードとその対処

失敗 実際に起きること ここでの対処 依然として壊れている点
数の正当な言い換え about 200 ms vs 180 to 240 milliseconds フラグ付き、改訂ラウンド 1 回の代償 範囲を解する数値チェックなし
クリティックがすべてに 0.95 をつける リフレクションが発火しない ペナルティ + errors == 0 の受理条件 校準されたクリティックには実データが要る(パート 10)
クリティック出力がパース不能 ループはクラッシュか空回り critic_unparseable で停止、草稿を返す 再試行なし — 持続的に壊れたクリティックはインシデント
毎ラウンド同じ論点 無限の改訂 フィンガープリント等価 → oscillation 改訂者が修正案を適用しない
証拠集合が空(検索なしで実行) すべての主張が無引用 全主張に no_citation 「証拠不要」と「証拠を飛ばした」の区別なし
草稿が失敗した検索を引用する 引用が一度も取得されていない unknown_citation モデルが検索を再試行して漂う可能性
改訂がきれいな主張を壊す 改訂後にスコア低下 no_progress がループを止める 改訂プロンプトは引用の保持を求めるが強制できない

最初の行は厳密なチェックの正直な代償です:number_mismatch は言い換えに発火します。コーパスが範囲と概数だらけなら、答えごとに 1 回の追加改訂ラウンドを受け入れるか、チェックを数値許容比較に緩めるか — 両方の数をパースし、10% 超 の差だけフラグする。後者は check への 10 行の変更であり良い演習ですが、何を諦めるかに注意してください:about 200 が 180 to 240 の範囲に合致するかは判断であり、チェックが判断を始めれば、それは反論可能になります。

トレードオフ

決定 代替案 選んだ理由 代償
まずプログラム的チェック クリティックがすべてを判断 決定可能、無料、反論不能 言い換えた数がフラグされる
整形不良の批評 = 受理 クリティックを再試行 無限界の失敗経路がない 不安定なクリティックが静かに受理する
max_rounds=2 5 または無制限 コストはラウンドに線形 難しい問題は早く止まるがラベル付き
ペナルティ算術(0.15 × errors) クリティックが判定をテキストで見る クリティックはチェックを覆せない パート 10 まで重みはマジックナンバー
論点の主張のフィンガープリント 完全な批評をハッシュ 並べ替えとスコアドリフトに堅牢 同じ主張でも言い換えるとすり抜ける
トレースからの証拠 モデルに証拠の添付を頼む トレースは事実の基準 トレース記録に data が必要
巻き戻しではなく論点から改訂 答えを再生成 検証済みの主張を保持 草稿の構造を引き継ぐ

ペナルティの行は、データとともに見直すべきものです。0.15 は 1 つのプログラム的エラーが 15 スコアポイントを消すという意味で、これは測定ではなく校準の当てずっぽうです。パート 10 のハーネスが置き換えます:ラベル付き集合上でエージェントを実行し、未決判定付きで受理された答えを数え、その数がゼロになるよう重みを設定する。

テスト

13 個のテスト、ネットワークなし、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 は意図的にほぼ同一です — 同じ批評の形、同じ草稿 — 2 つの停止条件がテストの環境ではなくスコアの動きで区別できなければならないからです。リファクタリングで両者を 1 つのチェックに統合すると、この 2 つのテストは異なる stopped_by 値で失敗し、統合が可視化されます。

test_unparseable_critic_never_forces_a_revision は整形不良時の受理ポリシーを固定します。誘惑的な代替 — クリティックの再試行 — はまさに無限界の経路であり、このテストがガードレールです。

演習

  1. 寛容な数値チェック。 number_mismatch を、主張と証拠の両方の数をパースし、10% 超の差だけフラグする形に変えてください。そのうえで敵対的ケースを書いてください:証拠は under 100 ms、草稿は 95 ms と主張。許容は誤った正確な数を通しますか?線はどこにありますか?
  2. チェックごとのペナルティ。 0.15 * errors をコードごとの重みに置き換えてください:unknown_citation は quote_missing より高くつくべきです。各重みを 1 文で正当化し、10 の草稿をループに通して受理率が変わったか報告してください。
  3. タスク内のリフレクション。 PlannedAgent._run_task にリフレクションのパスを与えます:返す前に、タスク自身の検索証拠に対して結果を検証する。タスクごとのリフレクションあり/なしで、4 タスク計画の総モデル呼び出し数と壁時計時間を測定します。タスクごとの検証が実行末の検証に勝るのはどこで、無駄になるのはどこですか?

演習 3 がアーキテクチャ的なものです。タスク境界での検証は、エラーが統合に入る前に捉えますが、すべてのタスクにリフレクションのコストを払います — 測定が決めます。そしてこのシリーズが品質メカニズムの住処をどこにするかを選ばねばならないのは初めてです。

次回

これまでのすべては 1 つのプロセス内で動いています:トレース、計画、証拠集合、リフレクション履歴は、プロセスとともに消えます。4 分かかる実行はデプロイを生き延びられず、8 タスク中 6 でクラッシュするとタスク 1 からやり直しです。

パート 8 の**チェックポイントと回復(Checkpointing and recovery)**は、永続的な状態を追加します:すべてのタスクとすべてのループステップの後に書かれるチェックポイント、再開した実行が副作用を繰り返さない冪等なツールリプレイ、プランナーのチェックポイントからの再開セマンティクス。今作ったリフレクション履歴はチェックポイントの一部になります — 再開した実行が、すでに通った答えを再批評すべきではありません。

Connect your agents without writing code

Everything above, running in Ball — no code, no install. Try it in your browser.

Try Ball free
Get the free AI agent kit

Only used to send Ball resources. No spam.

Try Ball in your browser — no install, no signup needed.

Try Ball in your browser — no install, no signup needed.

英語で読んでいますか?メニューで言語を切り替えられます。