ReAct, Reflection and Self-Correction

Learn the ReAct pattern of interleaving reasoning and acting, how reflection lets an agent critique its work, how self-correction with real feedback fixes errors, and how to design safe retry loops.

28 minIntermediateCode Examples

The Core Idea: ReAct interleaves thinking and acting: Thought → Action → Observation, repeated. Reflection adds a step where the agent critiques its own output, and self-correction uses real feedback, such as a failed test, to try again, within a retry limit.

  1. Beginner: What Is ReAct?

ReAct (Reason + Act) is a pattern in which the agent alternates between reasoning in words and taking an action. The reasoning guides which action to take. The action returns an observation that guides the next reasoning step.

Without ReActWith ReAct
Think everything through first, then actThink a little, act, look, think again
Mistakes are found at the endMistakes are noticed as soon as an observation surprises the agent
Hard to see why an action was chosenThe thoughts explain each action

Why it works: Real information from tools corrects the model's guesses at every step, and the written thoughts keep the plan on track.

  1. Beginner: Reason → Act → Observe in Practice

In the code the agent answers a two-part question. Look at how each thought leads to an action and each observation leads to the next thought:

1
Thought: I must find the capital of France first.
2
Action: lookup[capital of France]
3
Observation: Paris
4
Thought: Now I need the population of that city.
5
Action and observation: lookup[population of Paris] gives about 2.1 million, then the final answer.

Note: The second action only became possible because the first observation said Paris. That dependency is why interleaving beats planning everything in advance.

  1. Medium: Reflection

Reflection means the agent reviews its own work before finishing: Is this correct? Did I answer the whole question? What could be wrong? A separate critique prompt, or a second model call, produces feedback that is used to revise the output.

Reflection questionCatches
Did I answer every part of the question?Missing parts
Do the numbers add up?Arithmetic and logic errors
Is every claim supported by a source?Invented facts
Does it follow the required format?Format errors

Limit: A model reviewing its own text can miss its own mistakes. Reflection is much stronger when it uses real checks: tests, calculators or retrieved sources.

  1. Medium: Self-Correction With Feedback

Self-correction is the loop: produce, check, read the failure, fix, check again. The best feedback is concrete and external, such as a failing test message.

In the code: The first attempt at a sum function has an off-by-one bug. The test says total(3) returned 3 but should be 6. That exact message goes back to the model, which fixes the bug on attempt 2.

Weak feedbackStrong feedback
That is wrong, try againtotal(3) returned 3 but should be 6
Improve the answerThe second paragraph has no source
ErrorTypeError at line 4: cannot add str and int

  1. Advanced: Retry Loops and Their Limits

Self-correction needs boundaries, or it becomes an endless loop that burns tokens:

ControlSetting
Maximum attemptsUsually 2 to 5
Stop if no progressIf the same error repeats, change approach or ask for help
Always include the new feedbackRetrying with the same prompt gives the same failure
BudgetCap tokens, time and cost for the whole loop
Keep the best attemptIf all attempts fail, return the best one with a warning

Important: Retrying the identical request rarely helps. A good retry changes something: new feedback, a different tool, a simpler plan, or a human.

  1. Visual Explanation: ReAct and the Self-Correction Loop

The figure shows one turn of the ReAct loop, then the write, test, reflect and fix cycle from the code.

Part 1 · The ReAct LoopThink, act, look, repeat
ThoughtReason
I must find the capital first
↓
Chooses the action
ActionAct
lookup[capital of France]
↓
Uses a tool
ObservationLook
Paris
↓
Informs the next thought
Part 2 · The Self-Correction LoopFrom failure to fix
Write
Attempt 1
Off-by-one bug.
Test
Fails
total(3) returned 3, should be 6.
Reflect
Read the error
Spot the range mistake.
Fix
Attempt 2
All tests pass.
Click to see why feedback must be concreteCompare ▼
The model can only fix what it can see. A precise message such as total(3) returned 3 but should be 6 points straight at the bug, while a vague message gives it nothing new to work with.

Part 1 shows how thought, action and observation connect. Part 2 shows an error being found and fixed. Open the bar to see why concrete feedback matters.

  1. Python Implementation: A ReAct Trace and a Self-Correcting Coder

This script prints a ReAct trace for a two-step question, then runs a self-correction loop: a stand-in model writes code with a bug, a test fails, the failure message is fed back, and the second attempt passes. The attempt count is limited.

react_and_reflection.pyPython 3.10+ · standard library only
# ReAct: Thought -> Action -> Observation, repeatedKB = {"capital of France": "Paris", "population of Paris": "about 2.1 million"} steps = [    ("I must find the capital of France first.", "lookup", "capital of France"),    ("Now I need the population of that city.", "lookup", "population of Paris"),]for number, (thought, action, argument) in enumerate(steps, 1):    print("Thought", number, ":", thought)    print("Action", number, ":", action + "[" + argument + "]")    print("Observation", number, ":", KB[argument])print("Final answer: Paris has", KB["population of Paris"], "people.") # Reflection and self-correction: write, test, read the failure, fix, retrydef fake_llm_write(feedback=None):    if feedback is None:        return "def total(n):\n    return sum(range(n))"            # first attempt has an off-by-one bug    return "def total(n):\n    return sum(range(n + 1))"            # after seeing the failure, it fixes it def run_tests(source):    namespace = {}    exec(source, namespace)    cases = [(3, 6), (10, 55)]    return [(n, want, namespace["total"](n)) for n, want in cases if namespace["total"](n) != want] feedback = Nonefor attempt in range(1, 4):    source = fake_llm_write(feedback)    failures = run_tests(source)    if not failures:        print("Attempt", attempt, "-> all tests pass")        break    n, want, got = failures[0]    feedback = "total(" + str(n) + ") returned " + str(got) + " but should be " + str(want)    print("Attempt", attempt, "-> FAILED:", feedback)
EXPECTED OUTPUT (your numbers may differ slightly)
Thought 1 : I must find the capital of France first.
Action 1 : lookup[capital of France]
Observation 1 : Paris
Thought 2 : Now I need the population of that city.
Action 2 : lookup[population of Paris]
Observation 2 : about 2.1 million
Final answer: Paris has about 2.1 million people.
Attempt 1 -> FAILED: total(3) returned 3 but should be 6
Attempt 2 -> all tests pass

Observation 1 (Paris) makes Thought 2 possible. In the second part, only the first attempt fails. The exact error message is fed back, and attempt 2 passes. In a real system the code would run in a sandbox and the loop would stop after a few attempts.

Knowledge Check

Question 1: What does the Observation step in ReAct provide?
Question 2: Which retry is most likely to help?

Key Points

✓ReAct alternates thoughts, actions and observations.
✓Observations from tools correct the model's guesses at every step.
✓Reflection means reviewing one's own work against questions or real checks.
✓Self-correction works best with concrete, external feedback such as test failures.
✓A good retry changes something: new feedback, a different tool or a different plan.
✓Limit attempts and budget, and return the best attempt with a warning if all fail.

The Big Picture

ReAct and Correction in One Line

Think → act → observe → critique with real feedback → fix → stop after a few tries

These patterns are the engine of coding agents and research agents.

Up Next: When tasks have many branches, parallel steps and pauses, loose loops are not enough. In Agent Workflows and State Machines you will learn to structure agents with explicit states, branches and checkpoints.