Reflection, Self-Critique and Self-Refine

When asking an agent to review its work helps, when it does not, and how to build a loop that stops.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Reflection adds a review step: produce a draft, get feedback, revise. It works best when the feedback comes from outside the model, such as tests, validators or retrieved evidence. A model judging its own reasoning with no new information is unreliable. Always limit the rounds, keep the best attempt and escalate when checks still fail.

What you will learn: the reflection pattern, the main research methods and their limits, which sources of feedback to trust, how to write a critic, when to stop, and how to tell whether reflection helps.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and How Agents Reason and Decompose Tasks.

Beginner Draft, check, revise

The basic pattern

People rarely submit first drafts. They reread, run the numbers again or ask a colleague. Reflection gives an agent the same second look.

Generatefirst attempt
Checktests, rules, evidence or critic
Reviseusing specific feedback
Accept or escalate
↺ Check again after each revision, up to a fixed number of rounds
The check is the part that carries the value.

Three well-known methods

MethodSource of feedbackWhat is kept
Self-RefineThe same model critiques its output, then rewrites itThe latest draft
ReflexionSignals from the task, such as test results, turned into written lessonsLessons stored in memory for the next attempt
CRITICExternal tools, such as search or code execution, check the outputCritique grounded in tool results

Self-Refine reported gains across several tasks by iterating on the model's own feedback. Reflexion showed that agents could improve over repeated attempts by writing down what went wrong, without changing model weights. CRITIC found that checking with tools consistently improved results, and its authors stressed how important external feedback is.

What the evidence says about self-correction

The distinction between internal and external feedback is important. A study titled Large Language Models Cannot Self-Correct Reasoning Yet examined correction with no outside information. In the reasoning tasks it tested, models struggled to improve their answers, and sometimes performance got worse, partly because correct answers were changed. A later survey of self-correction research also questioned some earlier comparisons, for example those in which the first attempt was prompted weakly, which makes any later improvement look larger.

Models have changed since those studies, so do not treat their results as fixed limits. Treat them as a reason to measure: reflection is not automatically an improvement.

A useful rule

Ask what new information the second look has. A failing test, a source document or a validation error is new information. The same model reading the same text again has little.

A walk through one round

Suppose an agent is asked to write a query that returns monthly revenue by region. The first draft runs without error but counts canceled orders. Compare two kinds of second look:

ReviewWhat it receivesLikely result
"Check your query carefully"The same text againApproval, or cosmetic changes
Critic with the business definition"Revenue excludes canceled and refunded orders"Finds the missing filter and cites the rule
Reconciliation check in codeQuery total differs from the finance report by a stated amountA concrete failure to investigate

The second and third reviews succeed for the same reason: they bring in something the writer did not have or did not use. The third is the strongest because it does not depend on anyone's opinion. It also illustrates a limit. A matching total shows agreement with the report, not that every region is assigned correctly, so important results often need more than one check.

Where reflection tends to pay off

  • Code and queries, because they can be executed and tested.
  • Structured extraction, because fields can be validated and compared with the source.
  • Documents with rules, such as required sections, length and approved terms.
  • Research summaries, where each claim can be checked against a cited passage.
  • Plans, which code can validate against available tools and permissions.

It tends to pay off less for short factual replies with no source to compare, for matters of taste with no agreed criteria, and for time-critical interactions such as voice, where an extra round is felt as silence. In those cases, invest in better inputs instead.

Where to place the check

Reflection can sit in three places. After each step, it catches errors before they spread, at the highest cost. Before an action with side effects, it is a focused gate where a mistake would be expensive. At the end, it is cheapest but may find a fault that forces much work to be repeated. Many systems use quick code checks after every step and a fuller review only before consequential actions and before the final answer.

Intermediate Building the loop

Sources of feedback, strongest first

