Reflection & Reflexion: Self-Critique, Evaluator-Optimizer & Verifier Loops
How agents catch and fix their own mistakes before returning to the user: the Evaluator-Optimizer loop, Reflexion episodic self-critique, why grounded external verifiers beat blind LLM self-critique, and capping iterations at 2–3.
Reflection / Evaluator-Optimizer loops pair a Generator LLM with a Critic or deterministic Verifier (like unit tests or a linter) to iteratively fix mistakes before replying.
First-draft LLM outputs often contain subtle bugs or missed constraints; a single verifier-backed critique cycle dramatically boosts pass rates.
Even a fast, cheap 8B model inside a 2-iteration Grounded Reflection Loop (with pytest or a SQL/JSON validator) routinely beats a single-shot 400B frontier model!
Always prefer deterministic external verifiers (compilers, linters, Pydantic schemas, SQL EXPLAIN, unit tests) over an LLM-only Critic whenever possible — they are faster, free, and 100% un-hallucinated!
Knowing the ICLR 2024 Cannot Self-Correct Without External Feedback result saves you from wasting 3× token costs on blind 'Are you sure?' prompts that actually hurt accuracy!
Nuanced Agentic AI interview question: 'When does Self-Reflection genuinely improve agent accuracy, when does it hurt, and how does Reflexion differ from a simple retry?'
Which Critic/Evaluator produces the largest, most reliable accuracy jump inside a Reflection loop?
- Implement the Evaluator-Optimizer pattern: Generator produces Draft v_k → Verifier/Critic checks it → targeted revision on failure
- Explain Reflexion (Shinn et al., 2023): distilling failed trials into crisp verbal lessons stored in episodic memory for the next attempt
- Contrast Grounded Reflection (external unit tests, compilers, JSON validators) with Blind LLM-only self-critique (which often degrades after 1–2 loops!)
- Bound reflection loops with max_revisions (typically 2–3) and explicit pass criteria to maximize accuracy-per-dollar ROI
Think of writing an essay or a Python function: nobody publishes their first rough draft without running spell-check or unit tests! The Evaluator-Optimizer pattern gives the LLM an automated test bench & editor right before it replies — and Reflexion adds a sticky note on the monitor ('Remember to guard empty inputs!') so it never trips over the same bug twice!
1. The Evaluator-Optimizer Pattern
Click 1× through 5× in the ROI mini-lab below to see why Revisions #1 and #2 deliver huge accuracy jumps while #4 and #5 hit diminishing returns!
Two Types of Evaluators
- Deterministic Verifiers (Gold Standard):
pytest, TypeScripttsc, SQL syntax check, Pydantic/Zod schema validation, regex assertions. - Rubric-Based Critic LLM (When no code check exists): Uses a separate system prompt with an explicit checklist (e.g., tone, citations, completeness) and outputs
{"pass": bool, "issues": [...]}— never a vague"Looks okay".
Reflection Loops: Accuracy vs. Token Multiplier
2. Reflexion: Turning Failures into Episodic Lessons
Instead of dumping a raw 200-line stack trace into the next attempt, Reflexion distills the failure into a crisp 1-sentence lesson!
Why Verbal Reflection Beats Raw Retry
Raw retry (temperature = 0.7) hopes random sampling gets lucky. Reflexion explicitly diagnoses why Trial #1 failed ("Off-by-one bug in binary search upper bound") and prepends that lesson to Trial #2 — acting like gradient-free verbal reinforcement learning!
3. Grounded Feedback vs. Blind Self-Critique
Compare the green curve (grounded verifier) against the dashed red curve (blind LLM-only critique) below.
Production Reflection Guardrails
- Always pass concrete evidence (failed test case, schema diff, rubric violation) — never
"Try harder". - Keep the best-scoring draft (track
best_draft, best_score) so if Revision #3 accidentally regresses, you return Revision #2! - Cap at
max_revisions = 2or3to keep p95 latency and token cost crisp!
Worked Example: Grounded Reflection on a Broken SQL Query
User asks for monthly revenue. Draft v1 emits SELECT month, SUM(amount) FROM orders (missing GROUP BY).
Postgres returns exact error: column "orders.month" must appear in the GROUP BY clause.
Why does grounded reflection (using unit tests, linters, or schema validators) outperform blind LLM-only 'Are you sure?' self-critique?
In an Evaluator-Optimizer loop for writing marketing copy (no compiler!), how do you prevent a Critic LLM from nitpicking forever and rejecting every draft?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Often a fast cheap Generator paired with a stronger Critic (or a deterministic code verifier) gives the best cost/quality ratio — and keeping their system prompts separate prevents sycophantic self-approval!
Evaluator-Optimizer & Reflexion Self-Correction Loop
Watch a grounded verifier catch a real edge-case bug and guide the Generator to a passing v2 revision.
Text-to-SQL, Code Generation & Structured Extraction
1–2 grounded revision passes against EXPLAIN, pytest, or Pydantic lift pass rates by +15% to +30%.
# Evaluator-Optimizer (Reflection) Loop with Objective Verifier Stopping
def generator(prompt: str, feedback: str | None) -> str:
if feedback is None:
return "def add(a, b): return a - b" # buggy draft
return "def add(a, b): return a + b" # refined after critique
def critic_verify(code: str) -> tuple[bool, str]:
ns: dict = {}
exec(code, ns)
if ns["add"](2, 3) == 5:
return True, "All unit tests passed."
return False, f"Expected add(2, 3) == 5, got {ns['add'](2, 3)}."
feedback = None
for attempt in range(1, 4):
draft = generator("Write add(a, b)", feedback)
passed, feedback = critic_verify(draft)
print(f"Attempt {attempt} | passed={passed} | feedback={feedback}")
if passed:
break