Paper notes

ReAct: Treating Thought as an Action So a Language Model Can Reason and Act in One Trace

ReAct treats thought as an action: a model alternates thoughts, tool calls and observations in one trace, from a few examples and without parameter updates. This post covers the paper's four tasks, rechecks its tables, and compares four prompts with Qwen3-4B on a fictional wiki.

Published Updated 72 min read

On this page
  1. Why this paper is worth reading
  2. Background: what reasoning-only and acting-only each miss
  3. Method: treat thinking as an action
  4. Enlarge the action space by one
  5. Prompting only, no parameter updates
  6. Four tasks
  7. Fine-tuning
  8. What the paper’s experiments show
  9. Knowledge-intensive tasks: HotpotQA and Fever
  10. Decision making: ALFWorld and WebShop
  11. What to keep in mind when reading the tables
  12. Hands-on check: recompute the paper’s tables
  13. Hands-on experiment: four prompts on a fictional wiki
  14. Experiment design
  15. Results
  16. What this experiment can and cannot say
  17. Limits and what came after
  18. What to take away from this paper
  19. Further reading
  20. FAQ

ReAct: Synergizing Reasoning and Acting in Language Models (Yao et al., Princeton University and Google Research, ICLR 2023; the ReAct paper below) makes a change small enough to state in one sentence: treat thinking as an action. At every step the model either calls a tool (an action) or writes free text (a thought). A thought does not change the environment and produces no observation; it is only appended to the context to help later reasoning and acting. The trace becomes an alternation of thought, action and observation. With one to six hand-written examples, a frozen PaLM-540B is compared against reasoning-only and acting-only prompting on question answering (HotpotQA, Fever) and interactive decision making (ALFWorld, WebShop). On ALFWorld the best set of prompts reaches a 71% success rate, against 45% for the best acting-only prompt and 37% for the imitation-learning agent BUTLER; on WebShop ReAct reaches 40.0%, against 29.1% for imitation learning (IL). The paper’s conclusion is not “ReAct is better everywhere”, though: on HotpotQA ReAct (27.4) is slightly behind chain of thought (29.4), and the best method is a hybrid of the two.

Beyond the paper, this post does two things. Check: the numbers of the paper’s five tables are copied into a script and recomputed. The narrative largely holds up; three points need care: the small gaps in Table 1 come without error bars, the “best of” rows in Table 3 are not the same kind of number as its All column, and Table 5 and Table 1 differ by 2.0 for the same method. Small replication: four prompts (Standard, CoT, Act, ReAct) are compared with Qwen3-4B on a fictional wiki, 72 questions in two worlds. Standard and CoT each answer 9 questions right, all of them from the 18 two-way comparison questions, which is the level of chance; Act answers 44 (61.1%) and ReAct 48 (66.7%), and a gap of four questions is too small to call (paired sign test, p = 0.424). What the thoughts change is the path rather than the total: ReAct goes on to the next hop where Act stops one hop early, and it does no better than Act on the questions whose answer sits beyond the first five sentences of a page, where its thoughts often rule the page out instead of calling Lookup. The same experiment run with Chinese prompts saw a gap of 14 questions (50 against 36), so 72 questions and one small model support a direction at best; the sections below separate what can be concluded from what cannot.

Why this paper is worth reading

  • It is the smallest form of nearly every agent loop in use today. The model decides the next step, the environment executes it and returns a result, the result goes into the context, and the model decides again. Function calling, browser agents and coding agents change the interface format; the loop itself is the same.
  • It tests what thinking is for, one ablation at a time. The paper does not only compare ReAct with baselines on total score. It removes the thoughts (Act), removes the actions (CoT), and replaces the thoughts with a restatement of environment feedback (ReAct-IM); each control answers one specific question.
  • Its conclusion is not one-sided. ReAct loses to chain of thought on HotpotQA, and the authors run a failure analysis and design a hybrid because of it. Admitting where a method loses and then explaining why carries more information than a table that is ahead everywhere.
  • It sits next to other pages on this site. For the engineering of agents see Agents and tool calling, for the formats of function calling see Structured output and function calling, and for prompting patterns see Prompt engineering.

Background: what reasoning-only and acting-only each miss

Before ReAct, the two uses of large models mostly went their own ways. One was reasoning: chain of thought (CoT) has the model write intermediate steps before the answer, which helps a great deal on math and commonsense questions. But it relies entirely on what the parameters happen to remember. Once a fact is misremembered, every later step builds on the error, and the written reasoning sounds just as confident. The other was acting: have the model emit action sequences to operate an environment or call tools, as WebGPT does with a browser and SayCan does for robot action planning. In those systems the model outputs actions directly, and no step writes down why it acts or where it stands; the state stays implicit inside the model.

Figure 1 of the paper shows the gap on both sides with two failures. An acting-only model on HotpotQA reads three search results and cannot combine them into the final Finish action. On ALFWorld it fails to notice that “sinkbasin 1 does not contain peppershaker 1” and keeps generating the same useless action. What is missing in both is a way to summarize the current state in language between two actions and decide what to do next.

The shape of the trace under four prompting styles Four rows of boxes. Standard: question straight to answer. Chain of thought: question, one block of thought, answer. Act-only: after the question, actions and observations alternate and the last action is Finish. ReAct: every step is thought, action, observation, and the last step is a thought plus Finish. Question Thought Action Obs Answer model writes Thought and Action; the environment returns Obs Standard Question Answer no reasoning, no tools CoT (reason only) Question Thought Answer reasons from memory; the facts may be invented Act-only Question Action 1 Obs 1 Action 2 Obs 2 Action 3 calls tools but never writes down why ReAct Question Thought 1 Action 1 Obs 1 Thought 2 Action 2 Obs 2 Thought 3 Action 3 thoughts choose the next action; observations feed the next thought
Figure 1: The traces the four prompting styles produce. The last action is Finish[answer], which ends the task. ReAct and Act-only use the same tools and differ only in whether a thought comes before each action; CoT uses the same kind of thoughts but has no actions or observations.

Method: treat thinking as an action

Enlarge the action space by one

In the usual agent setting, step tt receives an observation oto_t and picks an action ata_t with a policy π(at∣ct)\pi(a_t\mid c_t), where the context ctc_t is the whole history so far:

ct=(o1,a1,…,ot−1,at−1,ot)c_t=(o_1,a_1,\dots,o_{t-1},a_{t-1},o_t)

When the map from context to action is implicit and needs heavy reasoning over the whole history, the policy is hard to learn; the two failures above are exactly that. ReAct enlarges the action space to A^=A∪L\hat{\mathcal A}=\mathcal A\cup\mathcal L, where L\mathcal L is the space of language. An “action” a^t\hat a_t in L\mathcal L is a thought: it does not change the external environment, produces no observation, and is only appended to the context:

ct+1=(ct,a^t)c_{t+1}=(c_t,\hat a_t)

The paper lists several uses of a thought: decomposing a goal and making a plan, injecting commonsense relevant to the task, extracting the important part of an observation, tracking progress and switching plans, and handling exceptions by adjusting the plan.

Prompting only, no parameter updates

The main setting is a frozen PaLM-540B given one to six human-written trajectories as examples, which the model continues. The thoughts in the examples are typed by the annotators in plain language between the actions, and the paper stresses that no special format, thought design or example selection was used. Two usages appear: in knowledge-intensive reasoning tasks thoughts and actions alternate strictly (the paper calls this dense thought); in decision-making tasks with many actions, thoughts appear only at the most relevant places and the model decides for itself when to think (sparse thought).

The prompts compared on HotpotQA and Fever are:

PromptWhat the trace contains
Standardthe question, then the answer
CoTthe question, one block of reasoning, the answer (a ReAct trace without actions and observations)
CoT-SC21 sampled CoT traces (temperature 0.7), majority answer
Actthe question, alternating actions and observations, then Finish (a ReAct trace without thoughts)
ReActthe question, alternating thoughts, actions and observations, then a thought plus Finish
ReAct→CoT-SCif ReAct gives no answer within the step limit (7 on HotpotQA, 5 on Fever), fall back to CoT-SC
CoT-SC→ReActif the majority answer among the 21 CoT-SC samples occurs fewer than half the time, fall back to ReAct

The paper sets the two step limits because more steps stop helping ReAct, and a footnote gives the evidence: among trajectories with a correct answer, those that use 7 steps (HotpotQA) or 5 steps (Fever) are only 0.84% and 1.33%.

Four tasks

TaskActionsExamplesMetric
HotpotQA, multi-hop QAsearch, lookup, finish (a Wikipedia API)6exact match (EM)
Fever, fact verificationsame3accuracy
ALFWorld, a text household gamego to, take, use and other text actions3 annotated per task type; 2 of them in 6 orders give 6 promptssuccess rate on 134 unseen games
WebShop, online shopping (1.18M real products)search, choose product, choose option, buy1score and success rate on 500 test instructions

HotpotQA and Fever use a Wikipedia API with only three actions, which the paper deliberately makes weak: search[entity] returns the first 5 sentences of the page if it exists, or suggests 5 similar entities; lookup[string] returns the next sentence of the current page containing the string, like Ctrl+F in a browser; finish[answer] ends the task. In the paper’s words this is much weaker than state-of-the-art lexical or neural retrievers, on purpose: it imitates how a person uses Wikipedia and forces the model to retrieve through explicit reasoning in language. These three actions are also the prototype of the small experiment later in this post.

Fine-tuning

Hand-written trajectories do not scale, so the paper also tries bootstrapping: it takes 3,000 trajectories with correct answers generated by ReAct (and by the other baselines) and fine-tunes PaLM-8B and 62B to decode the whole trajectory given the question.

What the paper’s experiments show

Knowledge-intensive tasks: HotpotQA and Fever

Paper Table 1: results with PaLM-540B prompting.

MethodHotpotQA EMFever accuracy
Standard28.757.1
CoT29.456.3
CoT-SC33.460.4
Act25.758.9
ReAct27.460.9
CoT-SC→ReAct34.264.6
ReAct→CoT-SC35.162.0
Best supervised67.589.5

The paper reads this in three ways:

  • ReAct is better than Act on both tasks, which shows that thinking helps in producing the final answer; the fine-tuning results support this too.
  • ReAct beats CoT on Fever (60.9 against 56.3) and trails it slightly on HotpotQA (27.4 against 29.4). The paper’s explanation is that SUPPORTS and REFUTES claims in Fever can differ by very little, so retrieving accurate and up-to-date knowledge is vital.
  • The two hybrids are best: ReAct→CoT-SC on HotpotQA and CoT-SC→ReAct on Fever. The paper’s Figure 2 shows that they match CoT-SC with 21 samples using only 3 to 5 CoT-SC samples.