SourceExamplesReliability
ExecutionUnit tests, compiler, running a queryHigh for what is tested
Deterministic validatorsSchema, totals that must reconcile, link checker, length rulesHigh, narrow
Ground-truth lookupCompare claims with the system of recordHigh if the record is right
Retrieved evidenceCheck each claim against a source passageMedium to high
Separate model criticAnother call with criteria and fresh contextMedium; must be calibrated
Same model, same context"Are you sure?"Low
Human reviewerApproval and commentsHigh but costly; use where it matters

A loop with a real checker

The example uses scripted drafts in place of a model so that it runs anywhere. The checker is real: it executes tests and returns specific messages.

"""Generate, check, revise. The checker is real tests, not model opinion."""

# Scripted drafts stand in for a model that revises using the feedback.
DRAFTS = [
    "def initials(name):\n    return name[0] + name.split()[1][0]",
    "def initials(name):\n    return ''.join(p[0] for p in name.split())",
    "def initials(name):\n    return ''.join(p[0].upper() for p in name.split())",
]
TESTS = [("Ada Lovelace", "AL"), ("cher", "C"),
         ("  grace  brewster hopper ", "GBH"), ("", "")]

def check(source):
    """Run the tests. Only for trusted code: exec is not a sandbox."""
    scope = {}
    exec(source, scope)
    failures = []
    for given, wanted in TESTS:
        try:
            got = scope["initials"](given)
        except Exception as error:
            failures.append(f"{given!r} raised {type(error).__name__}")
            continue
        if got != wanted:
            failures.append(f"{given!r} gave {got!r}, wanted {wanted!r}")
    return failures

def refine(drafts, max_rounds=3):
    best, best_failures = None, None
    for number, draft in enumerate(drafts[:max_rounds], start=1):
        failures = check(draft)
        print(f"round {number}: {len(failures)} failing")
        for line in failures[:2]:
            print("   feedback:", line)
        if best is None or len(failures) < len(best_failures):
            best, best_failures = draft, failures
        if not failures:
            break
    return best, best_failures

if __name__ == "__main__":
    _, remaining = refine(DRAFTS)
    print("accepted" if not remaining else "escalate: tests still fail")

Output:

round 1: 3 failing
   feedback: 'cher' raised IndexError
   feedback: '  grace  brewster hopper ' gave ' b', wanted 'GBH'
round 2: 2 failing
   feedback: 'cher' gave 'c', wanted 'C'
   feedback: '  grace  brewster hopper ' gave 'gbh', wanted 'GBH'
round 3: 0 failing
accepted

Each round receives concrete failures, not a general request to improve. The loop keeps the attempt with the fewest failures, stops on success and otherwise escalates. Only the first two messages are shown to keep feedback focused.

Running generated code

The example calls exec on text written in the file. Never do that with model output on your own machine. Run generated code in an isolated environment with no secrets, limited network and strict time limits. See Code Execution and Sandboxing.

Writing a model critic

When no code can judge the quality, a model critic can help. Make its job narrow:

  • Give explicit criteria, each answerable as met or not met.
  • Require evidence: a quoted line or a named field for each finding.
  • Give the critic a fresh context with the task, sources and draft, without the writer's reasoning.
  • Allow "no problems found" so that it does not invent faults.
  • Ask for a structured verdict that code can read.
  • Separate finding problems from fixing them.

A verdict could contain, for each criterion: the identifier, pass or fail, the evidence and the suggested change. Compare the critic's verdicts with human judgments on a sample before trusting it, as described in LLM Judges, Human Review and Ratings.

Knowing when to stop

Stop whenAction
All required checks passAccept
Maximum rounds reached (often two or three)Return the best attempt, marked as unverified, or escalate
No improvement between roundsStop early
The same error repeatsStop; the feedback is not being used or the task is impossible
Budget exhaustedReport what remains

Track the best version, because later revisions can be worse. Agent Decisions: Confidence, Stopping, Loops and Budgets covers limits in general.

Expert Memory, gaming and measurement

Remembering lessons

