Özer Cem KELAHMETKELAHMET
Articles · Reflexion

Reflexion explained: agents that learn from failure with verbal feedback, step by step

Reflexion lets an agent retry a task with a short written lesson from its last failure instead of new weights. This guide explains the paper's three models and memory, runs a full trial loop in Python and LangGraph 1.2, and shows where the method helps and where it breaks.

Download Markdown
At a glance
Reading time
14 min
Sections
7
Code examples
4
Tables
3
Sources
6
Published
24 Nov 2026
In 30 seconds
What changed
The Reflexion paper is posted on arXiv
Why it matters
Reflexion needs a trustworthy evaluator.
What to do
Pick tasks with a cheap, reliable check

Most agents forget their mistakes the moment a run ends. If a coding agent fails a test, the next attempt starts from the same prompt and often makes the same error. Reflexion, a 2023 paper from Northeastern, MIT and Princeton researchers, proposed a cheap fix: after a failed attempt, ask the model to write down in plain language what went wrong and what to do differently, then put that note into the prompt of the next attempt.

The authors called this "verbal reinforcement learning". Nothing is trained. The "policy update" is a paragraph of text stored in memory. It sounds modest, yet it lifted GPT-4 from 80% to 91% pass@1 on the HumanEval coding benchmark in the paper. It is also the idea behind many self-correcting loops in current coding agents, which run tests, read failures and try again with notes.

What happened

The Reflexion paper is posted on arXiv (20 March 2023)

Noah Shinn, Federico Cassano, Edward Berman, Ashwin Gopinath, Karthik Narasimhan and Shunyu Yao introduced Reflexion as a way to reinforce language agents "not by updating weights, but instead through linguistic feedback". The paper tested it on decision making (ALFWorld), multi-hop question answering (HotpotQA) and code generation (HumanEval, MBPP and a new LeetCodeHardGym set).

Reflexion is published at NeurIPS 2023 (December 2023)

The paper appeared at the Neural Information Processing Systems conference. The authors' repository holds notebooks for HotpotQA, run scripts for ALFWorld and logs of all paper runs, which matters because most readers cannot afford to re-run GPT-4 experiments.

LangGraph 1.2.24 makes the loop a small graph (20 November 2026)

Reflexion needs state that persists across attempts, a conditional edge for "passed or not" and an append-only list of reflections. Those are first-class features in LangGraph. The graph later in this article was run on langgraph==1.2.24.

How Reflexion works, step by step

Think of a student preparing for an exam with past papers. They do a paper, check it against the answer key, and write a note on the inside cover: "I keep forgetting units in physics answers." Next time they sit a paper, they read the note first. Their brain did not change overnight, but their behaviour did. Reflexion gives an agent that inside cover.

The paper splits the agent into three models and two memories.

  1. Actor (Ma). The language model that does the task. It can be a chain-of-thought prompt, a ReAct agent or a code writer. It reads the task plus the stored reflections.
  2. Evaluator (Me). Scores the actor's output or trajectory. It can be exact match against a reference answer, a heuristic, unit tests or an LLM judge.
  3. Self-reflection model (Msr). Given the trajectory, the score and its own memory, it writes a short verbal lesson: what failed and what to try next.
  4. Short-term memory. The trajectory of the current attempt.
  5. Long-term memory. The list of reflections from earlier attempts. The paper bounded it to a few recent items, typically one to three, to stay within the context window.

The loop then runs trial after trial: act, evaluate, reflect, store, act again. It stops when the evaluator says the task is solved or a trial budget is used up.

The evaluator is the hard part

Reflexion only helps if the feedback signal is correct. The paper used a different evaluator per domain:

Table 1. The evaluator is the hard part
Domain Evaluator used What the reflection gets
ALFWorld (text game) A heuristic: flag the run if the same action and observation repeat more than three times, or it exceeds 30 actions; plus the environment's binary success "You were stuck in a loop" or "you did not finish" plus the trajectory
HotpotQA Exact match against the gold answer A wrong or right signal plus the reasoning trace
Programming Unit tests the agent writes for itself, then runs Which self-written tests failed and the error messages

