Velamuvi AIAcademy

Lesson 3 of 5 · Planning

Self-Correction

How AI agents fix their own mistakes: why tests, validators and tool errors beat self-critique, generate-test-fix loops, retry limits and not gaming checks.

  • 8 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Explain why external feedback works better than asking a model to check itself
  • Build a generate, test and fix loop with a retry limit
  • Use validators to decide when an answer is good enough
  • Store reflections so an agent learns from failures across tasks
  • Prevent an agent from gaming its own checks

Mistakes are normal; unnoticed mistakes aren't

Agents make mistakes: a wrong formula, a missing field, a query that names a column that doesn't exist. The question is whether the agent notices and fixes them before the user sees the result.

The key word is information. A model asked “Are you sure?” has no new information, only a hint that it might be wrong. Studies such as “Large Language Models Cannot Self-Correct Reasoning Yet” (Huang et al., 2023) found that when models re-check their own reasoning with no outside feedback, accuracy often doesn't improve and can even get worse, as correct answers get changed to wrong ones. Self-correction works when the agent gets real feedback from outside the model.

Where good feedback comes from

Feedback sourceExampleHow reliable
Tests and compilers“is_leap(1900) returned True, expected False”Very: exact and repeatable
Validators and schemas“missing field: age”Very, for format and rules
Tool errors“column ‘delivery_dt’ does not exist”High, and they point to the fix
LookupsChecking a claimed figure against its sourceHigh, if the source is good
Another model as judgeA rubric score with commentsMedium: useful, but can be biased
The same model, unaided“Review your answer”Low for reasoning errors

Generate, test, fix

The strongest pattern is a loop: generate an answer, run it through a verifier, and if it fails, send the specific failures back with the task. Here the model's first attempt has a classic leap-year bug; the failing test tells it exactly what's wrong:

Try it yourselfPython
# Self-correction with real feedback: write code, run the tests, feed failures back, try again.
TESTS = [(2024, True), (2023, False), (1900, False), (2000, True)]

# Stand-in for the model: its first attempt has a classic bug; given the failures it fixes it.
ATTEMPTS = [
    "def is_leap(year):\n    return year % 4 == 0",
    "def is_leap(year):\n    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)",
]

def model(task, feedback, attempt):
    return ATTEMPTS[attempt]                    # a real agent sends task + feedback to an LLM

def run_tests(code):
    scope = {}
    exec(code, scope)                           # real systems run untrusted code in a sandbox
    return [f"is_leap({y}) returned {scope['is_leap'](y)}, expected {want}"
            for y, want in TESTS if scope["is_leap"](y) != want]

feedback = ""
for attempt in range(3):                        # a fixed limit: never retry forever
    code = model("Write is_leap(year) for the Gregorian calendar.", feedback, attempt)
    failures = run_tests(code)
    print(f"Attempt {attempt + 1}: {len(TESTS) - len(failures)}/{len(TESTS)} tests pass")
    if not failures:
        print(code)
        break
    feedback = "These tests failed:\n" + "\n".join(failures)
    print(feedback)

The feedback isn't “that's wrong, try again”. It's the exact input, the actual result and the expected result. That's what makes the second attempt likely to succeed. And the loop has a fixed limit: if three attempts don't pass, the agent stops and reports, rather than burning money forever.

Learning from failures: reflection

A retry loop fixes one answer. Reflection carries the lesson to future tasks: after a failure, the agent writes a short note on what to do differently, and that note is included the next time.

Try it yourselfPython
# Reflection memory: after a failure, write down the lesson so the NEXT task starts wiser.
reflections = []

def reflect(task, failures):
    """Stands in for an LLM asked: 'In one sentence, what should you do differently next time?'"""
    return "With calendar rules, test century years such as 1900 and 2000 before answering."

reflections.append(reflect("is_leap", ["is_leap(1900) returned True, expected False"]))

def build_prompt(task):
    lessons = "\n".join(f"- {r}" for r in reflections)
    return f"Lessons from earlier tasks:\n{lessons}\n\nTask: {task}"

print(build_prompt("Write days_in_february(year)."))

This is the idea behind Reflexion (Shinn et al., 2023), where agents improved over repeated attempts by storing verbal reflections on their failures in memory, rather than by retraining the model. In practice, store reflections like any long-term memory (see the Memory in AI Agents course): short, specific, and recalled only when relevant.

Don't let the agent game the checks

An agent rewarded for passing checks may find ways to pass them without doing the job: editing the tests, special-casing the exact test inputs, catching every error and printing “success”, or loosening a validator.

Common mistakes

Practice exercise

Write the check-and-retry loop of a self-correcting agent: a validator, not the model's own opinion, decides when an answer is good enough.

Your solutionPython
import json
attempts = ['{"name": "Mei"}', '{"name": "Mei", "age": "31"}', '{"name": "Mei", "age": 31}']

def problems(text):
    data = json.loads(text)
    found = [f"missing {k}" for k in ("name", "age") if k not in data]
    if "age" in data and not isinstance(data["age"], int):
        found.append("age must be a whole number")
    return found

# Check each attempt in turn (at most 3). Print the problems of each failed attempt,
# then for the first attempt with no problems print: Accepted attempt <n>
Knowledge check

Which feedback is most likely to help an agent fix a broken function?

Summary

  • Self-correction needs real feedback from outside the model; unaided self-review often doesn't help.
  • The best verifiers are tests, validators, tool errors and lookups.
  • Generate, test, fix loops send specific failures back, with a fixed attempt limit.
  • Reflection stores lessons from failures for future tasks.
  • Keep verifiers out of the agent's reach so it can't game them.

Next: search-based planning, exploring several options before committing.

Finished reading? Tick it off to track your progress.