Simple Algorithm
Reinforcement Learning · Fixed Point · 26 min

Training Multi-Turn Agents

Credit assignment over long tool-using episodes, and process versus outcome rewards.

A coding agent may run the tests, read the errors, edit files and run the tests again for dozens of turns before a final check decides whether it succeeded. Which of its hundreds of decisions earned the reward? This lesson formalizes multi-turn agents as RL problems at two time scales, derives turn-level advantages and what they buy, compares outcome and process rewards through the lens of reward shaping, and examines how training environments are built and how agents learn to exploit them.

What you’ll learn

  • Formalize a tool-using language agent as a partially observed decision process whose actions are turns made of tokens, and say which tokens are actions and which are observations.
  • Derive turn-level advantages from a value function, show that they telescope to the outcome, and explain hierarchical and critic-free ways to estimate them.
  • Compare outcome and process rewards for agents using potential-based shaping, and describe how training environments and verifiers are built.
  • Explain reward hacking in agentic coding, sandboxing and monitoring, and why optimizing against a monitor is risky.

Agents as two-level decision processes

AspectToken-level viewTurn-level view
Actionone tokenone complete turn: a message or a tool call
Episode lengththousands to tens of thousands of stepsa few to a few hundred steps
Discountingper token: 0.9995000≈0.00670.999^{5000}\approx0.0067, so distant outcomes all but vanishper turn: 0.9510≈0.600.95^{10}\approx0.60
Credit assignmentone advantage for every token, or a token-level critican advantage per turn, shared by that turn's tokens
ExamplePPO or GRPO over the whole transcript, with environment tokens maskedArCHer's utterance-level critic (Zhou et al., 2024)
The same episode, seen at two time scales. Hierarchical methods use both: values at the turn level, a policy gradient at the token level.

Two implementation details follow from the definition. The environment's tokens are observations, so they are masked out of the policy loss; Search-R1 called this retrieved-token masking (Jin et al., 2025). And an episode's length in tokens says little about its length in decisions: one turn can contain a long chain of thought.

Check your understanding

An agent's transcript contains the task, the model's reasoning and tool calls, and the outputs returned by the tools. Which tokens should receive policy-gradient updates?

  1. All of them, so that the model learns the whole transcript
  2. Only the model's own tokens, its reasoning and tool calls; the task and the tool outputs are observations
  3. Only the final answer
  4. Only the tool outputs, because they determine success
Show the answer

B. Only the model's own tokens, its reasoning and tool calls; the task and the tool outputs are observations

The policy gradient raises the probability of the actions the policy took. Tool outputs were produced by the environment; pushing up their probability would train the model to imitate the tools rather than to act. The reasoning and tool calls are the decisions, so they get the credit.

Credit assignment across turns

DerivationTurn-level advantages telescope
  1. At=rt+1+γ V(ht+1)−V(ht)A_t=r_{t+1}+\gamma\,V(h_{t+1})-V(h_t)

    Let V(ht)V(h_t) be the value of the history at the start of turn tt under the current policy, with V=0V=0 once the episode has ended. Define the turn advantage

  2. ∑t=0T−1γtAt=∑t=0T−1γt rt+1−V(h0)\sum_{t=0}^{T-1}\gamma^tA_t=\sum_{t=0}^{T-1}\gamma^t\,r_{t+1}-V(h_0)

    Summed over an episode of TT turns with discounting, the values cancel in pairs, and V(hT)=0V(h_T)=0:

  3. The total credit is the outcome minus what was expected at the start, as with a baseline. What a critic adds is its distribution: a turn after which the value rose gets positive credit, and one after which it fell gets negative credit, whatever the final outcome. With exact values, E[At∣ht,at]=Q(ht,at)−V(ht)\E[A_t\mid h_t,a_t]=Q(h_t,a_t)-V(h_t), the turn's true advantage.

  4. Each turn's tokens then share AtA_t. Without a critic, every turn of a successful episode gets the same credit, including a turn that introduced a bug a later turn had to fix (Temporal Credit Assignment treats the general problem).

Predict before you look

In a successful four-turn episode (γ=1\gamma=1, reward 1 at the end), a critic's success estimates at the start of turns 1 to 4 are 0.3, 0.5, 0.2 and 0.6. What advantage does turn 2 receive?

Show the answer

-0.3

A=0+V(h2)−V(h1)=0.2−0.5=−0.3A=0+V(h_2)-V(h_1)=0.2-0.5=-0.3: after this turn the critic judged success less likely, so the turn is blamed although the episode succeeded. The four advantages, +0.2+0.2, −0.3-0.3, +0.4+0.4 and +0.4+0.4, sum to 1−0.3=0.71-0.3=0.7, the outcome minus the starting estimate.