To understand why ReAct loses to CoT on HotpotQA, the paper samples 50 correct and 50 incorrect trajectories from each of ReAct and CoT (200 in total) and labels the type of success and failure by hand:

Paper Table 2: types of success and failure on HotpotQA (human labels).

TypeMeaningReActCoT
Success: true positivereasoning and facts both correct94%86%
Success: false positivereasoning or facts invented6%14%
Failure: reasoning errorwrong reasoning, including repetitive loops47%16%
Failure: search result errorempty or useless search result23%n/a
Failure: hallucinationreasoning or facts invented0%56%
Failure: label ambiguityright prediction that does not match the label exactly29%28%

The paper’s three observations: hallucination is a serious problem for CoT (56% of its failures, and 14% of its successes are really invented), while ReAct’s trajectories are more grounded and trustworthy because it can reach an external knowledge base; the interleaved structure limits how freely ReAct can reason, so it makes more reasoning errors, including one pattern specific to it, repeating earlier thoughts and actions without getting out of the loop (the authors suspect greedy decoding); and whether a search returns useful information is critical for ReAct, since uninformative searches make up 23% of its failures and derail the reasoning, which then has a hard time recovering.

Fine-tuning (paper Figure 3): when prompted, ReAct is the worst of the four methods at both PaLM-8B and 62B, because it is hard to learn both reasoning and acting from a few examples in context. After fine-tuning on 3,000 trajectories ReAct becomes the best of the four; fine-tuned 8B ReAct beats every prompted 62B method, and fine-tuned 62B ReAct beats every prompted 540B method. Fine-tuning Standard or CoT is clearly worse, which the paper explains by saying that the former teaches the model to memorize facts that may be hallucinated, while the latter teaches how to reason and act to get information, a more general skill.

Decision making: ALFWorld and WebShop

Paper Table 3: ALFWorld success rates (%) by task type.

MethodPickCleanHeatCoolLookPick 2All
Act, best of 6 prompts88427467724145
ReAct, average65398376552457
ReAct, best of 6 prompts92589686784171
ReAct-IM, average55596055232448
ReAct-IM, best of 6 prompts62688757393353
BUTLERg, best of 833267076171222
BUTLER, best of 8463974100222437

BUTLER is an imitation-learning agent trained on 105 expert trajectories per task type (it uses beam search; all other methods use greedy decoding), and its numbers come from the original ALFWorld paper. The paper’s claims: the best ReAct trial reaches a 71% overall success rate, clearly above the best Act (45%) and BUTLER (37%); even the worst ReAct trial (48%) beats the best trial of both; across the six prompts the relative gain of ReAct over Act ranges from 33% to 90% and averages 62%. Qualitatively, an Act agent with no thoughts at all fails to decompose goals into subgoals or loses track of the current state of the environment.

ReAct-IM is the paper’s control for Inner Monologue (IM): the thoughts are replaced by IM-style dense external feedback, limited to the current state of the environment and what still has to be done, with no high-level goal decomposition and no commonsense reasoning. ReAct wins clearly, 71 against 53 overall, with an advantage on five of the six task types; the paper observes that ReAct-IM often gets wrong whether a subgoal is finished or what the next subgoal is, and struggles to tell where an item is likely to be.

Paper Table 4: WebShop score and success rate (%).

MethodScoreSuccess rate
Act62.330.1
ReAct66.640.0
IL59.929.1
IL+RL62.428.7
Human expert82.159.6

IL used 1,012 human-annotated trajectories, and IL+RL additionally used 10,587 training instructions (numbers from the original WebShop paper). The paper’s reading: one-shot Act already performs on par with IL and IL+RL, and with additional sparse reasoning ReAct improves the success rate by an absolute 10 points over the previous best; but it is still far from human experts, who explore more products and reformulate queries more.

What to keep in mind when reading the tables

  • PaLM-540B is not public. Appendix A.1 repeats ReAct prompting with GPT-3 (text-davinci-002, greedy decoding): 30.8 on HotpotQA and 78.4 on ALFWorld, both above PaLM-540B’s 29.4 and 70.9 (paper Table 5), which the authors attribute possibly to GPT-3’s instruction fine-tuning.
  • The paper gives neither the evaluation-set size nor the number of runs for the PaLM experiments, and Table 1 has no error bars. Only Table 5 in Appendix A.1 says that HotpotQA is a random subset of 500 validation questions. A reader cannot tell whether a gap of one or two points in Table 1 is noise; the next section estimates it for a hypothetical 500 questions.
  • “Best of” is not the score of a single trial. In the Act, ReAct and ReAct-IM “best of” rows of Table 3, the per-task numbers look like separate maxima while the All column is the best single trial overall; the weighted recomputation in the next section shows that this reading fits the numbers, but the paper never says so.
  • BUTLER’s All column is not a weighted average of its six task types. In the original ALFWorld paper the per-task numbers come from agents trained per task, and All is a single policy trained on all 3,553 tasks together.
  • Every prompting method is far below supervised learning. In Table 1 the best prompting method is more than 30 points below the best supervised result on HotpotQA. The paper says so itself and suggests that fine-tuning on more human-written data may be the better way to release ReAct’s potential.

Hands-on check: recompute the paper’s tables

The script below needs no GPU and runs in milliseconds. It copies the numbers of paper Tables 1 to 5 into dictionaries (I transcribed them from the PDF text and checked them against the page layout) and recomputes five things: the differences between methods in Table 1; the column sums of Table 2; the overall ALFWorld success rate of Table 3 weighted by the task counts of the unseen set (24, 31, 23, 21, 18 and 17, 134 games in all); a few differences quoted in the abstract and text; and Table 5 against Table 1 for the same method.

Full code (about 78 lines)
"""Recheck the ReAct paper's tables and abstract from its own numbers"""
import math

T1 = {  # method: (HotpotQA EM, Fever accuracy)
    "Standard": (28.7, 57.1), "CoT": (29.4, 56.3), "CoT-SC": (33.4, 60.4),
    "Act": (25.7, 58.9), "ReAct": (27.4, 60.9),
    "CoT-SC -> ReAct": (34.2, 64.6), "ReAct -> CoT-SC": (35.1, 62.0),
    "Supervised SoTA": (67.5, 89.5)}
T2 = {  # share of each success/failure type (%): (ReAct, CoT)
    "success": {"true positive": (94, 86), "false positive": (6, 14)},
    "failure": {"reasoning error": (47, 16), "search result error": (23, 0),
                "hallucination": (0, 56), "label ambiguity": (29, 28)}}
W = {"Pick": 24, "Clean": 31, "Heat": 23, "Cool": 21, "Look": 18, "Pick2": 17}
T3 = {  # per row: 6 task types, then All
    "Act (best of 6)": (88, 42, 74, 67, 72, 41, 45),
    "ReAct (avg)": (65, 39, 83, 76, 55, 24, 57),
    "ReAct (best of 6)": (92, 58, 96, 86, 78, 41, 71),
    "ReAct-IM (avg)": (55, 59, 60, 55, 23, 24, 48),
    "ReAct-IM (best of 6)": (62, 68, 87, 57, 39, 33, 53),
    "BUTLERg (best of 8)": (33, 26, 70, 76, 17, 12, 22),
    "BUTLER (best of 8)": (46, 39, 74, 100, 22, 24, 37)}
T4 = {  # WebShop: (score, success rate)
    "Act": (62.3, 30.1), "ReAct": (66.6, 40.0), "IL": (59.9, 29.1),
    "IL+RL": (62.4, 28.7), "Human expert": (82.1, 59.6)}


def se(p, n):
    """standard error of a rate p (in %) on n samples, in points"""
    return 100 * math.sqrt(p / 100 * (1 - p / 100) / n)


print("Table 1: HotpotQA and Fever (PaLM-540B prompting)")
NAMES = ("HotpotQA", "Fever")
rows = [("ReAct", "Act", (0, 1)), ("ReAct", "CoT", (0, 1)),
        ("ReAct -> CoT-SC", "CoT-SC", (0,)), ("CoT-SC -> ReAct", "ReAct", (1,))]
for a, b, cols in rows:
    diffs = ", ".join(f"{NAMES[i]} {T1[a][i] - T1[b][i]:+.1f}" for i in cols)
    print(f"  {a} - {b}: {diffs}")
best = [max(v[i] for m, v in T1.items() if m != "Supervised SoTA")
        for i in (0, 1)]
sota = T1["Supervised SoTA"]
print(f"  Supervised SoTA - best prompt: HotpotQA {sota[0] - best[0]:+.1f}, "
      f"Fever {sota[1] - best[1]:+.1f}")
print(f"  If the set had 500 questions (the paper gives this only for its "
      f"GPT-3 runs),\n  the standard error of an EM near 30% is "
      f"{se(30, 500):.1f} points")

print("\nTable 2: column sums (%)")
for kind, rows in T2.items():
    sums = [sum(v[i] for v in rows.values()) for i in (0, 1)]
    print(f"  {kind}: ReAct {sums[0]}, CoT {sums[1]}")

print("\nTable 3: All recomputed with the ALFWorld unseen-set task "
      "counts\n(24/31/23/21/18/17, 134 in total)")
print(f"  {'row':<22}{'weighted':>9}{'printed':>9}{'diff':>7}")
for row, v in T3.items():
    wavg = sum(x * n for x, n in zip(v[:6], W.values())) / sum(W.values())
    print(f"  {row:<22}{wavg:9.1f}{v[6]:9d}{wavg - v[6]:+7.1f}")
print(f"  Standard error of ReAct's All=57 on 134 games: {se(57, 134):.1f} "
      f"points")

print("\nNumbers in the abstract and the text")
print(f"  ALFWorld: ReAct best 71 - BUTLER 37 = {71 - 37}")
print(f"  ALFWorld: worst ReAct trial 48 > best Act trial 45: {48 > 45}")
print(f"  WebShop: success rate {T4['ReAct'][1]} - {T4['IL'][1]} = "
      f"{T4['ReAct'][1] - T4['IL'][1]:.1f}")
print(f"  WebShop: score {T4['ReAct'][0]} - {T4['IL+RL'][0]} = "
      f"{T4['ReAct'][0] - T4['IL+RL'][0]:.1f}")
print(f"  WebShop: Act - IL success rate = {T4['Act'][1] - T4['IL'][1]:+.1f}")
print(f"  WebShop: Human expert - ReAct success rate = "
      f"{T4['Human expert'][1] - T4['ReAct'][1]:.1f}")
