AI Wiki中文/EN

Agent reflection: learning from failure needs a signal you can trust

智能体反思

Model Reflexion-style trial, evaluation and verbal lessons with a bounded memory, then compare oracle feedback, noisy self-generated tests and uninformative self-critique on synthetic tasks.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Retrying is easy; knowing what to change is the hard part

An agent writes a function, runs it, and a test fails. On the next attempt it should not make the same mistake. Humans do this by writing themselves a note: “I assumed the list was sorted; it is not.” Agent reflection is the same idea for language-model agents: after an attempt, the agent turns the outcome into a short natural-language lesson, stores it, and conditions the next attempt on the stored lessons. No weights change; what changes is the text in the prompt.

Reflexion, introduced in 2023, made this loop explicit with three components, an Actor, an Evaluator and a Self-Reflection model, plus a small episodic memory of reflections. Section 3 Its reported gains are large on tasks where feedback is grounded: the agent can execute code against tests, or the environment reports success. Later in 2023 (arXiv, October; published at ICLR 2024), Huang and colleagues asked what happens when that grounding is removed. On reasoning benchmarks, letting a model critique and revise its own answer without any external signal did not improve accuracy and often lowered it. Abstract and Section 3

The two results are consistent once you ask the question this article is built around: where does the information that a revision needs come from? Reflection can turn a weak signal (pass or fail) into a more useful one (which assumption was wrong). It cannot create the signal. Self-consistency and chain-of-thought prompting have their own entries; here the subject is the loop across attempts and the evaluator that drives it.

The loop, its memory and its accounting

Reflexion’s Actor is a language model prompted to produce actions or text; the authors use chain-of-thought and ReAct actors. The Evaluator scores a trajectory: exact match for reasoning tasks, hand-written heuristics for decision making, or another language model. The Self-Reflection model receives the trajectory, its reward and the current memory, and writes a verbal lesson. Section 3, pages 3–4 Writing τt\tau_t for the trajectory of trial tt and Ω\Omega for the memory bound, the loop in their Algorithm 1 is:

τt∼π(⋅∣x, memt),rt=Me(τt),srt=Msr(τt,rt,memt),memt+1=last⁡Ω(memt⊕srt).\tau_t\sim\pi\bigl(\cdot\mid x,\ \text{mem}_t\bigr),\quad r_t=M_e(\tau_t),\quad sr_t=M_{sr}(\tau_t,r_t,\text{mem}_t),\quad \text{mem}_{t+1}=\operatorname{last}_{\Omega}\bigl(\text{mem}_t\oplus sr_t\bigr).

The trajectory is short-term memory; the stored reflections are long-term memory. In practice the paper bounds memory to Ω\Omega experiences, usually 1 to 3, to stay within the context limit, and the loop stops when the evaluator judges the attempt correct or a trial limit is reached. Section 3, page 5

Reflection changes the next attempt only if the evaluator’s verdict is informative. Two quantities make this precise. First, for any revision procedure, final accuracy is initial accuracy plus fixes minus breakages:

Acc⁡after=Acc⁡before+P(wrong→right)−P(right→wrong).\operatorname{Acc}_{\text{after}}=\operatorname{Acc}_{\text{before}}+P(\text{wrong}\to\text{right})-P(\text{right}\to\text{wrong}).

A revision procedure helps only if it fixes more answers than it breaks. Huang et al. report exactly this breakdown: on GSM8K, GPT-3.5 kept its initial answer 74.7% of the time after two rounds of intrinsic self-correction, and among changed answers it was more likely to turn a correct answer into an incorrect one than the reverse. Section 3.3, page 4

Second, when the evaluator is a set of tests the agent wrote itself, a pass can be wrong. The relevant error rate is conditional on passing, which by Bayes’ rule depends on how often wrong answers pass and how common they are:

P(wrong∣pass)=P(pass∣wrong) P(wrong)P(pass).P(\text{wrong}\mid\text{pass})=\frac{P(\text{pass}\mid\text{wrong})\,P(\text{wrong})}{P(\text{pass})}.

