Reflexion

After every failure, the agent writes itself a critique. That critique lives in memory and shapes the next attempt. No gradient descent, no weight updates: just words, stored and reused. On 134 household tasks this lifts success from 71% to 97% in four trials.

Pick how the agent retries, then press Run 4 trials. Watch what the second attempt knows. Then we build, piece by piece, how a model learns from failure without changing a single weight.

You need what an LLM agent is and basic intuition about reinforcement learning. Reading ReAct first helps, but it is not required. We build the rest from zero.

Retry the task

Ready

The task is "put the pencil in the drawer". Choose a retry rule and press Run 4 trials.

The four-trial trace is a toy, written to show the mechanism. The 71% and 97% are the paper's AlfWorld success rates over 134 tasks, base agent against Reflexion with four trials (Chapter 6 gives the full table).

Chapter 0

The Problem

See why an agent that forgets every failure repeats it, and why updating weights is the wrong fix

You're playing a text-based game. You try to pick up a key, but instead you walk into a wall. You try again, and get the same result. The agent has no memory of its failure. Each attempt starts fresh, making the same mistake in the same room with the same wrong action. It learns nothing.

This is the fundamental problem with single-episode LLM agents. Each time the task resets, so does the agent's knowledge. A human playing the same game would think: "Last time I walked north when I meant to pick up the key. I should try 'pick up key' directly." The agent cannot do this, because it has no persistent memory of what went wrong.

RL's answer and its cost: Standard reinforcement learning (RL, learning from reward) addresses this with policy gradient updates. After each failure, you compute a reward signal, back-propagate gradients through billions of parameters, and nudge the weights. That works, but it costs thousands of GPU-hours per task, requires a differentiable reward signal, and produces a model that you can only interrogate as a black box. You can't ask it why it failed. Reflexion's answer: let the agent write down what went wrong in plain English, store it, and read it next time.

Three tasks make this concrete in the Reflexion paper:

Each task provides a natural evaluation: success or failure, as a binary signal. Reflexion uses that signal to trigger self-reflection. The agent fails, writes a critique, and tries again, up to a fixed number of trials. It is learning without learning: performance improves without touching a single weight.

Try the no-memory problem

An agent that tries a task again and again, without memory, repeats the same mistakes. Press Attempt a few times with no memory and watch it loop. Then switch to Reflexion memory and see how each failure improves the next try.

A toy trace for the task "put the pencil in the drawer". The first attempt always fails by walking into a wall. With memory, the second attempt reads the stored critique and succeeds. Without memory, every attempt repeats the mistake.

The road

Each chapter below explains one part of what you just played with.

  1. Self-Reflection: the critique the agent writes after a failure, and what makes it good.
  2. The Verbal RL Loop: the outer loop that wraps an agent, with the code.
  3. Memory: short-term, episodic and long-term, and what happens when memory fills up.
  4. vs Fine-Tuning: why Reflexion leaves the weights alone, and what that costs.
  5. Applications: AlfWorld, HotpotQA and code, with a real reflection for each.
  6. Results: the paper's numbers, and where Reflexion fails.
  7. Connections: the family of methods around it, and its limits.
Why does a standard LLM agent repeat the same mistakes across task attempts?

Chapter 1

Self-Reflection

Turn a failed attempt into a short written diagnosis that the next attempt can use

After a failed attempt, Reflexion asks the agent to do something humans do naturally: think about what went wrong. Given the task, the trajectory (every action and observation from the failed attempt), and the final outcome, the agent produces a verbal reflection. This is a free-text diagnosis of the failure and a strategy for the next attempt.

The analogy: A chess player who just lost replays the game in their head: "I should have traded bishops earlier. I got too focused on the kingside attack and missed the pawn structure collapsing." The reflection is not a new move. It is an updated mental model that shapes the next game. Reflexion is this, for LLM agents. The "mental model update" is a paragraph of English, stored in memory.

What makes a good reflection? The paper doesn't specify a fixed format. It uses few-shot examples of (trajectory, outcome) → reflection pairs to teach the LLM what a useful critique looks like. Good reflections tend to:

The same LLM that performed the task writes the reflection. There is no separate critic model. This works because LLMs have excellent meta-cognitive capabilities: they have seen enormous amounts of human writing about mistakes, corrections, and strategies. Given a failure, they can identify plausible explanations and better approaches.

reflection
The output: a short paragraph of English that names the mistake and the fix. It is not a number.
LLM
The same language model that attempted the task. Its weights are frozen.
task
The goal in words, such as "write a function that finds the second largest element".
‖
Join end to end. The model reads the four parts as one long prompt.
trajectoryfailed
Every thought, action and observation from the attempt that failed.
outcome
The success or failure signal, such as "FAILED: wrong answer", with any test output.
few-shot-examples
One to three samples of good critiques. They show the model what a useful reflection looks like.

