Chapter 12: Offline RL for Tool-Using LLM Agents

Agentic AI turns language-model usage into sequential decision-making; offline RL turns logged agent traces into a training substrate for safer policy improvement.


Why This Chapter Exists

Most current LLM agent training is still closer to SFT, DPO, rejection sampling, or online RL than to classical offline RL. That is not a criticism – those pipelines work well when pairwise preferences, live feedback, or cheap rollouts are available.

However, once agent execution traces are logged as state–action–reward trajectories, the problem becomes naturally compatible with the offline RL framing from Chapters 1–3:

task → context/observation → thought/plan → tool call/action → tool result → next state → reward/outcome

The difference from classical control benchmarks such as MuJoCo or the D4RL offline datasets is not conceptual but practical:

RL object Classical control Agentic LLM
State Low-dim vector Context, history, memory, tool observations
Action Continuous / discrete control Text, tool call, API request, plan step
Reward Environment return Task success, verifier score, human rating, cost/safety penalty
Episode Fixed horizon rollout Multi-turn interaction
Policy MLP / actor network LLM or LLM router over tools

States are high-dimensional and partially observed; the action space is enormous and structured; rewards are often sparse and delayed; credit assignment spans many reasoning and tool steps. These are the same failure modes as offline deep RL – extrapolation, distribution shift, and overoptimistic value estimates – but with messier observations and weaker simulators.

This chapter maps the ideas from the rest of the book onto agentic AI. It does not claim that CQL, IQL, or TD3+BC drop into LangChain unchanged. It explains what transfers, what must be adapted, and what infrastructure (logging, verifiers, replay) must exist first.


Agent Traces as Offline RL Data

An agent trace is a trajectory $\tau = (s_0, a_0, r_0, s_1, \ldots, s_T)$ where each step may include:

Behavioral cloning on successful traces (SFT on ReAct-style demonstrations) is the default baseline – analogous to Chapter 1. Frameworks such as AgentGym (Xi et al., 2024) collect multi-turn trajectories across web, embodied, and tool-using tasks and use them to bootstrap generally capable agents. AgentTraj-style datasets are BC fuel, not yet offline RL – but they are the substrate offline RL needs.

The applied prerequisite is a replayable trace schema: without consistent logging of state snapshots, actions, observations, rewards, and behavior-policy metadata, later OPE, reward relabeling, and conservative policy improvement are impossible.


MDP / POMDP Formulation

Treat each LLM call (or each tool step) as one decision in an MDP:

Agent Lightning (Luo et al., 2025) makes this explicit: agent execution is an MDP where state is an execution snapshot and action is an LLM output; trajectories decompose into transitions (state, action, reward) for training. Agent Lightning is not an offline RL method in the narrow CQL/IQL sense; it is better viewed as infrastructure that turns agent execution into RL-compatible transitions, which can support online, off-policy, or potentially offline training regimes.

The bridge for practitioners:

Agent observability / tracing → trajectories → offline or off-policy RL dataset

LangChain-, AutoGen-, or OpenAI Agents-style logs are not merely debugging artifacts – they are potential RL training data once rewards and state boundaries are defined.


The Policy Interface Determines the Training Method

Specify which policy is being updated before choosing a loss. A structured classifier is still a policy $\pi(a\mid s)$, even when it uses an LLM encoder; it need not generate language.

Policy interface Action space Baseline Candidate methods
Token-generating LLM Token sequences / serialized tool calls SFT on demonstrations ILQL-style token values; DPO on preference pairs; trajectory methods with compatible action probabilities
Action classifier Finite set of tool/action labels Cross-entropy BC on action logits Discrete CQL, IQL with a categorical actor, support-constrained value learning
Router / orchestrator Agent, tool, handoff or scheduling decisions BC on routing decisions Offline RL on the routing process, with its own observations, rewards and support constraints

DPO is preference optimization, not a replacement for trajectory-level credit assignment. Token-level ILQL and language-model SFT require a token policy and an LM head; a classifier instead learns through its action logits. Text retrospection can supply annotations or features, but a text-generation loss cannot directly train a classifier without a compatible output head and targets.

