ReAct agents: when does a thought change the next action?
ReAct 智能体
Separate thoughts that only extend the context from actions that return observations, then trace scripted controllers through alias titles, empty searches, step budgets and stale pages.
react-agentsTwo kinds of output from one controller
Ask an assistant where the designer of a certain bridge was born. Answering from memory is fast, but the assistant may never have seen the bridge or may remember an old fact. Searching helps only if each search result is read and used: the bridge page names the designer, so the next search should be for that person, not for the bridge again. If the person’s page is missing, the plan has to change.
ReAct, short for reasoning and acting, is a prompting pattern in which a language model alternates between two kinds of output. A thought is free text that never reaches the environment; it can decompose the question, pull a fact out of the last observation or decide to reformulate. An action is a command the environment executes, and it returns an observation. The paper introduced it with a frozen large model and a handful of human-written example trajectories. Sections 2–3
This article does not run a language model. We build an offline knowledge base of fictional pages, implement search, lookup and finish actions over it, and compare scripted controllers. The scripted ReAct-style controller writes template thoughts and follows hand-coded rules; it demonstrates the protocol and its failure modes, not a model’s ability to produce useful thoughts.
Thoughts extend the context; actions extend the world’s record
Let A be the environment’s action set and L the space of language. ReAct enlarges the agent’s choices to the union, and the two kinds of choice update the context differently:
A thought adds itself to the context and nothing else: it does not change the external environment and produces no observation. Section 2 Its value lies entirely in what it makes easier to do next, which is why a policy over this enlarged space is hard to learn and why the paper relies on a large model’s language prior. Section 2
The paper reports two scheduling choices. For knowledge-heavy tasks such as multi-hop question answering, thoughts and actions alternate densely, one thought per step. For decision tasks with many actions, thoughts appear sparsely and the model decides where. Sections 2 and 3.2
The knowledge-task environment. The paper’s Wikipedia interface has three actions: search for an entity, which returns the first five sentences of its page or suggests five similar titles; lookup of a string, which returns the next sentence on the current page that contains it; and finish with an answer. The authors note that this interface is much weaker than state-of-the-art retrievers and was chosen to make the model retrieve through explicit reasoning. Section 3.1 The authors’ released environment file implements those strings: a failed search prints “Could not find” with a list of similar titles, repeated lookups report a running result index, and an exhausted lookup prints “No more results.” wikienv.py lines 98–156
One implementation detail differs from the abstract description. In that file a think action returns a fixed acknowledgement string and, like every other action, increments the environment’s step counter. wikienv.py lines 153–158 So whether thoughts count toward a step limit depends on the harness, not on the definition above. Our offline environment never sees thoughts at all; only search, lookup and finish are counted.
Budgets and back-off. A ReAct trajectory can stall, for example by repeating the same thought and action. The paper reports this repetition as a frequent ReAct-specific failure, counted as a reasoning error. Section 3.3 Its experiments cap ReAct at 7 steps for HotpotQA and 5 for FEVER and back off to self-consistent chain-of-thought when no answer arrives; conversely, they switch from chain-of-thought to ReAct when the majority answer among n samples occurs fewer than n/2 times. Section 3.2 With a fallback answer from another method, the combined rule is
What the paper measured. With PaLM-540B prompting, Table 1 reports HotpotQA exact match and FEVER accuracy of 25.7 and 58.9 for acting only, 27.4 and 60.9 for ReAct, 29.4 and 56.3 for chain-of-thought, and 35.1 and 64.6 for the best ReAct/chain-of-thought combination on each task. Table 1, page 5 ReAct therefore beat acting alone on both tasks but trailed chain-of-thought on HotpotQA. In a hand-labelled sample of 200 HotpotQA trajectories (50 correct and 50 incorrect from each of ReAct and chain-of-thought, so the failure percentages are shares of 50 failures per method), hallucination accounted for 56% of chain-of-thought failures and 0% of ReAct failures, while uninformative search made up 23% of ReAct failures and reasoning errors, including loops, 47%. Table 2, page 6 These are results for one model, prompt set and benchmark version; they are not general rates for ReAct agents.
We score our offline runs with exact match over Q questions:
Nine fictional questions, four controllers
The knowledge base has thirteen invented pages about bridges, libraries, towers and people; none describes a real place or person. Our search returns the first two sentences of a page (the paper’s interface returned five), or up to three titles sharing a word with the query. Lookup and finish follow the protocol above. Each question has a topic, an optional first relation (designer or founder) and a final relation. Question parsing is given to the controllers, which keeps the focus on the loop.
- closed_book answers from a fixed memory table, standing in for knowledge stored in model weights. Some entries are stale or wrong, and two questions have no entry.
- fixed_script is an acting-only baseline: search, try the first keyword with one lookup, carry whatever it extracted forward, and finish with the last value it holds. It never reacts to a failed observation.
- react writes a template thought before choosing each action, follows a similar-title suggestion when a search misses, tries alternative keywords after “No more results”, abstains with “unknown” when no page exists, and stops when the budget of 7 environment actions (including finish) is used up.
- react_then_memory uses the closed-book answer when react exhausts its budget, mirroring the paper’s back-off rule.
The failure cases are designed into the data: an alias title (q3), a page that says “architect was” instead of “designed by” (q2), a founder with no page (q4), a page where five lookups are needed (q6) and a page whose year disagrees with the gold label (q9).
"""Original offline ReAct-protocol demo: fictional pages, scripted policies, no language model."""
import json
import re
PAGES = {
'Marrow Bridge': ['Marrow Bridge is a footbridge in Elsk.', 'It crosses the Pell river.',
'It was designed by Ivo Prand.', 'It opened in 1931.'],
'Ivo Prand': ['Ivo Prand was a civil engineer.', 'He was born in Tavel.'],
'Corran Library': ['Corran Library is a public library in Udo.', 'It has three reading rooms.',
'Its architect was Lena Vos.'],
'Lena Vos': ['Lena Vos is an architect.', 'She has worked in Udo and Brask.', 'She was born in Merrin.'],
'Halden Observatory': ['Halden Observatory was founded by Oda Kell.', 'It stands on a hill.'],
'Oda Kell-Marsh': ['Oda Kell-Marsh was an astronomer.', 'She was born in Sorr.'],
'Tarn Mill': ['Tarn Mill was founded by Rus Edo.', 'It closed in 1970.'],
'Vell Tower': ['Vell Tower is a clock tower.', 'Its base was designed by committee.',
'Its spire was designed by several firms.', 'Its clock was designed by students.',
'Its stair was designed by hand.', 'Its roof was designed by Aster Quine.'],
'Aster Quine': ['Aster Quine was a builder.', 'Aster Quine was born in Lisk.'],
'Pell Ferry Terminal': ['Pell Ferry Terminal was designed by Ivo Prand.', 'It serves Elsk.'],
'Udo Press': ['Udo Press is a publisher.', 'It prints maps.', 'It was founded by Mira Holt.'],
'Mira Holt': ['Mira Holt was a printer.', 'She lived in Udo.', 'She trained in Brask.',
'She was born in Kesh.'],
'Brask Station': ['Brask Station is a rail station.', 'It has two platforms.', 'It opened in 1960.'],
}
KEYWORDS = {'designer': ['designed by', 'architect was', 'design was by'],
'founder': ['founded by'], 'birthplace': ['born in'], 'opened': ['opened in']}
QUESTIONS = [ # (id, topic, hop relation or None, final relation, gold answer)
('q1', 'Marrow Bridge', 'designer', 'birthplace', 'Tavel'),
('q2', 'Corran Library', 'designer', 'birthplace', 'Merrin'),
('q3', 'Halden Observatory', 'founder', 'birthplace', 'Sorr'),
('q4', 'Tarn Mill', 'founder', 'birthplace', 'unknown'),
('q5', 'Marrow Bridge', None, 'opened', '1931'),
('q6', 'Vell Tower', 'designer', 'birthplace', 'Lisk'),
('q7', 'Pell Ferry Terminal', None, 'designer', 'Ivo Prand'),
('q8', 'Udo Press', 'founder', 'birthplace', 'Kesh'),
('q9', 'Brask Station', None, 'opened', '1962'),
]
MEMORY = {'q1': 'Tavel', 'q2': 'Udo', 'q3': 'Brask', 'q4': 'Elsk', 'q5': '1929',
'q6': 'Lisk', 'q7': 'Ivo Prand', 'q9': '1962'}
BUDGET = 7
class OfflineWiki:
"""search/lookup/finish over fixed fictional pages; thoughts never reach this object."""
def __init__(self):
self.page, self.keyword, self.hits, self.cursor, self.actions = None, None, [], 0, 0
def act(self, action):
self.actions += 1
kind, arg = re.fullmatch(r'(search|lookup|finish)\[(.*)\]', action).groups()
if kind == 'search':
title = next((t for t in PAGES if t.lower() == arg.lower()), None)
if title is None:
words = set(arg.lower().split())
similar = [t for t in PAGES if words & set(t.lower().replace('-', ' ').split())][:3]
return 'Could not find %s. Similar: %s.' % (arg, similar)
self.page, self.keyword = PAGES[title], None
return ' '.join(self.page[:2])
if kind == 'lookup':
if self.page is None:
return 'No page is open.'
if arg != self.keyword:
self.keyword, self.cursor = arg, 0
self.hits = [s for s in self.page if arg.lower() in s.lower()]
if self.cursor >= len(self.hits):
return 'No more results.'
self.cursor += 1
return '(Result %d / %d) %s' % (self.cursor, len(self.hits), self.hits[self.cursor - 1])
return 'Episode finished.'
def extract(text, keywords):
for key in keywords:
match = re.search(re.escape(key) + r' ((?:[A-Z][\w-]*|\d+)(?: [A-Z][\w-]*)*)', text)
if match:
return match.group(1)
return None
class OutOfBudget(Exception):
pass
def fixed_script(question):
"""Act-only baseline: one fixed action template, no reaction to failed observations."""
_, topic, hop, final, _ = question
env, trace, entity = OfflineWiki(), [], topic
def do(action):
trace.append(('action', action))
trace.append(('observation', env.act(action)))
return trace[-1][1]
for relation in ([hop] if hop else []) + [final]:
obs = do('search[%s]' % entity)
value = extract(obs, KEYWORDS[relation][:1]) or extract(do('lookup[%s]' % KEYWORDS[relation][0]),
KEYWORDS[relation][:1])
entity = value or entity
do('finish[%s]' % entity)
return entity, trace, env.actions
def react(question):
"""Scripted ReAct-style controller: a template thought precedes each action choice."""
_, topic, hop, final, _ = question
env, trace, entity = OfflineWiki(), [], topic
def do(action):
if env.actions >= BUDGET:
raise OutOfBudget
trace.append(('action', action))
trace.append(('observation', env.act(action)))
return trace[-1][1]
def finish(answer, why):
trace.append(('thought', why))
do('finish[%s]' % answer)
return answer, trace, env.actions
try:
for relation in ([hop] if hop else []) + [final]:
trace.append(('thought', 'Need the %s of %s.' % (relation, entity)))
obs = do('search[%s]' % entity)
if obs.startswith('Could not find'):
similar = re.findall(r"'([^']+)'", obs)
if not similar:
return finish('unknown', 'No page or close title exists; abstain.')
trace.append(('thought', 'Exact title missing; try %s.' % similar[0]))
obs = do('search[%s]' % similar[0])
value = extract(obs, KEYWORDS[relation])
for key in KEYWORDS[relation]:
while value is None:
obs = do('lookup[%s]' % key)
if obs == 'No more results.':
break
value = extract(obs, [key])
if value is None:
return finish('unknown', 'The page never states the %s.' % relation)
trace.append(('thought', 'Observed %s = %s.' % (relation, value)))
entity = value
return finish(entity, 'Answer with the last observed value.')
except OutOfBudget:
trace.append(('thought', 'Budget exhausted before finish.'))
return None, trace, env.actions
def evaluate():
rows, totals = [], {'closed_book': 0, 'fixed_script': 0, 'react': 0, 'react_then_memory': 0}
for question in QUESTIONS:
qid, gold = question[0], question[-1]
closed = MEMORY.get(qid, 'unknown')
fixed, _, fixed_actions = fixed_script(question)
answer, trace, actions = react(question)
backed = answer if answer is not None else closed
answers = {'closed_book': closed, 'fixed_script': fixed, 'react': answer, 'react_then_memory': backed}
for name, value in answers.items():
totals[name] += value == gold
rows.append(dict(id=qid, gold=gold, answers=answers, fixed_actions=fixed_actions,
react_actions=actions, react_thoughts=sum(kind == 'thought' for kind, _ in trace)))
return rows, totals
if __name__ == '__main__':
rows, totals = evaluate()
_, example_trace, _ = react(QUESTIONS[2])
print(json.dumps({'synthetic': True, 'budget': BUDGET, 'questions': len(QUESTIONS), 'exact_match': totals,
'rows': rows, 'q3_trace': example_trace}, indent=1))
| Question | Gold | closed_book | fixed_script | react | react actions | react thoughts |
|---|---|---|---|---|---|---|
| q1 | Tavel | Tavel | Tavel | Tavel | 4 | 5 |
| q2 | Merrin | Udo | Corran Library | Merrin | 6 | 5 |
| q3 | Sorr | Brask | Oda Kell | Sorr | 4 | 6 |
| q4 | unknown | Elsk | Rus Edo | unknown | 3 | 4 |
| q5 | 1931 | 1929 | 1931 | 1931 | 3 | 3 |
| q6 | Lisk | Lisk | Vell Tower | none (budget) | 7 | 6 |
| q7 | Ivo Prand | Ivo Prand | Ivo Prand | Ivo Prand | 2 | 3 |
| q8 | Kesh | unknown | Kesh | Kesh | 5 | 5 |
| q9 | 1962 | 1962 | 1960 | 1960 | 3 | 3 |
Exact match out of nine is 4 for closed_book, 4 for fixed_script, 7 for react and 8 for react_then_memory. These counts follow from how the nine cases were built; they show mechanisms, not a performance estimate.
The program also prints the full q3 trajectory. After the first search the controller records that the founder is Oda Kell. Its search for that name fails and the observation suggests one similar title, Oda Kell-Marsh. A new thought adopts that title, the next search returns a page with a birthplace, and the controller finishes with Sorr in four environment actions and six thoughts. The fixed script performs the same failing search but has no rule for the suggestion, so it finishes with the name it already held.
Three other rows show where interaction itself fails. In q6 the controller needs one search, five lookups (the first four matching sentences name no person), a second search and a finish: eight actions against a budget of seven. It actually reads the birthplace in its seventh action but cannot spend an eighth on finish, so react returns nothing and only the memory fallback recovers Lisk. In q9 the page itself is stale: every retrieving controller confidently answers 1960 while the gold label, by construction, is 1962. In q4 abstaining is correct, and only react does it; closed_book invents a town and fixed_script returns the founder’s name as if it were a birthplace.
A trace is not a proof of correct reasoning
The thoughts in our controller are templates written after the rule has already decided; they explain the rule rather than cause it. In a language model, a thought is generated text that conditions later tokens, and nothing guarantees that it states the real reason for the next action. The paper argues that ReAct traces help humans inspect and correct behavior. Section 2 That is a claim about usefulness for inspection, not evidence that every trace is faithful.
The q3 success depends on an unverified identity jump: the controller assumes that a page titled Oda Kell-Marsh is about the founder named Oda Kell. In real data the nearest title can be a different person. A careful controller would look for corroborating facts, such as the observatory being mentioned on the person’s page, before accepting the suggestion.
The environment is offline, deterministic and tiny, the question parse is supplied, and keyword lists are hand-written. None of this tests whether a model would produce these actions. The paper’s own environment queries live web pages; in the file we read, search requests have no explicit timeout, and a disambiguation page triggers a recursive search. wikienv.py lines 98–122 Neither behavior is reproduced here. We did not run the authors’ code, and we did not read the evaluation wrapper that computes rewards; in the file we read, the environment’s reward is always zero.
Follow the context, count the actions
-
In the formula for the enlarged action space, what does a thought add to the context, and what does it not produce? Why can a thought still change the final answer?
Answer: A thought adds only its own text to the context; it produces no observation and does not change the environment. It changes later behavior because the next action is chosen from the longer context: a thought that extracts “the founder is Oda Kell” makes the next search target that name rather than repeating the original topic.
-
In q6, list the environment actions the react controller needs to finish correctly. What is the smallest budget that would let it answer, and what happens with the budget of 7?
Answer: search[Vell Tower]; four lookups for “designed by” that return sentences without a capitalized name; a fifth lookup that returns “designed by Aster Quine”; search[Aster Quine], whose first two sentences contain “born in Lisk”; finish[Lisk]. That is 1 + 5 + 1 + 1 = 8 actions, so the minimum budget is 8. With 7, the controller has read the birthplace after action 7 but cannot issue finish, so react returns nothing. The fallback answer from memory happens to be Lisk, giving the combined controller its eighth correct answer. Whether finish should count against the budget is a protocol choice that changes this outcome.
-
The paper switches from self-consistent chain-of-thought to ReAct when the most common answer among n samples appears fewer than n/2 times. With n = 21 samples, does a majority count of 10 trigger the switch? A count of 11?
Answer: n/2 = 10.5. A count of 10 is below 10.5, so the system switches to ReAct; 11 is not, so it keeps the chain-of-thought answer. The rule treats agreement among samples as a confidence signal. That signal can still be wrong: 21 samples can agree on a hallucinated fact.
-
A product team wants to report “ReAct accuracy” for a customer-support assistant using the paper’s HotpotQA number, 27.4. Give two reasons why that number does not transfer, and say what you would measure instead.
Answer: The 27.4 is exact match with PaLM-540B, specific few-shot prompts, a Wikipedia interface returning five sentences and a 7-step limit; a different model, tool set, document base or budget changes the result. HotpotQA answers are short entities, while support answers are judged on correctness and policy compliance. Measure exact or graded correctness on a held-out set of real support questions, abstention rate on unanswerable ones, the distribution of action counts and budget exhaustion, and failure types such as empty search, loops and stale documents, with the fallback method reported separately.
What to check when reading agent traces
The paper’s core contribution is the protocol: an action space enlarged with language, with thoughts updating only the context. Its experiments compare prompting formats on a frozen model and report fine-tuning results for smaller models trained on 3,000 trajectories that reached correct answers. Sections 2–3 We read pages 3 to 6 of the 33-page arXiv v3, covering the method, the knowledge-task setup, Table 1 and Table 2; the decision-making experiments, the GPT-3 appendix and the prompts were not checked.
The released environment shows how much of an “agent” is ordinary interface code: string parsing, sentence splitting, lookup cursors and step counters. wikienv.py When comparing ReAct results, check what a search returns, whether thoughts count as steps, what the budget is, how the final answer is normalized and whether a fallback method was mixed in.
Make a prediction, then check
In ReAct's definition, what does a thought do to the environment and to the context?
Learning objectives
- Write the different context updates for thoughts and actions, and separate the paper's definition from the reference implementation's step counting.
- Trace alias, empty-search, budget and stale-page failures offline, and interpret the paper's reported numbers within their setting.
Prerequisites & connections
Explore related knowledge →References
- ReAct: Synergizing Reasoning and Acting in Language Models — arXiv v3 (ICLR 2023)
Shunyu Yao; Jeffrey Zhao; Dian Yu; Nan Du; Izhak Shafran; Karthik Narasimhan; Yuan Cao · 2023 - ReAct author repository — wikienv.py at a fixed commit
Shunyu Yao; ReAct contributors · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Claude · 2026-12-02 · Independent AI check (Claude subagent, not the author); this is not a human or expert review. Ran example.py with CPython 3.12.4 and compared with example.stdout.txt (identical); confirmed both code blocks are byte-identical to example.py and every table entry and exact-match count (4/4/7/8) matches. Traced q3, q4 and q6 by hand through the code (q6 needs 1+5+1+1 = 8 actions against a budget of 7) and checked n/2 = 10.5 for n = 21. Re-read ReAct arXiv v3 pages 3–6 by text and layout extraction: Section 2 setup, search/lookup/finish with first 5 sentences, 7/5-step back-off, n/2 switch rule, 3,000 fine-tuning trajectories, Table 1 rows (Act 25.7/58.9, ReAct 27.4/60.9, CoT 29.4/56.3, ReAct→CoT-SC 35.1, CoT-SC→ReAct 64.6) and Table 2 percentages and sampling. Fetched wikienv.py at commit 6bdb3a1 (168 lines, SHA-256 prefix 0de8f442 matches) and checked lines 98–158. Compared zh and en section by section. Did not run the authors' code or read Section 4 or the appendices.
- Program output, code-block identity and every table number verified.
- Table 1 and Table 2 numbers, the 7/5-step limits, the n/2 rule and 3,000 trajectories match paper pages 3–6.
- wikienv.py lines 98–158 support the claims on Could not find, No more results, think incrementing steps, no timeout and recursive disambiguation.
- zh and en align section by section; exercise answers hand-checked.
Source locations checked:
- ReAct: Synergizing Reasoning and Acting in Language Models — arXiv v3 (ICLR 2023) · arXiv v3 dated2023-03-10, ICLR2023 header, 33 pages. Read page1 identity and full text extraction of physical pages3–6: Section2 (context, augmented action space, thoughts without observations, dense/sparse), Sections3.1–3.3 (search/lookup/finish, 6/3 exemplars, baselines, 7/5-step back-off and n/2 rule, 3,000 fine-tuning trajectories, Tables1–2). Table1 columns checked against layout extraction. Section4, appendices and prompts unread.
- ReAct author repository — wikienv.py at a fixed commit · Fixed commit6bdb3a1. Read all168 lines of wikienv.py (SHA-256 0de8f442…) and the first3 LICENSE lines (MIT, 2023 Shunyu Yao). Live Wikipedia search without explicit timeout, recursive disambiguation, first five sentences and similar titles; lookup result index and No more results; think returns a fixed string and increments steps; reward always0. README and evaluation wrappers unread; nothing executed or copied.
Related topics