ReAct and reasoning with actions
ReAct is a way to run a language model as an agent that thinks between its actions. Before each tool call, the model writes a short note to itself, called a thought. After each call, it reads the result, called an observation, before it thinks again. A thought is plain text that no tool runs. It holds the plan and the facts found so far. Almost every agent you will build or be asked about in an interview, from a search assistant to a coding agent, runs some version of this cycle of thought, action, and observation.
The idea matters because the two simpler designs fail in opposite ways. Take a question that needs two facts in a row, such as the city where the architect of some library was born. A model that only reasons writes a fluent chain of steps from what its weights remember, the chain of thought of §18.1. If one of the two facts is missing from its memory, it fills the gap with something plausible, and nothing in the chain can notice. A model that only acts calls a search tool at every turn with no reasoning in between. It fetches true facts. Then, with no plan written down anywhere, it answers with the first fact and forgets that it needed a second.
Yao et al. (2023) named the method ReAct, for reasoning plus acting, and measured both failures on HotpotQA, a benchmark of questions that each need two Wikipedia facts combined. Among the chain-of-thought runs that failed, 56% failed because the model made up a fact or a reasoning step. Interleaving thoughts with searches brought that share to 0%. It left failures of a new kind. Of ReAct's failures, 47% were reasoning errors, many of them loops that repeat an earlier thought and action, and 23% were searches that returned nothing useful.
This section builds on the agent loop of §24.1, so here it is in brief. The model writes text, and a parser pulls an action out of it. The environment, everything outside the model that the agent acts on, runs the action and returns an observation as text. The loop repeats until the model writes a final answer or a step budget, a cap on the number of turns, runs out. Every token of the finished episode is tagged by who wrote it with a source mask , which is 1 for a token the model sampled and 0 for a token that the prompt or the world supplied. §24.2 made the parsed action reliable.
Here we answer two questions. What should the model write besides the action? And how is a model trained to act well? The first half is about running agents. We define ReAct precisely, build one from scratch with error recovery and loop detection, follow one task through it token by token, and measure in a small simulation what thoughts and actions each contribute. The second half is about training. A model can label its own text with useful tool calls, it can imitate good episodes, and it can learn from its own episodes by reinforcement learning. There we prove the fact that every agent-training system rests on. Tokens written by the environment carry no learning signal for the model, and putting them in the loss teaches the model to expect whatever tool results came with success. We end with the decision an agent makes at every turn, whether a tool call is worth its cost.
Three ways to answer one question
Here is a small world to reason about, five encyclopedia pages invented for this section. There is one tool, search[entity]. It returns the first five sentences of the page whose title is exactly entity. If no title matches, it returns up to five similar titles instead. That is the Wikipedia search interface ReAct used. ReAct's agent had two more actions, lookup[keyword], which returns the next sentence of the current page that contains the keyword, and finish[answer], which ends the episode with an answer.
Vela Library (Tarsko) The Vela Library is a public library in Tarsko. It was designed by the
architect Ines Moreau and opened in 1998.
Ines Moreau Ines Moreau is an architect known for libraries and museums. She was born
in Quebec City in 1961.
Tarsko Tarsko is a port town known for its shipyards.
Moreau Bridge The Moreau Bridge is a steel bridge in Lyon, opened in 1907.
Quebec City Quebec City is the capital of the province of Quebec, in Canada.
The widget steps through these traces, plus a fourth in which ReAct repeats a failed search until a loop detector stops it. Press Play or move the slider to reveal one step at a time, and watch where an error enters. The switch on the right, who wrote each token, boxes every token of the context and colors green the ones the model wrote. Only those tokens are trained, as the second half of this section proves.
The pattern is short enough to memorize. A thought changes only the context. An action changes the world, or at least queries it. An observation brings the world back into the context. Chain of thought has only thoughts, so it reasons well from premises that may be false. The act-only agent has actions and observations, so it gets true premises and reasons poorly about them. ReAct has all three. That is the one-paragraph answer to the interview question "why does ReAct work?"
A thought is an action that only changes the context
ReAct's authors state the idea as a change to what the model may do at each step. Besides the environment's actions, the model may now write any string at all, and such a string does nothing except sit in the context. The training half of this section depends on knowing exactly which text counts as what, so here is the precise statement. A policy is the rule that picks the next step given everything so far, here the language model with parameters .
In plain words, a thought is an action whose only effect is on what the agent reads next.
The model writes both the thoughts and the actions, so both have , and observations have . A trained ReAct model therefore learns to write thoughts in the same way it learns to write actions.
Why a thought helps
Writing a thought helps for two different reasons. The first is computation. A Transformer does a fixed amount of work for each token it writes, so every extra token buys another pass through the network (§18.1). A thought spends that work on the decision at hand, for example on pulling the name "Ines Moreau" out of a page before choosing the next query.
The second reason is memory. The context is the agent's only record of the episode. An observation is long, noisy, and about the world rather than about the task. A thought writes down the plan and the facts that matter in a few tokens, so later turns read them instead of re-deriving them from raw pages. The act-only trace above failed for lack of memory, not of computation.
Observations do the opposite job. They replace a recalled fact, which can be wrong with no warning, by a fetched fact, which is wrong only when its source is. That is why made-up facts vanished from ReAct's failures. It is also why ReAct depends on something new, the quality of its tools. An interviewer who asks "what does a thought buy you that a longer prompt does not?" wants these two answers, computation spent on the current decision and a short written memory of the plan.
What ReAct measured
ReAct prompted PaLM-540B, a 540-billion-parameter language model from Google, with a few hand-written example trajectories in the prompt. That is few-shot prompting, and the model's weights were never changed. HotpotQA got 6 examples and FEVER got 3, because more examples did not help. FEVER asks whether a claim is supported, refuted, or not decidable from Wikipedia. Every baseline used prompts built from the same example trajectories with parts removed.
- Standard removes thoughts, actions, and observations, so the model answers at once.
- CoT (chain of thought) removes actions and observations, so the model reasons and then answers.
- CoT-SC samples 21 chains of thought at temperature 0.7 and takes the majority answer. This is the self-consistency of §18.2.
- Act removes the thoughts.
HotpotQA is scored by exact match, the share of answers equal to the reference string after light normalization such as lower-casing.
ReAct alone losing to chain of thought on HotpotQA is the result interviewers ask about, and the paper's error analysis explains it. The authors drew 50 correct and 50 incorrect trajectories from each of ReAct and CoT, 200 in all, and labeled each one by hand.
| ReAct | CoT | ||
|---|---|---|---|
| success | correct reasoning and facts | 94% | 86% |
| right answer from made-up reasoning or facts | 6% | 14% | |
| failure | reasoning error, including loops | 47% | 16% |
| search returned nothing useful | 23% | none | |
| made-up fact or step | 0% | 56% | |
| right answer that did not match the label exactly | 29% | 28% |
Read the two columns as two different machines. CoT reasons freely and invents facts. ReAct reasons under a constraint, since every thought must lead to an action and every result must be read. Its facts are grounded, but its reasoning is less flexible. Its signature failure is to repeat its previous thought and action and never leave the loop. An uninformative search also derails it badly, because the next thought has nothing to work with. The two machines fail on different questions, which is why combining them works.
Each rule uses a cheap signal that one method is failing, running out of steps or a split vote, to hand the question to the other method. With these rules, ReAct plus CoT-SC matched the accuracy of 21-sample CoT-SC while drawing only 3 to 5 samples. In practice this is the first design lesson of agents. Pair a method that grounds facts with a method that reasons freely, and route between them on a signal you can observe.
A ReAct agent from scratch
Python cells in this book run in your browser with no network, so no cell can call a real model. The policies below are short scripts with the same interface as a model, a context string in and text out. The loop is real, and only the decisions are hand-written. Each script reads the observations and decides what to do, as a model would. First come the five pages, the search tool, and a parser for one step.
That parser handles the tidy text our scripts write, and it breaks on what models actually produce. Real outputs number their steps (Thought 3:), put brackets inside arguments, and spread a thought over several lines. Sometimes they run past the action and write an Observation: line of their own. That is an invented tool result, and the harness, the program that runs the loop, must never trust it. Text-based ReAct implementations prevent it with a stop sequence, a string at which the API stops generating (§6.4), here Observation. A robust parser also ignores everything after the first action line.
Parse a ReAct step
Write parse_react_step(text). It returns (thought, action, arg), or None if the text holds no valid action.
- The action line. It is the first line that, after optional leading spaces, starts with
Action:or withAction <n>:for a step number , then hasname[arg], and ends with](trailing spaces allowed). Thenameis letters, digits, or underscores. Returnactionasnamein lower case. Returnargas everything between the first[after the name and the last]of that line, so an argument may contain brackets. - The thought. It is the text after the first
Thought:orThought <n>:that comes before the action line, with leading and trailing whitespace removed. It may span several lines. If there is no thought, return the empty string. - Ignore everything after the action line.
- If no line qualifies as an action line, return
None.
The loop
Now the loop. It keeps the episode as a list of segments, each tagged with who wrote it, because that tag becomes the training mask. A failed tool call becomes an observation, as in §24.1, so the loop never crashes. An optional loop detector replaces the third identical action in a row with a warning.
The scripted policy reads the last observation. If the search failed, it picks the closest similar title. If a page names an architect, it searches for that person. If a page gives a birthplace, it answers.
The printout is the ReAct trace of the example box, now produced by running code.
One task, end to end
Here is what happens to the task at each turn, in numbers. Training sees the episode as tokens, so we need a tokenizer. A toy one that splits words and punctuation is enough here. Real tokenizers split words into subword pieces (§2.2), but only the proportions matter for this count.
The next cell follows the episode turn by turn. At each turn the policy reads the whole context so far and writes one thought and one action, and the world writes back one observation.
Even in this tiny episode the world wrote almost half the tokens. Real pages run to thousands of tokens per observation, so in a long real episode nearly every token has . That fact drives the cost of agents and, as the second half shows, the way they must be trained.
Error recovery belongs in the loop and in the policy
The loop above makes four decisions that every production agent makes, and each has a reason.
- Errors are observations. An unknown action, a malformed output, and a tool exception all come back as text. The exact message matters, because the model reads it. The message
Error: unknown action 'serch'. Valid actions are ['search'] and finish.tells the model how to fix the call, and a bare "error" does not. The Model Context Protocol makes this a rule for arguments that fail validation, which go back to the model as tool errors rather than protocol errors (§24.6). - Retrying is the policy's decision. The loop never retries a tool on its own. It reports what happened, and the model chooses whether to retry, rephrase, or give up, because only the model knows whether the same call can succeed. Automatic retries of a call that timed out on the network, with backoff and idempotency keys, are a different layer, covered in §24.6.
- Loops are detected by repeated pairs of action and normalized argument. A loop is ReAct's most common reasoning error. The cheapest detector is exact repetition after normalizing the argument (lower case, one space between words), so
search[Vela Library]andsearch[vela library]count as the same call. Three identical actions in a row is a common threshold. An agent can also alternate between two failing calls, A, B, A, B, which no test of consecutive repeats catches, so the harness also compares each action with the one two steps back. On a loop, the harness injects a warning instead of executing the call, or, more aggressively, forbids the repeated action. Near-repeats, such as the same query with one word changed, need a fuzzier test, for example a threshold on string similarity. - Back off after a step limit. When the budget runs out without an answer, the trajectory is evidence that tools are not helping, and ReAct's back-off rule hands the question to self-consistency.
Agents often add one more kind of thought, a reflection. It is written after a failed attempt, says what went wrong, and stays in the context for the next attempt (Shinn et al. 2023 call this Reflexion). It is one more element of , and §24.4 works out what it adds over a plain retry. Whether a model can correct itself this way without an outside signal has a careful answer in §26.1. With a real error message or a failing test as the signal, reflection helps. Without one, it often does not.
A ReAct agent with loop detection and a training mask
This is the ReAct loop as an interviewer asks for it, with the loop detector a production harness needs and the training mask at the end. It leaves out two guards that a general loop also needs, a separate message for unknown tools and truncation of long observations, which Exercise 24.1c covers. Write react_agent(policy, tools, question, max_steps, tokenize), which returns (answer, segments, tokens, mask). The setup provides parse_action(text), a robust parser that returns (thought, action, arg) or None.
- Segments.
segmentsis a list of(source, text)pairs. It starts as[("prompt", f"Question: {question}\n")]. - One step. At step
t = 1, 2, ..., callout = policy(context)once, wherecontextis the concatenation of all segment texts so far, and append("policy", out). - Finishing. If
parse_action(out)gives the actionfinish, the episode ends with its argument as the answer. Append nothing more. - The key of a step. Every other step has a key,
(action, normalize(arg)). Herenormalizelower-cases the argument, collapses every run of whitespace to one space, and strips the ends. A malformed output has no key and gives the observation"Error: could not parse an action.". - Loops. A step is a loop in two cases. Either its key equals the keys of the two previous steps (three identical actions in a row), or its key equals the key from two steps back and the previous key equals the key from three steps back (a cycle A, B, A, B, caught at its fourth step). A loop gets the observation
"Warning: repeated action. Try something different."and runs no tool. A malformed step is never part of a loop. Record every step's key, warned or not. - Running the tool. Otherwise run
tools[name](arg)with the argument as written, since normalization is only for comparing. Any exception, including aKeyErrorfor an unknown name, givesf"Error: {type(e).__name__}: {e}", and success givesstr(result). - Observations and the budget. Append
("env", f"\nObservation {t}: {obs}\n"). Ifmax_stepscalls pass withoutfinish, the answer isNone. - Tokens and mask.
tokensconcatenatestokenize(text)over the segments in order.maskis a list of ints, 1 for every token of a"policy"segment and 0 for every other token.
What each part buys, in a simulation
One trace proves nothing about rates. To see how the mechanisms combine, we run every method on 200 generated two-hop questions of the form "Where was the director of Film born?" against a noisy search tool. The failure modes are HotpotQA's, in miniature.
- The world. Each film page names a director, and each director's page names a birth city. Each director's page is missing with probability 0.25 (63 of the 200 here), and then a search for it returns only unrelated titles. Each page has a disambiguated title such as "Ada Cruz (director)" with probability 0.3, and then an exact search misses but the list of similar titles shows the right page.
- The model's memory. Chain of thought recalls each fact correctly with its own probability , drawn from a distribution with mean 0.5. When recall fails, the model states its favorite wrong value with probability 0.7 and a random one otherwise, and it is equally confident either way. The favorite wrong value is what stops majority voting from improving forever, as §18.2 showed for models with a preferred wrong answer.
- The agents. The ReAct and Act policies read each observation and act on it. Each has one slip probability that stands in for a measured failure. After a failed search, the policy repeats the same search with probability 0.5 instead of reading the similar titles. Once it has repeated itself, it keeps repeating until a warning arrives, because greedy decoding gives the same output for the same context. The Act policy, with no plan written down, answers with the director's name after the first hop with probability 0.35.
These probabilities are invented. The point is not the particular numbers but how the mechanisms combine.
The agent is one script for both ReAct and Act. With think=False it writes no thoughts and can lose track of the goal.
The pattern is ReAct's, in miniature. Chain of thought fails only by confident wrong answers, the analogue of the 56% share of made-up facts. Plain ReAct edges past CoT-SC, and its failures are the analogue of ReAct's loops and useless searches, runs stuck repeating a failed search or looking for a page that does not exist. Each fix targets one of those failures. The loop warning turns most stuck runs into answers, and the back-off to CoT-SC answers many of the questions the tools cannot. Because the two methods fail on different questions, using both fixes gives 81.5%, far above either alone.
CoT-SC then ReAct does less well here, for two reasons. The vote is split on most questions, so most of them go to plain ReAct, whose stuck runs then have no fallback. And some clear majorities are favorite wrong answers, which never ask for help. In practice, this is the argument for detecting loops and for keeping a fallback. An interviewer who asks how you would raise an agent's success rate wants to hear both.
Toolformer, a model that labels its own data
Prompting a frozen model with example trajectories, as ReAct did, teaches the format of tool use but not the judgment of when a tool helps. Toolformer (Schick et al. 2023) asked whether a model can learn that judgment from plain text, with no human labels of where calls belong. The idea fits in one sentence. Let the model propose calls inside ordinary text, run them, and keep only the calls whose results make the following text easier for the model to predict. Then fine-tune the model on the text with those calls written in. The model's own loss is the teacher.
First, what "easier to predict" means. The loss is the negative log-likelihood, minus the log-probability the model gives each actual next token, measured in nats (natural-log units). One nat saved on a token means the model's probability for it grew by a factor of .
The pipeline has four steps, run separately for each tool. The tools were a question-answering model, a Wikipedia search, a calculator, a calendar, and a translator.
- Sample positions. Show the model a prompt with a few examples of calls written into text. For every position of a text , compute the probability that the model starts a call there. Keep the positions with , at most the top of them.
- Sample calls. At each kept position, sample up to candidate calls from the model.
- Execute. Run each call to get a result , a string.
- Filter, then fine-tune. Keep a call only if its result lowers the model's loss on the next tokens by at least , as defined below. Write the kept calls and their results into the text, and fine-tune the model on the new corpus with the ordinary next-token loss.
Three details of the definition are easy to get wrong. First, the call is given as a prefix before the whole text, not inserted at position . The model has not yet seen calls in the middle of text, and inserting one there would disturb its predictions for reasons that have nothing to do with the result. Second, the weights fall to zero after five tokens, so a result is credited only for helping the text right after it. Third, takes the better of two baselines, no call at all and the call without its result, so a call is never credited for information that was already in its own wording.
The hand computation found the saving as the difference of two weighted sums. Taken token by token, that difference says what the threshold really asks of a result. Each token contributes its weight times the log of a ratio, its probability with the result in view over its probability without it.
∂ Proof
Substitute the definitions,
and combine the two sums term by term. ∎
In plain words, the criterion counts how many nats the result saves on the next few tokens. Each log-ratio is the model's own estimate of how much the result tells it about the next token. So the criterion is a measure of information, judged by the model on this one text. Two consequences are worth carrying into an interview. A threshold of is demanding. If the whole saving falls on the first token, whose weight is , that token's log-probability must rise by 3 nats, a factor of . And the criterion measures usefulness for prediction, not truth. A result that is wrong but fits the text, or right but irrelevant to the next five tokens, is judged by its effect on the loss alone.
The cell below computes the criterion for five candidate calls in one sentence. The scorer is a toy language model. With probability 0.5 it copies an earlier token of its context, chosen uniformly, and otherwise it guesses one of 1,000 words uniformly. Copying is a crude stand-in for what a real model does with a result in its context, and it is enough to make the criterion behave as it does at scale.
Read the five rows. The right calculation is kept and the wrong one is dropped, since a wrong result makes the next tokens harder to predict. The calendar's result has nothing to do with "1998" and raises the loss. The question about eggs is the instructive case. Its wording alone, without the result, already lowers the loss, because the words "eggs" and "pack" can be copied. uses that better baseline, so the call is credited only for what its result adds, which is still enough. The question about the shop gains 0.95 nats, below the default threshold of 1 and above the 0.5 used for the calculator and the translator. The widget lets you move the threshold and how many tokens after the call carry weight.
Toolformer's filter
Write two functions.
toolformer_weights(L, rate=0.2)returns the weights . Each is divided by , the sum over all , not only the first .toolformer_filter(lp_none, lp_empty, lp_result, tau_f=1.0, rate=0.2)takes three arrays of shape(n_calls, L). Row of each holds the log-probabilities of the continuation tokens of candidate call . The first array has them under no call, the second under the call without its result, and the third under the call with its result. Return(L_plus, L_minus, keep).L_plusandL_minusare float arrays of shape(n_calls,)holding and for each call, with the weights oftoolformer_weights(L, rate).keepis a boolean array of the same shape, True where .
The paper is candid about its limits, and they define what came next.
- No chains. Calls are sampled independently for each tool, so the training data has no chains, in which the result of one call is the input of the next.
- No interaction. The model cannot browse a list of search results or refine a query the way ReAct does.
- Sample inefficiency. More than a million documents gave only a few thousand useful calculator calls.
- Sensitivity. The decision to call depended on the exact wording of the input.
- Cost is ignored. The decision to call does not weigh what the call costs to run.
The evaluation also allowed at most one call per input, so that the model could not get stuck calling forever.
Toolformer answers "when does a call help this text?" well, and "how should a sequence of calls solve this task?" not at all. The second question needs whole episodes as training data.
Fine-tuning on trajectories
The simplest way to teach a model ReAct is to show it many successful ReAct episodes and fine-tune on them. This is supervised fine-tuning, training on example outputs with the ordinary next-token loss, as in §14.3, applied to whole trajectories.
ReAct itself did a first version. It generated trajectories with the 540B model, kept 3,000 that reached a correct answer, and fine-tuned PaLM-8B and PaLM-62B to write whole trajectories, thoughts, actions, and observations alike. Fine-tuned ReAct became the best of the four methods at both sizes. PaLM-8B fine-tuned on ReAct beat every prompting method at 62B, and PaLM-62B fine-tuned on ReAct beat every prompting method at 540B. Fine-tuning on CoT or Standard trajectories did much worse. The authors read this as the difference between memorizing facts, possibly made-up ones, and learning a skill for finding them. Keeping only the attempts that succeed and training on them is the bootstrapping recipe that §26.3 studies for reasoning (Zelikman et al. 2022).
FireAct (Chen et al. 2023) made this the main object of study, with a Google search tool on HotpotQA.
Fine-tuned agents also learned to adapt the length of their trajectories, answering some simple questions in a single round.
Fine-tuning on trajectories differs from fine-tuning on chats in four ways that matter in practice.
- Most of the text is the world's. Observations dominate the tokens. In supervised learning, whether to train on them is a choice, not a law. Training on observations is maximum-likelihood learning of the environment's text, a model of the world. FireAct found that masking them had no consistent effect either way (its Appendix A.7). But training on them teaches the model to write tool results, which the stop sequence or the message format must then prevent, and it spends capacity on text the model will never be asked to write. The usual practice is to mask observations, as §14.3 masks tool results. In reinforcement learning, below, the choice stops being a choice.
- Every step of a successful trajectory is imitated, including the wasted ones. A trajectory that reached the right answer after two pointless searches teaches the pointless searches too. Filtering by success selects episodes, not steps.
- The model never sees its own mistakes. Demonstrations come from a stronger model or a careful human, so they rarely contain the states that the student's own errors lead to, and the student never learns how to recover from them. Its cost is worked out next.
- Format and judgment are learned together. Few-shot prompting has to teach the format in the context, which is why small models prompted with ReAct did worst of all. Fine-tuning moves the format into the weights, which frees the context for the task.
Why cloned agents compound their errors
Behavior cloning is supervised learning of a policy from an expert's demonstrations, one pair of state and expert action at a time. Fine-tuning on successful trajectories is behavior cloning. A cloned agent is accurate on the states its expert visited. After its first mistake it is somewhere the expert never went, and there its error rate can be far higher. This mismatch between the states trained on and the states visited is called covariate shift. It is the agent-sized version of the exposure bias of §3.5, where a model trained only on correct prefixes must continue its own imperfect ones. Once the first mistake happens, mistakes stop being rare.
§3.5 stated the quadratic bound below for translation and named its fix, and §14.1 applied it to supervised fine-tuning. Here we prove it, show that it is tight, and prove the linear bound that training on the student's own states achieves. Agents are where the difference matters most, because their episodes run for many steps and the first bound grows with the square of the number of steps.
Here are numbers first. Suppose a cloned agent errs on 1% of the expert's states, and after its first mistake every remaining step is wasted. Over a 30-step task, the chance that step is already off track is , and the expected number of wasted steps is . Now suppose instead that the agent errs on 1% of its own states, and that each mistake costs one step before it is back on track. Then it wastes at most steps on average. Same error rate, fourteen times the waste. Two things changed, whether a mistake can be repaired and on whose states the error rate is measured, and the theorem below separates them.
∂ Proof of the three parts
Part 1. Run the student and the expert on the same random draws of the world, so they are in the same state for as long as they have taken the same actions. Let be the event that they agree at steps 1 to . Before the first disagreement, the shared state is the expert's own state at that step. So a first disagreement at step requires the student to disagree with the expert at the expert's state , which is distributed as , and that has probability . A union bound gives . On the two pay the same cost at step , and off it their costs differ by at most 1, so their expected costs at step differ by at most . Summing over the steps gives .
Part 2. The cost at step is 1 exactly when at least one of the first steps erred, which has probability , and .
Part 3. Let play the student for steps and the expert afterward, so that and . The difference telescopes,
The two policies in the -th term act alike for steps, so both pay the same costs up to then and both reach . From there one takes the student's action and the other the expert's, and both follow the expert. The term is therefore . It is 0 where the actions agree and at most where they differ, so it is at most . Summing over gives . ∎
In plain words, part 1 charges each mistake for every step that remains, because nothing guarantees that the student can find its way back. Its first mistake comes after about steps, so in a long episode many steps come after it. Part 3 charges each mistake only , the price of one wrong step that the expert could repair. But it counts mistakes where the student actually goes, so it is only as good as the student's training on its own states. The numbers at the start of this subsection are parts 2 and 3 at and , and part 1 allows up to 9 wasted steps. When mistakes cannot be undone, can be as large as and nothing escapes the quadratic, one more reason §24.4 asks whether actions can be reversed.
Part 3 says what to fix. The student must be trained on the states it reaches, with labels for what to do there. Ross, Gordon, and Bagnell turned that into an algorithm.
For language agents each remedy has a direct form. Recovery demonstrations patch the data by hand. The DAgger recipe uses a stronger model as the expert. It runs the student, has the teacher write the right next step at states taken from the student's own trajectories, and fine-tunes on those corrections. On-policy distillation is the same idea token by token, with the student sampling and the teacher scoring every token it wrote. An interviewer who asks why supervised fine-tuning alone plateaus for agents wants to hear covariate shift, the against contrast, and one of these remedies.
Reinforcement learning on the student's own episodes, the subject of the rest of this section, goes one step further. It needs no expert at all, only a reward, and its training states are the student's own by construction, so the covariate shift is gone. What it gives up is the dense label, one right action for every state, in exchange for one number per episode. That is why assigning credit across turns becomes the hard problem below.
Reinforcement learning with environment tokens
Supervised trajectories teach a model to imitate a good agent. Reinforcement learning teaches it to succeed. The model samples its own episodes, and each episode gets a reward, one number such as an exact-match check, a passing test, or a verified final state. Training makes the high-reward episodes more likely. Everything in §15.3 to §18.4 applies, with one new fact to establish first. An agent's episode contains tokens that the policy did not write.
Start with the smallest case. The policy writes the token search, the world writes hit, and the policy writes answer. The probability of this episode is a product of three factors,
The middle factor belongs to the world, and changing cannot change it. So when we take the gradient of the log-probability, the middle term contributes nothing. That is the whole idea, and the rest of this part makes it exact.
Serialize a finished episode into tokens , as §24.1 did. The source mask is if was sampled from and if it came from the task, the chat template, or the environment. The prefix decides which source writes token , since the policy writes until it emits its stop token and the harness then writes the observation. Let be the probability that the outside world produces token after the prefix when it is the world's turn.
This conditional does not depend on , and here is why. The world's hidden state , such as the contents of a database, enters only through the posterior . The policy sees only the prefix, so its probabilities are the same factor in for every , and they cancel when we normalize over . The chain rule then splits the probability of the episode into the policy's tokens and the world's,
∂ Proof
Take the log of the factorization. The terms with are , which do not depend on , so their gradient is zero. The terms with give the sum shown. The score-function identity of §15.3, , gives the second formula. For the baseline, condition on the prefix of a policy token. Then , and the expected-score lemma of §15.4 gives . So . ∎
In plain words, the world's tokens are context, never targets. They shape the gradient through attention, since every later policy token is conditioned on them, but they contribute no terms of their own. This is the "environment drops out" step of §15.3, applied token by token inside one sequence. The one assumption to check is that the world's text does not depend on . A simulated user played by a frozen copy of the model satisfies it. A user played by the policy itself does not, and then those tokens are the policy's own moves in a two-player game.
Leaving the world's tokens in the loss teaches wishful thinking
The mask is often described as a trick for stability. It is more than that. Leaving environment tokens in the loss changes what the estimator estimates.
∂ Proof
Condition on the prefix and use (§0.2). The expected added term is . Its -th entry is . That is zero for every exactly when . ∎
In plain words, with a constant reward the extra term is ordinary maximum-likelihood learning of the world, harmless if wasteful. With a real reward it teaches the model to expect the observations that came with success. If searches that found the answer earned reward and searches that failed did not, the model learns that searches find the answer. It learns to predict good news, and a model that predicts tool results it never received is a model that makes them up.
A baseline makes this worse, not better. With the usual baseline , the coefficient of in the added term is . The term becomes the constant vector . It never vanishes unless is the same for every observation, and it pushes the logits of the above-average observations up without limit.
The cell checks both theorems exactly on a world small enough to enumerate. The policy chooses one of three queries . The world returns a hit or a miss, with probabilities that depend on the query. Then the policy answers. The reward is 1 only if the search hit and the policy used the result. The same model also has logits for predicting the observation token, as any language model does. Those logits never influence what happens, so the true gradient of with respect to them is exactly zero.
The masked estimator matches the true gradient to five decimals, as the first theorem says. The unmasked estimator adds a nonzero push on logits that do not affect the reward at all. Follow that push for a few hundred steps, holding the rest of the policy fixed, and watch what the model comes to believe about its search tool.
An interviewer who asks "which tokens go in the agent's RL loss?" wants the answer and both halves of its proof, the factorization that makes the world's tokens drop out, and the bias toward good news that appears when they are left in.
The multi-turn GRPO objective
With the gradient settled, the training objective is the group-relative policy optimization (GRPO) of §18.4, applied to whole episodes. Here it is in one paragraph. For one prompt, sample responses with rewards . Each response's advantage is its reward minus the group mean, divided by the group's standard deviation, so a response is pushed up when it beat its siblings. Each token's update uses the probability ratio between the current policy and the policy that sampled it. That ratio is clipped to a small range as in PPO (§15.6), so one batch cannot move the policy far. In an agent, a response is an episode.
In plain words, run the same task times and score each run against its siblings. Push every token the policy wrote in a run up or down by that run's score, clipped as in PPO, and ignore every token the world wrote.
The normalization here is one average over all policy tokens of the group, the token-level choice of DAPO (Yu et al. 2025). The two alternatives are GRPO's original average within each episode and a constant divisor (Liu et al. 2025, Dr. GRPO), with the length and difficulty biases that §18.4 derived for each. Agents make this choice matter more than reasoning did, because episode lengths vary by an order of magnitude, for example a three-turn success next to a thirty-turn failure. Under a per-episode average, each policy token of the short episode weighs ten times as much as one of the long episode. Some trainers also add a KL penalty, a term that keeps the policy close to a fixed reference model. If one is used, it is masked the same way, and Search-R1, below, masks its retrieved tokens in the KL term too.
Masked multi-turn GRPO loss
Write multiturn_grpo_loss(logp, logp_old, mask, rewards, group, clip_eps=0.2, eps_num=1e-6).
- Inputs.
logpandlogp_oldhave shape(B, T). They hold the log-probabilities of the tokens of episodes, padded to length , under the current policy and under the sampling policy.maskhas shape(B, T), 1 at policy tokens and 0 at environment tokens and padding. The log-probabilities at masked positions may be arbitrary garbage.rewardshas shape(B,).grouphas shape(B,)and holds integer task ids. Episodes with the same id are rollouts of the same task, at least two per task, in any order. - Advantages.
advholds each episode's GRPO advantage within its own group, using the sample standard deviation (ddof=1) pluseps_num. - Loss.
lossis a float, the negative of the definition's surrogate with the token average pooled over the whole batch, as DAPO does when a batch holds several tasks, .
Return (loss, adv).
The loss in PyTorch
In a real trainer the log-probabilities come from the model, and autograd does the rest. The block below computes the masked multi-turn loss from logits and checks two things. At the ratio is 1, so the gradient with respect to each policy position's logits is , the masked policy gradient of the theorem. And the gradient at every environment position is exactly zero.
What masking measured at scale
Search-R1 (Jin et al. 2025) trained Qwen2.5 models to interleave <think>, <search>, and <answer> blocks, with retrieved passages inserted between <information> tags. The reward was exact match, and the optimizer was PPO or GRPO. It masks the retrieved tokens from the policy loss and from the KL term, and it tested the choice. With Qwen2.5-7B-base and PPO, the average exact match over seven question-answering benchmarks was 0.431 with the mask and 0.343 without it, and the mask won on every one of the seven. Overall, Search-R1 improved on retrieval-augmented baselines by 24% (Qwen2.5-7B) and 20% (Qwen2.5-3B) in relative terms.
ReTool (Feng et al. 2025) trained a model to run code during long reasoning, with the interpreter's output masked from the loss in the same way. Starting from Qwen2.5-32B-Instruct, it reached 67.0% on AIME 2024, a high-school mathematics competition, after 400 RL steps. A text-only RL baseline, fine-tuned on text reasoning first, reached 40.0% after 1,080 steps. Starting instead from DeepSeek-R1-Distill-Qwen-32B, a model distilled from a reasoning model, ReTool reached 72.5%.
One practical detail decides whether the theorem actually holds in code. The log-probabilities in the loss must be those of the exact tokens the policy sampled. Suppose the trainer re-tokenizes the episode's text. A tokenizer may merge characters across the boundary between the policy's output and an observation, so the "policy tokens" in the loss are not the tokens the policy produced. Their log-probabilities are then off-policy in a way that no importance ratio corrects. Agent RL frameworks therefore carry token ids, not strings, from the sampler to the trainer.
Credit across many turns
The group advantage gives every token of an episode the same number. In a 30-turn episode with one reward at the end, that is a blunt instrument. A run that wasted ten turns and then succeeded pushes up the wasted turns too, and only many episodes average out which turns mattered. Deciding which turns earned the reward is the credit assignment problem. There are four answers, in increasing order of machinery.
- Better group baselines. LOOP (Chen et al. 2025) trained a 32B agent in AppWorld, a simulation of nine everyday apps driven by API calls. It used PPO with no value network, so only one copy of the model sits in memory. Each episode's baseline was the mean reward of the other rollouts of its task, the leave-one-out estimator of §18.4, and the ratio was clipped per token. The reward was the fraction of the task's unit tests passed. LOOP completed 71.3% of the tasks in AppWorld's normal test split and beat the much larger OpenAI o1 agent by 9 points. The agents learned to read API documentation before calling, to avoid unwarranted assumptions, and to recover from failed calls.
- A critic over turns. ArCHer (Zhou et al. 2024) runs two learners. A high-level critic, trained off-policy like a Q-function on whole turns, estimates the value of each turn. A low-level token policy is trained within each turn against that value. Turn-level values give each turn its own advantage, and the authors report about 100 times the sample efficiency of on-policy methods such as PPO on their agent tasks.
- Process rewards. A process reward model scores intermediate steps, as in §18.6, and for an agent a step is a turn. Judging an agent's step is harder than judging a reasoning step, because its quality depends on a hidden state of the world.
- Shaped rewards. These are small rewards for intermediate events, such as a well-formed call, a successful tool execution, or a correct sub-answer, studied for tool use by ToolRL (Qian et al. 2025). Every shaped reward is a new target for reward hacking, earning reward without doing the task. An agent paid for successful calls learns to make easy calls, and one paid for format learns format.
Multi-turn RL is also less stable than single-answer RL, because a policy that stops varying its behavior leaves its groups with identical rewards and no signal. The deeper box describes the measured failure.
Rollouts wait on tools
In RL for reasoning, generating a batch means running the model. In RL for agents, each rollout also waits for tools, such as a search engine, a code sandbox, or a browser, with latencies from milliseconds to minutes and long tails. If a training step waits for the whole batch, the slowest rollout sets the pace. Large systems therefore generate rollouts asynchronously, training on whatever episodes are ready. That makes training slightly off-policy, since some episodes were drawn by an older copy of the policy, and PPO's ratio corrects for it. The box gives the numbers.
Environments at scale
Frontier labs train agents on thousands of environments, most of them synthesized. An environment here is a task, the tools an agent may call, a simulated or real world those tools act on, and a check that decides whether the task was done.
The published recipes share three moves. First, tools and users are simulated by language models, so that thousands of tasks can run in parallel and reset for free, with real sandboxes kept where fidelity matters, as in coding. Second, every task comes with a check, such as a rubric, a verification function, or unit tests. Third, tasks are filtered to the right difficulty, kept only if the current model solves them sometimes, so that every group of rollouts has mixed rewards and carries signal. The deeper box gives the numbers for two published recipes.
Browsing agents are the most visible result of this recipe. Their benchmark, BrowseComp (Wei et al. 2025), is a set of 1,266 questions from OpenAI that are hard to find and easy to check, and the deeper box after its results shows how such questions are built.
Step back from the individual systems. Each one trained a model on its own episodes against a reward that a program, a rubric, or a reference answer could check. The table puts their numbers side by side, with what each one trained, so you can quote them in an interview with their context.
ReAct inside frontier models
ReAct began as a prompt format. In frontier models it has become a trained behavior inside the reasoning itself. OpenAI's system card for o3 and o4-mini (April 2025) states that the models use tools within their chains of thought, for example searching the web or running Python while they think. It also states that they are trained with large-scale reinforcement learning on chains of thought. Anthropic's API documents interleaved thinking, in which Claude reasons about each tool result before it decides what to do next, between tool calls within one assistant turn. The thinking blocks are passed back with the tool results so that the reasoning can continue. Both are ReAct's cycle of thought, action, and observation, with the thoughts now long, learned by RL, and hidden from or summarized for the user.
When a tool call is worth it
Every agent in this section, prompted or trained, makes one decision over and over. The agents above search until they can answer, but a real agent must decide at every turn whether a call is worth its cost in latency, tokens, and money, or whether to answer from what it already knows. A two-line model makes the decision exact and shows why calibration matters for tool use. An agent is calibrated if, among the answers it gives with confidence 0.7, about 70% are right.
Start with numbers. Suppose the agent is 60% sure of its own answer, a search tool is right 90% of the time, and a call costs 0.1 in units where a correct answer earns 1. Answering alone earns 0.6 on average. Calling and using the tool's answer earns . So call. If the agent were 85% sure, answering alone would earn 0.85, more than 0.8, so it should not call.
∂ Proof of the three parts
Part 1. Not calling earns in expectation and calling earns , so calling is better exactly when .
Part 2. After calling, the two answers agree only if both are right, because wrong answers never coincide. That happens with probability . They disagree with probability . Then the agent's own answer is the right one with probability and the tool's with probability . So the best choice on disagreement is the tool's answer if , which simplifies to . The expected reward is therefore . That equals when and when , that is, . Calling beats not calling if and only if . With this needs , and then it reads .
Part 3. The agent calls if and only if , which for increasing means . And gives . So the overconfident agent calls on a subset of the questions where calling is optimal. On the questions it skips, those with , it earns instead of . ∎
In plain words, call the tool when it is better than you by more than it costs, and the honesty of your own confidence decides whether you can follow that rule. Comparing the two answers buys nothing extra in this model. Overconfidence makes an agent skip exactly the calls it needed, which is how a fluent model ends up answering from a wrong memory with a search tool right there.
The model is simple on purpose, and its lesson survives the complications. Calibration (§19.8) is not only an honesty property. It is what makes a tool policy work. And when a call has a real cost, training should reward correctly skipping a call as well as making a correct one. That is why tool-use training data includes examples where the right move is not to call (§24.2), and why RL rewards for tool use often charge for each call.
When is a tool call worth it?
Work with a population of questions, given as an array c of the agent's true probabilities of answering correctly on its own, each question weighted equally. The tool is right with probability q and costs lam. The agent calls on a question if and only if its reported confidence is below a threshold t, and when it calls it submits the tool's answer. Write three functions.
tool_call_utility(c, t, q, lam, reported=None)returns the mean reward per question.reported(defaultc) is the confidence the agent uses for the decision, while the reward of not calling is always the truec.best_call_threshold(c, q, lam, grid)returns the threshold ingridwith the highest utility for a calibrated agent, the first one if several tie.overconfidence_regret(c, q, lam, g)returns the utility of the optimal calibrated policy (thresholdq - lamonc) minus the utility of an agent that applies the same threshold tog(c).
Where it breaks
Each way of producing an agent has its own data, its own cost, and its own typical failure.
| method | data it needs | what it learns | cost | typical failure |
|---|---|---|---|---|
| ReAct prompting | a few written trajectories | the format only, from the context | nothing to train, long prompts | loops, derailment by bad searches |
| Toolformer | plain text plus tools that run | when a single call helps the next tokens | sampling and running many calls | no chains, no interaction, sensitive to wording |
| Trajectory fine-tuning (FireAct) | hundreds to thousands of good trajectories | the format and habits of a strong agent | cheap, offline | imitates wasted steps, never sees its own errors |
| Multi-turn RL (Search-R1, LOOP) | tasks, environments, and a checker | whatever earns reward | rollouts wait on tools, many environments | reward hacking, unstable groups, credit over turns |
In practice the rows build on each other. The published recipes (ReTool, Kimi K2, DeepSeek-V3.2) fine-tune on trajectories before RL. RL then starts from a policy that can already finish some tasks, so its groups have mixed rewards and carry signal.
Read more
- Yao et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. The augmented action space, the ablations against Act and CoT, the error analysis of Table 2, and the back-off rules; read the appendix trajectories.
- Schick et al. (2023). Toolformer: Language Models Can Teach Themselves to Use Tools. Self-supervised tool-use data from the model's own loss, with an honest limitations section that set the agenda for later work.
- Chen et al. (2023). FireAct: Toward Language Agent Fine-tuning. The systematic study of fine-tuning on agent trajectories, including data scale, mixtures of methods, and observation masking.
- Ross, Gordon, and Bagnell (2011). A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning. DAgger, with the quadratic bound for behavior cloning and the linear bound for training on the learner's own states; Section 2 is short and worth reading in full.
- Jin et al. (2025). Search-R1: Training LLMs to Reason and Leverage Search Engines with Reinforcement Learning. Multi-turn RL with retrieved-token masking, its ablation, and the dynamics of learning when to search.
- Chen et al. (2025). Reinforcement Learning for Long-Horizon Interactive LLM Agents. LOOP, a critic-free PPO for a stateful multi-app environment, with an analysis of the behaviors RL taught.
- Wei et al. (2025). BrowseComp: A Simple Yet Challenging Benchmark for Browsing Agents. How inverted questions are built, checked, and graded, and the gap between browsing models and agents trained with RL.
- DeepSeek-AI (2025). DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models. Section 3.2 describes thinking across tool calls and the synthesis of verifiable agent environments at scale.