Reflexion’s programming results show why this matters. The agent generates up to six unit tests with chain-of-thought prompting, filters them for valid syntax, and keeps one experience in memory. Section 4.3, page 7 On HumanEval Python it reports 91.0% pass@1 against 80.1% for GPT-4 alone; on MBPP Python it reports 77.1%, below GPT-4’s 80.1%. Table 1, page 7 The paper attributes the gap to false positives: the probability that a submission fails given that all internal tests pass is 16.3% on MBPP Python and 1.4% on HumanEval Python. Section 4.3 analysis, page 8 Its ablation on the 50 hardest HumanEval problems translated to Rust is also informative: base 0.60, self-reflection without test generation 0.52, test generation without self-reflection 0.60, both 0.68. Table 3, page 8 Without tests, the agent could not tell whether its current code was correct and kept making harmful edits.

Huang et al. separate two evaluation regimes. With oracle labels, the loop stops as soon as the answer is correct, which requires the ground truth; with intrinsic self-correction, the model decides on its own whether to keep or change its answer. Their summary table lists Reflexion among methods whose reasoning evaluation used oracle labels. Table 1, page 3 With oracle stopping, GPT-3.5 rose from 75.9 to 84.3 on GSM8K, from 75.8 to 89.7 on CommonSenseQA and from 26.0 to 29.0 on HotpotQA. Intrinsically, after two rounds (five model calls), it fell to 74.7, 41.8 and 25.0; GPT-4 fell from 95.5 to 89.0 on GSM8K and from 49.0 to 43.0 on HotpotQA. Tables 2–3, page 4 The authors’ point is not that feedback is useless but that oracle-stopped numbers measure an oracle’s performance, not the model’s ability to judge itself.

The two papers therefore agree on the mechanism. Reflexion’s strongest results come with grounded evaluators: an environment that reports completion, a heuristic that detects loops (repeating an action with the same observation more than three times, or exceeding 30 actions), or code execution. On 134 ALFWorld environments, ReAct with Reflexion and this heuristic completed 130. Section 4.1, page 5

A synthetic reflection loop with three evaluators

The program below simulates the loop on 1,000 synthetic “write a function” tasks, without any language model. Each task has six candidate programs, described only by their outputs on eight hidden inputs; exactly one candidate matches the reference on all eight. Wrong candidates agree with the reference on each input with probability 0.65 and differ on at least one input. A scripted Actor tries candidates in a task-specific prior order in which the correct candidate is three times as likely as each other candidate to be drawn early; its first attempt is correct on 37.1% of tasks.

A reflection is stored as a lesson “on input j, the output should be y”, taken from the first failing test. The Actor’s next choice is the highest-ranked candidate that has not already failed (within the memory window) and agrees with every stored lesson. Window 0 means no memory: the Actor retries a random different candidate. Each run allows at most five trials and submits the last candidate tried. The three evaluators are:

  • oracle: run all eight hidden inputs, the analogue of oracle-label stopping. Its scores cannot be reported as pass@1, because the evaluator consults the hidden tests;
  • self-tests: three test inputs chosen per task, each with its expected output corrupted with probability 0.2, the analogue of model-written tests;
  • intrinsic: no tests at all; a scripted critic doubts the current answer with probability 0.5 regardless of whether it is correct, the extreme case of a critic with no information.
"""Original synthetic reflection study. No language model or network is called.

Each task has six candidate programs, exactly one correct on eight hidden inputs.
A scripted actor picks candidates in prior order; reflections are stored lessons
of the form (input, expected output) that rule out inconsistent candidates.
"""
import random

CANDIDATES, INPUTS, TRIALS = 6, 8, 5


def make_task(rng):
    gold = [rng.randrange(10) for _ in range(INPUTS)]
    outputs = []
    for _ in range(CANDIDATES - 1):
        row = [g if rng.random() < 0.65 else (g + rng.randrange(1, 10)) % 10 for g in gold]
        if row == gold:
            j = rng.randrange(INPUTS)
            row[j] = (row[j] + 1) % 10
        outputs.append(row)
    correct = rng.randrange(CANDIDATES)
    outputs.insert(correct, gold)
    weights = [3.0 if c == correct else 1.0 for c in range(CANDIDATES)]
    prior = []
    pool = list(range(CANDIDATES))
    while pool:
        pick = rng.choices(pool, [weights[c] for c in pool])[0]
        prior.append(pick)
        pool.remove(pick)
    return dict(gold=gold, outputs=outputs, correct=correct, prior=prior)