The programming setup is clever and risky. HumanEval gives the hidden tests only for final scoring, so the agent generates its own tests, runs its code on them and reflects on failures. If its tests are wrong, it can "fix" correct code or accept broken code.

A runnable Reflexion loop in Python

This version uses real unit tests as the evaluator and a scripted actor and reflector, so it runs with no API key. Replace actor() and self_reflect() with model calls that read the memory.

TESTS = [("median([3, 1, 2])", 2), ("median([4, 1, 3, 2])", 2.5), ("median([5])", 5)]

ATTEMPTS = [
"""def median(xs):
    xs = sorted(xs)
    return xs[len(xs) // 2]""",
"""def median(xs):
    xs = sorted(xs)
    n = len(xs)
    if n % 2:
        return xs[n // 2]
    return (xs[n // 2 - 1] + xs[n // 2]) / 2""",
]
REFLECTIONS = [
    "My function returned the upper middle element for even-length lists. "
    "median([4, 1, 3, 2]) gave 3, not 2.5. Next time: if the length is even, "
    "average the two middle elements.",
]

def actor(task, memory, trial):          # real: llm(task + "\n".join(memory))
    return ATTEMPTS[min(trial, len(ATTEMPTS) - 1)]

def evaluator(code):
    env = {}
    exec(code, env)
    failures = []
    for expr, want in TESTS:
        got = eval(expr, env)
        if got != want:
            failures.append(f"{expr} returned {got}, expected {want}")
    return failures

def self_reflect(code, failures, trial):  # real: llm(code + failures + "What went wrong?")
    return REFLECTIONS[trial]

def reflexion(task, max_trials=3, memory_size=3):
    memory = []
    for trial in range(max_trials):
        code = actor(task, memory, trial)
        failures = evaluator(code)
        print(f"trial {trial + 1}: {len(TESTS) - len(failures)}/{len(TESTS)} tests pass")
        if not failures:
            return code, trial + 1
        reflection = self_reflect(code, failures, trial)
        memory = (memory + [reflection])[-memory_size:]
        print("  feedback:", failures[0])
        print("  reflection:", reflection)
    return None, max_trials

code, trials = reflexion("Write median(xs) for a non-empty list of numbers.")
print("solved after", trials, "trials")

The output is the whole method in four lines:

trial 1: 2/3 tests pass
  feedback: median([4, 1, 3, 2]) returned 3, expected 2.5
  reflection: My function returned the upper middle element for even-length lists. ...
trial 2: 3/3 tests pass
solved after 2 trials

Notice what the reflection adds beyond the raw test failure. The failure says "returned 3, expected 2.5". The reflection names the cause ("upper middle element for even-length lists") and the plan ("average the two middle elements"). The paper's argument is that this compressed, causal summary is a better signal for the next attempt than the raw trajectory alone.

The same loop as a LangGraph graph

In production you want the loop to be inspectable and resumable. Here it is as a graph, reusing the functions above:

import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    task: str
    code: str
    failures: list[str]
    reflections: Annotated[list[str], operator.add]   # appended, never overwritten
    trial: int

def act(s: State):
    return {"code": ATTEMPTS[min(s["trial"], len(ATTEMPTS) - 1)], "trial": s["trial"] + 1}

def evaluate(s: State):
    return {"failures": evaluator(s["code"])}

def reflect(s: State):
    return {"reflections": [REFLECTIONS[s["trial"] - 1]]}

def route(s: State):
    return END if not s["failures"] or s["trial"] >= 3 else "reflect"

g = StateGraph(State)
g.add_node("act", act); g.add_node("evaluate", evaluate); g.add_node("reflect", reflect)
g.add_edge(START, "act"); g.add_edge("act", "evaluate")
g.add_conditional_edges("evaluate", route, ["reflect", END])
g.add_edge("reflect", "act")
app = g.compile()