Here is one worked case, taken from the coding task you will see in Chapter 2. The task is to find the second largest element. The failed trajectory is the one line return max(nums). The outcome is "FAILED: second_largest([5,5]) returned 5, wanted None". The model reads all of that plus the examples, and writes back: "I assumed no duplicates. I need to handle duplicates and return None if fewer than 2 unique values."

python (pseudocode)
def generate_reflection(task, trajectory, outcome, llm):
    # Build the reflection prompt
    prompt = REFLECT_TEMPLATE.format(
        task=task,
        trajectory=format_traj(trajectory),   # all thought/action/obs
        outcome=outcome,                          # e.g., "FAILED: wrong answer"
        examples=FEW_SHOT_REFLECTIONS            # 1-3 examples of good critiques
    )
    # LLM generates verbal critique
    reflection = llm.generate(prompt)
    return reflection  # e.g., "I searched too broadly. Next time focus on..."
What is a verbal reflection in Reflexion, and who generates it?

Chapter 2

The Verbal RL Loop

Run the full loop trial by trial and watch the memory fill with reflections

Reflexion wraps any base agent (like ReAct) in an outer loop. The inner loop is the agent solving the task: taking actions, observing outcomes, thinking through steps. The outer loop handles failure. It generates a reflection, stores it in memory, resets the environment, and tries again.

Watch the full loop unfold below. Each trial shows what the agent does differently because of its accumulated reflections. You control when the next trial runs, and you see the memory fill up.

Run the Reflexion loop

A coding task: write a function to find the second largest element. Press Next trial to watch the agent fail, reflect, and improve. Each trial card lists the reflections carried in as memory, then the actions.

A toy run of one coding task, written to show the mechanism. The trials, tests and reflections are illustrative, not output from the paper's experiments.

Full data flow: Trial 1 context = [task description + few-shot examples]. The agent generates a solution, it fails the tests, and a reflection is generated from (task, full trajectory, test output). Trial 2 context = [task + few-shot + reflection from trial 1]. The agent generates an improved solution. The context of trial N includes all previous reflections, summarized if too long. The LLM's weights never change. Only the context grows richer with each trial.
python
def reflexion_agent(task, env, llm, max_trials=4):
    memory = []  # persistent verbal memory across trials

    for trial in range(max_trials):
        # Build context: task + all past reflections
        context = build_context(task, memory, FEW_SHOT)

        # Run inner agent (e.g. ReAct) to completion
        trajectory, success = run_agent(llm, env, context)

        if success:
            return trajectory  # done

        # Generate verbal reflection from failed trajectory
        reflection = reflect(llm, task, trajectory)
        memory.append(reflection)  # accumulate in memory
        env.reset()               # reset environment, not memory

    return "Max trials reached"
What is the key difference between what resets between trials and what persists?

Chapter 3

Memory

Separate the three kinds of memory, and see what happens as reflections pile up

Reflexion uses three types of memory, which the paper calls short-term, long-term, and episodic. Knowing the difference shows both how Reflexion works and where it can fail.

Short-term memory is the agent's context window during a single trial: the current task description, the few-shot examples, and the accumulated thought/action/observation trace. This is what any LLM agent has. It is erased when the trial ends.
Episodic memory is the log of verbal reflections from past trials. This is Reflexion's key addition. After each failed trial, the reflection is appended to an episodic memory store. The next trial's context begins with this memory: "In a previous attempt, I failed because X. My strategy this time is Y." Episodic memory is what makes Reflexion more than a single-shot agent.
Long-term memory is the LLM's pre-trained weights, everything it knows from training. Reflexion never modifies this. Long-term memory is fixed. Episodic memory is the learning signal.

Memory Limits and What to Do About Them

The context window is finite. With long reflections and many trials, the episodic memory can overflow. Reflexion handles this with a simple priority: keep the most recent reflections, and drop older ones if needed. Alternatively, a summarization step can compress several reflections into one.