def self_tests(task, rng, n=3, wrong_rate=0.2):
    tests = []
    for j in rng.sample(range(INPUTS), n):
        y = task['gold'][j]
        if rng.random() < wrong_rate:
            y = (y + rng.randrange(1, 10)) % 10
        tests.append((j, y))
    return tests


def first_failure(task, cand, tests):
    for j, y in tests:
        if task['outputs'][cand][j] != y:
            return (j, y)
    return None


def run(task, rng, evaluator, window, tests=None):
    """Return (submitted candidate, trials used)."""
    memory, cand = [], task['prior'][0]
    for t in range(1, TRIALS + 1):
        if evaluator == 'oracle':
            lesson = first_failure(task, cand, [(j, task['gold'][j]) for j in range(INPUTS)])
        elif evaluator == 'self-tests':
            lesson = first_failure(task, cand, tests)
        else:
            lesson = ('doubt',) if rng.random() < 0.5 else None
        if lesson is None or t == TRIALS:
            return cand, t
        if window == 0:
            cand = rng.choice([c for c in range(CANDIDATES) if c != cand])
            continue
        memory = (memory + [(cand, lesson)])[-window:]
        banned = {c for c, _ in memory}
        allowed = [c for c in task['prior'] if c not in banned and
                   all(len(les) == 1 or task['outputs'][c][les[0]] == les[1] for _, les in memory)]
        cand = allowed[0] if allowed else task['prior'][0]
    return cand, TRIALS


def main(seed=0, n=1000):
    rng = random.Random(seed)
    tasks = [make_task(rng) for _ in range(n)]
    suites = [self_tests(task, rng) for task in tasks]
    first = sum(t['prior'][0] == t['correct'] for t in tasks)
    print('tasks', n, 'candidates', CANDIDATES, 'hidden_inputs', INPUTS, 'max_trials', TRIALS, 'seed', seed)
    print('first_attempt_accuracy %.3f' % (first / n))
    rows = [('oracle', 0), ('oracle', 1), ('oracle', 3), ('self-tests', 0), ('self-tests', 1),
            ('self-tests', 3), ('intrinsic', 3)]
    for evaluator, window in rows:
        r = random.Random(seed + 1)
        right = trials = fp = wrong_to_right = right_to_wrong = 0
        for task, tests in zip(tasks, suites):
            cand, used = run(task, r, evaluator, window, tests)
            ok = cand == task['correct']
            first_ok = task['prior'][0] == task['correct']
            right += ok
            trials += used
            wrong_to_right += ok and not first_ok
            right_to_wrong += first_ok and not ok
            if evaluator == 'self-tests' and first_failure(task, cand, tests) is None and not ok:
                fp += 1
        print('%-10s window=%d accuracy %.3f mean_trials %.2f wrong->right %3d right->wrong %3d false_pass %3d'
              % (evaluator, window, right / n, trials / n, wrong_to_right, right_to_wrong, fp))
    passing = [first_failure(t, t['prior'][0], s) is None for t, s in zip(tasks, suites)]
    bad_pass = sum(p and t['prior'][0] != t['correct'] for p, t in zip(passing, tasks))
    print('first attempt: self-tests pass %d, of which hidden-wrong %d (P(wrong | pass) = %.3f)'
          % (sum(passing), bad_pass, bad_pass / sum(passing)))


if __name__ == '__main__':
    main()

The recorded output is:

tasks 1000 candidates 6 hidden_inputs 8 max_trials 5 seed 0
first_attempt_accuracy 0.371
oracle     window=0 accuracy 0.704 mean_trials 2.89 wrong->right 333 right->wrong   0 false_pass   0
oracle     window=1 accuracy 0.759 mean_trials 2.39 wrong->right 388 right->wrong   0 false_pass   0
oracle     window=3 accuracy 0.992 mean_trials 2.00 wrong->right 621 right->wrong   0 false_pass   0
self-tests window=0 accuracy 0.368 mean_trials 3.52 wrong->right 156 right->wrong 159 false_pass 184
self-tests window=1 accuracy 0.506 mean_trials 3.33 wrong->right 143 right->wrong   8 false_pass 146
self-tests window=3 accuracy 0.544 mean_trials 3.23 wrong->right 180 right->wrong   7 false_pass 158
intrinsic  window=3 accuracy 0.306 mean_trials 1.90 wrong->right  89 right->wrong 154 false_pass   0
first attempt: self-tests pass 274, of which hidden-wrong 91 (P(wrong | pass) = 0.332)

Oracle feedback. With the hidden tests as evaluator, blind retrying already lifts accuracy from 0.371 to 0.704 within five trials, because the loop never abandons a correct answer (right→wrong is 0) and keeps drawing until it finds one. Lessons make the search efficient: with a three-lesson window, accuracy reaches 0.992 in 2.00 trials on average, since every lesson rules out all candidates that disagree on that input. A one-lesson window reaches only 0.759: forgetting the earlier lesson lets the Actor return to candidates that failed before. This is the shape of the gains reported with grounded or oracle evaluators, and it is also why such numbers overstate what an agent can do when the ground truth is unavailable.

Noisy self-tests. Without memory, retrying under self-tests gains nothing: 156 fixes are cancelled by 159 breakages, which happen when a corrupted test fails a correct program and the Actor moves away. Stored lessons help (0.506 with one lesson, 0.544 with three), but 146 to 184 submissions are wrong even though they pass the agent’s own tests. On the first attempt, 274 tasks pass their self-tests and 91 of those are wrong, so the conditional false-pass rate is 91/274 = 0.332, the quantity in the Bayes equation above.

Uninformative self-critique. When the critic’s doubts carry no information, revision is a random walk away from the initial answer. It fixes 89 answers and breaks 154, so accuracy falls from 0.371 to 0.306, matching the accounting identity: 0.371 + (89 − 154)/1000 = 0.306. The direction of this result resembles Huang et al.’s intrinsic findings, but the size is an artifact of the chosen doubt probability and candidate structure, not an estimate for any model.

Each trial costs one Actor call and one evaluator call in a real system, plus one reflection call after each failure; mean_trials therefore approximates cost. In the toy, three-lesson memory is both the most accurate and the cheapest oracle setting, because good lessons shorten the search.

Where the toy and the papers stop

Lessons in the program are exact input-output facts, and the Actor applies them perfectly. A real self-reflection is free text that may misdiagnose the cause (“the loop bound is wrong” when the parsing is wrong), may be too vague to act on, or may be ignored. The program measures what happens when the evaluator’s signal is good, noisy or empty, assuming perfect use of that signal; it does not measure reflection quality.

The candidate space is small and fixed. Real agents generate new candidates, so a lesson can steer generation rather than merely filter. The 0.65 agreement rate, the three-to-one prior weight for the correct candidate, the 0.2 corruption rate and the 0.5 doubt rate are arbitrary teaching settings chosen to make the three regimes visible. None of them was fitted to either paper, so any numerical resemblance between the toy’s rates and the papers’ figures is coincidence.

Reflexion’s authors note that verbal policy optimization can settle in local minima, that the sliding-window memory is a simplification, and that test-driven evaluation is hard for nondeterministic, impure or concurrent functions. They also recommend isolated execution environments, since generated code runs before it is validated. Sections 5 and 8, page 9 Huang et al. state their conclusion for intrinsic self-correction on reasoning tasks, without external feedback; it is not a finding about feedback from tools, code execution or people. Abstract

Results from both papers are tied to the 2023 model versions, prompts, sample sizes and benchmarks they describe. HotpotQA results in both use 100 questions, for example, so a few questions change the percentage noticeably.