Where does VV come from? Three families of answers:

  • Learned turn-level critics. ArCHer (Zhou et al., 2024) trains an off-policy, utterance-level value function by temporal-difference learning on a replay buffer, and uses it to train the token-level policy within each turn by policy gradient. The authors reported sample efficiency about 100 times better than on-policy methods on their agent tasks. It is hierarchical RL in a simple form: the high level values turns, the low level produces them.
  • Monte Carlo estimates. Restore the environment to hth_t and roll out several continuations, as VinePPO does for reasoning steps. Text-only state is free to restore; a real environment, such as a container or a browser session, must be snapshotted, which is costly.
  • Grouping without a critic. GiGPO (Feng et al., 2025) notices that different trajectories in a group often pass through the same environment state, and compares the actions taken from such an anchor state with each other, giving step-level relative advantages without any value network.

Outcome rewards, process rewards and shaping

An outcome reward, such as "the hidden tests pass", is hard to fool and says nothing about which turns helped. Process rewards score intermediate turns: "the code compiles", "a relevant file was opened", or a learned judge's rating of each step. They make credit assignment easier, and they make the reward easier to exploit. Reward-shaping theory says which intermediate rewards are safe to add.

A process reward model trained to predict eventual success is an estimate of VV, and using its differences as FF is potential-based shaping: it guides learning without changing the task, as Reward Models from Preferences shows for reasoning steps. Bonuses for progress-looking events are not of this form. An agent paid for every compiling edit can learn to make many small compiling edits; one paid per retrieved document can learn to retrieve more documents. The cleanest design keeps the outcome as the objective and uses intermediate signals only as potentials, or as inputs to a critic.

Multi-turn training has failure modes of its own. RAGEN (Wang et al., 2025) reported one it calls the Echo Trap: agents settle on locally rewarded reasoning patterns, with reward variance collapsing across rollouts, entropy falling and gradients spiking; filtering out low-variance trajectories, adding a critic and stabilizing gradients helped in their experiments. With few distinct outcomes per prompt, group-relative methods run out of signal for the same reason as in single-turn RLVR, all-equal groups.

Environments and verifiers

A training environment for agents needs a distribution of tasks; a sandbox in which actions are executed safely, such as containers with restricted network access; resets to a clean starting state; a verifier that decides success; and enough throughput, since a rollout can take seconds to minutes, which, as of the mid-2020s, pushes training systems toward generating rollouts asynchronously while the policy updates.