Memory TypeWhat It StoresLifetimeEditable?
Short-termCurrent trial trajectoryOne trialVia generation
EpisodicVerbal reflections from past trialsAll trialsVia appending
Long-termPre-trained LLM weightsPermanentNo (Reflexion doesn't fine-tune)

The episodic memory design also explains why Reflexion scales gracefully. Storing a reflection costs only tokens, not compute. Adding a third trial's reflection is as cheap as adding a sentence to a document. Compare this to RL, where each additional episode requires a full forward and backward pass through the model.

Watch memory accumulate

Each bar is one trial's context. Blue is the task and few-shot examples, purple is the reflections carried forward. Each trial sees all prior critiques. Drag the slider to add trials; the text below the bars is the memory the last trial reads.

1

Illustrative: the four reflections are examples from a household task, and every block is drawn the same width for clarity. Real reflections vary in length, which is why the context eventually fills.

What is episodic memory in Reflexion, and how does it differ from the model's long-term memory?

Chapter 4

vs Fine-Tuning

Weigh a paragraph of reflection text against a full weight update, and know when each one wins

The natural competitor for Reflexion is fine-tuning: update the model's weights using the failed trajectory as a negative training signal (or the successful trajectory as a positive one). This is the standard RL approach. Reflexion deliberately avoids it. Why?

Three reasons Reflexion doesn't fine-tune: First, access: you often don't have access to the model's weights. GPT-4, Claude and Gemini are API-only, so fine-tuning isn't an option. Second, cost: one fine-tuning run on a modern LLM costs orders of magnitude more than generating a paragraph of reflection text. Third, catastrophic forgetting: fine-tuning on specific task failures can degrade the model's performance on other tasks. Reflexion's context-only approach has zero risk of forgetting.

But Reflexion has its own failure modes compared to fine-tuning:

PropertyFine-TuningReflexion
Requires model weightsYesNo (API-only works)
Compute cost per trialVery high (full backward pass)Low (text generation)
Knowledge persistencePermanent (in weights)Context-window-limited
Cross-task transferYes (if trained on many tasks)No (per-task memory)
Risk of forgettingYes (catastrophic forgetting)None
InterpretabilityBlack box weightsHuman-readable reflections
The sweet spot: Reflexion is best for tasks where you need to improve quickly with a small number of trials, using an API-only model, on a specific task instance. Fine-tuning is better when you need general improvement across a class of tasks and have the compute budget and model access. In practice, the two can be combined: fine-tune with successful Reflexion trajectories as positive examples.
What is the most practical advantage of Reflexion over fine-tuning for most users?

Chapter 5

Applications

Read a real failure, reflection and new strategy from each of the paper's three task families

Reflexion was evaluated on three very different task families. The diversity is the point: verbal self-reflection is a general mechanism that works wherever (1) there is a clear success or failure signal and (2) the failure modes can be diagnosed in words.

Sequential Decision Making: AlfWorld

AlfWorld is a text-based household environment. It has 134 test tasks from 6 categories: pick up, put in, cool, heat, clean, examine. The agent must navigate rooms, interact with objects, and achieve multi-step goals in natural language. Failure modes include wrong room, wrong object, and wrong sequence.

Reflexion's reflections on AlfWorld failures look like: "I picked up the pan before heating it, but the task requires heating a pan already in the microwave. I should first identify which pan is already placed, then operate the appliance." This kind of sequential reasoning correction transfers directly to the next attempt.

Reasoning: HotpotQA

HotpotQA requires multi-hop reasoning over Wikipedia. The failure mode is searching too broadly or in the wrong direction. Reflexion reflects: "My search for 'French revolution leaders' was too broad. I need the specific person who was executed on Thermidor 9. Searching 'Robespierre execution date' directly would have worked." The next trial uses a targeted search strategy.

Programming: HumanEval + LeetCode

Code generation is perhaps the most natural fit. Unit tests provide a precise, binary signal. When a test fails, the failure message contains the exact input, expected output, and actual output. A reflection might say: "My solution fails for empty lists because I don't check for the edge case before calling max(). I need to add an early return for len(nums) == 0." The next attempt includes this check.

Why programming is the hardest test: Coding failures are diverse: off-by-one errors, missing edge cases, wrong algorithm choice, type errors. If verbal self-reflection works here, it is doing something genuinely useful, not just pattern-matching to obvious corrections. The paper shows Reflexion achieves 91% pass@1 on HumanEval with GPT-4, compared to 80% for GPT-4 alone. That 11% gap comes entirely from reflection.

Compare reflection quality by task type

See the example reflection text for each domain. The specificity and actionability of the reflection decide whether it helps the next attempt. Pick a domain.

These are illustrative examples written for this lesson in the style of the paper's reflections. They are not quoted from the paper's logs.

Why is programming one of the strongest applications of Reflexion?

Chapter 6

Results

Read the paper's gains, see where they come from, and learn when Reflexion stops helping

Across all three task families, Reflexion shows consistent improvement over the base agent (ReAct or simple prompting) with only 1 to 4 additional trials.

TaskMetricBase AgentReflexion (trials=4)Gain
AlfWorld (avg)Success Rate71%97%+26%
HotpotQAEM Score30%37%+7%
HumanEvalpass@1 (GPT-4)80%91%+11%
LeetCode (easy)pass@140%57%+17%

The AlfWorld improvement is the most striking: a +26% absolute gain from verbal self-reflection alone, across 134 household tasks. The paper attributes this to AlfWorld's structured failure modes. The same types of mistakes (going to the wrong room, not recognizing synonyms for objects) recur across tasks. Reflexion identifies these patterns and eliminates them.

Sample efficiency: Most of Reflexion's gain comes from the first reflection (trial 1 → trial 2). By trial 4, returns diminish. This suggests verbal self-reflection is most valuable for identifying clear, correctable mistakes, not for systematically improving on hard problems. For the hard tail of tasks that Reflexion still fails on after 4 trials, a different approach (more compute, better tools, fine-tuning) is needed.

The paper's failure analysis says tasks where Reflexion fails tend to involve hallucinated reflections ("I think I failed because X", where X is wrong). They also involve multi-step compounding errors, where no single reflection captures the root cause, and tasks that need genuine knowledge the model simply doesn't have. Verbal reflection can correct strategy. It cannot supply missing knowledge.

Follow success trial by trial

Success rate across trials for each task domain. Most of the gain comes from the first reflection. Pick a domain.

The base value at trial 1 and Reflexion's value at trial 4 are the paper's table above. The points between them are drawn as an illustration of the curve's shape, not individually reported numbers.

When does Reflexion fail to improve performance, even after multiple trials?

Chapter 7

Connections

Place Reflexion among its relatives, name its limits, and carry the core idea away

Reflexion is a loop that turns a failure into a stored sentence. The agent fails, writes one critique with the same frozen model, keeps it in episodic memory, and reads it on the next trial. The paper reports gains of 7 to 26 points over base agents, and most of that comes from the first reflection.

Result (paper, base agent → Reflexion, 4 trials)Number
AlfWorld success rate71% → 97%
HotpotQA exact match30% → 37%
HumanEval pass@1 (GPT-4)80% → 91%
LeetCode easy pass@140% → 57%

Here is the core as code. It is the whole method: one loop, one list.

python (the core)
memory = []
for trial in range(4):
    traj, ok = run_agent(llm, env, build_context(task, memory))
    if ok: break
    memory.append(llm.generate(REFLECT(task, traj)))   # words, not gradients
    env.reset()

Reflexion sits at the intersection of RL theory, agentic AI, and cognitive science. Its descendants and relatives show how the field has been building toward language-native learning.

MethodKey Ideavs Reflexion
ReAct (Yao 2022)Interleave thought + actionReflexion's inner loop; Reflexion adds outer loop + memory
Reflexion (this paper)Verbal critique → episodic memory → next trialn/a
Self-Refine (Madaan 2023)Critique and refine a single output iterativelySingle-shot refinement; Reflexion uses environment feedback across episodes
LATS (Zhou 2023)Monte Carlo tree search over agent trajectoriesReflexion: linear retry. LATS: tree search with backtracking.
Voyager (Wang 2023)Skill library grows with reflectionReflexion adds memories; Voyager adds reusable code skills
Constitutional AI (Bai 2022)Self-critique for alignmentDifferent goal (safety), same mechanism (self-evaluation + revision)
The broader principle: Reflexion is an instance of in-context learning from feedback. LLMs can improve at a task within a single context window given structured feedback, without any parameter updates. This connects to earlier work on few-shot learning (Brown et al. 2020) and tool use (Schick 2023): the model's in-context flexibility is an underexplored axis of capability.
Key limitations: (1) Context window ceiling: once the reflection history fills the window, no more learning is possible. (2) Hallucinated diagnoses: the model may misidentify why it failed, storing a wrong correction that hurts future trials. (3) No cross-task transfer: starting a new task clears all memories. (4) Evaluation dependence: Reflexion needs a clear success signal, so it cannot improve on tasks with ambiguous outcomes. (5) Deterministic failure: if the task is genuinely beyond the model's capabilities, repeated reflection won't help.

Go Deeper

Key Paper

Shinn, Cassano, Labash, Gopalan, Narasimhan, Yao. "Reflexion: Language Agents with Verbal Reinforcement Learning." NeurIPS 2023. arXiv:2303.11366

The takeaway: "The ability to learn from failure in language, without updating a single weight, is perhaps the most human thing a language model has ever done."
Which statement about Reflexion's limits is correct?

Try the idea in your own words with Teach mode: explain the loop on a whiteboard and see if it holds up. Present mode turns it into a talk. Then go back to the retry task at the top and run it once more with what you know now.

REFLEXION: LANGUAGE AGENTS WITH VERBAL REINFORCEMENT LEARNING
Read the paper · Back to Gleams