Exercises

  1. In Reflexion, what does the Self-Reflection model add that the Evaluator’s scalar reward does not?

    Answer: The Evaluator gives a score, often just success or failure. The Self-Reflection model converts the trajectory and that score into a specific statement of what went wrong and what to do differently, for example a note that an earlier step assumed an item was in hand when it was not (the paper describes this as a common ALFWorld failure), and that statement is stored and placed in the next attempt’s context. It adds a hypothesis about the cause, not new evidence about correctness.

  2. On the first attempt in the program, 274 tasks pass their three self-tests and 91 of those are wrong on the hidden tests. Compute P(wrong | pass). If self-tests were perfect, what would it be, and what would that imply for submitting on pass?

    Answer: 91/274 ≈ 0.332. With perfect tests that covered every input on which some wrong candidate differs, a wrong candidate could never pass, so P(wrong | pass) would be 0 and stopping on pass would be safe. With three tests out of eight inputs, even correct expected outputs could let a wrong candidate pass, because it may agree on those three inputs.

  3. With oracle feedback, a three-lesson memory reaches 0.992 but a one-lesson memory only 0.759. Explain the difference, and say whether a larger window always helps.

    Answer: With one lesson, the Actor forgets which candidates failed earlier and what outputs were required, so it can return to a candidate it already rejected and waste trials; within five trials it runs out more often. Three lessons rule out more candidates at once. A larger window is not always better: in a real model, more stored reflections consume context and can carry wrong lessons forward. In the self-tests rows, lessons derived from corrupted tests can even exclude the correct candidate.

  4. You are deciding whether to add a reflect-and-retry loop to two systems: (a) an agent that writes SQL queries for a test database where expected result rows are known for a set of example questions; (b) an agent that answers open-domain factual questions with no retrieval and no checker. Which one benefits, and what would you measure?

    Answer: (a) has a grounded evaluator: running the query and comparing rows gives informative feedback, so reflection can help; measure final accuracy on held-out questions whose expected rows the loop does not see, plus the false-pass rate on the example checks. (b) has no external signal; the loop would be intrinsic self-correction, which Huang et al. found does not improve reasoning accuracy and often lowers it. Measure fixes and breakages separately before deploying, and prefer adding a real signal such as retrieval or a checker.

How to read reflection results

Reflexion shows that verbal lessons stored in a small episodic memory can raise success when the evaluator is grounded, and its own analysis identifies false-positive tests as the limiting factor in code generation. Section 4.3 Huang et al. show that when the stopping decision and the critique both come from the model, reasoning accuracy does not improve; their summary table also flags an unfair comparison with self-consistency in another method’s evaluation, and their results table lists the number of model calls beside each accuracy. Tables 1 and 3

When reading a claim that an agent “learns from its mistakes”, ask four questions: who decides that an attempt failed; does that decision use information unavailable at deployment, such as hidden tests or labels; how many model calls were spent compared with a baseline such as sampling several answers and voting; and how many correct answers were broken along the way. Related entries cover the actor loops reflection is built on (ReAct agents), memory design (agent memory), and alternatives that spend the same compute differently (self-consistency, tree of thoughts).

Make a prediction, then check

A reflection loop stops as soon as the answer is correct, judged against the ground-truth label. What does its result show?

Choose one answer

Learning objectives

  • Describe Reflexion's actor, evaluator, self-reflection and bounded-memory loop, and explain that reflection can only amplify signal the evaluator already provides.
  • Use fix/break accounting and the conditional false-pass rate to distinguish oracle stopping, noisy self-generated tests and intrinsic self-correction.

Prerequisites & connections

Explore related knowledge →