print(f"  WebShop, 500 instructions: standard error of SR 40.0 is "
      f"{se(40, 500):.1f};\n  the 1.0-point Act vs IL gap is inside the noise")
print("\nTable 5: PaLM-540B vs GPT-3 (text-davinci-002)")
print(f"  HotpotQA: {30.8 - 29.4:+.1f}; ALFWorld: {78.4 - 70.9:+.1f}")
gap = 29.4 - T1["ReAct"][0]
print(f"  Table 5 gives 29.4 for PaLM-540B on HotpotQA,\n"
      f"  Table 1 gives {T1['ReAct'][0]} for the same method: gap {gap:.1f}")

Output:

Table 1: HotpotQA and Fever (PaLM-540B prompting)
  ReAct - Act: HotpotQA +1.7, Fever +2.0
  ReAct - CoT: HotpotQA -2.0, Fever +4.6
  ReAct -> CoT-SC - CoT-SC: HotpotQA +1.7
  CoT-SC -> ReAct - ReAct: Fever +3.7
  Supervised SoTA - best prompt: HotpotQA +32.4, Fever +24.9
  If the set had 500 questions (the paper gives this only for its GPT-3 runs),
  the standard error of an EM near 30% is 2.0 points

Table 2: column sums (%)
  success: ReAct 100, CoT 100
  failure: ReAct 99, CoT 100

Table 3: All recomputed with the ALFWorld unseen-set task counts
(24/31/23/21/18/17, 134 in total)
  row                    weighted  printed   diff
  Act (best of 6)            63.6       45  +18.6
  ReAct (avg)                57.3       57   +0.3
  ReAct (best of 6)          75.5       71   +4.5
  ReAct-IM (avg)             48.6       48   +0.6
  ReAct-IM (best of 6)       60.1       53   +7.1
  BUTLERg (best of 8)        39.7       22  +17.7
  BUTLER (best of 8)         51.6       37  +14.6
  Standard error of ReAct's All=57 on 134 games: 4.3 points

Numbers in the abstract and the text
  ALFWorld: ReAct best 71 - BUTLER 37 = 34
  ALFWorld: worst ReAct trial 48 > best Act trial 45: True
  WebShop: success rate 40.0 - 29.1 = 10.9
  WebShop: score 66.6 - 62.4 = 4.2
  WebShop: Act - IL success rate = +1.0
  WebShop: Human expert - ReAct success rate = 19.6
  WebShop, 500 instructions: standard error of SR 40.0 is 2.2;
  the 1.0-point Act vs IL gap is inside the noise

Table 5: PaLM-540B vs GPT-3 (text-davinci-002)
  HotpotQA: +1.4; ALFWorld: +7.5
  Table 5 gives 29.4 for PaLM-540B on HotpotQA,
  Table 1 gives 27.4 for the same method: gap 2.0

Reading it item by item:

  • The differences in Table 1 agree with the paper’s narrative. ReAct is above Act by 1.7 (HotpotQA) and 2.0 (Fever); against CoT it is 2.0 lower on HotpotQA and 4.6 higher on Fever; each hybrid is above the method it falls back to by 1.7 (ReAct→CoT-SC over CoT-SC on HotpotQA) and 3.7 (CoT-SC→ReAct over ReAct on Fever); the best supervised result is above the best prompting method by 32.4 and 24.9. No sentence of the paper overstates these.
  • But the paper gives no basis for judging the small gaps in Table 1. If the evaluation set had 500 questions (the paper mentions that number only for its GPT-3 runs), the standard error of an EM near 30% is 2.0 points, the same order as the 1.7-point gap between ReAct and Act. The paper’s case therefore rests more on the much larger ALFWorld gaps, the fine-tuning experiments and the failure analysis than on one or two points in Table 1.
  • Table 2 is consistent. The success columns sum to 100, the ReAct failure column to 99 (rounding), the CoT failure column to 100.
  • In Table 3 the “average” rows match the weighted recomputation and the “best of” rows do not, which is itself informative. ReAct’s average recomputes to 57.3 against a printed 57, ReAct-IM’s to 48.6 against 48. All three “best of” rows recompute well above the printed All: Act 63.6 against 45, ReAct 75.5 against 71, ReAct-IM 60.1 against 53. That fits the reading “per-task maxima, with All being the best single trial” (the best score on different task types usually comes from different prompts). The two BUTLER rows differ even more (51.6 against 37, 39.7 against 22) because their All is a different, jointly trained policy (see the previous section). The paper does not say any of this, so it is an explanation that fits the numbers, not a statement of the paper.
  • The choice of prompt is itself a large variable. ReAct’s overall success rate goes from 48% to 71% across the six prompts, while the standard error of 57% on 134 games is only 4.3 points, so the spread is far larger than the sampling error. Reporting the average and the best over six prompts, as the paper does, is the right practice; a conclusion drawn from one prompt would be fragile.
  • The numbers in the abstract and the text check out. 71 minus 37 is 34, the “34%” of the abstract; the worst ReAct trial (48) is indeed above the best Act trial (45) (the 48 appears only in the text, not in a table, so all that can be checked is that it exceeds 45); the WebShop success rate 40.0 minus IL’s 29.1 is 10.9, which the abstract rounds to “10%”, and the score is 4.2 above IL+RL; Act is only 1.0 above IL while the standard error of a 40.0 success rate on 500 instructions is 2.2, so “Act on par with IL” is an accurate description; the human expert is 19.6 above ReAct.
  • Table 5 does not agree with Table 1. Table 5 gives 29.4 for PaLM-540B on HotpotQA while Table 1 gives 27.4 for the same method, a gap of 2.0 that the paper does not explain. The caption of Table 5 mentions a random subset of 500 questions, so a different evaluation subset is the most likely cause, but that is a guess. GPT-3 is 1.4 above PaLM on HotpotQA and 7.5 above it on ALFWorld.

Hands-on experiment: four prompts on a fictional wiki

The paper’s PaLM-540B is not public, and the facts behind HotpotQA have probably been written into small models’ parameters long ago, so this section does not try to reproduce the paper’s numbers. It asks a narrower question: when the answer is not in the model’s parameters and has to be fetched with a tool, what does “thinking” change? The setting is a fictional Wikipedia: names of people, companies, cities and countries are assembled at random, so the model cannot remember them and every correct answer has to come from a page it retrieved. Standard and CoT are therefore a floor, and the comparison that matters is Act against ReAct.

Experiment design

The wiki of the experiment: Search shows 5 sentences, Lookup reaches the rest On the left, a page of 7 sentences; the first 5 are boxed and marked as what Search returns. Sentence 6, the birthplace, lies outside the box and can only be read with Lookup on a keyword. On the right, the meaning of the three actions. Page "Torvin Hesk" (7 sentences) 1 Torvin Hesk is a glassblower. 2 Torvin Hesk won the Amber Prize in 1994. 3 Torvin Hesk works at Lumara Glassworks. 4 Torvin Hesk has written 3 books. 5 Torvin Hesk enjoys chess. 6 Torvin Hesk was born in Dovrek. 7 Torvin Hesk's mentor was Idris Vane. Search returns these 5 Lookup[born] reaches it Search[entity] Returns the first 5 sentences; if there is no page, 5 similar titles Lookup[keyword] Returns the next sentence of the current page containing it (Ctrl+F) Finish[answer] Gives the answer and ends the task
Figure 2: The fictional wiki of the experiment, with the same three actions as Section 3.1 of the paper. Only part of a page is visible through Search; a sentence such as the birthplace can sit at position 6 or 7, so the model has to think of Lookup.
  • Worlds. Each world has 40 people, 16 companies, 14 cities and 6 countries, generated from a fixed seed (two worlds, seeds 1 and 2). A page is assembled from template sentences: a person has 7 (occupation, birthplace, employer, mentor, plus three irrelevant ones: a prize, the number of books and a hobby), a company 6 (line of business, headquarters, founding year, founder, plus headcount and the number of countries it sells in), a city 3 and a country 2. The first sentence is fixed and the rest are shuffled, so on a person page a given fact falls beyond the first five sentences (all that Search returns) with probability one third, on a company page one fifth; reading it takes Lookup.
  • Actions. The same three as the paper. Search[entity] returns the first five sentences of the page, or, if there is no such page, the five most similar titles; Lookup[keyword] returns the next sentence of the current page that contains the keyword, marked “(Result i/n)”, or “No more results.”; Finish[answer] ends the episode. This Lookup is a literal string match with no notion of synonyms, which matters later.
  • Questions. 36 per world, nine in each of four types: 1 hop (birth city, employer), 2 hops (founding year of the employer, country of birth, founder of the employer), 3 hops (country of the employer’s headquarters, founding year of the mentor’s employer) and comparisons (were two people born in the same city; which of two companies is older: all two-way choices, so guessing is right half of the time). In each world 6 questions carry a typo in the first name (one letter typed twice), and the true name is guaranteed to be the closest of the similar titles, so the model can recover from the typo. Of the 72 questions, 34 need at least one sentence that lies beyond the first five.
  • Prompts. All four prompts share the same four hand-written examples. They live in their own tiny world, and none of their names occurs in a test world: a 2-hop question with distractor sentences, a 1-hop question with a misspelled name that is then resolved with Lookup, a comparison, and a 2-hop country question. There is no 3-hop example and no yes/no example. Standard has only the question and the answer; CoT joins the thoughts of an example into one paragraph before the answer; Act has only actions and observations; ReAct has thoughts, actions and observations. The four prefixes are 89, 368, 764 and 1,096 tokens long (Qwen3 tokenizer).
  • Decoding and steps. Greedy decoding, at most 7 steps (the paper’s cap on HotpotQA), with the KV cache of the examples computed once. A ReAct step may generate at most 150 new tokens (a thought and an action together), an Act step 48. The model is Qwen3-4B (the official post-trained release, not the Base model), used here as a plain continuation model: no chat template, so its thinking mode is never triggered.
  • Grading and failure types. Exact match after lowercasing and removing articles and punctuation, as in the paper. Every wrong Act or ReAct trace is classified automatically: it ran out of the 7 steps without answering (no_finish); it answered without having opened a page it needed (unopened); it opened the pages but a sentence it needed never appeared in an observation (unseen); or it saw everything and still answered wrongly (misread). Three more flags count over all 72 questions: repeating an action (loop), a Search that found no page (miss) and an invalid action format (invalid).

The differences from the paper should be clear before reading any number:

PaperThis experiment
ModelPaLM-540B, not publicQwen3-4B, Apache-2.0
Datareal HotpotQA and Fever questionsan invented wiki, 72 questions (36 per world)
Examples6 on HotpotQA4, shared by the four prompts
Environmentthe real Wikipedia APItemplate sentences, Lookup is a literal match
Answer in the parameters?possibly (pretraining saw Wikipedia)no (the names are invented)

Environment: Apple M2 Max (MPS backend), Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0; Qwen3-4B loaded in float32, greedy decoding. The 288 answers (72 questions × 4 prompts) took 53 minutes; at the end the script reruns the first four questions with ReAct and the traces come out word for word identical. Greedy decoding is repeatable in the same environment; on other hardware or library versions, individual traces may differ. The statistics script only reads the saved react_runs.json and never calls the model.

The history of the prompts and rules should be on the record. The script was edited several times while I developed it, and before the full runs I started it once as a trial and stopped it after about two minutes without saving the output, so the wording of the examples was not written in one go; I never compared or searched over prompts. The 288 answers below come from one complete run, the first attempt, started after the last edit, and the script was not changed during the run. A lenient re-grade row was added after the run as a check (see below); the main table keeps exact match.

Full code (about 481 lines): fictional wiki, four prompts and run script
"""ReAct mini-replication: four prompting styles on a fictional wiki"""
import copy
import difflib
import json
import random
import re
import string
import sys
import time

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache
from transformers.utils import logging as hf_logging

hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
NAME, DEV, MAX_STEPS = "Qwen/Qwen3-4B", "mps", 7
T, A, O, Q, ANS = (
    "Thought", "Action", "Observation", "Question", "Answer")
NOT_FOUND = "Could not find"
INVALID = "Invalid action. Use Search[...], Lookup[...] or Finish[...]."

# --- A fictional world ---
GIV = "bre vel tar kor nis dal mor qui zen fal".split()
SUR = "Hars Quist Ondu Vorn Lek Mari Thess Dray Senk Olm".split()
SYL = "tar nov kel os ven dro mir ka lu pes ba zor".split()
IND = (
    "Instruments Foods Shipping Glassworks "
    "Textiles Software Shipyards Optics").split()
JOB = ["a ceramicist", "a composer", "a geologist", "an architect",
       "an astronomer", "a botanist"]
PRZ = "Amber Heron Bronze Starfield Turquoise Ginkgo".split()
SIGHT = "lighthouse clock-tower harbour market stone-bridge".split()
HOBBY = "chess sailing gardening photography hiking".split()
S = dict(  # sentence templates of the pages
    job="{p} is {x}.",
    born="{p} was born in {x}.",
    works="{p} works at {x}.",
    mentor="{p}'s mentor was {x}.",
    prize="{p} won the {x} Prize in {y}.",
    books="{p} has written {y} books.",
    hobby="{p} enjoys {x}.",
    kind="{p} is a company in the {x} business.",
    hq="{p} has its headquarters in {x}.",
    year="{p} was founded in {x}.",
    founder="{p} was founded by {x}.",
    staff="{p} employs about {y} people.",
    sells="{p} sells its products in {y} countries.",
    city="{p} is a city known for its {x}.",
    land="{p} is located in {x}.",
    pop="{p} has a population of about {y}.",
    cap="The capital of {p} is {x}.",
)
QT = dict(  # question templates
    born="Which city was {p} born in?",
    works="Which company does {p} work at?",
    year="In which year was the company that employs {p} founded?",
    country="In which country was {p} born?",
    founder="Who founded the company that employs {p}?",
    hqc="In which country is the headquarters of the company "
        "that employs {p}?",
    myear="In which year was the company that employs the mentor "
        "of {p} founded?",
    same="Was {p} born in the same city as {x}?",
    early="Which was founded earlier, {p} or {x}?",
)
YES, NO = ("yes", "no")


def build_world(seed, n_people=40, n_comp=16, n_city=14, n_country=6):
    rng, used = random.Random(seed), set()

    def uniq(make):
        while True:
            s = make()
            if s not in used:
                used.add(s)
                return s

    def stem(k):
        return "".join(rng.choice(SYL) for _ in range(k)).title()

    def person():
        return (
            (rng.choice(GIV) + rng.choice(GIV)).title()
            + " " + rng.choice(SUR))

    country = [uniq(lambda: stem(3) + "ia") for _ in range(n_country)]
    city = {uniq(lambda: stem(3)): rng.choice(country) for _ in range(n_city)}
    comp = {uniq(lambda: stem(2) + " " + rng.choice(IND)): None
            for _ in range(n_comp)}
    ppl = [uniq(person) for _ in range(n_people)]
    for c in comp:
        comp[c] = dict(hq=rng.choice(list(city)), year=rng.randint(1950, 2012),
                       founder=rng.choice(ppl))
    who = {p: dict(born=rng.choice(list(city)), works=rng.choice(list(comp)),
                   mentor=rng.choice([q for q in ppl if q != p])) for p in ppl}
    pages = {}

    def page(name, first, facts, fillers):
        rest = facts + fillers
        rng.shuffle(rest)  # first sentence fixed, the rest shuffled
        pages[name] = [first] + rest

    for p, f in who.items():
        page(p, S["job"].format(p=p, x=rng.choice(JOB)),
             [S[k].format(p=p, x=f[k]) for k in ("born", "works", "mentor")],
             [S["prize"].format(p=p, x=rng.choice(PRZ),
                                y=rng.randint(1980, 2020)),
              S["books"].format(p=p, y=rng.randint(2, 12)),
              S["hobby"].format(p=p, x=rng.choice(HOBBY))])
    for c, f in comp.items():
        page(c, S["kind"].format(p=c, x=c.split()[-1]),
             [S["hq"].format(p=c, x=f["hq"]),
              S["year"].format(p=c, x=f["year"]),
              S["founder"].format(p=c, x=f["founder"])],
             [S["staff"].format(p=c, y=rng.randint(40, 9000)),
              S["sells"].format(p=c, y=rng.randint(2, 30))])
    for x, k in city.items():
        page(x, S["city"].format(p=x, x=rng.choice(SIGHT)),
             [S["land"].format(p=x, x=k)],
             [S["pop"].format(p=x, y=rng.randint(20, 900) * 1000)])
    for k in country:
        cap = rng.choice([x for x in city if city[x] == k] or list(city))
        page(k, S["land"].format(p=k, x="a far-off continent"),
             [S["cap"].format(p=k, x=cap)], [])
    return dict(pages=pages, who=who, comp=comp, city=city, ppl=ppl, rng=rng)