Reflexion's idea of storing written lessons is useful and risky. A lesson such as "check for an empty input" helps next time. A wrong lesson spreads the error to future tasks, and text from an untrusted source could be stored as if it were advice.

  • Store lessons only after the outcome is verified.
  • Record where each lesson came from and when.
  • Scope it to a task type, user or project.
  • Expire or review old lessons, and let people delete them.
  • Never let a stored lesson grant a permission.

See Memory Write, Recall and Forgetting Policies and Learning, Self-Improvement, World Models and RL.

When the agent satisfies the check, not the goal

A loop pushes the output toward whatever the checker measures. An agent asked to make tests pass may special-case the test inputs, weaken or delete a test, or catch and ignore every error.

  • Keep tests and validators outside the agent's write access.
  • Hold back some checks that the agent never sees.
  • Review differences, not only the final status.
  • State that changing the check is forbidden, and enforce it.
  • Reward an honest "cannot be done" over a false success.
A pass is evidence, not proof

Tests show behavior on the cases they contain. Important changes still need review. See Code Review, Refactoring and Quality Measures.

How reflection can make things worse

ProblemWhyGuard
Correct answer changedPressure to find faultRevise only on a failed check or cited evidence
Empty approvalCritic shares the writer's blind spotIndependent signals; hidden cases
Text grows each roundFixes are added and nothing removedLength limit as a check
Cost multipliesEach round adds generation and reviewReflect only when the first check fails
Endless polishingNo definition of good enoughWritten acceptance criteria

Does it help? Measure it

  1. Run the test set once without reflection and record success, cost and time.
  2. Run it with reflection, same model and cases.
  3. Count cases fixed and cases broken, not only the net change.
  4. Compare with a simpler alternative: a stronger model, a better prompt, or several attempts with the checker choosing.
  5. Keep reflection only for the task types where it wins.

Selecting among independent attempts is often a strong competitor when a reliable checker exists, and the attempts can run in parallel.

What to record

For each round, keep the draft, the checks run, each failure message, the revision and the final status. This record answers practical questions: which checks fire most, how often the second round succeeds, and whether any check never fails and could be removed. It also shows when an agent changed something it should not have, which a final pass or fail would hide. Apply the same redaction and retention rules as for other traces; see Safe Logging, Sampling and Retention.

What it costs

If a draft uses one call and each round adds a critique and a revision, two rounds mean five calls and a longer conversation each time. Send only the draft, the failures and the necessary context to later rounds. Skip reflection altogether when the first attempt passes.

Illustrative example: report figures

An invented reporting agent drafts a monthly summary. Code compares every number in the text with the source table. Mismatches are returned with the correct values, the agent revises once, and the check runs again. A second model call that merely rated the writing was removed after it changed correct sentences without improving reviewer acceptance.

Turn repeated feedback into prevention

If the critic raises the same point every week, fix its cause: add the rule to the instructions, compute the value in code or change the tool. Reflection is a safety net, not a substitute for getting the first attempt right.

A sensible way to start

Begin without a model critic. Add the cheapest objective check your task allows, return its message to the agent once, and measure how many failures that single round repairs. Then read the failures that remain. If they share a pattern that code could detect, add that check. Introduce a model critic only for the faults that no rule can express, and give it one criterion at a time until its verdicts agree well with your reviewers. This order keeps the loop understandable and makes it clear which part earns its cost.

Reflection checklist

  • At least one check uses information from outside the model.
  • Feedback is specific and tied to evidence.
  • Rounds, time and tokens are limited.
  • The best attempt is retained.
  • The agent cannot edit its own checks.
  • Stored lessons are verified, scoped and removable.
  • A comparison shows reflection beats the simpler option.

Frequently asked questions

Is asking "are you sure?" useful?

Rarely on its own. It adds no information and can push a model to abandon a correct answer. Give it something to check against.

Should the critic be a different model?

It can help, but a fresh context, clear criteria and real evidence matter more. Test both.

How many rounds are best?

Measure it. Many tasks gain most in the first revision, so a limit of two or three is a sensible starting point.

References and further reading

Next steps