out = app.invoke({"task": "Write median(xs).", "trial": 0, "reflections": []})
print(out["trial"], out["failures"], len(out["reflections"]))   # 2 [] 1

The operator.add reducer makes reflections the long-term memory: each reflect node appends one lesson. Add a checkpointer at compile time and every trial becomes a saved step you can inspect or replay, as the LangGraph checkpoints simulation shows.

What the paper measured

The paper reports improvements over strong baselines in all three domains. In its introduction the authors summarise them as absolute gains of 22% on ALFWorld over 12 iterative learning steps, 20% on HotpotQA and up to 11% on HumanEval.

Table 2. What the paper measured
Benchmark Baseline Reflexion Notes
HumanEval (Python), pass@1 GPT-4: 80% 91% Self-generated unit tests as evaluator
ALFWorld ReAct alone 130 of 134 tasks solved ReAct actor with heuristic plus binary evaluator
HotpotQA CoT and ReAct actors About 20 points better 100 sampled questions, exact-match evaluator
MBPP (Python) GPT-4 Slightly worse Weak self-tests produced false positives

The MBPP result is the useful warning. The paper traces it to the self-generated tests: when tests pass on wrong code, the agent stops early with a false positive; when tests are wrong, it "fixes" correct code. Reflexion amplifies whatever the evaluator says, good or bad.

An ablation on HotpotQA also matters for design. Giving the agent only its last trajectory as context helped less than giving it the written reflection. The episodic memory of lessons, not just more history, did the work.

Cost per solved task

Reflexion trades tokens for accuracy. Each extra trial costs one actor run, one evaluation and one reflection call. Suppose a ReAct actor run costs 20,000 tokens, the reflection 1,500 and evaluation is free unit tests. If 60% of tasks pass on trial 1 and half of the rest pass on trial 2, then per 100 tasks you pay 100 runs, 40 reflections and 40 second runs: 2,860,000 tokens for 80 solved tasks, or about 35,750 tokens per solved task, against about 33,300 per solved task (2,000,000 / 60) without Reflexion. Here accuracy rises by 20 points for about 7% more tokens per solved task. If the second trial rarely succeeds, the maths turns against you fast, so log the per-trial success rate.

Reflexion is one of several patterns that add a second pass to an agent. They differ in where the feedback comes from and what is kept between attempts.

Table 3. Reflexion compared with related loops
Pattern Feedback source What persists between attempts Typical cost
Plain retry Error message or failed check Nothing, or only the last error One extra actor call per retry
Self-refine (critique and revise) The model's own critique, no external check The current draft One critique and one revision per round
Reflexion An external evaluator plus a written diagnosis A bounded list of lessons One actor run, one evaluation and one reflection per trial
LATS Value estimates and reflections inside a search tree The whole tree of tried branches Many actor and value calls per task

The table shows the main design choice. If you have no reliable evaluator, Reflexion collapses into self-critique, which the model may simply agree with. If you have a strong evaluator and a budget for many calls, tree search can explore alternatives that a single retry path never reaches. Reflexion sits in the middle: it needs a real signal but only one path at a time. The base loop each trial runs is usually a ReAct loop, and the agentic patterns simulation lets you compare reflection with ReAct, planning and multi-agent designs on the same task. Whatever you choose, keep a fixed task set and score it with the same evals before and after adding the loop.

What it means in practice

Reflexion needs a trustworthy evaluator. Unit tests, schema validators, compilers and exact-match checks are ideal. An LLM judge can work, but measure its agreement with humans first; the LLM judge agreement simulation shows how quickly a weak judge misleads you.

It is retry with memory, not learning across users. The lessons live in one task's memory. Some teams store reusable lessons in a long-term store keyed by task type, which turns Reflexion into a simple form of agent memory. That is an extension, not what the paper evaluated.

It fits coding agents naturally. Run tests, read failures, write a short diagnosis, try again. Current coding agents do a version of this inside one session. Reflexion's contribution is to make the diagnosis an explicit, bounded memory item. The broader reflection pattern also covers critique-and-revise loops without an external evaluator.