References

  1. Reflexion: Language Agents with Verbal Reinforcement Learning — scoped arXiv v4
    Noah Shinn; Federico Cassano; Edward Berman; Ashwin Gopinath; Karthik Narasimhan; Shunyu Yao · 2023
  2. Large Language Models Cannot Self-Correct Reasoning Yet — scoped arXiv v2 (ICLR 2024)
    Jie Huang; Xinyun Chen; Swaroop Mishra; Huaixiu Steven Zheng; Adams Wei Yu; Xinying Song; Denny Zhou · 2024

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Claude · 2026-12-02 · Independent AI check (Claude subagent, not the author; not a human or expert review). Ran example.py with python3 3.12 and diffed it against example.stdout.txt (identical); confirmed the python block is byte-identical in en.mdx and zh.mdx and the three display equations match. Re-derived the accounting identity for every row (e.g. 0.371 + 0.621 = 0.992; 0.371 + 0.156 - 0.159 = 0.368; 0.371 + 0.089 - 0.154 = 0.306), P(wrong | pass) = 91/274 = 0.332 and the exercise answers. Downloaded Reflexion arXiv v4 (19 pages) and Huang et al. arXiv v2 (17 pages) with curl and read pdftotext output of Reflexion pp. 4-5 and 7-9 (Actor/Evaluator/Self-Reflection, Omega usually 1-3, 134 ALFWorld environments and 130/134, >3 repeats or >30 actions, last 3 reflections, up to 6 tests and memory 1, Table 1 91.0/80.1 and 77.1/80.1, Table 2, page-8 prose with 82%/80% baselines and 16.3%/1.4% false positives, Table 3 0.60/0.52/0.60/0.68, Sections 5 and 8) and Huang pp. 1, 3-4 (abstract, Table 1, setup with HotpotQA 100 questions and two rounds, Tables 2-3, Section 3.3 74.7%). Confirmed the article cites only Table 1 values and the false-positive rates, not the inconsistent 82% prose baseline. Compared zh and en section by section and checked data.json IDs. Did not read Reflexion's Figure 1 or appendices, Huang Sections 4-5, and did not render the MDX.

  • Code output matches the recording; code blocks are byte-identical; every row satisfies the initial + fixes - breakages identity; 91/274 = 0.332 recomputed.
  • Reflexion's page-8 prose gives an 82% baseline while Table 2 shows 0.80; the article cites only Table 1 (91.0/80.1, 77.1/80.1) and the 16.3%/1.4% false-positive rates, never the 82%.
  • Reflexion's 130/134, Omega usually 1-3, six tests and Table 3 ablation, and Huang's Tables 1-3 values and 74.7%, all match the PDFs.
  • All scripted rates are labelled arbitrary teaching settings, with any resemblance to paper figures stated as coincidence; zh and en correspond; IDs exist; quiz answer is correct.

Source locations checked:

  • Reflexion: Language Agents with Verbal Reinforcement Learning — scoped arXiv v4 · arXiv v4 PDF pages 3–5 (Section 3, Algorithm 1, memory bound Ω usually 1–3; Section 4.1 ALFWorld 134 environments, 130/134, loop heuristic >3 repeats or >30 actions, last 3 reflections) and pages 7–9 (Section 4.2 analysis 8% over episodic memory on 100 HotPotQA questions; Section 4.3 up to 6 tests, memory 1; Table 1 HumanEval PY 91.0 vs 80.1, MBPP PY 77.1 vs 80.1; Table 2 and false-positive rates 16.3% vs 1.4%; Table 3 Rust ablation 0.60/0.52/0.60/0.68; Sections 5, 8). Discrepancy: page 8 prose 82% baseline vs Table 2 0.80; not used. Figure 1 garbled; appendix unread.
  • Large Language Models Cannot Self-Correct Reasoning Yet — scoped arXiv v2 (ICLR 2024) · arXiv v2 PDF page 1 (abstract), page 3 (Table 1 issues list including Reflexion oracle labels; setup with GPT-3.5/GPT-4 on GSM8K 1,319, CommonSenseQA 1,221, HotpotQA 100; three-step prompt; max two rounds), page 4 (Table 2 oracle: GPT-3.5 75.9→84.3, 75.8→89.7, 26.0→29.0; Table 3 intrinsic with 1/3/5 calls: GPT-3.5 74.7, 41.8, 25.0 after round 2; GPT-4 95.5→89.0, 49.0→43.0; Section 3.3 74.7% retained). Sections 4–5 and appendices not read.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.