15 / 27 · Memory, Planning and Reflection
Reflection and self-correction
When a language-model agent can fix its own mistakes: Self-Refine and Reflexion, why critique without an external signal often fails, why tests, tools and verifiers work, the arithmetic of best-of-n with an imperfect verifier, and the pitfalls of a model as judge.
Chain of thought and reasoning · ReAct and the agent loop · LLM evaluation
On this page 7
The previous note found that a model’s plans become reliable when something other than the model checks them: a plan validator that names the failed precondition, a goal test, a unit test. The same question arises for any output of an agent, a program, an answer, a sequence of web actions. Can the agent look at what it did, notice the mistake and fix it? Sometimes, and the conditions are sharper than the enthusiasm around “reflection” suggests. This note describes the two best-known methods, Self-Refine and Reflexion; the evidence that self-correction without an external signal often makes answers worse; why tests, tools and verifiers work instead; how much a verifier of known error rates adds when the agent samples many attempts and keeps one that passes; and what changes when the verifier is itself a language model.
Notation. A single attempt is correct with probability . A verifier accepts a correct attempt with probability , its true-positive rate, and a wrong attempt with probability , its false-positive rate. From independent attempts the agent returns the first accepted one, or the first attempt if none is accepted. is the probability that the returned attempt is correct. In Reflexion, a trial produces a trajectory and a score , and the model writes a reflection into a memory of at most reflections.
Baseline: one attempt, or “think again”#
The agent of the earlier notes submits its first result. The cheapest form of self-correction asks the same model to look again: “Review your answer. If you find a problem, fix it.” This costs one or two more calls and needs no infrastructure, which is why it is everywhere. Whether it helps depends entirely on whether the second look contains information the first did not. Rereading one’s own work with the same knowledge and the same blind spots adds little; running the code adds a lot.
Self-Refine: feedback and refinement by the same model#
Self-Refine (Madaan et al., 2023) uses one model in three roles. It generates an output, writes feedback on that output (“the response does not mention the user’s budget”), and writes a refined output conditioned on the feedback; the loop repeats until the feedback says to stop or a limit is reached (four iterations in the paper). There is no training, no reward and no external tool.
The results split by task. With GPT-4 as the model (2023), preference-judged tasks improved a lot: in dialogue response generation the share of outputs preferred over the base output went from 25.4% to 74.6%, and in constrained generation (a sentence containing up to 30 given concepts) coverage went from 15.0% to 45.0%. On math word problems, with an exact answer to compare against, the solve rate went from 92.9% to 93.1%. Two readings of this split are both correct. Where quality has many dimensions and a first draft visibly misses some (a concept left out, an unanswered part of the question), a second pass that looks for omissions finds them. Where the answer is right or wrong and the error is a single slip in a chain that looks consistent, the model rarely sees it; the paper itself attributes the small gain in math to the model’s inability to tell whether there is an error. And on the preference tasks, the judge of “better” was partly GPT-4 again, which is the evaluation problem discussed at the end of this note.
Reflexion: verbal reinforcement in an episodic memory#
Reflexion (Shinn et al., 2023) puts self-correction across trials of the same task, with a signal from outside:
One trial of Reflexion
- Act. The actor, a language model in a ReAct-style loop, attempts the task and produces a trajectory .
- Evaluate. An evaluator scores the trial with : success or failure from the environment in a household simulator, exact match of the answer in question answering, the results of unit tests in programming.
- Reflect. A self-reflection model reads and writes a short lesson in natural language: “I searched for the actor’s name, but the question asked for the director; search for the film first.”
- Remember. The lesson is appended to an episodic memory, bounded to the last lessons ( was 1 to 3 in the paper) to fit the context.
- Retry. The next trial’s actor reads the memory, together with the task, before it acts.
The paper calls this verbal reinforcement learning. In reinforcement learning proper, a scalar reward is turned into a change of the policy’s weights. Here the policy’s weights never change; the reward is turned into text, and the text conditions the policy in the next trial, a memory of the kind described in Context and memory. The lesson carries more than the scalar could, since it says which step went wrong, at the cost of being only as good as the model’s diagnosis.
With GPT-3-era models in the ALFWorld household environment, ReAct with Reflexion completed 130 of 134 tasks over 12 trials, 22 points more than ReAct alone. In programming, where the evaluator ran unit tests that the model wrote itself, GPT-4 with Reflexion reached a pass@1 of 91.0% on HumanEval, against 80.1% for GPT-4 alone (2023). The informative result is the one where it failed: on MBPP, Reflexion scored 77.1% against 80.1% without it. The authors traced the difference to the self-written tests. On HumanEval, 1.4% of the programs that passed the model’s own tests were wrong; on MBPP, 16.3% were. A program that passes flawed tests is submitted as correct, and no amount of reflection recovers from a verifier that says yes to a wrong answer. That is the false-positive rate of the notation, and it sets the ceiling computed below.
When self-correction fails#
Huang et al. (2024) separated two settings that earlier papers had mixed. In self-correction with oracle labels, the loop stops as soon as the answer is correct, which can only be known with the gold answer in hand. In intrinsic self-correction, the model decides by itself whether to change its answer. With gpt-3.5-turbo-0613 and GPT-4 in August 2023, at most two rounds of “review your previous answer and find problems with it”:
| model, benchmark | first answer | after round 1 | after round 2 | with oracle stopping |
|---|---|---|---|---|
| GPT-3.5, GSM8K | 75.9 | 75.1 | 74.7 | 84.3 |
| GPT-3.5, CommonSenseQA | 75.8 | 38.1 | 41.8 | 89.7 |
| GPT-4, GSM8K | 95.5 | 91.5 | 89.0 | 97.5 |
| GPT-4, HotpotQA | 49.0 | 49.0 | 43.0 | 59.0 |
Accuracy in percent. With oracle stopping every number goes up; without it no number ends above the first answer. The oracle column measures something no deployed agent can do: it never changes a right answer, because it stops at the first right one. Looking at what the models changed, GPT-3.5 kept its answer on GSM8K 74.7% of the time, and when it did change it, it more often turned a correct answer into a wrong one than the reverse. On CommonSenseQA, where the wrong options are plausible, the request to find problems pushed it to switch away from correct answers in bulk. The same paper found that multi-agent debate, several copies of the model criticizing each other, did no better than self-consistency (majority vote over independent samples, from Chain of thought and reasoning) when both were given the same number of model calls.
Planning showed the same pattern with a sound verifier for comparison (Valmeekam, Marquez and Kambhampati, 2023). GPT-4 generated Blocksworld plans and GPT-4 verified them, sending its critique back for a new plan. Of 100 problems, the generator alone solved 40, the loop with GPT-4 as verifier 55, and the same loop with the validator VAL as verifier 88. The model-verifier’s errors were lopsided: it accepted 54 of 55 valid plans but also 38 of 45 invalid ones, a false-positive rate of 84%.
The mechanism is not mysterious. A model asked to check its answer uses the same knowledge that produced the answer; an error it could see, it would mostly not have made. Its critique is therefore correlated with its mistakes, and the prompt that asks it to find a problem biases it toward finding one whether or not it exists. Self-correction becomes reliable when the check is easier than the generation and does not share its failure modes:
- Execution. Running code, a compiler’s error, a type checker, a failing assertion. A coding agent that runs the test suite is the strongest case of self-correction in practice.
- Tools. CRITIC (Gou et al., 2024) lets the model verify claims with a search engine and code with an interpreter before revising, and attributes its gains to the external feedback.
- The environment. A web page that did not change, an API that returned an error, a game that did not advance.
- Sound validators. A plan validator, a proof checker, a schema.
- Training for it. Self-correction can be learned. SCoRe (Kumar et al., 2024) trained Gemini 1.0 Pro and 1.5 Flash with reinforcement learning on their own correction attempts and reported self-correction gains of 15.6 points on MATH and 9.1 on HumanEval over the base models. The reasoning models of Reasoning models and test-time compute backtrack inside long chains of thought for the same reason: they were rewarded for final answers checked by a verifier.
Generate and verify#
If attempts can be checked, the agent need not repair one attempt; it can make several and keep one that passes. How much this buys depends on the verifier. Each attempt has one of three outcomes, independently: correct and accepted, with probability ; wrong and accepted, ; rejected, . The agent returns the first accepted attempt, so it is correct when attempts were rejected and attempt was correct and accepted, for some , or when all were rejected and the fallback, attempt 1, is correct:
Three consequences follow. At , : one attempt is one attempt. As , and
the precision of the verifier on this distribution of attempts, the probability that an accepted attempt is correct. With a sound verifier () the ceiling is 1, and with the formula becomes , the pass@ of the evaluation note. With any the curve flattens at the precision however many attempts are made. And verification helps at all only if , which after dividing by and rearranging is
a true-positive rate above the false-positive rate. A verifier that accepts right and wrong attempts at the same rate is a coin, and the curve stays at .
Best of n attempts with an imperfect verifier
Worked example. and a verifier with , . Then , , , and the ceiling is . With four attempts, , already most of the way: by it is 0.793. A verifier with caps the agent at 0.563, and with the agent stays at 0.3. Now the GPT-4 plan verifier above, with , and the generator’s own : its ceiling is , barely above . Its sound counterpart has ceiling 1. The observed numbers (55% against 88%) came from a feedback loop rather than independent samples, so the formula does not predict them exactly, but it explains the gap: the bottleneck was the verifier, not the generator.
The measurements agree with the arithmetic. With a GPT-4-based generator on 500 MATH problems and 1,860 samples per problem, choosing by majority vote solved 69.6%, by an outcome reward model (a learned verifier of final answers) 72.4%, and by a process reward model, trained on human labels of each step, 78.2% (Lightman et al., 2023): the better verifier, the higher the plateau. With DeepSeek-Coder-V2-Instruct on SWE-bench Lite, the share of issues solved by at least one of samples, checked with the benchmark’s tests, rose from 15.9% at one sample to 56% at 250 samples (Brown et al., 2024); this coverage is the curve of a sound verifier, while majority voting and reward models on math plateaued after a few hundred samples, the curve of an imperfect one.
A model as judge#
When nothing mechanical can check an attempt, the verifier is often another language model asked to grade it, as in the LLM evaluation note. Everything above applies, with three additions.
- Its error rates are unknown until measured. A judge’s and have to be estimated on attempts with known labels, from the same distribution the agent will produce, before its acceptances mean anything. The NLP note’s experiment found a small judge whose agreement with people could not be told from zero.
- Its errors are systematic. Judges prefer the first of two answers shown (position bias), longer answers (verbosity bias) and their own style (Zheng et al., 2023); models can recognize their own outputs and rate them higher than humans do (Panickssery, Bowman and Feng, 2024). An agent whose judge is its own model inherits all three.
- Optimization finds the errors. Selecting the best of by a judge’s score, or training against it, picks out exactly the attempts the judge overrates. The effective false-positive rate rises with the pressure applied: sampling more makes the selected attempt more likely to be one that fooled the judge. This is reward hacking in miniature, the subject of Alignment and oversight of agents.
The practical rules follow from the formula: prefer a mechanical verifier; if a judge is unavoidable, measure its and on labelled data, use a different model from the generator, present pairs in both orders, and keep modest.
What changed#
| one attempt | intrinsic self-correction | correction from an external signal | generate and verify | |
|---|---|---|---|---|
| extra information | none | none | test results, errors, rewards | the verifier’s decision |
| typical effect | baseline | flat or worse on reasoning; better on omissions | large gains when the signal is sound | rises toward the verifier’s precision |
| limited by | the model | the model’s blind spots | the signal’s false positives | , the false-positive rate |
| example | a single sample | “review your answer” | Reflexion with tests, a coding agent running its suite | best-of- with unit tests |
Limitations#
- External signals are partial. Tests check what someone thought to test; a validator checks preconditions, not intent. An agent that optimizes for passing them can pass them without solving the task.
- The independence assumption is optimistic. Attempts from one model at one prompt are correlated: they share misconceptions, so samples are worth fewer than independent ones, and the formula is an upper bound on what resampling buys.
- Self-written checks are themselves generated. Reflexion’s and LATS’s internal tests have their own error rates, which differ by benchmark (1.4% against 16.3% false positives above) and are rarely reported.
- Verbal memory is not learning. Reflections help on the next trial of the same task; they do not change the model, and a long memory of lessons has the context problems of the earlier note.
- Evidence ages fast. The negative results are for 2023 models without training for self-correction; reasoning models trained with verifiable rewards correct themselves inside a chain of thought much more often. The principle, that a check must add information, has held.
What you should remember#
- Self-Refine (generate, critique, refine with one model) improves outputs whose flaws are visible omissions, and barely moves exact-answer reasoning.
- Reflexion turns an external score into a verbal lesson stored in a bounded episodic memory and read on the next trial; it is only as good as its evaluator, as its self-written tests showed.
- Without external feedback, asking a model to correct itself often lowers accuracy; studies that stop on the gold answer measure an oracle, not self-correction.
- Feedback that works comes from outside the model: execution, tools, the environment, sound validators, or training that rewards correct final answers.
- Best-of- with a verifier of true-positive rate and false-positive rate has success , which saturates at the verifier’s precision and helps only if . A model as judge is a verifier whose error rates must be measured and whose errors optimization will find.
Code#
A toy coding task (write median) with real unit tests executed on generated programs, a scripted stand-in for the model that drafts a program from three features, repairs the feature named in a failing test, or reviews its code without running it; four loops with the same budget of attempts; and the best-of- formula checked against simulation. With a real model the drafts and repairs are generated text, parsed as code and executed in a sandbox; the loops, the tests and the arithmetic stay as they are. NumPy and the standard library only; seeds are fixed, the script runs in about ten seconds, and exact numbers can differ across platforms and library versions.
import numpy as np
# 1. a toy coding task: write median(xs). A program is assembled from three features; each missing one is a bug
def render(features):
lines = ['def median(xs):']
if 'empty' in features: lines.append(' if not xs: raise ValueError("median of an empty list")')
lines.append(' s = sorted(xs)' if 'sort' in features else ' s = xs')
if 'even' in features:
lines.append(' n = len(s)')
lines.append(' return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2')
else:
lines.append(' return s[len(s) // 2]')
return '\n'.join(lines)
TESTS = [('median([3, 1, 2])', 2, 'sort'), ('median([4, 1, 3, 2])', 2.5, 'even'), ('median([])', ValueError, 'empty')]
def run_tests(code): # the external signal: execute the code on unit tests
env = {}
exec(code, env)
for expr, want, _ in TESTS:
try:
got = eval(expr, env)
if want is ValueError: return f'FAIL {expr}: expected ValueError, got {got!r}'
if got != want: return f'FAIL {expr}: expected {want!r}, got {got!r}'
except Exception as e:
if want is not ValueError or not isinstance(e, ValueError): return f'FAIL {expr}: raised {type(e).__name__}'
return 'PASS'
# 2. a scripted stand-in for the model: a noisy first draft, a fix keyed on the failing test, and a self-review
# without tests that misses bugs and sometimes "fixes" what was right
class ScriptedCoder:
def __init__(self, rng): self.rng = rng
def draft(self):
return {f for f in ('sort', 'even', 'empty') if self.rng.random() < 0.6}
def fix_from_feedback(self, features, message): # read the failure, repair what it names
culprit = next(f for expr, _, f in TESTS if expr in message)
return features | {culprit} if self.rng.random() < 0.9 else set(features)
def self_review(self, features): # no execution: judge the code by reading it
out = set(features)
for f in ('sort', 'even', 'empty'):
if f not in out and self.rng.random() < 0.2: out.add(f) # notices a missing case
elif f in out and self.rng.random() < 0.15: out.discard(f) # "corrects" a right line into a bug
return out
feats = {'sort'}
print(render(feats)); print(run_tests(render(feats)))
# def median(xs):
# s = sorted(xs)
# return s[len(s) // 2]
# FAIL median([4, 1, 3, 2]): expected 2.5, got 3
# 3. four loops with a budget of k attempts; each returns whether the program it submits passes the tests
def attempt(mode, k, rng):
coder = ScriptedCoder(rng)
feats = coder.draft()
first = feats
for _ in range(k - 1):
report = run_tests(render(feats))
if mode == 'tests': # run the tests, read the failure, fix it
if report == 'PASS': break
feats = coder.fix_from_feedback(feats, report)
elif mode == 'resample': # generate and verify: new independent drafts
if report == 'PASS': break
feats = coder.draft()
elif mode == 'self': # intrinsic: review k - 1 times without running anything
feats = coder.self_review(feats)
elif mode == 'self+oracle': # the same review, but stopped as soon as the answer is right
if report == 'PASS': break
feats = coder.self_review(feats)
if mode == 'resample' and run_tests(render(feats)) != 'PASS': feats = first
return run_tests(render(feats)) == 'PASS'
rng = np.random.default_rng(0)
for mode in ('tests', 'resample', 'self', 'self+oracle'):
print(mode, [round(float(np.mean([attempt(mode, k, rng) for _ in range(4000)])), 3) for k in (1, 2, 3, 4)])
# tests [0.215, 0.604, 0.876, 0.974] (share of submitted programs that pass, for k = 1, 2, 3, 4 attempts)
# resample [0.225, 0.394, 0.525, 0.627]
# self [0.223, 0.214, 0.194, 0.206]
# self+oracle [0.227, 0.296, 0.352, 0.412]
# 4. best-of-n with an imperfect verifier: each sample is right with probability p; the verifier accepts a right one
# with probability a and a wrong one with probability b; return the first accepted sample, else the first sample
def best_of_n(p, a, b, n):
q1, q0 = p * a, (1 - p) * b
r = 1 - q1 - q0
return q1 * (1 - r ** n) / (1 - r) + r ** (n - 1) * p * (1 - a)
def simulate(p, a, b, n, trials, rng):
right = rng.random((trials, n)) < p
accept = np.where(right, rng.random((trials, n)) < a, rng.random((trials, n)) < b)
first = np.where(accept.any(1), accept.argmax(1), 0)
return right[np.arange(trials), first].mean()
rng = np.random.default_rng(1)
p = 0.3
for a, b in ((1.0, 0.0), (0.9, 0.1), (0.9, 0.3), (0.7, 0.7)):
exact = [round(best_of_n(p, a, b, n), 3) for n in (1, 4, 16, 64)]
print(a, b, exact, round(simulate(p, a, b, 16, 200_000, rng), 3), round(p * a / (p * a + (1 - p) * b), 3))
# 1.0 0.0 [0.3, 0.76, 0.997, 1.0] 0.997 1.0 (a, b; exact for n = 1, 4, 16, 64; simulated n = 16; the ceiling)
# 0.9 0.1 [0.3, 0.652, 0.793, 0.794] 0.794 0.794
# 0.9 0.3 [0.3, 0.526, 0.562, 0.563] 0.562 0.563
# 0.7 0.7 [0.3, 0.3, 0.3, 0.3] 0.3 0.3
# 5. the ceiling for a verifier with the error rates measured for GPT-4 checking its own Blocksworld plans
a, b, p = 54 / 55, 38 / 45, 0.40
print(round(p * a / (p * a + (1 - p) * b), 3), round(best_of_n(p, a, b, 15), 3), round(best_of_n(p, 1.0, 0.0, 15), 3))
# 0.437 0.437 1.0 (ceiling; 15 samples with that verifier; 15 samples with a sound one)
The four loops reproduce the pattern of the evidence. Repairing from the failing test lifts the pass rate from 0.215 to 0.974 in four attempts. Resampling with the tests as verifier lifts it to 0.627, close to the of a sound verifier, since a first draft passes with probability . Reviewing without running anything leaves it near the first-attempt rate, because the review adds missing lines and breaks correct ones at comparable rates. The same review stopped on the hidden tests appears to reach 0.412: that is the oracle effect, produced entirely by the stopping rule.
Next#
Reflection, verification and search are patterns made of model calls and checks arranged in a fixed way. The evaluator-optimizer loop of this note, the router that sends a task to a specialist, the orchestrator that splits work among workers: each can be built as a fixed workflow or left to an agent to improvise. The next note catalogues these patterns, says when a fixed workflow beats an open-ended agent, and describes the protocols, above all the Model Context Protocol, that connect agents to their tools.
References#
- A. Madaan, N. Tandon, P. Gupta, S. Hallinan, L. Gao, S. Wiegreffe, U. Alon, N. Dziri, S. Prabhumoye, Y. Yang, S. Gupta, B. P. Majumder, K. Hermann, S. Welleck, A. Yazdanbakhsh, P. Clark. Self-Refine: iterative refinement with self-feedback. NeurIPS, 2023. Table 1.
- N. Shinn, F. Cassano, E. Berman, A. Gopinath, K. Narasimhan, S. Yao. Reflexion: language agents with verbal reinforcement learning. NeurIPS, 2023. Section 3 (memory), section 4 and tables 1–2 (programming).
- J. Huang, X. Chen, S. Mishra, H. S. Zheng, A. W. Yu, X. Song, D. Zhou. Large language models cannot self-correct reasoning yet. ICLR, 2024. Tables 2 and 3, section 3.3.
- K. Valmeekam, M. Marquez, S. Kambhampati. Can large language models really improve by self-critiquing their own plans? arXiv:2310.08118, 2023. Tables 1 and 2.
- Z. Gou, Z. Shao, Y. Gong, Y. Shen, Y. Yang, N. Duan, W. Chen. CRITIC: large language models can self-correct with tool-interactive critiquing. ICLR, 2024.
- A. Kumar, V. Zhuang, R. Agarwal, et al. Training language models to self-correct via reinforcement learning. arXiv:2409.12917, 2024.
- R. Kamoi, Y. Zhang, N. Zhang, J. Han, R. Zhang. When can LLMs actually correct their own mistakes? A critical survey of self-correction of LLMs. Transactions of the Association for Computational Linguistics, 2024.
- K. Cobbe, V. Kosaraju, M. Bavarian, M. Chen, H. Jun, L. Kaiser, M. Plappert, J. Tworek, J. Hilton, R. Nakano, C. Hesse, J. Schulman. Training verifiers to solve math word problems. arXiv:2110.14168, 2021.
- H. Lightman, V. Kosaraju, Y. Burda, H. Edwards, B. Baker, T. Lee, J. Leike, J. Schulman, I. Sutskever, K. Cobbe. Let’s verify step by step. ICLR, 2024. Best-of-1860 results.
- B. Brown, J. Juravsky, R. Ehrlich, R. Clark, Q. V. Le, C. Ré, A. Mirhoseini. Large language monkeys: scaling inference compute with repeated sampling. arXiv:2407.21787, 2024.
- L. Zheng, W.-L. Chiang, Y. Sheng, S. Zhuang, Z. Wu, Y. Zhuang, Z. Lin, Z. Li, D. Li, E. P. Xing, H. Zhang, J. E. Gonzalez, I. Stoica. Judging LLM-as-a-judge with MT-Bench and Chatbot Arena. NeurIPS Datasets and Benchmarks, 2023.
- A. Panickssery, S. R. Bowman, S. Feng. LLM evaluators recognize and favor their own generations. arXiv:2404.13076, 2024.