Module 4 · Lesson 4 · 15 min read

Reflection and self-correction

Reflection and Self-Correction

Introduction

Even the best agents make mistakes on the first attempt. The difference between a fragile agent and a reliable one is its ability to detect its mistakes and correct them. In this lesson we learn the generate, critique and revise loop, the idea of Reflexion, and the most important condition for self-correction to succeed: a real evaluation signal.

Learning objectives

  • Explain the generate, then critique, then revise loop
  • Describe the idea of Reflexion of saving lessons learned between attempts
  • Distinguish between bare self-critique and evaluation with a checkable external signal
  • Design a correction loop with a maximum number of attempts and a clear success condition

Why does an agent need reflection?

The model generates the answer token by token and does not automatically go back to review what it wrote. If it makes a mistake in an early step, it may build the rest of the answer on it. Reflection is adding an explicit step after generation in which the output is evaluated, then the result of the evaluation is used to improve a new attempt.

The generate, critique and revise loop

The simplest form of reflection is a loop of three stages:

  1. Generate: the agent produces a draft: code, a plan or a summary.
  2. Critique: some component evaluates the draft and writes specific notes.
  3. Revise: the agent generates a new version that takes the notes into account.

The loop repeats until the draft passes the evaluation or a maximum number of attempts is reached. Anthropic's guide calls this pattern "evaluator-optimizer", and recommends it when the evaluation criteria are clear and when the critique brings a noticeable improvement.

Test tasksEval SetRun the agentRunTracingTracesMetricsSuccess · Latency · CostImprove
The evaluation cycle: a fixed set of tasks, a logged run, metrics, then improvement and re-measurement on the same set.

The idea of Reflexion

The Reflexion paper (Shinn and colleagues, 2023) proposed that after each failed attempt the agent writes a verbal reflection: a sentence or two explaining why it failed and what should change; these reflections are saved in memory and shown to it in the next attempt. The model is not retrained; the learning happens through the text saved in the context. The idea is close to a student writing in a notebook "I got it wrong because I forgot the empty list case" before solving the problem again.

The most important condition: a real evaluation signal

Bare self-critique, that is, asking the model itself "Is your answer correct?" without any new information, is of limited use. The model may confidently confirm its mistake, and it may change a correct answer into a wrong one. Self-correction is much stronger when it relies on a checkable external signal:

Signal sourceExample
Automated testsUnit tests on the generated code
A rule checkerChecking that the plan does not exceed the budget
A real toolRunning the query and making sure it does not return an error
A humanA supervisor's review or a user's rating

A practical example: a grade average function

An agent was asked to write a function that computes a student's average grade and returns zero if there are no grades. The evaluator here is a set of real tests. To keep the examples runnable without a model, we represent the agent's successive attempts with ready-made functions, and save the reflections in a list as in Reflexion:

python
def attempt_1(grades):
    return sum(grades) / len(grades)

def attempt_2(grades):
    if not grades:
        return 0
    return round(sum(grades) / len(grades), 2)

ATTEMPTS = [attempt_1, attempt_2]   # a stand-in for what the model generates in each attempt
TESTS = [([80, 90], 85), ([], 0), ([70, 75, 77], 74.0)]

def critic(fn):
    for grades, expected in TESTS:
        try:
            got = fn(grades)
        except Exception as e:
            return f"Failed with input {grades}: {type(e).__name__}"
        if got != expected:
            return f"Input {grades} gave {got}, expected {expected}"
    return None

reflections = []                     # memory of lessons learned
for i, fn in enumerate(ATTEMPTS, 1):
    print(f"Attempt {i}, available reflections: {reflections}")
    feedback = critic(fn)
    if feedback is None:
        print("All tests passed")
        break
    reflections.append(f"Attempt {i}: {feedback}; handle this case")
else:
    print("Attempts exhausted: escalate to a human")

The first attempt fails with a division by zero on the empty list, so a reflection is saved that names the case specifically. In a real system this reflection is shown to the model, which generates the second attempt that succeeds. Notice that the note is specific and names the input and the error, which is what makes it actionable.

Design tips

  • Make the critique specific: "The date field is missing" is better than "The answer is inaccurate".
  • Separate the evaluator from the generator as much as possible: a tool, tests or different instructions.
  • Set a maximum number of attempts and an escalation path to a human.
  • Save useful reflections in long-term memory if the type of task recurs, as you saw in the memory module.

Summary

Reflection is an explicit step after generation in which the output is evaluated and then improved in a new attempt through the generate, critique and revise loop. Reflexion proposes saving verbal reflections on the reasons for failure in a memory that is shown in later attempts without retraining. Self-correction is much stronger when it relies on an external signal such as tests, checkers or a human. Good design needs specific critique, a limit on attempts and an escalation path.

Terms

TermEnglishDefinition
ReflectionReflectionThe agent evaluating its output and using the evaluation to improve a later attempt
Self-correctionSelf-CorrectionThe agent revising its answer based on notes about its mistakes
CriticCriticA component that checks the output and writes specific notes
Evaluator-optimizerEvaluator-OptimizerA pattern in which a generator and an evaluator alternate until the criterion is met
Verbal reflectionVerbal ReflectionA short text that explains the reason for failure and is saved for the next attempt
External evaluation signalExternal FeedbackNew information from a test, a tool or a human that judges whether the output is correct

Review questions

  1. What are the three stages in the reflection loop? Apply them to writing a summary of a lecture.
  2. How does the agent learn in Reflexion without retraining the model?
  3. Why is bare self-critique weaker than automated tests?
  4. What risks result from a reflection loop without a maximum?

References