def misspell(name, pages):
    """One letter typed twice; the right title must be the unique best match"""
    for i in sorted(range(len(name)), key=lambda i: abs(i - len(name) // 2)):
        t = name[:i] + name[i] + name[i:]
        r = sorted((difflib.SequenceMatcher(None, t, x).ratio(), x)
                   for x in pages)
        if t not in pages and name[i] != " " and r[-1][1] == name \
                and r[-1][0] > r[-2][0]:
            return t
    raise ValueError(name)


def make_questions(w):
    """9 each: 1, 2, 3 hops, comparison; need = evidence (page, sentence)"""
    rng, who, comp = w["rng"], w["who"], w["comp"]
    city, ppl, out = w["city"], w["ppl"], []

    def fact(page, key, x):
        return page, S[key].format(p=page, x=x)

    def add(kind, key, gold, need, typo=False, **kw):
        if typo:  # the question has a typo in the first name
            kw["p"] = misspell(kw["p"], w["pages"])
        out.append(dict(kind=kind, q=QT[key].format(**kw), gold=str(gold),
                        need=need, typo=typo))

    for i, p in enumerate(rng.sample(ppl, 9)):
        k = "born" if i < 5 else "works"
        add(1, k, who[p][k], [fact(p, k, who[p][k])],
            typo=i in (1, 3, 8), p=p)
    for i, p in enumerate(rng.sample(ppl, 9)):
        c, b = who[p]["works"], who[p]["born"]
        if i % 3 == 0:
            add(2, "year", comp[c]["year"],
                [fact(p, "works", c), fact(c, "year", comp[c]["year"])],
                typo=i == 0, p=p)
        elif i % 3 == 1:
            add(2, "country", city[b],
                [fact(p, "born", b), fact(b, "land", city[b])],
                typo=i == 4, p=p)
        else:
            add(2, "founder", comp[c]["founder"],
                [fact(p, "works", c), fact(c, "founder", comp[c]["founder"])],
                typo=i == 8, p=p)
    for i, p in enumerate(rng.sample(ppl, 9)):
        c, m = who[p]["works"], who[p]["mentor"]
        if i < 5:
            h = comp[c]["hq"]
            add(3, "hqc", city[h], [fact(p, "works", c), fact(c, "hq", h),
                                    fact(h, "land", city[h])], p=p)
        else:
            mc = who[m]["works"]
            add(3, "myear", comp[mc]["year"],
                [fact(p, "mentor", m), fact(m, "works", mc),
                 fact(mc, "year", comp[mc]["year"])], p=p)
    pairs = [(a, b) for a in ppl for b in ppl if a < b]
    same = [(a, b) for a, b in pairs if who[a]["born"] == who[b]["born"]]
    diff = [(a, b) for a, b in pairs if who[a]["born"] != who[b]["born"]]
    for a, b in rng.sample(same, 3) + rng.sample(diff, 2):
        add(4, "same", YES if who[a]["born"] == who[b]["born"] else NO,
            [fact(a, "born", who[a]["born"]),
             fact(b, "born", who[b]["born"])], p=a, x=b)
    for _ in range(4):
        a, b = rng.sample(sorted(comp), 2)
        while comp[a]["year"] == comp[b]["year"]:
            a, b = rng.sample(sorted(comp), 2)
        add(4, "early", a if comp[a]["year"] < comp[b]["year"] else b,
            [fact(a, "year", comp[a]["year"]),
             fact(b, "year", comp[b]["year"])], p=a, x=b)
    rng.shuffle(out)
    return out


class Wiki:
    """The same three actions as Section 3.1 of the paper"""

    def __init__(self, pages):
        self.pages, self.cur, self.kw, self.pos = pages, None, None, 0
        self.visited, self.flags, self.acts = [], set(), []
        self.shown = set()  # sentences that appeared in an observation

    def search(self, name):
        key = {t.lower(): t for t in self.pages}.get(name.strip().lower())
        if key is None:
            sim = difflib.get_close_matches(name, list(self.pages), n=5,
                                            cutoff=0.0)
            return f"{NOT_FOUND} [{name}]. Similar: {sim}"
        self.cur, self.kw = key, None
        self.visited.append(key)
        self.shown.update(self.pages[key][:5])
        return " ".join(self.pages[key][:5])

    def lookup(self, kw):
        if self.cur is None:
            return "No page is open yet; use Search first."
        hits = [s for s in self.pages[self.cur] if kw.lower() in s.lower()]
        if kw != self.kw:
            self.kw, self.pos = kw, 0
        if self.pos >= len(hits):
            return "No more results."
        self.pos += 1
        self.shown.add(hits[self.pos - 1])
        return f"(Result {self.pos}/{len(hits)}) {hits[self.pos - 1]}"

    def act(self, text):
        """Run one action string; return (kind, observation)"""
        m = re.match(r"\s*(Search|Lookup|Finish)\[(.*?)\]", text)
        if not m:
            self.flags.add("invalid")
            return None, INVALID
        kind, arg = m.groups()
        if kind == "Finish":
            return kind, arg  # here the second item is the answer
        if text.strip() in self.acts:
            self.flags.add("loop")
        self.acts.append(text.strip())
        obs = self.search(arg) if kind == "Search" else self.lookup(arg)
        if obs.startswith(NOT_FOUND):
            self.flags.add("miss")
        return kind, obs


# --- Prompts ---
EXW = {  # the shots' own tiny world; no name occurs in a test world
    "Torvin Hesk": [
        "Torvin Hesk is a glassblower.",
        "Torvin Hesk won the Amber Prize in 1994.",
        "Torvin Hesk works at Lumara Glassworks.",
        "Torvin Hesk has written 3 books.", "Torvin Hesk enjoys chess.",
        "Torvin Hesk was born in Dovrek.",
        "Torvin Hesk's mentor was Idris Vane."],
    "Lumara Glassworks": [
        "Lumara Glassworks is a company in the Glassworks business.",
        "Lumara Glassworks employs about 900 people.",
        "Lumara Glassworks has its headquarters in Dovrek.",
        "Lumara Glassworks was founded in 1971.",
        "Lumara Glassworks was founded by Idris Vane."],
    "Quenzo Instruments": [
        "Quenzo Instruments is a company in the Instruments business.",
        "Quenzo Instruments employs about 300 people.",
        "Quenzo Instruments has its headquarters in Kelvar.",
        "Quenzo Instruments was founded in 1983.",
        "Quenzo Instruments was founded by Natara Lowe."],
    "Maren Votsha": [
        "Maren Votsha is a composer.", "Maren Votsha has written 5 books.",
        "Maren Votsha works at Quenzo Instruments.",
        "Maren Votsha won the Heron Prize in 2003.",
        "Maren Votsha's mentor was Natara Lowe.",
        "Maren Votsha was born in Kelvar."],
    "Idris Vane": [
        "Idris Vane is a botanist.", "Idris Vane was born in Kelvar.",
        "Idris Vane has written 8 books.",
        "Idris Vane works at Lumara Glassworks.",
        "Idris Vane won the Heron Prize in 1999.",
        "Idris Vane enjoys sailing.", "Idris Vane's mentor was Natara Lowe."],
    "Marenko Vott": [
        "Marenko Vott is an astronomer."],
    "Kelvar": [
        "Kelvar is a city known for its lighthouse.",
        "Kelvar has a population of about 310000.",
        "Kelvar is located in Ostrenia."],
}
# 4 shots, each: question, steps (thought, action); env gives obs
SHOTS = [
    ("In which year was the company that employs Torvin Hesk founded?", [
        ("I need the company that employs Torvin Hesk, then its "
         "founding year.",
         "Search[Torvin Hesk]"),
        ("Torvin Hesk works at Lumara Glassworks. Next I need its "
         "founding year.",
         "Search[Lumara Glassworks]"),
        ("It was founded in 1971 (the 1994 on the earlier page is a "
         "prize year, not relevant), so the answer is 1971.",
         "Finish[1971]")]),
    ("Which city was Maren Votcha born in?", [
        ("I need Maren Votcha's birth city.",
         "Search[Maren Votcha]"),
        ("There is no such page; the spelling may be off. "
         "'Maren Votsha' is the closest, so I search it.",
         "Search[Maren Votsha]"),
        ("This page does not mention a birthplace. I use Lookup to "
         "find 'born' on the page.",
         "Lookup[born]"),
        ("Maren Votsha was born in Kelvar, so the answer is Kelvar.",
         "Finish[Kelvar]")]),
    ("Which was founded earlier, Lumara Glassworks or Quenzo "
     "Instruments?", [
        ("I need the founding year of each company, then compare.",
         "Search[Lumara Glassworks]"),
        ("Lumara Glassworks was founded in 1971. Now Quenzo "
         "Instruments.",
         "Search[Quenzo Instruments]"),
        ("Quenzo Instruments was founded in 1983. 1971 is earlier "
         "than 1983, so Lumara Glassworks is earlier.",
         "Finish[Lumara Glassworks]")]),
    ("In which country was Idris Vane born?", [
        ("I need Idris Vane's birth city, then the country of that "
         "city.",
         "Search[Idris Vane]"),
        ("Idris Vane was born in Kelvar. Next I need the country "
         "of Kelvar.",
         "Search[Kelvar]"),
        ("Kelvar is located in Ostrenia, so the answer is Ostrenia.",
         "Finish[Ostrenia]")]),
]
TOOLS = (
    "Action is one of: Search[entity], which returns the first sentences of "
    "the page or, if there is none, similar titles; Lookup[keyword], which "
    "returns the next sentence of the current page that contains the "
    "keyword; Finish[answer], which gives the answer and ends the task.")
HEAD = dict(
    std="Answer the question.",
    act="Answer with Action and Observation steps only. " + TOOLS,
    react="Answer with interleaved Thought, Action, Observation steps. "
          "Thought reasons about the situation. " + TOOLS,
)
HEAD["cot"] = HEAD["std"]


def render_shot(method, q, steps):
    env, out = Wiki(EXW), f"{Q}: {q}\n"
    for i, (th, act) in enumerate(steps, 1):
        kind, obs = env.act(act)
        if method == "react":
            out += f"{T} {i}: {th}\n"
        if method in ("act", "react"):
            out += f"{A} {i}: {act}\n"
            out += f"{O} {i}: {obs}\n" if kind != "Finish" else ""
    if method == "cot":
        out += f"{T}: {' '.join(th for th, _ in steps)}\n"
    if method in ("std", "cot"):
        out += f"{ANS}: {obs}\n"  # last step is Finish: obs = answer
    return out + "\n"


def prefix_for(method):
    shots = "".join(render_shot(method, q, s) for q, s in SHOTS)
    return HEAD[method] + "\n\n" + shots


# --- Model and loop ---
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME, dtype=torch.float32).to(DEV)
CACHE = {}


def gen(method, text, max_new, stop):
    """Greedy decoding; the shots' KV cache is computed once"""
    pre = prefix_for(method)
    if method not in CACHE:
        ids = tok(pre, return_tensors="pt").input_ids.to(DEV)
        cache = DynamicCache()
        with torch.no_grad():
            model(input_ids=ids, past_key_values=cache, use_cache=True)
        CACHE[method] = (ids, cache)
    pids, pcache = CACHE[method]
    ids = tok(pre + text, return_tensors="pt").input_ids.to(DEV)
    assert torch.equal(ids[0, :pids.shape[1]], pids[0]), "prefix tokens moved"
    out = model.generate(
        input_ids=ids, attention_mask=torch.ones_like(ids),
        max_new_tokens=max_new, do_sample=False, temperature=None,
        top_p=None, top_k=None, past_key_values=copy.deepcopy(pcache),
        stop_strings=stop, tokenizer=tok)
    new = out[0, ids.shape[1]:]
    torch.mps.empty_cache()
    return tok.decode(new, skip_special_tokens=True), int(new.shape[0])


def norm(s):
    s = re.sub(r"\b(a|an|the)\b", " ", (s or "").lower())
    drop = string.punctuation + " "
    return " ".join("".join(c for c in s if c not in drop).split())


def closed_book(method, q):
    lead = f"{T}:" if method == "cot" else f"{ANS}:"
    txt, n = gen(method, f"{Q}: {q}\n{lead}", 120 if method == "cot" else 16,
                 ["\n\n", f"\n{Q}"])
    txt = txt.split(f"{ANS}:")[-1] if method == "cot" else txt
    return txt.strip().split("\n")[0], n, [txt.strip()]


def agent(method, q, env):
    """(Thought ->) Action -> Observation, until Finish or out of steps"""
    hist, toks, log = f"{Q}: {q}\n", 0, []
    for i in range(1, MAX_STEPS + 1):
        lead = f"{T} {i}:" if method == "react" else f"{A} {i}:"
        txt, n = gen(method, hist + lead, 150 if method == "react" else 48,
                     [f"\n{O}"])
        toks += n
        m = re.search(rf"{A} {i}:[ ]*([^\n]*)", lead + txt)
        act = m.group(1).strip() if m else ""
        thought = (lead + txt)[len(f"{T} {i}:"):m.start()].strip() if m else ""
        kind, obs = env.act(act)
        if kind == "Finish":
            log.append(f"{i} {thought} | {act}")
            return obs, toks, log
        log.append(f"{i} {thought} | {act} -> {obs}")
        hist += f"{T} {i}: {thought}\n" if method == "react" else ""
        hist += f"{A} {i}: {act}\n{O} {i}: {obs}\n"
    env.flags.add("no_finish")
    return None, toks, log


def run(method, item, world):
    t0, env = time.time(), Wiki(world["pages"])
    if method in ("std", "cot"):
        ans, toks, log = closed_book(method, item["q"])
    else:
        ans, toks, log = agent(method, item["q"], env)
    ok = norm(ans) == norm(item["gold"])
    why = ""
    if not ok and method in ("act", "react"):
        if ans is None:
            why = "no_finish"  # out of steps, no answer
        elif not {pg for pg, _ in item["need"]} <= set(env.visited):
            why = "unopened"  # a needed page never opened
        elif not {sen for _, sen in item["need"]} <= env.shown:
            why = "unseen"  # page opened, needed sentence never shown
        else:
            why = "misread"  # all evidence shown, answer still wrong
    # is a needed sentence beyond the first 5 (Lookup needed)
    hidden = any(s not in world["pages"][pg][:5] for pg, s in item["need"])
    return dict(method=method, kind=item["kind"], typo=item["typo"],
                hidden=hidden, q=item["q"], gold=item["gold"], ans=ans,
                ok=ok, calls=len(env.acts), toks=toks,
                flags=sorted(env.flags), why=why, log=log,
                secs=round(time.time() - t0, 1))


if __name__ == "__main__":
    seeds, runs, t_all = (1, 2), [], time.time()
    limit = int(sys.argv[1]) if len(sys.argv) > 1 else 36
    for seed in seeds:
        world = build_world(seed)
        for item in make_questions(world)[:limit]:
            for method in ("std", "cot", "act", "react"):
                runs.append(dict(run(method, item, world), world=seed))
            with open("react_runs.json", "w", encoding="utf-8") as f:
                json.dump(runs, f, ensure_ascii=False)
    print("Prompt prefix tokens: " + ", ".join(
        f"{k} {CACHE[k][0].shape[1]}" for k in ("std", "cot", "act", "react")))
    mins = (time.time() - t_all) / 60
    print(f"{len(runs)} answers in {mins:.0f} minutes")
    # determinism check: rerun ReAct, traces must be identical
    world = build_world(seeds[0])
    base = [r for r in runs if r["world"] == seeds[0]
            and r["method"] == "react"][:4]
    again = [run("react", it, world) for it in make_questions(world)[:4]]
    same = sum(a["log"] == b["log"] for a, b in zip(base, again))
    print(f"Determinism check: {len(base)} questions rerun, "
          f"{same} identical traces")

Output at the end of the run:

Prompt prefix tokens: std 89, cot 368, act 764, react 1096
288 answers in 53 minutes
Determinism check: 4 questions rerun, 4 identical traces
Full code (about 193 lines): statistics script
"""Statistics of react_runs.json: accuracy, cost and failure types"""
import json
import math
from collections import Counter

runs = json.load(open("react_runs.json", encoding="utf-8"))
METHODS = ("std", "cot", "act", "react")
LABEL = dict(std="Standard", cot="CoT", act="Act", react="ReAct")
T, A, O = ("Thought", "Action", "Obs")
GOLD, MODEL = ("gold", "model")


def pick(m, f=lambda r: True):
    return [r for r in runs if r["method"] == m and f(r)]


def score(rows):
    return sum(r["ok"] for r in rows), len(rows)


def wilson(k, n, z=1.96):
    """Wilson 95% interval (in %)"""
    p, d = k / n, 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return 100 * (c - h), 100 * (c + h)


def show(rows):
    k, n = score(rows)
    return f"{k}/{n}" if n else "-"


N = len(pick("std"))
print(f"1. Accuracy (exact match), {N} questions")
print(f"   {'':<10}{'all':>9}{'95% CI':>12}{'world 1':>9}{'world 2':>9}")
for m in METHODS:
    k, n = score(pick(m))
    lo, hi = wilson(k, n)
    w = [show(pick(m, lambda r: r["world"] == i)) for i in (1, 2)]
    print(f"   {LABEL[m]:<10}{k:>3}/{n} {100 * k / n:4.1f}%"
          f"  [{lo:3.0f},{hi:3.0f}]{w[0]:>9}{w[1]:>9}")



def first_word(ans):
    """yes/no questions: judge by the first word of the answer"""
    a = (ans or "").strip().lower()
    w = a.replace(",", " ").replace(".", " ").split()[:1]
    return {"no": "no", "not": "no", "yes": "yes"}.get(w[0], a) if w else a


YN = ("yes", "no")
print("\n   Lenient re-grade: for yes/no questions only the first word counts")
for m in ("act", "react"):
    rows = pick(m)
    lenient = [r["ok"] or (r["gold"] in YN
                           and first_word(r["ans"]) == r["gold"])
               for r in rows]
    changed = sum(a and not r["ok"] for a, r in zip(lenient, rows))
    print(f"   {LABEL[m]:<10}{sum(lenient):>3}/{len(rows)}"
          + f", answers re-graded: {changed}")

print("\n2. By question type (correct/total)")
KINDS = {1: "1 hop", 2: "2 hops", 3: "3 hops", 4: "compare"}
print("   " + " " * 10 + "".join(f"{v:>9}" for v in KINDS.values()))
for m in METHODS:
    cells = [show(pick(m, lambda r: r["kind"] == k)) for k in KINDS]
    print(f"   {LABEL[m]:<10}" + "".join(f"{c:>9}" for c in cells))

print("\n3. By question property (correct/total)")
PROPS = [("typo in name", lambda r: r["typo"]),
         ("name correct", lambda r: not r["typo"]),
         ("Lookup needed", lambda r: r["hidden"]),
         ("no Lookup needed", lambda r: not r["hidden"])]
print(f"   {'':<18}{'Act':>8}{'ReAct':>8}")
for name, f in PROPS:
    print(f"   {name:<{18 - sum(ord(c) > 0x2e80 for c in name)}}"
          f"{show(pick('act', f)):>8}{show(pick('react', f)):>8}")

print("\n4. Cost (mean per question)")
print(f"   {'':<10}{'tool calls':>11}{'new tokens':>12}{'seconds':>9}")
for m in METHODS:
    rows = pick(m)
    mean = lambda key: sum(r[key] for r in rows) / len(rows)
    print(f"   {LABEL[m]:<10}{mean('calls'):>11.1f}{mean('toks'):>12.1f}"
          f"{mean('secs'):>9.1f}")

print("\n5. Why Act and ReAct failed, and behavior flags (questions)")
print("   First four columns: wrong answers only; flags count all questions")
WHY = ("no_finish", "unopened", "unseen", "misread")
print(f"   {'':<10}" + "".join(f"{w:>10}" for w in WHY)
      + f"{'loop':>6}{'miss':>6}{'invalid':>9}")
for m in ("act", "react"):
    rows = pick(m)
    why = Counter(r["why"] for r in rows if not r["ok"])
    flags = Counter(f for r in rows for f in r["flags"])
    print(f"   {LABEL[m]:<10}" + "".join(f"{why[w]:>10}" for w in WHY)
          + f"{flags['loop']:>6}{flags['miss']:>6}{flags['invalid']:>9}")

print("\n6. Use of Lookup")
print("   used / correct: Lookup-needing questions that used it / got it right")
print("   calls / empty: all Lookup calls and those with no result")
print(f"   {'':<10}{'used':>8}{'correct':>9}{'calls':>7}{'empty':>7}")
EMPTY = "No more results"
for m in ("act", "react"):
    hid = pick(m, lambda r: r["hidden"])
    used = [r for r in hid if any("Lookup[" in x for x in r["log"])]
    calls = [x for r in pick(m) for x in r["log"] if "Lookup[" in x]
    empty = [x for x in calls if EMPTY in x]
    right = sum(r["ok"] for r in used)
    print(f"   {LABEL[m]:<10}{len(used):>4}/{len(hid)}{right:>9}"
          f"{len(calls):>7}{len(empty):>7}")

print("\n7. Act vs ReAct, paired per question")
act = {(r["world"], r["q"]): r["ok"] for r in pick("act")}
rea = {(r["world"], r["q"]): r["ok"] for r in pick("react")}
both = sum(act[k] and rea[k] for k in act)
only_rea = sum(rea[k] and not act[k] for k in act)
only_act = sum(act[k] and not rea[k] for k in act)
n_diff = only_rea + only_act
tail = sum(math.comb(n_diff, i) for i in range(min(only_rea, only_act) + 1))
p_val = min(1.0, 2 * tail / 2 ** n_diff) if n_diff else 1.0
print(f"   both right {both}, only ReAct {only_rea}, only Act {only_act}, "
      f"neither {len(act) - both - n_diff}")
print(f"   two-sided exact sign test: p = {p_val:.3f}")
by = {m: {(r["world"], r["q"]): r for r in pick(m)} for m in ("act", "react")}
for tag, win, lose in (
        ("only ReAct right", "react", "act"),
        ("only Act right", "act", "react")):
    ks = [k for k in act if by[win][k]["ok"] and not by[lose][k]["ok"]]
    kinds = Counter(by[win][k]["kind"] for k in ks)
    why = Counter(by[lose][k]["why"] for k in ks)
    hid = sum(by[win][k]["hidden"] for k in ks)
    print(f"   {tag} ({len(ks)}): "
          + ", ".join(f"{KINDS[i]} {kinds[i]}" for i in KINDS)
          + f"; needed sentence beyond the first 5: {hid}")
    print("      Failure type of the loser: "
          + ", ".join(f"{w} {why[w]}" for w in WHY))


def steps(log):
    """split a log into (thought, action, observation)"""
    out = []
    for line in log:
        _, rest = line.split(" ", 1)
        thought, rest = rest.split(" | ", 1)
        act, _, obs = rest.partition(" -> ")
        out.append((thought, act, obs))
    return out


def trace(title, r):
    print(f"\n   [{title}] {r['q']}")
    print(f"   {GOLD}: {r['gold']} | {MODEL}: {r['ans']}")
    for i, (th, a, ob) in enumerate(steps(r["log"]), 1):
        if th:
            print(f"   {T} {i}: {th}")
        print(f"   {A} {i}: {a}")
        if ob:
            print(f"   {O} {i}: {ob[:80]}" + ("..." if len(ob) > 80 else ""))


print("\n8. Traces (first match by a fixed rule, not hand-picked)")
first = lambda rows: next(iter(rows), None)
react = pick("react")
ok3 = first([r for r in react if r["ok"] and r["kind"] == 3 and r["hidden"]])
bad = {w: first([r for r in react if not r["ok"] and r["why"] == w])
       for w in WHY}
if ok3:
    trace("ReAct success: 3 hops, Lookup needed", ok3)
for w in ("unseen", "misread", "no_finish"):
    if bad[w]:
        trace(f"ReAct, {w}", bad[w])
for w in ("unopened", "unseen"):
    act_bad = first([r for r in pick("act")
                     if not r["ok"] and r["why"] == w])
    if act_bad:
        trace(f"Act, {w}", act_bad)


print("\n9. Names that exist only in the examples, written by the model itself")
EXAMPLE_ONLY = ("Torvin Hesk", "Lumara Glassworks", "Quenzo Instruments",
                "Maren Votsha", "Idris Vane", "Marenko Vott", "Kelvar",
                "Ostrenia", "Dovrek", "Natara Lowe", "Maren Votcha")
for m in ("act", "react"):
    rows = pick(m)
    leaky = [r for r in rows
             if any(n in f"{t} {a}" for t, a, _ in steps(r["log"])
                    for n in EXAMPLE_ONLY)]
    wrong = sum(not r["ok"] for r in leaky)
    frac = f"{len(leaky)}/{len(rows)}"
    print(f"   {LABEL[m]:<10}" + f"{frac} questions, {wrong} of them wrong")

Output of the statistics script (the traces in section 8 are the first of each kind by a fixed rule, not hand-picked):

1. Accuracy (exact match), 72 questions
                   all      95% CI  world 1  world 2
   Standard    9/72 12.5%  [  7, 22]     5/36     4/36
   CoT         9/72 12.5%  [  7, 22]     4/36     5/36
   Act        44/72 61.1%  [ 50, 72]    23/36    21/36
   ReAct      48/72 66.7%  [ 55, 76]    26/36    22/36

   Lenient re-grade: for yes/no questions only the first word counts
   Act        44/72, answers re-graded: 0
   ReAct      48/72, answers re-graded: 0

2. By question type (correct/total)
                 1 hop   2 hops   3 hops  compare
   Standard       0/18     0/18     0/18     9/18
   CoT            0/18     0/18     0/18     9/18
   Act           18/18     8/18     3/18    15/18
   ReAct         15/18    11/18     8/18    14/18

3. By question property (correct/total)
                          Act   ReAct
   typo in name          8/12   11/12
   name correct         36/60   37/60
   Lookup needed        13/34   10/34
   no Lookup needed     31/38   38/38

4. Cost (mean per question)
              tool calls  new tokens  seconds
   Standard          0.0         4.5      1.0
   CoT               0.0        69.7      5.6
   Act               2.4        66.8      8.2
   ReAct             3.3       258.4     29.7

5. Why Act and ReAct failed, and behavior flags (questions)
   First four columns: wrong answers only; flags count all questions
              no_finish  unopened    unseen   misread  loop  miss  invalid
   Act                0        21         7         0     1    13        0
   ReAct              8         8         8         0    16    26        5

6. Use of Lookup
   used / correct: Lookup-needing questions that used it / got it right
   calls / empty: all Lookup calls and those with no result
                 used  correct  calls  empty
   Act         23/34       11     27      7
   ReAct       28/34       10     47     15

7. Act vs ReAct, paired per question
   both right 39, only ReAct 9, only Act 5, neither 19
   two-sided exact sign test: p = 0.424
   only ReAct right (9): 1 hop 0, 2 hops 3, 3 hops 6, compare 0; needed sentence beyond the first 5: 2
      Failure type of the loser: no_finish 0, unopened 9, unseen 0, misread 0
   only Act right (5): 1 hop 3, 2 hops 0, 3 hops 1, compare 1; needed sentence beyond the first 5: 5
      Failure type of the loser: no_finish 0, unopened 1, unseen 4, misread 0

8. Traces (first match by a fixed rule, not hand-picked)

   [ReAct success: 3 hops, Lookup needed] In which country is the headquarters of the company that employs Morbre Vorn?
   gold: Mirpestaria | model: Mirpestaria
   Thought 1: I need the company that employs Morbre Vorn, then its headquarters country.
   Action 1: Search[Morbre Vorn]
   Obs 1: Morbre Vorn is a ceramicist. Morbre Vorn works at Mirzor Shipping. Morbre Vorn e...
   Thought 2: Morbre Vorn works at Mirzor Shipping. Now find the headquarters of Mirzor Shipping.
   Action 2: Search[Mirzor Shipping]
   Obs 2: Mirzor Shipping is a company in the Shipping business. Mirzor Shipping was found...
   Thought 3: The headquarters country is not directly stated. I need to find the headquarters city, then the country.
   Action 3: Lookup[headquarters]
   Obs 3: (Result 1/1) Mirzor Shipping has its headquarters in Lutarmir.
   Thought 4: Lutarmir is the headquarters city. Now find the country of Lutarmir.
   Action 4: Search[Lutarmir]
   Obs 4: Lutarmir is a city known for its lighthouse. Lutarmir has a population of about ...
   Thought 5: Lutarmir is located in Mirpestaria, so the answer is Mirpestaria.
   Action 5: Finish[Mirpestaria]

   [ReAct, unseen] Which company does Falqui Ondu work at?
   gold: Luos Instruments | model: Unknown
   Thought 1: I need to find the company that employs Falqui Ondu.
   Action 1: Search[Falqui Ondu]
   Obs 1: Falqui Ondu is a botanist. Falqui Ondu has written 3 books. Falqui Ondu was born...
   Thought 2: No mention of the company. Try searching for Velfal Ondu, his mentor.
   Action 2: Search[Velfal Ondu]
   Obs 2: Velfal Ondu is a botanist. Velfal Ondu enjoys hiking. Velfal Ondu won the Ginkgo...
   Thought 3: Still no mention of the company. Maybe search for the city where Falqui Ondu was born, Vennovzor.
   Action 3: Search[Vennovzor]
   Obs 3: Vennovzor is a city known for its lighthouse. Vennovzor is located in Kakabaia. ...
   Thought 4: No company mentioned. Maybe search for Kakabaia, the country of Vennovzor.
   Action 4: Search[Kakabaia]
   Obs 4: Kakabaia is located in a far-off continent. The capital of Kakabaia is Ospesnov.
   Thought 5: No company found. Maybe Falqui Ondu is not mentioned in the data. The answer is unknown.
   Action 5: Finish[Unknown]

   [ReAct, no_finish] In which year was the company that employs Nisvel Quist founded?
   gold: 1982 | model: None
   Thought 1: I need the company that employs Nisvel Quist, then its founding year.
   Action 1: Search[Nisvel Quist]
   Obs 1: Nisvel Quist is a composer. Nisvel Quist was born in Osmirzor. Nisvel Quist enjo...
   Thought 2: No mention of company. Search for Nisvel Quist's company.
   Action 2: Search[Nisvel Quist's company]
   Obs 2: Could not find [Nisvel Quist's company]. Similar: ['Nisvel Quist', 'Brevel Quist...
   Thought 3: No page found. Maybe the name is misspelled. 'Brevel Quist' is the closest, so I search it.
   Action 3: Search[Brevel Quist]
   Obs 3: Brevel Quist is a ceramicist. Brevel Quist was born in Lubaos. Brevel Quist's me...
   Thought 4: No mention of company. Maybe the name is misspelled again. 'Dalnis Quist' is the next closest.
   Action 4: Search[Dalnis Quist]
   Obs 4: Dalnis Quist is a geologist. Dalnis Quist's mentor was Dalfal Senk. Dalnis Quist...
   Thought 5: Still no company. Maybe the original name is correct, but no info. Alternatively, maybe the company is Quenzo Instruments, which employs Maren Votsha. But that's a guess. Alternatively, maybe the company is Lumara Glassworks, which employs Torvin Hesk. But that's a guess. Alternatively, maybe the company is not mentioned, so I can't answer. But the question says the company exists. Maybe I need to search for the company that employs Nisvel Quist again, but I don't have the name. Alternatively, maybe the answer is that it's not available. But the question implies it's known. Maybe I made a mistake in the search. Let me try again.
   Action 5: 
   Obs 5: Invalid action. Use Search[...], Lookup[...] or Finish[...].
   Action 6: 
   Obs 6: Invalid action. Use Search[...], Lookup[...] or Finish[...].
   Action 7: 
   Obs 7: Invalid action. Use Search[...], Lookup[...] or Finish[...].

   [Act, unopened] In which country was Morfall Lek born?
   gold: Mirpestaria | model: Lutarmir
   Action 1: Search[Morfall Lek]
   Obs 1: Could not find [Morfall Lek]. Similar: ['Morfal Lek', 'Morbre Lek', 'Morfal Mari...
   Action 2: Search[Morfal Lek]
   Obs 2: Morfal Lek is a botanist. Morfal Lek has written 8 books. Morfal Lek enjoys gard...
   Action 3: Lookup[born]
   Obs 3: (Result 1/1) Morfal Lek was born in Lutarmir.
   Action 4: Finish[Lutarmir]

   [Act, unseen] Who founded the company that employs Korzen Dray?
   gold: Nisnis Ondu | model: Idris Vane
   Action 1: Search[Korzen Dray]
   Obs 1: Korzen Dray is a botanist. Korzen Dray enjoys chess. Korzen Dray won the Starfie...
   Action 2: Search[Venba Instruments]
   Obs 2: Venba Instruments is a company in the Instruments business. Venba Instruments wa...
   Action 3: Finish[Idris Vane]

9. Names that exist only in the examples, written by the model itself
   Act       3/72 questions, 3 of them wrong
   ReAct     7/72 questions, 7 of them wrong

Results

Accuracy of the four prompting styles by question type Grouped bar chart: the x axis is the question type, each group has four bars for Standard, CoT, Act-only and ReAct, and the y axis is accuracy. 0% 25% 50% 75% 100% 0/18 0/18 18/18 15/18 1 hop 0/18 0/18 8/18 11/18 2 hops 0/18 0/18 3/18 8/18 3 hops 9/18 9/18 15/18 14/18 compare Standard CoT Act ReAct
Figure 3: In the replication of this post, the number of correct answers by question type (two worlds combined, 18 questions per type). The label on each bar is correct/total.
  • Overall (section 1). Standard and CoT answer 9 of 72 questions each (12.5%), all of them among the 18 two-way comparison questions, where guessing gets 9 right; the 0/18 on 1- to 3-hop questions is what the design predicts, since the names are invented and the parameters hold no answer. Act gets 44 right (61.1%) and ReAct 48 (66.7%). Question by question (section 7), both are right on 39, only ReAct on 9 and only Act on 5; the two-sided sign test gives p = 0.424. A gap of four questions is well within what chance produces here, and the Wilson 95% intervals (50 to 72 and 55 to 76 percent) overlap almost completely.
  • The two worlds agree on direction only. ReAct is ahead by 3 in world 1 (26 against 23) and by 1 in world 2 (22 against 21). Within a world the same person or company appears in several questions, so the 72 questions are not independent, and the p value, if anything, flatters the result.
  • Where the difference lies (sections 2 and 3). By hops, 1 hop: Act 18/18, ReAct 15/18; 2 hops: 8 against 11; 3 hops: 3 against 8; comparisons: 15 against 14. ReAct is ahead only on the multi-hop questions (19 against 11 right out of 36) and behind on the 1-hop ones. By property, on the 38 questions that need no Lookup ReAct gets all 38 right and Act 31; on the 34 that do, ReAct gets 10 and Act 13. The 12 questions with a typo in the name split 11 for ReAct and 8 for Act: too few to interpret.
  • Why Act loses on multi-hop questions (sections 5 and 7). Of Act’s 28 wrong answers, 21 came before it opened a page it needed (unopened) and 7 after opening it, with the needed sentence never appearing (unseen); none ran out of steps and none misread something it had seen. The typical failure is stopping one hop early: asked in which country Morfall Lek was born, Act finds the birth city with Lookup and writes Finish[Lutarmir], the city, without opening the city page (the fourth trace in section 8). Among the 9 questions only ReAct got right, Act had stopped before opening a needed page in all 9 (6 are 3-hop and 3 are 2-hop questions), and only 2 of the 9 needed a Lookup. Act’s own examples include 2-hop questions, so it is not that Act has never seen a second hop. In ReAct the thought after each observation says what is still missing (“Lutarmir is the headquarters city. Now find the country of Lutarmir.”), and the first trace in section 8 shows how this carries the model through three hops. That the thoughts are what prevents the early stop is the reading that fits these traces; this experiment has no control that isolates it.
  • Why ReAct does not win on questions that need Lookup (sections 5, 6 and 7). ReAct’s 24 wrong answers split into 8 no_finish, 8 unopened and 8 unseen. Among the 5 questions only Act got right, all 5 needed a Lookup, and ReAct failed 4 of them with unseen. The second trace in section 8 shows how: asked for Falqui Ondu’s employer, the thought after the first page reads “No mention of the company. Try searching for Velfal Ondu, his mentor.”, and the following steps visit the mentor, the birth city and the country before Finish[Unknown]; it never issues a Lookup on the page that held the sentence. The thought treats the five sentences it was shown as the whole page and moves on. ReAct used Lookup on 28 of the 34 questions that need it and Act on 23, yet of those 28 ReAct runs 10 ended right, against 11 of Act’s 23. Of ReAct’s 47 Lookup calls 15 returned no result, against 7 of Act’s 27: the keyword came from the words of the question while the page used other words.
  • Loops, misses and invalid actions (section 5). In 16 of 72 ReAct runs an action was repeated, 26 searched for a title that does not exist and 5 produced an invalid action; for Act the counts are 1, 13 and 0. The misses are mostly invented queries. In the third trace in section 8, asked for the founding year of Nisvel Quist’s employer, the model searches Nisvel Quist's company, gets “Could not find”, walks through similar names (Brevel Quist, Dalnis Quist) and then writes a thought of 146 tokens that lists guesses and uses up almost the whole 150-token budget of the step; no action text fits after it, so the action is empty, which is invalid, and so are the next two. Of the 5 invalid runs, 3 wrote free text where an action belongs and 2 produced an empty action (this one and one other). The paper’s failure analysis has the same two classes, repetitive loops and searches that return nothing useful; the cause is clearer here: Lookup and Search keywords come from the question’s wording and the page does not use it.
  • Names from the examples turn up in guesses (section 9). 7 of 72 ReAct runs and 3 of 72 Act runs write a name that exists only in the prompt’s examples (such as Quenzo Instruments or Ostrenia), and all 10 of those runs answer wrongly. In the third trace the model labels its own guesses (“But that’s a guess”) and does not answer with them, but the last trace in section 8 ends with Act answering Finish[Idris Vane], the founder in the prompt’s example. This is the hallucination class of the paper’s Table 2 turning up inside ReAct and Act: once a retrieval step is skipped or fails, the content is invented, and the examples are what the model has seen.
  • The grader (section 1, lenient re-grade). The answers to the yes/no questions could have been written in other ways, so I added a row in which only the first word of a yes/no answer counts. It changes none of the answers in this run, and the main table stands (Act 44/72, ReAct 48/72).
  • Cost (section 4). ReAct makes 3.3 tool calls per question on average and generates 258.4 new tokens, against 2.4 calls and 66.8 tokens for Act; with the longest prefix as well (1,096 tokens against 764), it needs 29.7 seconds per question on this machine against 8.2. The seconds depend on this machine, and the token counts depend on how long the model’s thoughts run.

What this experiment can and cannot say

  • It can say: with answers that can only be retrieved, Act and ReAct are not distinguishable in total accuracy here (48 against 44 of 72, p = 0.424), but their paths differ: ReAct goes on to the next hop where Act stops early, and it gives up on a page after its first five sentences where the answer sits further down. The failure types agree with the paper’s analysis: loops, searches that return nothing useful, and invented content (here, names taken from the examples).
  • It cannot say: that ReAct is no better than Act. The paper’s own HotpotQA gap (27.4 against 25.7) is also small, and the same experiment run with Chinese prompts on a Chinese fictional wiki (a separate run with its own numbers) found ReAct 14 questions ahead (50 against 36) and found that gain on the questions that need Lookup (19 right out of 37 against Act’s 10), which is the opposite of where the gain sits here. Nor can it say how large the gap is in the paper’s setting, since I closed the route through the parameters here and the pages are template sentences.
  • Scale: 72 questions, one 4B model, two worlds, four examples, one set of prompts. In the paper’s Table 3, ReAct’s success rate on ALFWorld moves from 48% to 71% across six sets of prompts, so the choice of prompts can matter more than the method, and I changed none. Two versions of this experiment that differ only in the prompt language and the invented names gave gaps of 4 and 14 questions; that spread is a better estimate of the noise than any p value above.
  • A simplified environment: pages are template sentences with no ambiguity, synonyms, noise or stale facts, and Lookup is a literal match, stiffer than real retrieval and more predictable than real pages.
  • Greedy decoding and token caps: the paper suspects that loops are related to greedy decoding; I did not try sampling, so I cannot tell whether a loop comes from the prompt or from the decoding. One of the five invalid runs follows a thought of 146 tokens that left no room for an action inside the cap of 150, a setting I did not vary.

Limits and what came after

The paper’s own admitted limits: with prompting only, ReAct is the hardest for small models (at 8B and 62B it is the worst of the four prompts and becomes the best only after fine-tuning), the quality of retrieval caps what it can do, and on HotpotQA it is behind chain of thought. The paper’s conclusion stops there: hybrid methods and fine-tuning are the way out it offers, and more human-annotated data may be a better one.

The recomputation above adds a few more: the paper gives neither the size of the evaluation sets nor the number of runs for the PaLM experiments, and Table 1 has no error bars, so gaps of one or two points cannot be judged; the “best of” rows of Table 3 are per-task maxima, not the result of a single trial; and Table 5 and Table 1 differ by 2.0 for the same method, which the paper does not explain.

Later work changed where this paper sits:

  • Tool use is no longer only prompting. The self-supervised method of Toolformer lets a model learn from data when to call a tool; today’s models are trained to make function calls directly and express actions through structured interfaces (see Structured output and function calling).
  • Thinking was trained into the model. Reasoning models have a thinking phase of their own, and tool calls can occur inside it, so “think before acting” no longer has to be taught by the format of the examples (see Reinforcement learning for reasoning).
  • Reflection after failure. Reflexion (arXiv 2303.11366) has the agent write a verbal reflection after a failure and puts it in the context of the next attempt, which targets exactly ReAct’s loops and useless searches.
  • Evaluation. A single success rate is not enough; agent evaluation cares about stability and trajectories (see pass^k and trajectory evaluation in Agents and tool calling).

What to take away from this paper

  1. Thought is one extra cell in the action space. The whole change of ReAct is to widen the action space to “actions plus language”: a thought does not change the environment, only the context, and is used to plan, track state and handle exceptions.
  2. Run the controls separately. The paper removes the thoughts (Act), removes the actions (CoT) and replaces the thoughts with a restatement of environment feedback (ReAct-IM); the replication here also varies one thing, whether there are thoughts. With a single total score you cannot see what the thoughts changed.
  3. ReAct is not better everywhere. On HotpotQA it loses to chain of thought, and the paper’s answer is hybrids and fine-tuning. When you evaluate a prompting method, first ask whether its failure modes are ones you can live with.
  4. Failure modes carry more information than the total. CoT fails by hallucinating, ReAct by looping and being led astray by useless searches, Act by stopping early; the small experiment saw all three, and also ReAct guessing names it had only seen in the examples.
  5. Keep error bars in mind. Table 1 has none; in the 72 questions here each question is one seventy-second of the score, and the same experiment run in two languages gave a gap of 4 questions and a gap of 14. Differences smaller than the noise should not be interpreted, and the spread between two reasonable versions of an experiment is often larger than the spread between methods.

Further reading

FAQ

What is ReAct, and how is it different from chain-of-thought prompting?
ReAct (Reasoning and Acting) treats thinking as one more kind of action: the model alternates between thoughts, actions that call a tool (such as search and in-page lookup) and observations returned by the environment. A thought changes nothing outside the context; it only helps the next step. Chain of thought has reasoning but no actions, so it relies entirely on what the parameters remember, and once a fact is misremembered every later step builds on it. In the paper's PaLM-540B results ReAct beats CoT on fact checking (Fever 60.9 against 56.3) and trails it slightly on multi-hop QA (HotpotQA 27.4 against 29.4); a hybrid of the two is best.
Is ReAct always better than chain of thought?
No. In the paper's own HotpotQA numbers ReAct's exact match (27.4) is below CoT's (29.4): the interleaved structure makes reasoning less flexible, and a useless search result can send it into a loop of repeating the same thought and action. The best results in the paper come from hybrids that fall back on each other (ReAct to CoT-SC gets 35.1 on HotpotQA, CoT-SC to ReAct gets 64.6 on Fever) and from ReAct fine-tuned on 3,000 trajectories.
What does a ReAct prompt look like, and does it need fine-tuning?
In the main setting no fine-tuning is needed. Each example is a complete trajectory: the question, then thought i, action i and observation i repeated, ending with Finish[answer]. Actions have a fixed format (on HotpotQA: Search[entity], Lookup[keyword], Finish[answer]), observations are filled in by the environment, and the thoughts in the examples are plain language written by the annotators. The paper gives a frozen PaLM-540B one to six such human-written examples; fine-tuning is a separate experiment, in which PaLM-8B and 62B are trained on 3,000 trajectories that ended in a correct answer.
How does ReAct typically fail?
In the paper's human labels, ReAct's failures are mostly reasoning errors (47%, including loops that repeat the same thought and action) and searches that return nothing useful (23%), while CoT's are mostly hallucinations (56%). The small experiment in this post (Qwen3-4B on an invented wiki, 72 questions) shows the same kinds of failure: in 16 of 72 ReAct runs an action was repeated, 26 runs searched for a title that does not exist, and in 7 runs the model wrote names that exist only in the prompt's examples.
How does ReAct relate to function calling and today's agents?
The ReAct loop (the model decides the next step, the environment executes it and returns an observation, the observation goes into the context, the model decides again) is the smallest form of almost every agent loop today. Current models express actions through a function-calling interface, reasoning models have a built-in thinking phase, and tool use is often trained into the model rather than taught by a prompt; the alternating structure of thought, action and observation has not changed.