Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Reflexion,
explained.
Reinforcement learning improves an agent by nudging millions of weights — slow, expensive, and impossible if the model is behind an API. Reflexion found a shortcut hiding in plain sight: when the agent fails, have it write down why, keep the note, and let it read its own advice before trying again. No gradients. No fine-tuning. The agent gets better the way people do — by remembering what went wrong.
What changes against ReAct: a failure becomes an instruction
Rungs 1 and 2 get one attempt. If the agent fails, it fails; retrying it gives you a fresh sample from the same distribution, which fails in much the same way. The obvious fix is to learn from the failure, and the obvious way to learn is a gradient step — expensive, slow, and impossible if you do not own the weights.
The change is to learn in words instead of weights. After a failed attempt, the agent is shown the trajectory and asked to write a reflection on why it failed — a short, specific diagnosis, not a score. That reflection is stored and placed in the context of the next attempt. The policy has changed, in the only sense that matters for behaviour, with no parameters touched.
Stated in the units the ladder compares on: the loop is actor, evaluator, reflector — something acts, something determines that the outcome was bad, and something converts that into an instruction the next attempt can use. The reported result on a code benchmark is in the region of 91%, from repeated attempts where a single attempt is far lower. And the cost is a few extra model calls, which against any form of training is close to nothing.
Agents that make the same mistake twice
A ReAct-style agent can act, observe, and adapt within one attempt. But let it fail the whole task and try again, and something embarrassing happens: it repeats the same mistake. Nothing carried over. The standard fixes were both bad — fine-tune on failures (expensive, impossible via API, and one task's lessons overwrite another's) or just replay the failed attempt in context (raw trajectories help some, but a short written lesson distilled from the failure is a stronger and more compact signal).
What's missing is what humans do between attempts: compress the failure into a lesson. Not "here are the 4,000 tokens of my failed attempt" but "I forgot to handle the empty-list case."
Actor, Evaluator, Reflector
Reflexion splits the retry loop into three roles. The Actor attempts the task — writing code, navigating a household simulator, searching for answers. The Evaluator grades the attempt: unit tests for code, task success for environments, an LLM judge where nothing crisper exists. And the Self-Reflection model turns the graded failure into a short, specific verbal lesson.
tests · env · judge
why it failed
lessons persist
in context
The lessons accumulate in an episodic memory buffer that's prepended to every new attempt. Attempt three doesn't just know the task — it knows exactly how attempts one and two died.
Why words beat scalars
Classic RL compresses feedback into a single number — reward 0. Everything about why is discarded, and the algorithm spends thousands of episodes rediscovering it through trial and error. A verbal reflection keeps the why: which assumption was wrong, which edge case was missed, what to try instead. It's credit assignment in prose — precise, immediate, and executable by the very next attempt.
Reflection: "I treated touching intervals as disjoint. Boundary equality must merge — use start <= prev_end, not <."
Attempt 2: passes.
The model already contains the machinery to diagnose failures and follow advice — it's a language model. Reflexion routes the learning signal through that machinery instead of through the weights. Policy improvement becomes a context update.
The whole loop is one line of state that survives between attempts — the memory of what went wrong:
Delete that memory arrow and every retry is attempt one again. The runnable version below shows it fix the boundary bug on attempt two — and a memoryless retry failing forever.
The limits
Reflexion learns nothing durable — lessons live in a context buffer, bounded by the window, gone when the episode ends (unless you persist them into real memory). It leans on the Evaluator: crisp signals like unit tests make it soar; fuzzy self-evaluation can reinforce confident nonsense. And reflection quality is capped by the model's own diagnostic ability — an agent that misunderstands why it failed writes itself bad advice and then dutifully follows it.
It's also, quietly, a test-time method: multiple attempts cost multiple rollouts. Like self-consistency and ToT, it buys capability with inference compute.
Why it still matters
Reflexion named and validated the pattern that now lives inside nearly every serious agent: try → check → diagnose in words → retry with the diagnosis. Every coding agent that reads its own test failures and patches, every harness with a critique-then-revise step, every eval loop that feeds errors back as guidance — that's the Reflexion loop, productionized.
Its deeper claim aged even better: a model's language channel is a legitimate substrate for learning. That idea threads through self-critique training, agent post-mortems written to memory, and the whole self-improvement research line. Weights are one place to store lessons; words, it turns out, are another.
The within-attempt loop it extends: ReAct. Where the lessons should live: MemGPT. The evaluator side: Agent Evals.
How a Reflexion run works, trial by trial
Reflexion is a loop around an existing agent, built from three prompted models and a short memory. Nothing is trained; every component is a language-model call.
- Choose the actor. The actor Ma is whatever agent suits the task: ReAct for the ALFWorld household games and for HotpotQA with a Wikipedia API, chain of thought for HotpotQA with the supporting paragraphs supplied, and a code writer for programming. Its policy is πθ(ai | si) with θ = {Ma, mem}: the frozen model plus whatever is in memory.
- Run one trial. The actor produces a trajectory of actions and observations, conditioned on the task and on the memory.
- Score it. The evaluator Me returns a sparse signal, usually pass or fail. On HotpotQA it is exact match against the answer. In ALFWorld, where the environment only reports completion, it is either an LLM classifier or a hand-written heuristic that flags failure when the agent repeats the same action and gets the same response more than three times, or takes more than 30 actions. For code it is a test suite the agent writes itself: chain-of-thought prompting proposes tests, any that do not parse into a valid syntax tree are dropped, and up to six are sampled.
- Reflect. The self-reflection model Msr reads the signal, the trajectory and the current memory and writes a short diagnosis with a plan: in one ALFWorld example, that it should have found the desk lamp first and then the mug, not the other way round.
- Store it, within a cap. The reflection is appended to an episodic memory that keeps only the last Ω entries, usually 1 to 3 so the prompt fits the context window: three for ALFWorld and HotpotQA, one for programming.
- Retry. The next trial starts with the memory in the prompt. The loop stops when the evaluator passes or the trial budget runs out. ALFWorld ran for 12 trials; on HotpotQA an agent retried a question until it failed three times in a row.
- Submit once. For code, only the final program is scored against the benchmark's hidden tests. All the iteration happens against the agent's own tests, which is what keeps the reported number a pass@1.
The baselines are the same agents without the reflection step. In ALFWorld, a baseline run that trips the heuristic simply resets and starts a new trial with nothing learned. On HotpotQA, sampling at temperature 0.7, the baselines solved none of their first-trial failures on any later trial.
The models differ by task: GPT-4 for the programming results, a GPT-3 model with ReAct's two few-shot trajectories for ALFWorld, and text-davinci-003, gpt-3.5-turbo and GPT-4 compared on 100 HotpotQA questions. HotpotQA prompts used 6 examples for chain of thought, 2 for ReAct and 2 for self-reflection.
Reflexion's policy, loop and stopping rule
θ— the parameters of the policy. Reflexion's move is that one of them is text: updatingmemchanges behavior without touchingMa.rt— the evaluator's reward, usually binary: exact match, task success, or all self-written tests passing.srt— the verbal reinforcement: a few sentences naming what went wrong and what to do instead.Ω— the memory cap, 1 to 3 reflections.
The extremes map onto the failure modes. With Ω = 0 every retry is a fresh sample from the same policy, and on HotpotQA such retries fixed nothing. If Me passes a wrong answer, the loop stops early and never reflects, which is how false-positive self-tests hurt MBPP. If Msr cannot diagnose its own errors, the memory fills with useless advice: with the smaller starchat-beta model, HumanEval pass@1 stayed at 0.26 with or without Reflexion.
Reflexion on HumanEval, MBPP, ALFWorld and HotpotQA, including the misses
The programming runs use GPT-4 with self-generated tests and report pass@1; each baseline is the same model's single attempt.
| Benchmark | Baseline | Reflexion |
|---|---|---|
| HumanEval, Python (pass@1) | 80.1 | 91.0 |
| HumanEval, Rust | 60.0 | 68.0 |
| MBPP, Python | 80.1 | 77.1 |
| MBPP, Rust | 70.9 | 75.4 |
| LeetcodeHardGym, Python | 7.5 | 15.0 |
| ALFWorld, 134 tasks, ReAct actor | stops improving after trial 6 or 7 | 130 of 134 solved within 12 trials |
| HotpotQA, ReAct actor, GPT-4, 100 questions | 0.39 | 0.51 |
Plain GPT-4 at 80.1 was the state of the art Reflexion had to beat; the best earlier method the authors list, CodeT with GPT-3.5, scored 65.8. LeetcodeHardGym is the authors' own set of 40 hard Leetcode problems released after GPT-4's pretraining cutoff, to avoid contamination. On ALFWorld the ReAct-only agent settled at a 22 percent hallucination rate with no sign of recovering; a common baseline error was believing it held an item it did not.
Two ablations isolate what does the work. On the 50 hardest HumanEval Rust problems the full method scored 0.68 against a 0.60 baseline. Keeping the self-written tests but dropping reflection stayed at 0.60. Keeping reflection but dropping the tests fell to 0.52, below the baseline, because an agent that cannot tell when its code is correct never stops early and keeps editing working programs. On HotpotQA with the supporting paragraphs given, reflection added 8 points over episodic memory alone, which simply replays the last trajectory.
The misses are as informative. MBPP Python got worse, 80.1 to 77.1, because the self-written tests were unreliable there: 16.3 percent of submissions that passed the agent's own tests failed the hidden ones, against 1.4 percent on HumanEval Python, and a false positive ends the loop on wrong code. On WebShop, two-shot ReAct plus Reflexion showed no improvement after four trials across 100 environments, and its reflections were unhelpful, which the authors read as a limit on tasks needing diverse exploration. And the method needs a strong model: with starchat-beta, HumanEval pass@1 was 0.26 with and without reflection.
What the authors admit, and what happened next
The loop needs an evaluator, and that is where it is strong or hopeless with nothing in between. Where failure is detected by running tests — code, as in the headline result — the signal is reliable and the method works well. Where the agent must judge its own success, the loop inherits a known weakness: models are poor at recognising their own errors, and an agent that believes it succeeded will not reflect at all.
The second failure mode is that a reflection can be wrong. A confident, incorrect diagnosis of the failure is now in the context, actively steering the next attempt away from the answer, and nothing removes it. Verbal lessons accumulate without being validated, which is a different risk profile from a gradient step that at least moved in the direction of a measured loss.
How it held up: retry-with-reflection is in every agent framework, because it is the cheapest self-correction available and it needs no infrastructure. The framing — natural language as the medium of policy improvement — is the durable idea, and rung 4's answer to the wrong-reflection problem is to store something that can be executed and tested rather than merely read.
Watch an agent learn from its own failure
Reflexion's loop is small enough to run — using the paper's own merge_intervals boundary bug. The Actor writes code, the Evaluator runs unit tests, and the Reflector turns the failing case into a specific lesson ("touching intervals must merge — use <=") that persists in memory. Watch it fail attempt one, reflect, and pass attempt two. Then watch a memoryless retry repeat the same mistake five times. The only difference is whether the lesson is remembered.
Write the body of actor. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 5 assertions below — they start red.
- Attempt one, with no lessons, fails the touching-intervals test
- With the reflected lesson the actor passes
- The reflexion loop succeeds on attempt two
- A memoryless retry never succeeds
- The reflection targets the real boundary bug
Questions people ask about Reflexion
How is Reflexion different from ReAct?
ReAct works inside a single attempt: the agent alternates thoughts, actions and observations until it finishes. Reflexion works across attempts. It wraps an agent, often ReAct itself, with an evaluator that judges each finished trial and a self-reflection model that writes a short diagnosis of a failure into memory for the next trial. In the paper's ALFWorld runs, ReAct alone stopped improving after six or seven trials, while ReAct plus Reflexion went on to solve 130 of 134 tasks within 12 trials. Neither method updates the model's weights. ReAct changes what the agent does within a trial; Reflexion changes what it knows at the start of the next one.
How did Reflexion reach 91 percent on HumanEval?
By letting GPT-4 test and critique its own code before submitting. For each problem the agent wrote candidate unit tests with chain-of-thought prompting, kept only the syntactically valid ones and sampled up to six. It wrote a solution, ran its own tests, and on any failure wrote a reflection on what went wrong, held in a one-entry memory for the next attempt. Only the final program was scored on HumanEval's hidden tests, so the result counts as pass@1: 91.0 percent against 80.1 for GPT-4 alone and 65.8 for CodeT with GPT-3.5, the best earlier method the authors list. The self-tests on HumanEval were reliable, with only 1.4 percent of passing submissions actually wrong.
Why did Reflexion score lower than GPT-4 alone on MBPP?
Because its own tests misled it. Reflexion stops as soon as a solution passes the tests it wrote, so a weak test suite that passes wrong code ends the loop early and submits the mistake without any reflection. On MBPP Python, 16.3 percent of submissions that passed the agent's internal tests failed the real ones, against 1.4 percent on HumanEval Python. The result was a drop from 80.1 to 77.1 percent pass@1, while HumanEval rose from 80.1 to 91.0. The authors note that a false negative does less harm, since a reflection can conclude that a failing test, not the code, is the thing that is wrong.
What does verbal reinforcement learning mean?
It is the paper's name for improving an agent's policy with words instead of gradient updates. In reinforcement learning the policy changes by adjusting parameters toward higher reward. In Reflexion the policy is a frozen language model plus a memory, and learning means adding a sentence to that memory: after a failure, a reflection model turns the sparse reward, often just pass or fail, into an explanation of which step went wrong and what to try instead. That text is placed in the context of the next attempt. The authors frame it as policy optimization carried out in natural language, which also means it can settle into local minima like any optimizer.
How many reflections does Reflexion keep in memory?
Very few. The episodic memory is a sliding window capped at a maximum number of stored experiences, usually one to three, so the prompt stays within the model's context limit. The ALFWorld and HotpotQA agents kept their last three reflections; the programming agent kept one. Older lessons are simply dropped, which is why the paper lists the bounded memory as a limitation and suggests future versions use vector databases or SQL stores. The small cap is also why reflections have to be specific: a few sentences of advice are all the agent carries from one attempt to the next.
Does Reflexion work with smaller open models?
Not in the paper's test. Run with starchat-beta, an open code model, Reflexion left HumanEval Python pass@1 unchanged at 0.26 across eight trials, and the authors conclude that writing useful self-corrections is an emergent ability of stronger, larger models. The method also failed on WebShop with a capable model: after four trials across 100 shopping requests there was no sign of improvement and the reflections were unhelpful, which the authors attribute to tasks that need very diverse exploration and precise search queries. Reflexion amplifies an agent that can already diagnose its own mistakes; it does not create that ability.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
On the 50 hardest HumanEval Rust problems, dropping the self-written tests took Reflexion from 0.68 to 0.52, below the 0.60 baseline. Why would reflection without tests be worse than no reflection at all?
Show answer
Without tests the agent cannot tell when its code is already correct, so it cannot stop early. It runs every trial and keeps reflecting and editing, which damages implementations that were right. Dropping reflection but keeping the tests scored 0.60: errors were caught, but the fixes did not follow from them.
Reflexion's self-tests had a false-positive rate of 16.3 percent on MBPP Python and 1.4 percent on HumanEval Python. Which benchmark should Reflexion help more, and through what mechanism?
Show answer
HumanEval. A false positive means wrong code passes the agent's tests, so the loop ends with no reflection and submits it. MBPP's unreliable tests let many wrong solutions out early, and Reflexion fell from 80.1 to 77.1 there while HumanEval rose from 80.1 to 91.0.
An ALFWorld agent repeats the same action and sees the same response four times. Under the paper's heuristic, what happens next in a Reflexion run, and what does the baseline do instead?
Show answer
Four repeats exceed the limit of three, so the evaluator flags a failure. Reflexion writes a reflection, keeps it in its last-three memory, resets the environment and starts a new trial with the lesson in context. The baseline skips the reflection: it resets and retries with nothing learned.
Why are Reflexion's HumanEval scores pass@1 even though the agent attempts each problem several times?
Show answer
Every intermediate attempt is checked against tests the agent wrote, never against the benchmark's hidden tests. Only the final submission is graded, once, so one solution per problem is scored. A method that debugs against the ground-truth tests would not qualify as pass@1.
Agents that act
Give the model a tool, then a loop, then a memory, then a world. Ends on the 2026 paper measuring how badly the whole stack degrades over many turns.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- MemGPTAn operating system for LLM memory. Context window as RAM, external storage as disk, and the model as its own memory manager — paging facts in and out with function calls, revising core memories when facts change, and summarizing under memory pressure. The architecture behind modern agent memory (and Letta).Read →
- VoyagerThe Minecraft agent that never stops learning. An automatic curriculum picks the next just-hard-enough goal, the agent writes code to achieve it, debugs against environment feedback, and saves every verified program to a compounding skill library. 3.3× more items, 15.3× faster tech tree — and the blueprint for agents that build their own tools.Read →
- Generative AgentsThe Smallville paper: 25 LLM characters living in a simulated town. A memory stream retrieved by recency × importance × relevance, reflection trees that turn events into beliefs, and plans that bend to interruptions — producing a Valentine's party that organized itself. The memory architecture behind modern persistent agents.Read →
- LLMs Get Lost in Multi-Turn ConversationThe ICLR 2026 Outstanding Paper that measured a failure everyone had felt: give a top model a fully-specified task in ONE prompt (concat) and it shines; split the IDENTICAL requirements across several turns (sharded) and 15 leading LLMs fall apart — ~39% average drop. The decomposition is the punchline: APTITUDE (best-case ability) barely moves, but RELIABILITY craters — the spread between a model's best and worst runs roughly DOUBLES. The mechanism is premature commitment: handed partial info, the model guesses a full answer early, locks it in, and when a later turn contradicts it "gets lost and does not recover." A small decay model captures the shape — concat R=p (flat), sharded R=p·(1−q)^(turns−1) (geometric decay), so longer chats get less reliable and the whole loss lives in a reliability term while the ceiling p is untouched. Fixes: front-load the spec, or consolidate/recap a long chat back into one fresh full-spec message. Worked math plus runnable code.Read →
- MuZeroPlanning without knowing the rules. MuZero learns its own model — representation, dynamics, and prediction networks — and runs tree search entirely in a learned latent space, so it works where no simulator exists (like Atari). The three networks, the value-equivalence idea (a model trained to be useful for planning, not to reconstruct observations), and the n-step return — worked math plus runnable code.Read →
- AlphaFold 2The system that solved the 50-year protein-folding problem — by reading evolution. Residues that touch in a folded protein mutate together across related sequences, so covarying columns of a multiple-sequence alignment reveal 3D contacts; the Evoformer refines them with attention and a structure module predicts coordinates. The coevolution insight, the Evoformer, and pLDDT confidence — worked math plus runnable code.Read →