Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 3

Reflection Loops That Actually Help

Build an evaluator-optimizer loop that improves results: run cheap code checks before a model critic, score drafts against a written rubric, treat an unreadable verdict as a failure, and stop with a round cap that hands the task to a person or a fallback.

Contentsand lesson path

What you will learn

  • Add an evaluator-optimizer (reflection) loop with an explicit quality criterion and iteration cap, and measure whether it improves results.

Prerequisites: Agent Loops & ReAct

01. The Evaluator-Optimizer Pattern: Beyond Superficial Self-Critique

Reflection is a feedback loop: a model produces an answer, the answer is critiqued, and the model produces a revised answer. The Reflexion framework (Shinn et al., 2023) has an agent reflect in words on feedback from the task, such as unit-test results, and keep those reflections for the next attempt. The paper reports 91% pass@1 on the HumanEval coding benchmark, against 80% for GPT-4 without it. Gains like that depend on a useful feedback signal; they do not come from the loop itself.

Many reflection loops fail because of ungrounded self-critique: you ask the same model that produced a wrong answer to "critique and improve your work", with no external ground truth, deterministic checker or independent evaluator. Huang et al. (2023) studied this on reasoning tasks and found that models struggle to correct themselves without external feedback, and that accuracy sometimes drops after self-correction. The model may invent flaws in a correct answer or defend its original mistake, and either way the loop spends tokens and time.

Reflection works best when the feedback comes from the environment or from a separate judge. If a model writes faulty SQL, asking it to reread its own query often misses the error. Feeding back the error message from the database engine gives the model a concrete fact to fix, and it is much more likely to correct the query on the next attempt.

Reflection loops that help usually follow the evaluator-optimizer pattern, one of the workflows in Anthropic's "Building effective agents". One step, the generator, writes the draft. A separate step, the evaluator, checks the draft against rules that can be tested, such as a JSON schema, unit tests or a written policy, and returns the problems it found.

Because the evaluator returns a list of specific problems rather than a vague opinion, each revision has something definite to fix.

02. Anatomy of an Evaluator-Optimizer Engine

A reflection loop has four parts:

  1. Generator. Writes the first draft from the user context and the requirements.

  2. Deterministic checks. Before calling an LLM evaluator, run cheap checks in code: JSON Schema validation, regex assertions, linters or unit tests in a sandbox. If one fails, send its exact output back to the generator, without spending LLM tokens on evaluation.

  3. Evaluator (critic). If the deterministic checks pass, a separate critic (often a different model or model family, with a strict written rubric) checks the output against the domain criteria. Ask it for structured output, a verdict and a list of deficiencies such as {"passed": false, "deficiencies": ["..."]}, and treat a reply you cannot parse as a FAIL rather than a pass.

  4. Optimizer (refiner). If the critic returns FAIL, the refiner gets the original prompt, the previous draft and the critic's feedback, and writes a targeted revision.

Checking in code first and with the rubric second keeps inference costs down. Calling a large model to critique a formatting error that a five-line regex could detect costs a model call and its latency for nothing.

The Python module below implements the loop. The deterministic check validates types as well as syntax, so a risk_score of "high" or 72.5 becomes feedback for the refiner instead of a crash. The critic is a function you pass in: in production it sends CRITIC_PROMPT to a model; in the demo after it, a scripted stand-in plays that role so you can run it offline.

Python · patterns/evaluator_optimizer.py
import json
from typing import Any, Callable, Dict, List, Optional

CRITIC_PROMPT = """You are grading a credit-risk note. Rubric:
1. The analysis names the borrower's main risk factor.
2. The analysis cites at least one figure from the input.
3. The risk_score is consistent with the analysis (high risk -> score above 60).
Reply with JSON only: {{"passed": true|false, "deficiencies": ["..."]}}
Input: {task}
Candidate: {candidate}"""


def deterministic_check(output: str) -> Optional[str]:
    """Cheap checks first; returns an error message for the refiner, or None."""
    try:
        parsed = json.loads(output)
    except json.JSONDecodeError as err:
        return f"Invalid JSON: {err}"
    if not isinstance(parsed, dict):
        return "Output must be a JSON object"
    if not isinstance(parsed.get("analysis"), str):
        return "analysis must be a string"
    score = parsed.get("risk_score")
    if isinstance(score, bool) or not isinstance(score, int):
        return f"risk_score must be an integer, got {type(score).__name__}"
    if not 0 <= score <= 100:
        return f"risk_score must be between 0 and 100, got {score}"
    if len(parsed["analysis"]) < 40:  # an extra rule that needs no model
        return "analysis is too short (under 40 characters)"
    return None


def critique_with_rubric(task: str, candidate: str,
                         critic: Callable[[str], str]) -> Dict[str, Any]:
    """Asks a critic model for a structured verdict; a bad reply counts as FAIL."""
    reply = critic(CRITIC_PROMPT.format(task=task, candidate=candidate))
    try:
        verdict = json.loads(reply)
        passed = verdict["passed"] is True
        found = [str(d) for d in verdict.get("deficiencies", [])]
    except (json.JSONDecodeError, KeyError, TypeError):
        return {"passed": False, "deficiencies": ["critic reply was not valid JSON"]}
    if not passed and not found:  # a FAIL with no reason must not look like a PASS
        found = ["critic returned FAIL without naming a deficiency"]
    return {"passed": passed, "deficiencies": found}