Budget trials explicitly. The paper ran many trials on ALFWorld; most products cannot. Two or three trials capture most of the gain in many settings, but only your own logs can confirm that.

What to do now

  1. Pick tasks with a cheap, reliable check. Code with tests, SQL with expected rows, JSON with a schema. Avoid Reflexion where you cannot say clearly whether an attempt succeeded.
  2. Separate the three roles in code. Keep actor, evaluator and reflector as distinct functions or graph nodes so you can swap each one and trace it on its own.
  3. Make reflections short and causal. Prompt the reflector for "what went wrong, why, and one concrete change", in two or three sentences, not a retelling of the trajectory.
  4. Bound the memory. Keep the last one to three reflections, as the paper did. Long memories cost tokens and can contain contradictory advice.
  5. Cap trials and log success per trial. If trial 3 almost never succeeds, drop it.
  6. Audit evaluator false positives. Sample passed tasks and check them by hand or with stronger hidden tests, because self-tests can pass broken code.
  7. Trace the whole loop. Record each trial's output, evaluation and reflection; the agent run simulation shows the kind of trace that makes failures readable.
  8. Compare against simple retries. Run "retry with the error message" as a baseline. If written reflections do not beat it on your data, keep the simpler loop.

Risks and open questions

Self-generated tests can lie. A model that writes both the code and its tests can share one misunderstanding across both. The MBPP result shows this is not theoretical.

Reflections can be confidently wrong. A wrong diagnosis ("the bug is in sorting") steers the next attempt away from the real cause. There is no guarantee each reflection is better than the last.

Local minima. The paper notes that Reflexion can get stuck when the task needs a very different strategy, not an adjustment. Search methods such as LATS combine reflection with exploring several branches for this reason.

Benchmarks have moved. HumanEval is now close to saturated for frontier models. The mechanism still matters, but do not expect the same jump on today's models without measuring.

Watch next: how coding agents store lessons across sessions, how judges are calibrated before they drive retries, and whether reflection plus tree search becomes the default for hard tasks with verifiable rewards.

Frequently asked questions

Is Reflexion reinforcement learning?

Not in the usual sense. No weights change and there is no gradient. The paper calls it verbal reinforcement because a scalar or binary signal is turned into text that changes the agent's behaviour on the next trial.

How is Reflexion different from just retrying with the error message?

A plain retry shows the model the error. Reflexion adds a separate step where the model explains the cause and plans a change, and it keeps these explanations in a bounded memory across trials. The paper's ablations found the written reflection helped more than the raw last trajectory alone.

What evaluator should I use?

The most objective one you can get: tests, validators, exact match or environment success signals. Use an LLM judge only after checking how often it agrees with human labels on your own data.

How many trials should I allow?

Start with two or three and measure success per trial. Stop adding trials when the marginal solve rate no longer justifies the extra actor and reflection calls.

Can I use Reflexion with any framework?

Yes. It is a control loop around any actor. LangGraph makes it a three-node graph with an append-only reflections field, and the same structure works in plain Python or other agent frameworks.

Summary

Reflexion improves an agent across attempts by converting feedback into short written lessons that are fed into the next attempt. It uses three roles, an actor, an evaluator and a self-reflection model, plus a small episodic memory of lessons. The paper reported 91% pass@1 on HumanEval against GPT-4's 80%, 130 of 134 ALFWorld tasks solved and large gains on HotpotQA, and it also showed the method's weak spot: weak self-generated tests made MBPP results worse. Use it where you can check success cheaply and reliably, bound the memory and trials, and compare it against a plain retry.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 24). Reflexion explained: agents that learn from failure with verbal feedback, step by step. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/reflexion-verbal-reinforcement-agents-explained

BibTeX
@online{kelahmet2026reflexion,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{Reflexion explained: agents that learn from failure with verbal feedback, step by step}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/reflexion-verbal-reinforcement-agents-explained}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 24, 2026
Type to search.
    ↑↓ navigate↵ open