The orchestrator row already has a worked example at realistic scale. HarnessMDP (Yi & Song, 2026) keeps the LLM executor frozen and trains only a small controller that chooses among seven structural operations: observe, retrieve, call a tool, draft, check, revise and submit. The controller is fitted by advantage-weighted regression on trajectories from existing harnesses. The gains are real but modest: averaged over six controlled domains task success rises by 2.8%, accuracy improves clearly on coding (+10 points under the authors' calibrated verifier), and in several other domains the change in accuracy is negligible or slightly negative. Its authors state the limit plainly: the controller can amplify patterns already present in the buffer, but cannot learn strategies outside its support, and its gains depend on the quality and coverage of the logs. The same lesson emerges from the calculator below, on a much smaller stage.

The calculator example below implements the tabular stage; a classifier and then an LLM are possible extensions. Changing the model does not remove the need to define action support; changing the interface can require a different training objective.


BC / SFT as the Baseline

Supervised fine-tuning (SFT) on expert or filtered successful trajectories is behavioral cloning in disguise. It is strong when:

It fails in the same way as BC (Chapter 1): compounding error on long horizons, no use of reward beyond filtering, and no way to combine good segments from mixed-quality episodes.

For multi-step tool use, SFT also cannot assign credit across steps: a trajectory may fail at step 8 while steps 1–7 were sound. Offline RL and advantage-weighted methods exist precisely to exploit partial progress – when rewards and coverage support it.


Offline RL Beyond SFT

DPO vs trajectory-level offline RL

DPO optimizes a sequence-level log-likelihood ratio (a sum of per-token log-probs relative to a reference model), supervised by a pairwise preference label. As a result, it provides weak step-level credit assignment for multi-turn reasoning and tool use.

OREO – Offline Reinforcement Learning for LLM Multi-Step Reasoning (Wang et al., 2024/2025, ACL Findings 2025) – is a useful anchor: it jointly trains an LLM policy and value function via a soft Bellman-style objective, motivated by sparse rewards and credit assignment across reasoning steps. Empirically it improves over DPO-style baselines on math reasoning (GSM8K, MATH) and embodied control (ALFWorld).

A direct precursor is ILQL (Implicit Language Q-Learning; Snell et al., 2023) – IQL (Chapter 5) adapted to language generation: an expectile value function plus an implicit dataset-support constraint, with the policy realized by advantage-reweighting the base model's token logits. It is the most direct bridge from this book's value-pessimism chapters to LLM policies.

The conceptual contrast:

Approach Data Credit assignment
DPO / preference learning Pairwise chosen vs rejected Sequence-level preference signal
Offline RL (OREO-style) Full trajectories + rewards Value function + Bellman backup across steps

Mapping classical offline RL ideas

Let $\pi_b$ denote the policy that collected the logs and $\pi_{\mathrm{ref}}$ the frozen reference model. Two acronyms recur below. RLHF (reinforcement learning from human feedback) fine-tunes a model against a learned reward, usually with a KL penalty to the reference. GRPO (Group Relative Policy Optimization) is an online policy-gradient method that scores each sampled answer against others drawn for the same prompt. TD3+BC fits actions actually observed in the dataset; DPO instead compares sequence probabilities relative to $\pi_{\mathrm{ref}}$. They may be close when the same SFT checkpoint collected the data with matching prompts and sampling, but mixtures of checkpoints, filtering and changed decoding break that correspondence. A reference penalty does not itself establish dataset support. DPO encodes reference regularization through its preference objective; the presence, coefficient and role of an explicit KL penalty in GRPO depend on the implementation.

Do not read this table as “drop in CQL unchanged.” Read it as design vocabulary:

Classical offline RL (this book) Agentic AI analogue
BC SFT on successful traces
Dataset-action constraint (TD3+BC, Ch. 6) Penalize distance to logged actions; this constrains deviation from dataset behavior
Reference-policy regularization KL to a frozen reference in KL-regularized RLHF; DPO uses policy/reference log-probability ratios; GRPO variants differ
AWR / AWAC / IQL-style extraction Weight steps or trajectories by advantage, verifier score, or process reward (ILQL applies IQL directly to token-level language generation)
CQL / pessimism Penalize unsupported tool calls, plans, or API invocations
FQE / learned Q Critic over agent states and actions (text or structured)
Decision Transformer Condition generation on desired return / success label
Model-based offline RL Simulator, verifier, or world model for tool outcomes
OPE (Ch. 3) Environment re-execution / action-conditioned simulation / learned value model; distinguish direct evaluation from fixed-data OPE

Agent Lightning’s LightningRL adds hierarchical credit assignment: allocate trajectory-level return to individual LLM calls, then apply standard single-turn RL updates – a practical pattern when episodes are long but each call is trainable. Treat this as an off-policy RL bridge, not a drop-in replacement for CQL or IQL on fixed logs.


Credit Assignment in Reasoning and Tool Use

Multi-turn agents combine language generation with externalized actions. Rewards often arrive only at episode end (task solved or not). Offline RL methods that maintain a value function – OREO, goal-conditioned critics, or FQE-style models – address the same problem as TD learning in control: which intermediate step contributed?

Online agentic RL highlights how hard this is. RAGEN (Wang et al., 2025) studies multi-turn LLM agent RL (StarPO) and reports instability: reward variance cliffs, Echo Trap dynamics, and shallow or hallucinated reasoning without fine-grained rewards. RAGEN-2 (Wang et al., 2026) analyzes template collapse – fluent but input-agnostic reasoning – and proposes SNR-aware filtering. These are online results, but the caveats transfer directly to offline training: if online agentic RL is unstable, offline agentic RL depends even more on data coverage, reward quality, and evaluator fidelity.

For offline settings, prefer:

A single terminal label is not automatically a statistical dead end, but what the objective is matters. Ren and Xie (2026) study offline RL when each trajectory carries one outcome label, and propose OPAC, a pessimistic actor-critic that learns a latent per-step reward together with the value function. When the objective is the usual sum of per-step rewards and only the total is observed, OPAC's sample complexity is polynomial in the horizon. The barrier appears when the objective itself is trajectory-level: under an all-success objective, where an episode counts only if every step succeeds, the outcome is informative on an exponentially small set of trajectories, and any learner can need on the order of $2^H$ episodes to come close to the optimal policy. Process rewards help precisely there: they return to the data the information that a single all-or-nothing bit discards. A recent survey of credit assignment for LLM agents (Zhang, 2026) adds a second caution: when the log holds only text histories and an earlier state cannot be restored, even the sign of a step's credit may be unidentifiable.

The rest of this section makes these trade-offs precise.

A Decomposition of the Terminal Reward

Let $h_t$ be the history the agent conditions on before its $t$-th decision, $a_t$ the decision itself (a tool call, a plan, a final answer), and $o_t$ what the environment returns, so that $h_{t+1} = (h_t, a_t, o_t)$. An episode has $H$ decisions and one terminal reward $R$. For a policy $\pi$ define

$$Q^\pi(h_t, a_t) = \mathbb{E}_\pi\left[R \mid h_t, a_t\right], \qquad V^\pi(h_t) = \mathbb{E}_{a \sim \pi(\cdot \mid h_t)}\left[Q^\pi(h_t, a)\right], \qquad V^\pi(h_H) = R.$$

These are ordinary value functions with the history in place of the state. No Markov assumption is needed: the history is, by construction, everything that has happened.

Writing $R - V^\pi(h_0)$ as a telescoping sum of $V^\pi(h_{t+1}) - V^\pi(h_t)$ and inserting $Q^\pi(h_t, a_t)$ into each term splits the outcome into two kinds of contributions:

$$R - V^\pi(h_0) = \sum_{t=0}^{H-1} \underbrace{\left[Q^\pi(h_t, a_t) - V^\pi(h_t)\right]}_{A_t:\ \text{the decision}} \;+\; \sum_{t=0}^{H-1} \underbrace{\left[V^\pi(h_{t+1}) - Q^\pi(h_t, a_t)\right]}_{\varepsilon_t:\ \text{the environment}}.$$

The advantage $A_t$ measures how much the decision changed the expected outcome. The term $\varepsilon_t$ measures how much the environment's response did: a search that happened to return the right document, an API that timed out. On trajectories generated by $\pi$, each term has zero mean given everything before it – $A_t$ given $h_t$, and $\varepsilon_t$ given $(h_t, a_t)$. The terms therefore form a martingale difference sequence, are mutually uncorrelated, and their variances add:

$$\operatorname{Var}\left[R - V^\pi(h_0)\right] = \sum_{t=0}^{H-1} \mathbb{E}\left[A_t^2\right] + \sum_{t=0}^{H-1} \mathbb{E}\left[\varepsilon_t^2\right].$$

The identity holds for a fixed prompt $h_0$, and because $\mathbb{E}[R - V^\pi(h_0) \mid h_0] = 0$ for every prompt, it also holds averaged over prompts: subtracting $V^\pi(h_0)$ removes the prompt-to-prompt difficulty $\operatorname{Var}[V^\pi(h_0)]$, which is the job of the baseline below. It also assumes that $R$ is fixed once the episode is over, $V^\pi(h_H) = R$. With a stochastic grader – a human rating, or an LLM judge sampled at nonzero temperature – $V^\pi(h_H) = \mathbb{E}[R \mid h_H]$, and one more term appears, $\varepsilon_H = R - V^\pi(h_H)$, adding $\mathbb{E}[\operatorname{Var}(R \mid h_H)]$ to the variance. That is grading noise: no decision can be credited with it, and averaging several grades per trajectory is the only way to reduce it.

Temporal credit assignment is the problem of recovering the individual $A_t$ from data in which only their sum, mixed with the $\varepsilon_t$, is observed. The identity is a yardstick for the methods below: each is a way of estimating $A_t$, and they differ in which other terms leak into a step's credit. Two caveats keep it honest. The terms are defined for any policy and any history, but whether they can be estimated from fixed logs is a separate question: identification needs assumptions about coverage and about what the logged history captures, and the section on offline estimation below returns to it. And the identity is exact only for the true $Q^\pi$ and $V^\pi$ on complete histories; with learned values or truncated contexts it holds only approximately.

Four Ways to Estimate Step Credit

Trajectory-level advantage. Every step receives the same signal, $R - b$, where the baseline $b$ is a learned $V(h_0)$ or the mean outcome of other attempts at the same prompt, as in GRPO. Summed with the score function $\nabla \log \pi(a_t \mid h_t)$ over trajectories sampled from $\pi$ itself, this is an unbiased policy gradient (on logged trajectories from another policy it needs the importance weights discussed next), but as credit for one step it is $A_t$ plus every other advantage plus every $\varepsilon$: its variance is the whole sum above and grows with the horizon. Offline there is a second cost. The trajectories come from $\pi_b$, and turning them into a signal for a new policy requires importance weights $\prod_t \pi(a_t \mid h_t) / \pi_b(a_t \mid h_t)$, whose variance grows exponentially in $H$ (Chapter 3). Filtering successful traces for SFT is the degenerate case: weight one if $R = 1$, zero otherwise.

Value learning over tool decisions. Fit $Q(h_t, a_t)$ and $V(h_t)$ by Bellman backups and use $\hat{A}_t = \hat{Q}(h_t, a_t) - \hat{V}(h_t)$. The target $V(h_{t+1})$ already reflects $o_t$, so an unlucky tool response is charged to $\varepsilon_t$ rather than to the decision before it – exactly the separation that trajectory-level signals cannot make. The price is bias, from two sources specific to agents. First, nobody fits a value over raw histories: the network sees an encoding $\phi(h_t)$, such as a truncated context, a summary or an embedding. When two histories with different prospects share an encoding, their values are averaged, the identity no longer holds for the learned quantities, and credit leaks between steps. Second, offline, $Q(h_t, a)$ is needed for calls the logs never made, whose responses were never observed. In-sample methods sidestep this: fitting $Q^{\pi_b}$ by SARSA-style backups and improving one step (Chapter 5, $\tau = 0.5$), or IQL's expectile regression, which never evaluates an unlogged call. OREO and ILQL belong to this family.

Process rewards. Add a per-step reward from a verifier, or from a process reward model (PRM) trained on human step labels (Lightman et al., 2023) or on the success rate of continuations sampled from each prefix (Math-Shepherd; Wang et al., 2024). Whether this changes what the agent optimizes depends on the form of the reward. Ng, Harada and Russell (1999) showed that adding $F_t = \gamma\,\Phi(h_{t+1}) - \Phi(h_t)$ for any potential $\Phi$ leaves the optimal policy unchanged: the discounted sum of $F_t$ telescopes to $\gamma^H \Phi(h_H) - \Phi(h_0)$, which does not depend on the actions when $\Phi(h_H)$ is a constant, as it is at a terminal state. The factor $\gamma$ matters; without it the sum keeps terms that depend on the intermediate histories, and the optimal actions can change. The setting of this section is undiscounted ($\gamma = 1$), where $F_t = \Phi(h_{t+1}) - \Phi(h_t)$. Take $\Phi = V^\pi$. Then $F_t = A_t + \varepsilon_t$ exactly, but $\Phi(h_H) = V^\pi(h_H) = R$ is not a constant, so the theorem does not apply as stated; what holds instead is that the shaping terms sum to $R - V^\pi(h_0)$. Training on these process rewards alone therefore ranks trajectories exactly as the outcome $R$ does, shifted by a quantity fixed by the start; added on top of $R$, they count the outcome twice, which again leaves the ranking unchanged. Either way, a PRM that predicts the probability of eventual success is value learning under another name and inherits its biases. A PRM that scores something else – fluency, the formal validity of a step, agreement with a judge – is not of this form, changes the objective, and invites the agent to collect process reward without finishing the task. Labels of the Math-Shepherd kind also require restarting the episode from a prefix, which fixed logs do not allow.

Return decomposition. Learn a redistribution $\tilde{r}_0, \dots, \tilde{r}_{H-1}$ with $\sum_t \tilde{r}_t = R$ and train on the dense rewards. RUDDER (Arjona-Medina et al., 2019) predicts the return from each prefix and gives each step the change in that prediction. With an exact predictor of $Q^\pi$ the redistributed reward is $Q^\pi(h_t, a_t) - Q^\pi(h_{t-1}, a_{t-1}) = A_t + \varepsilon_{t-1}$: the decision, plus the luck of the observation that preceded it. Ren and Xie's latent per-step reward, above, is a statistical version of the same idea. The constraint $\sum_t \tilde{r}_t = R$ does not determine the split by itself: every redistribution that sums correctly fits the outcome labels equally well. Decomposition therefore needs structure – additivity over steps, a function class small enough to generalize – and when the predictor sees $\phi(h_t)$ rather than $h_t$, the aliasing problem returns.

Method Credit given to step $t$ Needs Main source of error Offline risk
Trajectory-level advantage $R - b$: all $A_s$ and all $\varepsilon_s$ Outcome labels Variance growing with $H$ Importance weights explode with $H$
Value learning $\hat{Q}(h_t,a_t) - \hat{V}(h_t)$ Bellman backups over $\phi(h)$ Aliasing in $\phi$; approximation Unlogged calls: needs in-sample learning or pessimism
Process reward, potential-based $\approx A_t + \varepsilon_t$ PRM or verifier PRM error; non-potential terms change the objective Step labels need a resettable environment
Return decomposition $\approx A_t + \varepsilon_{t-1}$ Return predictor over prefixes Split not identified without structure Aliasing; predictor fitted only to $\pi_b$'s data

What Changes Offline

Every quantity above is defined relative to a policy. The logs give $A^{\pi_b}$: the credit of a decision assuming the logging policy continues afterwards. That is what one-step methods use, and it is the safe choice. The credit of a decision under the improved policy requires continuations that the logs do not contain – the extrapolation problem of Chapters 2 and 4, now with tool responses that were never observed.

There is also an evaluation problem: credit has no ground truth in the logs. Where the environment can be reset, rolling out several continuations from a logged prefix estimates $Q(h_t, a_t)$ directly, and that is the right benchmark for any credit estimator, even one trained only on logs. Where the state cannot be restored and only text was logged, Zhang's caution applies: credit may not be identifiable at all.

Temporal Versus Multi-Agent Credit

With several agents, the decision at step $t$ is a joint action $a_t = (a_t^1, \dots, a_t^n)$. The identity above still splits the outcome along time; dividing each $A_t$ among agents is a separate problem along a different axis. Counterfactual baselines answer the second question: COMA (Foerster et al., 2018) compares the joint $Q$ with its average over one agent's alternative actions, the other agents' actions held fixed. Mixing the two problems – assigning a team outcome directly to one agent's step, say – confounds a teammate's work with luck and with earlier decisions. Resolving credit over time first and then across agents is a convenient decomposition, not a theorem: when agents act simultaneously and their actions interact, the two axes need not separate without structural assumptions, such as an additive team value. What the data must allow in any case is keeping them apart, which is why the logging schema below has separate team and individual reward fields.

Open Problems


OPE for Agents

Chapter 3’s OPE toolbox applies, but agent environments rarely offer a faithful closed-form simulator.

Practical evaluation layers:

  1. Environment re-execution / action-conditioned simulation – execute candidate actions in a resettable sandbox, or simulate their outcomes under explicit model assumptions; cached responses require matching actions and environment snapshots.
  2. Verifiers – unit tests, SQL result checks, retrieval precision, code execution outcomes.
  3. Learned critics – FQE-style $Q(s,a)$ or goal-conditioned value models trained on logs. Planning without Search (Hong et al., 2025) – uses offline goal-conditioned values as a natural-language critic at inference without fine-tuning the base LLM.
  4. Human or A/B review – expensive but necessary for high-stakes deploy.

Offline RL for agents fails quietly when OPE measures format quality instead of task success. Align metrics with deployment risk, as in Chapter 3’s coverage warnings.

Replay Is Not Counterfactual Evaluation

Distinguish three operations before interpreting an evaluation score:

  1. Exact trace replay feeds the same recorded actions and observations through the pipeline. It tests parsing, state reconstruction and regressions, but cannot measure the return of a policy that chooses different actions.
  2. Environment re-execution executes the candidate's actual actions in a resettable sandbox. It estimates performance in that environment; transfer depends on sandbox fidelity, tool versions and representative initial tasks. It is direct interaction with a test environment, rather than evaluation from a fixed dataset alone.
  3. Simulator rollout generates observations conditioned on each new action and the current simulated state. A learned simulator adds model bias, especially outside logged support; validate it separately and report uncertainty.

Four ways to score a candidate agent policy: exact replay, re-execution, simulator rollout and an invalid stitched cache

A cached response may be reused only when the complete request and relevant environment state match: arguments, authentication scope, document/database snapshot, tool version and any random inputs that affect the result. Determinism alone is insufficient if the snapshot changed. A cache miss must trigger sandbox execution, a validated simulation, or an explicit unsupported outcome; never silently substitute a response from another action.

For example, a recorded open_pdf(page=42) result cannot become the observation after open_pdf(page=43). Even the same page number is insufficient if the underlying filing changed. Reusing the old observation hides the consequences of the candidate's decision and creates an invalid counterfactual.

Report which operation produced each metric. Exact replay can establish that a pipeline reproduces a logged run; it cannot establish that a new policy improves task success. For unavailable environments, use supported statistical OPE or learned value estimates with their assumptions and coverage limitations, rather than treating cached transcripts as new rollouts.

Recent work gives this warning a measurement. In The Replay Gap (Gonuguntla, 2026), a workshop study on SWE-bench Verified, agent trajectories are forked midway and continued with a different model. The switch rewrites 61–94% of the subsequent actions, and an evaluator that stitches logged outputs together mispredicts all five cases in which success actually changed. The sample is small, yet the direction is clear: a stitched log scores a world the new policy would never visit. A learned simulator is the constructive alternative. ADWM (Liu et al., 2026) models each transition of a multi-turn agent with a latent diffusion world model trained on logged trajectories; on HotpotQA, ScienceWorld, ALFWorld and WebShop it ranks candidate policies more reliably than the direct method, FQE, importance sampling and doubly robust estimators. The authors are careful about scope: the experiments do not cover fully out-of-support policies, and rank correlation says nothing about the calibration of absolute values.

Evaluation Contract for an Agent Policy

OPE methods tell you how to estimate return; they do not define what counts as improvement. For tool-using agents, a policy can raise task success while increasing cost, latency, redundant tool calls, or safety violations. Before comparing offline-trained candidates, write a short evaluation contract – a spec stakeholders can execute without re-debating metrics after every training run.

Baselines (always report against both):

  1. Current deployed agent – the behavior policy in production (or the best available shadow of it).
  2. SFT / BC on successful traces – imitation on filtered wins; the honest “no RL” ceiling when logs are good but sparse on reward structure.

Metric groups (do not collapse to one number):

Group What to measure Typical role
Task success Verifier pass rate, task completion, human accept rate Primary – the metric you want to improve
Cost / latency USD per episode, tokens, p95 wall-clock per task Guardrail
Tool-call efficiency Calls per episode, duplicate lookups, empty retries Guardrail
Safety / constraints Forbidden tools, PII leaks, policy violations, out-of-allowlist APIs Guardrail

Evaluation set: Use a held-out task suite – never tasks seen during training or prompt tuning. Stratify by task type (search, code, CRM, etc.) and difficulty (single-hop vs multi-hop). Report per-stratum tables, not only a global average. Chapter 3’s coverage warnings apply: OPE on logs is not a substitute for held-out task eval when deploy states differ from the log.

Acceptance rule (example template):

Accept candidate policy $\pi$ over baseline $b$ only if:

If primary improves but a guardrail breaks tolerance, the answer is not to ship with caveats by default – iterate on reward shaping, constraints, or support filtering until the contract is satisfied or the candidate is rejected.

Illustrative comparison (fictional numbers):

Policy Success (held-out) Cost / task Tool calls / task Safety violations
Deployed agent 62% $0.041 4.2 0.3%
SFT / BC 68% $0.038 3.9 0.2%
Offline RL candidate 71% ± 2% $0.044 4.0 0.2%

With tolerances $\tau_{\text{cost}} = +5\%$ and $\tau_{\text{calls}} = +10\%$, the candidate passes success and safety but fails cost ($0.044 > 1.05 \times 0.041$). The contract rejects deployment until cost is brought down – even though success beat both baselines.

This contract is the agentic analogue of Chapter 13’s Industrial Deployment: Gated Readiness: offline metrics and OPE inform Gate 2; the evaluation contract is what Gate 3 (shadow) and Gate 4 (limited rollout) must verify on live tasks.


LLMs as Annotators, Generators, and Critics

LLMs appear in agentic offline pipelines in several roles – not only as the policy. KALM and TEDUO are LLM-assisted offline RL lines (language-conditioned or rollout-augmented control), not always narrow “tool-using chat agents” – but the data-layer pattern transfers:

Role Example Offline RL connection
Trajectory generator KALM (Pang et al., NeurIPS 2024) – LLM imaginary rollouts merged with real data, then standard offline RL Expands coverage; watch semantic gap between text and low-level actions
Dataset labeler TEDUO – hindsight labeling and state abstraction on unlabeled logs, then offline RL + SFT LLM as annotator before RL
Inference-time critic Planning without Search (arXiv:2505.18098) – goal-conditioned value function guides plan refinement Offline RL trains critic; base LLM may stay frozen
Environment generator SPADE (Liu et al., 2026) – an LLM writes executable environments with reset()/step(); an online self-play method, not offline RL Executable, resettable environments make re-execution OPE and prefix rollouts possible; synthetic tasks may not transfer to production tools
Reward model LLM-as-judge scores Cheap but gameable; combine with verifiers

KALM grounds the LLM on environment dynamics before generating rollouts – addressing the semantic gap between tokens and numerical state. TEDUO shows LLMs can enrich unlabeled interaction logs so offline RL has goals and abstract states to condition on.


Failure Modes

Agentic offline RL inherits classical offline RL failures and adds agent-specific ones:

Conservative methods (CQL-style pessimism, support constraints, rejection of low-coverage tool branches) are conceptually appropriate but require defining action support in structured action spaces – an open engineering problem.


Toy Example: Offline RL for a Calculator Agent

This example intentionally removes language modeling complexity. The policy does not generate free text; it chooses among structured tool calls. That isolates the offline RL question: can we improve over logged behavior using value learning and support constraints?

📄 Full code: agentic_offline_rl_toy.py

Environment

The agent solves x + y, x - y, or x * y but never sees x and y directly. It must call tools:

Action Effect
lookup_x observe hidden $x$
lookup_y observe hidden $y$
add / sub / mul compute on known values
estimate a tempting shortcut that returns a plausible but wrong result; the logging policy never uses it
final submit answer (verifier checks against true task)

Rewards: +1 correct final answer, −1 wrong final or invalid tool, −0.02 per step (latency/cost proxy).

This mirrors an LLM agent trace:

Real agent Toy analogue
Context window Discrete state tuple
Tool-call JSON Discrete action
Tool output Observation update
Final answer final action
Verifier Exact arithmetic checker
Agent trace Offline RL transition

The tabular state key is (task, x, y, result), with None for values not yet observed. Keeping the observed operands as well as the result prevents correct and incorrect outcomes from sharing a key. The policy never receives hidden operands before lookup.

Four policies on two datasets

Policy Role
Behavior Stochastic logger (sometimes wrong op)
BC Majority action per state in logs (SFT-on-traces)
Naive FQI Tabular fitted Q with greedy improvement over valid actions; ties broken at random
Support-constrained FQI Same, but argmax restricted to logged actions at each state; abstains if none are supported (support mask, not the CQL objective)

Two data regimes:

  1. Good coverage – mul appears in logs when the task is multiplication.
  2. Coverage gap – on mul tasks, behavior logs only add / sub, never mul.

An unknown state or an empty valid support set makes the constrained policy abstain (None); evaluation counts this as an unsuccessful termination.

Run: python code/agentic_offline_rl_toy.py

Example output (deterministic for the default seed; other seeds give slightly different numbers):

Dataset: good coverage (mul in logs)
  mul-task op support (x,y known): ['add', 'mul', 'sub']
  Behavior success (all tasks):    0.72
  BC success:                    0.99
  Naive FQI success:             1.00  (range 1.00–1.00 over tie-breaks)
  Support-constrained FQI:       1.00

Dataset: no multiplication support
  mul-task op support (x,y known): ['add', 'sub']
  Behavior success (all tasks):    0.52
  BC success:                    0.67
  Naive FQI success:             0.83  (range 0.81–0.85 over tie-breaks)
  Support-constrained FQI:       0.72
  --- mul tasks only ---
  BC / naive FQI / constrained:  0.01 / 0.51 / 0.02

What this demonstrates

  1. BC clones the behavior policy. It improves over raw logging when the majority action at a state is good, but cannot invent unsupported tools.
  2. Naive FQI can stitch successful sub-trajectories (lookup_x → lookup_y → correct op → final) when coverage exists.
  3. Without mul in the logs, support-constrained FQI never selects multiplication. It may still succeed when a supported operation happens to give the same answer. That is the conservative behavior you want offline.
  4. Naive FQI on mul tasks faces two actions the logs never contain, mul and estimate. Both keep the default Q-value of 0, which beats the negative Q of the logged wrong operations, so naive FQI picks one of them – and which one is decided by a tie-break, not by evidence. Averaged over tie-breaks it solves about half of the multiplication tasks: right when it happens to pick mul, wrong when it picks estimate. That is the extrapolation / OOD action effect in miniature. Its overall score looks better than the constrained policy's, but the gain is a coin flip that the data cannot call in advance; in deployment, the unsupported choice could just as well be the harmful one.

Thesis (same as classical offline RL): improvement is possible inside the action/state support of the dataset; conservative methods refuse unsupported gains; unconstrained value learning can overtrust unvisited actions.

Start with this tabular agent before LLM confounders (stochastic decoding, prompt drift, missing log-probs, expensive OPE). A natural next step is replacing the tabular policy with a small classifier over trace states, then an LLM that proposes tool calls filtered by a support or critic model.


From Agentic Offline RL to Offline MARL

Everything so far has assumed a single tool-using agent. When several agents act in one episode, that assumption fails for a specific reason. If the other agents' policies are held fixed, each agent still faces a (PO)MDP: its teammates are part of the environment. Offline training, however, changes several policies at once, so the dynamics each agent experiences shift with its teammates' behavior, and logs collected under the old teammate policies no longer describe the new environment. The appropriate model is a stochastic (Markov) game; with local observations and a shared team reward, a Dec-POMDP. Concatenating all agents' turns into one transcript discards who observed what and who chose which action, which is exactly the information needed to estimate support and assign credit.

Notation. With $N$ agents, let $s_t$ be the joint state (shared workspace or ticket state), $o_t^i$ the local observation of agent $i$ (its prompt, tools and private memory), and

$$a_t = (a_t^1,\ldots,a_t^N)$$

the joint action, where $a_t^i$ is a message, a tool call or a plan step. Rewards can be shared by the team ($r_t$), individual ($r_t^i$), or a mix of both. A usable log therefore records per-agent observations and actions, not only the merged conversation.

Single-agent offline RL does not address three problems that arise here:

  1. Joint-action coverage. Support is defined over tuples $(a^1,\ldots,a^N)$, not over each agent's actions separately. Logs can contain "agent A searches" and "agent B edits" in different episodes and never the combination needed at deployment. If each agent is constrained only to its own logged actions, the team can still execute a joint action that never appears in the data.
  2. Credit assignment across agents. A team success does not indicate which agent's step produced it. Separating an agent's contribution from luck and from teammates' work requires agent- or role-level returns, counterfactual baselines or process rewards.
  3. Coordination conventions. Multi-agent logs encode who speaks when, which role owns which tool and how handoffs work. Improving each agent's policy separately can break the conventions that made the logged episodes succeed.

LLM stacks often conflate two learning problems:

Level What is learned Typical offline data
Shared LLM (post-training) One base model used by several roles or prompts Preference pairs, successful multi-agent traces for SFT, optionally per-agent credit
Orchestration policy Who acts next, when to hand off, how to route tools and messages Logs of routers, schedulers or Autogen/LangGraph graphs, treated as a separate decision process

Fine-tuning the shared LLM on role-conditioned traces (DPO, SFT or single-agent offline RL) updates a different policy from the orchestration policy that chooses joint actions. State which of the two a method updates; otherwise multi-agent failure modes enter under the label of agent fine-tuning.

Example. Two agents act at the same step without seeing each other's choice: agent 1 picks a query $m \in \{A, B\}$ while agent 2, working in parallel, picks a tool $u \in \{a, b\}$. The team receives $r = 1$ only for the pairs $(A, a)$ and $(B, b)$. Under a uniformly random behavior policy, every individual query and every individual tool succeeds in half of the logged episodes, so per-agent action values are all equal and carry no signal; only the value of the pair separates good from bad behavior. Agents that learn their own values from these logs – independent learners – have nothing to break the tie, choose independently, and end up at a mismatched pair such as $(A, b)$ half of the time. The example depends on the moves being simultaneous. If agent 2 observed $m$ before choosing, the problem would reduce to a two-step MDP that ordinary dynamic programming on the concatenated transcript solves exactly; credit assignment across agents becomes hard when an agent cannot see what it has to coordinate with. Offline MARL methods model the joint action explicitly for this reason.

Classical offline MARL already offers tools for this. MACCA (Wang et al., 2025) represents the offline data as a dynamic Bayesian network and identifies each agent's causal contribution to the reward. For LLM agents the nearest work is still online. LangMARL (Yao et al., 2026) uses a centralized language critic to assign credit to each agent and rewrites the agents' natural-language policies, their instructions and exemplars, rather than model weights, collecting fresh rollouts at every iteration. Carrying such agent-level credit over to fixed logs remains an open problem.

This chapter deliberately stays with a single agent. If your product is multi-agent, the evaluation practices above and the logging schema below still apply; the schema includes a multi-agent extension. Single-agent conservative RL does not carry over directly: its support constraints and credit assignment must first be redefined for joint actions and team rewards.


Practical Logging Schema

For applied work, a consistent JSON (or parquet) schema matters as much as algorithm choice:

{
  "episode_id": "task_001",
  "t": 3,
  "task": "Find quarterly revenue in uploaded 10-K",
  "state": {
    "user_goal": "...",
    "conversation_history": "...",
    "available_tools": ["search", "open_pdf", "calculator"],
    "memory": "...",
    "retrieved_context": "..."
  },
  "action": {
    "type": "tool_call",
    "tool": "open_pdf",
    "arguments": {"page": 42}
  },
  "observation": {
    "tool_result": "...",
    "error": null
  },
  "reward": 0.0,
  "terminated": false,
  "truncated": false,
  "prompt_version": "agent_prompt_v12",
  "tool_schema_version": "tools_2026_06_20",
  "environment_version": "sandbox_v3",
  "action_logprobs": null,
  "reward_components": {
    "task_success": 0.0,
    "format_valid": 1.0,
    "tool_error_penalty": 0.0,
    "cost_penalty": -0.0031
  },
  "reward_source": "verifier_v2",
  "verifier_version": "sec_filing_checker_2026_06",
  "task_family_id": "sec_revenue_extraction_filing_001",
  "source_hash": "sha256:<source-snapshot-digest>",
  "collection_window": {"start": "2026-06-01", "end": "2026-06-30"},
  "split": "train",
  "metadata": {
    "behavior_policy": "gpt-4.1-agent-v3",
    "temperature": 0.2,
    "latency_ms": 1400,
    "cost_usd": 0.0031,
    "safety_flags": []
  }
}

Design choices:

Multi-agent extension

Attach this record to each acting agent's transition; the parent record holds its action and episode identifier.

{
  "multi_agent_extension": {
    "joint_step_id": "task_001:3",
    "turn_id": 7,
    "agent_id": "reader_1",
    "role": "document_reader",
    "recipient_ids": ["analyst_1"],
    "local_observation": {
      "visible_document": "filing_snapshot_v1",
      "message": "Read page 42"
    },
    "policy_checkpoint": "reader_policy_v3",
    "team_reward": {
      "value": 0.0,
      "source": "task_verifier_v2"
    },
    "individual_reward": {
      "value": 0.0,
      "source": "tool_validity_v1"
    },
    "credit_label": {
      "value": null,
      "source": null
    }
  }
}

Use joint_step_id to link actions and messages belonging to one environment decision; turn_id preserves order within it. Record each agent's local observation, recipients and checkpoint here; the probability of its actual sampled action under the collection-time policy, including sampling settings, goes in the parent record's action_logprobs, so it is not duplicated. A null probability means unknown, not zero.

A flat transcript does not preserve private observations, simultaneous decisions or policy provenance. Team reward, individual reward and later credit annotations have different meanings and sources; a credit label is not an observed counterfactual. These records enable reconstruction but do not identify counterfactual contributions without additional assumptions or interventions.

Dataset Splits and Leakage

Assign splits before extracting transitions, keeping whole episodes together. Group related episodes by task family and source document: variants, shared cached outputs and near-duplicate sources must not cross splits. Record task_family_id, source_hash (of the source snapshot) and collection_window; a hash alone does not detect semantic duplicates.

Define the grouping granularity first: task_family_id identifies a base task and its related variants, not a broad category such as all revenue-extraction tasks. Hold out independent task groups and source documents within the intended task categories to test new instances. Holding out entire categories instead tests transfer to unseen task families; label that result separately. Add a temporal/version holdout collected later or under changed prompts, tools or environments, and report it separately because version changes also test robustness.

Leakage checklist:


Limitations and Honest Scope

This is a rapidly moving research area, not a settled production stack. Most deployed agents still train via SFT + online RLHF/GRPO loops. Offline RL for agents is strongest when:

When those conditions fail, invest in logging, BC baselines, and OPE before value-based offline RL.

See the Appendix: Algorithm Selection Guide for classical method anchors. Chapter 13 concludes the book.


References