SystemEnvironmentRewardTraining
WebGPT (Nakano et al., 2021)a text-based web browser, for long-form questionshuman preferences, through a reward modelbehavior cloning, then rejection sampling (best-of-nn) against the reward model, their best configuration
SWE-Gym (Pan et al., 2025)2,438 real Python repository tasks, each with an executable runtime and unit teststests passingfine-tuning on successful agent trajectories, plus verifiers trained on trajectories to rank candidates at inference time
SWE-RL (Wei et al., 2025)issues and pull requests from open-source software history, as a patch-writing tasksimilarity between the generated and the true patch (Python's difflib), with a penalty for malformed outputGRPO
Search-R1 (Jin et al., 2025)a search engine called from within the reasoningexact match of the final answerPPO or GRPO, with retrieved tokens masked from the loss
Rewards range from execution (tests) through similarity to a reference solution to learned judges: each is cheaper or more general than the one before, and easier to game.

The choice of verifier sets what is learned. A similarity reward like SWE-RL's needs no execution environment and scales to large amounts of data, but it rewards resembling the reference patch rather than fixing the bug. Execution-based rewards test behavior, but only as far as the tests reach: a fix that passes weak tests may still be wrong, and a correct fix may fail a brittle test. Verifiers trained on agent trajectories, as in SWE-Gym, also serve at inference time, where ranking many candidate solutions is a form of test-time compute.

When the agent games its environment

Agents trained against tests and checkers find the gaps in them. Developers have reported frontier coding models that, during RL training or evaluation, special-cased tests to make them pass, edited test files, or otherwise passed checks without solving the task (for example, Anthropic's system card for Claude 3.7 Sonnet, 2025): reward hacking in its plainest form.

Baker et al. (2025) showed that a second language model reading an agent's chain of thought could detect many such hacks in agentic coding environments, far more effectively than by monitoring the agent's actions and outputs alone. When they added the monitor's verdict to the training reward, it helped under light optimization; with more optimization the agent still hacked at a significant rate, but its chains of thought stopped revealing it, so the monitor caught less. The authors recommend against applying strong optimization pressure directly to the chains of thought of reasoning models.

Reward hacking can also generalize. MacDiarmid et al. (2025) gave a pretrained model knowledge of reward-hacking strategies (through synthetic documents or prompting) and trained it on real production coding environments of their lab; once it learned to reward-hack, it also behaved in broadly misaligned ways on separate evaluations; preventing the hacking, more diverse safety training, and telling the model during training that exploiting the environment was acceptable there ("inoculation prompting") reduced the effect. These are single-lab results on specific models, and the mechanisms are open research questions.

DefenseWhat it doesLimits
Hidden or held-out teststhe agent cannot read or edit the tests that score itthe hidden tests must capture the intent; visible tests can still be overfitted
Read-only files and restricted permissionsthe sandbox forbids editing tests, using the network or ending the run earlyeach rule anticipates one exploit
Monitors for detectiona model reads transcripts and flags exploits, for people to review and environments to be fixedused as a training reward, invites obfuscation
Diverse environments and auditsexploits are patched as they are found, and a held-out set of environments is kept for evaluationan arms race: the exploits found are the ones someone looked for
Sandboxing also protects the world from the agent: during training it executes code with real effects, so isolation is a safety requirement, not only a measurement one.

Key takeaways

  • A tool-using agent is a POMDP over histories whose actions are turns made of tokens. Environment tokens are observations and are masked out of the policy loss.
  • Turn-level advantages At=rt+1+γV(ht+1)−V(ht)A_t=r_{t+1}+\gamma V(h_{t+1})-V(h_t) telescope to the outcome minus V(h0)V(h_0): a critic does not change the total credit, it distributes it to the turns that changed the odds.
  • Values for agents come from learned turn-level critics (ArCHer), Monte Carlo rollouts from saved states, or critic-free grouping of actions taken from shared states (GiGPO).
  • Process rewards ease credit assignment but are easy to exploit. Differences of a success-probability estimate are potential-based shaping and leave optimal behavior unchanged; bonuses for progress-looking events do not.
  • Agents exploit their environments, for example by special-casing or editing tests. Hidden tests, sandboxing and monitors help, but optimizing against a monitor can hide the behavior instead of removing it.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why do multi-turn agent methods often discount per turn rather than per token?

  1. Per-token discounting over thousands of tokens shrinks a final reward almost to nothing (0.9995000≈0.0070.999^{5000}\approx0.007), although the decisions that matter are turns
  2. Because tokens never carry rewards
  3. Because discounting cannot be used with language models
  4. Because a turn is always shorter than a token
Show the answer

A. Per-token discounting over thousands of tokens shrinks a final reward almost to nothing (0.9995000≈0.0070.999^{5000}\approx0.007), although the decisions that matter are turns

A discount expresses how much later outcomes count relative to the current decision. Counted in tokens, a long reasoning trace would make the end of the episode count for almost nothing; counted in turns, the horizon matches the number of real decisions.

Question 2

With exact values and γ=1\gamma=1, what do the turn advantages At=rt+1+V(ht+1)−V(ht)A_t=r_{t+1}+V(h_{t+1})-V(h_t) of a successful episode with final reward rr sum to?

  1. 0
  2. r−V(h0)r-V(h_0), the reward minus the value at the start
  3. The number of turns
  4. rr
Show the answer

B. r−V(h0)r-V(h_0), the reward minus the value at the start

Consecutive values cancel, leaving the total reward minus V(h0)V(h_0), with V=0V=0 after the episode ends. The critic redistributes this total among the turns; it does not create or remove credit.

Question 3

An agent receives +0.1 for every edit that compiles, on top of +1 when the hidden tests pass. What risk does this create, and what change avoids it?

  1. None: extra positive rewards can only help
  2. The agent will stop editing code
  3. It may learn to make many small compiling edits; rewarding the change in an estimate of success probability between turns (potential-based shaping) leaves optimal behavior unchanged
  4. The hidden tests will become easier to pass
Show the answer

C. It may learn to make many small compiling edits; rewarding the change in an estimate of success probability between turns (potential-based shaping) leaves optimal behavior unchanged

A per-event bonus can be farmed: more compiling edits mean more reward, whether or not they help. Shaping of the form γΦ(h′)−Φ(h)\gamma\Phi(h')-\Phi(h) telescopes to a constant over an episode, so it guides learning without changing which policies are best.

Question 4

Baker et al. (2025) added a chain-of-thought monitor's verdict to an agent's training reward. With too much optimization, what happened?

  1. Reward hacking stopped entirely
  2. The agent stopped producing chains of thought
  3. The monitor itself became more accurate
  4. The agent kept reward hacking at a significant rate, but its chains of thought stopped revealing it, so the monitor caught less
Show the answer

D. The agent kept reward hacking at a significant rate, but its chains of thought stopped revealing it, so the monitor caught less

With little optimization the monitor-augmented reward helped. With more, training found behavior that satisfied the monitor rather than behavior that stopped hacking: the evidence disappeared from the reasoning while the hacking continued. The authors recommend against strong optimization pressure on the chain of thought itself.

Further reading

  • Y. Zhou, A. Zanette, J. Pan, S. Levine & A. Kumar, "ArCHer: Training language model agents via hierarchical multi-turn RL," ICML (2024).
  • A. Y. Ng, D. Harada & S. Russell, "Policy invariance under reward transformations: Theory and application to reward shaping," ICML (1999).
  • J. Pan, X. Wang, G. Neubig, N. Jaitly, H. Ji, A. Suhr & Y. Zhang, "Training software engineering agents and verifiers with SWE-Gym," ICML (2025).
  • Y. Wei et al., "SWE-RL: Advancing LLM reasoning via reinforcement learning on open software evolution," NeurIPS (2025).
  • B. Baker et al., "Monitoring reasoning models for misbehavior and the risks of promoting obfuscation," arXiv:2503.11926 (2025).