def run(task: str, generate, refine, critic, max_refinements: int = 3):
    output, log = generate(task), []
    for iteration in range(max_refinements + 1):
        problems: List[str] = []
        error = deterministic_check(output)
        if error:
            problems = [error]
        else:
            verdict = critique_with_rubric(task, output, critic)
            problems = verdict["deficiencies"] if not verdict["passed"] else []
        log.append((iteration, "PASS" if not problems else "; ".join(problems)))
        if not problems:
            return {"passed": True, "output": output, "log": log}
        if iteration < max_refinements:
            output = refine(task, output, problems)
    return {"passed": False, "output": output, "log": log}  # route to a human
Python · patterns/demo_reflection.py
"""Scripted generator, refiner and critic, so the loop runs offline."""
import json

from evaluator_optimizer import run

DRAFTS = [
    '{"analysis": "Risky.", "risk_score": "high"}',
    '{"analysis": "Risky borrower.", "risk_score": 72.5}',
    '{"analysis": "High risk: the borrower is highly leveraged.", "risk_score": 72}',
    '{"analysis": "High risk: debt is 6.1x EBITDA, above the 4x covenant.",'
    ' "risk_score": 72}',
]
drafts = iter(DRAFTS)


def generate(task):
    return next(drafts)


def refine(task, output, problems):
    return next(drafts)


def critic(prompt):  # stands in for a model call with CRITIC_PROMPT
    candidate = prompt.split("Candidate: ", 1)[1]
    if any(ch.isdigit() for ch in json.loads(candidate)["analysis"]):
        return '{"passed": true, "deficiencies": []}'
    return '{"passed": false, "deficiencies": ["cite a figure from the input"]}'


result = run("Debt 6.1x EBITDA; covenant 4x.", generate, refine, critic)
for iteration, outcome in result["log"]:
    print(f"round {iteration}: {outcome}")
print("passed:", result["passed"])
Terminal (Python 3.12 or later, standard library only)
python3 demo_reflection.py
Expected output
round 0: risk_score must be an integer, got str
round 1: risk_score must be an integer, got float
round 2: cite a figure from the input
round 3: PASS
passed: True

The first two rounds never reach the critic: the type checks catch a string and a float score for free. Round 2 passes every deterministic rule but fails the rubric because it cites no figure, which only a reader of the content can judge. Round 3 passes. With max_refinements=1 the same drafts would end at round 1 with passed: False, and the task would go to a person.

03. Production Stopping Criteria: Preventing Infinite Oscillations

A common failure mode in naive self-reflection systems is endless oscillation. For example, in an editorial workflow, an evaluator might criticize draft one for being "too terse", prompting the generator to expand the prose. In iteration two, the evaluator criticizes the new draft for being "overly verbose and lacking conciseness". Without explicit safeguards, the agent switches between long and short drafts until it hits the context window limit or a timeout.

Three rules keep a reflection loop under control. Only the first one stops the loop; the other two make sure that the rounds it runs are judged on the right evidence:

  • Hard iteration caps: Set a strict limit in code (two or three refinement rounds is a common choice). If the output still does not pass, end the loop and send the task to human review or a fallback route.

  • No regressions: Check that later rounds do not break rules that already passed. If round one fixed a syntax error, round two must not bring it back. Re-running every check on every round, as run() above does, catches this.

  • Deterministic checks over model opinions: Where you can, let deterministic checks (unit tests, type checking, schema validation) make the final decision rather than another LLM evaluation.

Also budget for latency. Each round adds at least one evaluation call and one generation call, so a draft that needs one revision costs three or four model calls instead of one. For interactive interfaces where users expect a fast answer, a synchronous reflection loop is usually too slow. Use reflection in background pipelines, high-stakes analysis or code generation, where correctness matters more than speed.

With these rules, reflection has a bounded cost and a clear exit, and you can measure whether it improves your results.

04. Practice

Practice check · 3 questions

Reflection loop check

Three questions on which component catches a bad draft, what to do with an unparseable verdict, and which stopping rule is missing.

Q1. A draft has `"risk_score": "high"`. Which component should catch this, and why?
Q2. The critic replies with prose instead of the requested JSON verdict. What should the loop do?
Q3. Round 1 fixes a failing type check. Round 2 fixes the critic's style note but breaks the type check again, and the loop only re-checks the style note. Which rule is missing?
Practice only: not graded, not saved, not evidence.

05. Apply it

When you add a reflection loop to an agent:

  • Separate generator and critic: Avoid a single model reviewing its own work with no outside signal. Use a separate critic prompt with a rubric, or a different model, for evaluation.
  • Gate with deterministic code: Check schemas, types and unit tests before calling the LLM critic, so obvious errors cost no model call.
  • Ask for structured critiques: Have the critic return a list of specific defects rather than a general impression.
  • Put stopping rules in code: Cap refinement rounds (two or three) so a loop that does not converge ends instead of spending without limit.
  • Track how often reflection helps: Log the share of tasks that pass on the first attempt and after each round, to see whether the extra calls are worth it.

These numbers also point to weak prompts: if one kind of task often needs three rounds, the initial task prompt is often underspecified, and fixing it can be cheaper than more rounds.

06. Review prompt

Explain why self-reflection without external feedback can make agent output worse. Detail the four core stages of an Evaluator-Optimizer pipeline, and describe how combining deterministic test suites with strict iteration caps prevents infinite reflection loops.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check