Chapter 6 of 32 · ~20 min read & lab+80 XP
Chapter 6 · Agentic AI

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.

What Is It?

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.

Why Is It Required?

First-draft LLM outputs often contain subtle bugs or missed constraints; a single verifier-backed critique cycle dramatically boosts pass rates.

Everyday Analogy: Writing a draft, running spellcheck and a peer review, and polishing the final version before hitting Send.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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!

Data Scientist

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!

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

Which Critic/Evaluator produces the largest, most reliable accuracy jump inside a Reflection loop?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Gen↔Eval\text{Gen} \leftrightarrow \text{Eval}Say aloud:“Evaluator-Optimizer loop”
Plain-English Meaning
Iterative refinement pair where an Evaluator grades Draft v_k and returns structured critique until PASS or max_iters
Everyday Example
Code Gen ↔ pytest / linter
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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!

Evaluator-Optimizer Loop: Generator + Verifier/Critic → Targeted RevisionGenerator LLMProduces Draft v_kVerifier / Criticpytest / JSON / RubricPASS ✓Return v_kFAIL → Send exact traceback/critique back to Generator!
The Evaluator-Optimizer pattern pairs a Generator LLM with a Critic/Verifier (unit tests, linter, or Judge LLM) that feeds concrete failure reasons back for targeted revision!

Two Types of Evaluators

  1. Deterministic Verifiers (Gold Standard): pytest, TypeScript tsc, SQL syntax check, Pydantic/Zod schema validation, regex assertions.
  2. 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".
Animated Mini-Lab • 1.5

Reflection Loops: Accuracy vs. Token Multiplier

Grounded Code Pass Rate
84%
LLM Calls per Task
3× calls

2. Reflexion: Turning Failures into Episodic Lessons

Everyday Story First (Zero Math Yet!)

Instead of dumping a raw 200-line stack trace into the next attempt, Reflexion distills the failure into a crisp 1-sentence lesson!

Reflexion: Converting Execution Failures into Verbal Episodic Lessons1. Trial #1 FailsAssertionError: empty list2. Verbal Reflection'Always guard len(xs)==0'3. Trial #2 Passes ✓Injects lesson into prompt!
Reflexion extends simple retry by writing verbal self-critiques ('I forgot to handle empty arrays') into episodic memory so the next attempt never repeats the same mistake!

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

Everyday Story First (Zero Math Yet!)

Compare the green curve (grounded verifier) against the dashed red curve (blind LLM-only critique) below.

Grounded Tool Verification vs. Blind LLM Self-Critique Over IterationsWith Grounded Verifier (pytest/linter) ↑Blind LLM-Only Critique (over-edits!)Key finding (Huang et al., ICLR 2024): Reflection shines with EXTERNAL feedback — cap iterations at 2–3!
Most reflection gains arrive on Revision #1 and #2 (especially with external execution feedback); blind LLM-only self-critique past 3 iterations often degrades quality!

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 = 2 or 3 to keep p95 latency and token cost crisp!
Walk Through With Me · Interactive Worked Example

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).

11. Deterministic Evaluator runs `EXPLAIN` against DBStep 1 / 2

Postgres returns exact error: column "orders.month" must appear in the GROUP BY clause.

Teacher's Note: Costs $0 and 3 milliseconds!
Pause & Check · Quick Intuition Pulse

Why does grounded reflection (using unit tests, linters, or schema validators) outperform blind LLM-only 'Are you sure?' self-critique?

Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch all 4 stages of the 60 FPS Evaluator-Optimizer & Reflexion Loop catch a ZeroDivisionError and ship a passing v2.
Interactive Animation • 1.5 Deep Lab

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.

Pass 1 / 4
1. GENERATOR (Draft v1)
def avg(xs): return sum(xs) / len(xs)
0%
1. GENERATOR (Draft v1)
Intuition Takeaway: Evaluator-Optimizer and Reflexion loops dramatically boost agent reliability when grounded in objective external verifiers (tests, schemas, compilers), capped at 2–3 revisions with best-draft tracking.
Where This Powers Real ML, Deep Learning & Generative AI

Text-to-SQL, Code Generation & Structured Extraction

1–2 grounded revision passes against EXPLAIN, pytest, or Pydantic lift pass rates by +15% to +30%.

Production NumPy & PyTorch Code Patterns
# 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
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Assuming more reflection loops always equal higher accuracy.
Best Practice: Cite diminishing returns and blind-critique degradation: always ground the Evaluator in external feedback and cap at 2–3 revisions!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1What distinguishes Reflexion from a simple blind retry loop?

Apply What You Learned — Solve Matching Coding Problems