Agents in the World
Multi-agent systems, robots and LLM agents.
A Q-table masters one gridworld. An agent in the world must act on partial observations, plan with a model it learned itself, share the world with other learners, control a body whose physics no simulator gets exactly right, and, more and more often, run a language model inside its loop. This lesson builds the machinery for each: Dyna and model-predictive control, Markov games and mixed equilibria, imitation with DAgger, and the ReAct loop, along with the arithmetic of why long tasks fail.
What you’ll learn
- Explain why agents act on histories rather than states, and compare reactive, model-based and hybrid agent architectures.
- Implement Dyna-Q and model-predictive control with the cross-entropy method, and derive how the error of planning with a learned model and a learned value function depends on the horizon.
- Define Markov games and Nash equilibria, compute a mixed equilibrium of a zero-sum game by indifference, and explain why independent learners face a non-stationary problem.
- Explain domain randomization, the covariate shift of behavior cloning, and how DAgger turns its worst case into .
- Describe the ReAct loop of a language-model agent, and compute how per-step reliability compounds over a long task.
From percepts to actions: agent architectures
An agent maps the history of its percepts to actions. In the RL lessons so far the percept was the state of an MDP; in the world it rarely is. A camera frame does not show velocities, a web page does not show the database behind it, and two corridors can look identical. The formal model is the partially observable MDP: an MDP plus an observation kernel , where the agent sees only the history . A sufficient summary of is the belief state , updated by Bayesian filtering:
The belief evolves as a Markov process, so planning over beliefs is again an MDP (POMDPs & Belief States). Exact beliefs are intractable beyond small problems, so practical agents compress the history into a learned memory: a recurrent state, a transformer over recent observations, or a language model's context window.
| Architecture | Chooses actions by | Strengths | Weaknesses | Examples |
|---|---|---|---|---|
| Reactive (model-free policy) | one forward pass, | fast at decision time; immune to model error | data-hungry; retrained when the goal changes | DQN and PPO policies |
| Planner (model-based) | optimizing actions inside a model at every step | sample-efficient; one model serves many goals | compute at decision time; the optimizer exploits model errors | MPC, PETS |
| Hybrid | a learned policy or value guiding search in a model, or a model generating training data | gets both benefits when the model is good | two error sources to manage | Dyna, AlphaZero, MuZero, Dreamer |
Think first A robot drives down one of two corridors, equally likely, that look identical except for a colored sign at the entrance. At the far end it must turn left in one corridor and right in the other. Its policy sees only the current camera frame. What success rate at the junction can it guarantee in both corridors, and what would fix it?
50%. At the junction both corridors produce the same observation, so a memoryless policy uses the same action distribution in both: if it turns left with probability , it succeeds with probability in one corridor and in the other. Remembering the sign, which is what a belief state or a learned memory does, restores perfect play. A bigger network or more exploration cannot recover information that is not in the input.
Model-based RL in practice: Dyna and MPC
A learned model , can be used in two ways. Background planning turns it into extra training data for a model-free learner. Decision-time planning optimizes actions inside it at every step. Dyna (Sutton, 1990) is the simplest instance of the first: after each real step, it replays simulated transitions drawn from the model.
function DYNA-Q(n, α, γ, ε):
Q(s, a) ← 0; Model ← empty
loop over real time steps:
S ← current state; A ← ε-greedy action for Q in S
take A; observe reward R and next state S′
Q(S, A) ← Q(S, A) + α · (R + γ · max_a Q(S′, a) − Q(S, A)) # real update
Model(S, A) ← (R, S′) # deterministic world
repeat n times: # planning
s, a ← a previously visited state and an action taken there
r, s′ ← Model(s, a)
Q(s, a) ← Q(s, a) + α · (r + γ · max_b Q(s′, b) − Q(s, a))With this is Q-learning. Each real transition is now used times: in Sutton & Barto's maze example (§8.2), Dyna-Q with found the shortest path in about 3 episodes, against about 25 without planning. The price is trusting the model; if the world changes, simulated updates keep teaching the old world until real experience corrects it.
Model-predictive control (MPC) plans at decision time. It searches for the best action sequence over a horizon in the model, executes only the first action, observes the real next state, and plans again, so feedback from the world keeps correcting the model's drift. With continuous actions, a common optimizer is the cross-entropy method (CEM), which refits a Gaussian over action sequences to the best samples.
function MPC-CEM(model f̂, reward r, value V̂, state s, H, N, K, I):
μ[1..H] ← 0; σ[1..H] ← σ0 # Gaussian over action sequences
repeat I times:
sample N sequences a(j)[1..H] ~ Normal(μ, σ²)
for each j: # imagined rollout from the real state
ŝ ← s; G(j) ← 0
for t = 1..H:
G(j) ← G(j) + γ^(t−1) · r(ŝ, a(j)[t]); ŝ ← f̂(ŝ, a(j)[t])
G(j) ← G(j) + γ^H · V̂(ŝ) # optional terminal value
E ← the K sequences with the largest G(j)
μ, σ ← mean and standard deviation of E, per time step
return μ[1] # act, observe, then plan againEach real step costs model evaluations, for example , so MPC needs a fast model and batched rollouts. PETS (Chua et al., 2018) planned this way through an ensemble of probabilistic networks, averaging over the ensemble so that the errors of any single model are harder to exploit. MBPO (Janner et al., 2019) went the Dyna way instead, using short model rollouts branched from real states as training data for a model-free learner.
How far to trust a learned model
Planning steps with a model and then bootstrapping from a learned value , as the optional line in MPC-CEM does, mixes two sources of error. How the mix depends on follows from the rollout bound proved in World Models & Video Generation.
Evaluate a policy from state by , where hats denote rollouts in the model. Rewards lie in , the model's one-step error is , and takes values in and is within of 's true value everywhere. Split the error into the simulated rewards and the terminal term:
After steps the simulated and real state distributions differ by at most in total variation, and a function with range changes in expectation by at most times the total variation. So the reward at step is off by at most , and the terminal term by at most :
The bracket has a closed form: start from and subtract the tail from on. The bound then interpolates, with weight , between the error of a pure value function () and the simulation-lemma error of a pure model (, Bellman Equations & Contraction):
A planner that picks the best of its candidates loses at most twice this bound against the best candidate. Short lookahead leans on : with , ten steps of planning still leave weight on the value error. Short-horizon planners with learned models, such as TD-MPC (Hansen, Wang & Su, 2022) and MuZero (Schrittwieser et al., 2020), therefore need a good value function, while long-horizon MPC without one needs a good model.
The bound is a worst case over all errors of size . A planner, however, does not meet errors at random: it seeks out actions the model overrates. The widget shows the extreme case, a model that is exactly right except that it leaves out slipping.
Many agents: Markov games and equilibria
When several agents learn in one environment, each one's best behavior depends on the others'. The model is a Markov game (Shapley, 1953; Littman, 1994): states , players with action sets , a transition kernel driven by the joint action , and one reward function per player. A joint policy gives each player a value . A game is fully cooperative when all the are equal, zero-sum when two players have , and general-sum otherwise.
| Kicker aims | Keeper dives left | Keeper dives right |
|---|---|---|
| left | 0.60 | 0.90 |
| right | 0.95 | 0.70 |
In equilibrium, how often should the kicker aim left, in percent?
Show the answer
45 %
, from the keeper's indifference condition derived below. The kicker aims right more often, but not always: any predictable preference would be exploited.
No pure pair is stable: against a keeper who always dives left the kicker aims right, against which the keeper dives right, and so on around the cycle. So both players mix. In a mixed equilibrium each player's mix makes the opponent indifferent between its actions, since otherwise the opponent would play its better action purely. With the probability of aiming left, the keeper is indifferent when
Likewise the keeper's probability of diving left makes the kicker indifferent:
The value, the scoring probability under these mixes, comes out the same from either side, as the minimax theorem promises:
Each mix is pinned by the opponent's options, not by the player's own favorite. Palacios-Huerta (2003) found professional penalty kicks consistent with minimax play.
The simplest way to learn in a Markov game gives each agent its own Q-learner and treats the others as part of the environment. From player 's view the transition kernel is
which changes whenever the other players' policies change. The environment is non-stationary: the convergence theorem of Convergence of Q-Learning no longer applies, replay buffers fill with experience against opponents that no longer exist, and learners can cycle or settle on poor coordination (Claus & Boutilier, 1998).
Two remedies dominate. Centralized training with decentralized execution gives critics access to all agents' observations and actions during training, which makes their targets stationary again, while each actor still acts on its own observations (MADDPG; QMIX for teams). Self-play trains against copies and past versions of oneself in zero-sum games, as in AlphaZero (AlphaGo & AlphaZero), and populations of diverse opponents guard against strategy cycles, as in AlphaStar's league for StarCraft II (Vinyals et al., 2019).
Two warehouse robots each run tabular Q-learning, treating the other as part of the environment. Which assumption behind single-agent Q-learning's convergence guarantee breaks?
- That rewards are bounded
- That the discount factor is below 1
- That each agent's transition and reward probabilities stay fixed: they depend on the other robot's policy, which keeps changing
- That the state space is finite
Show the answer
C. That each agent's transition and reward probabilities stay fixed: they depend on the other robot's policy, which keeps changing
Averaged over the other robot's action, depends on , which moves as the other robot learns. The stationarity behind the stochastic-approximation argument is gone, so convergence can fail even though each learner is sound on its own. A centralized critic that conditions on both actions restores stationary targets.
Robots: learning from simulators and demonstrations
A real robot practices slowly, breaks things and needs someone to reset it, so robot learning leans on two cheaper sources of data, each with its own error to control.
Simulation is fast and safe, but its physics and rendering differ from reality: contact and friction are approximate, actuators have unmodeled delays, and images look synthetic. A policy optimized in one simulator overfits its quirks, as the cliff example showed. Domain randomization trains across a distribution of simulator parameters (masses, friction coefficients, latencies, textures, lighting, camera poses), solving
in the hope that the real world looks like one more sample from . Tobin et al. (2017) trained an object detector only on simulated images with random, deliberately unrealistic textures, and it localized real objects to within about 1.5 cm, enough for a robot arm to grasp them. Randomizing the dynamics as well transferred control policies (Peng et al., 2018), and a robot hand trained entirely in simulation manipulated a Rubik's cube through full solves, with the move sequence supplied by a standard solver (OpenAI et al., 2019).
Demonstrations come from a human teleoperating the robot or from an expert controller. Behavior cloning treats them as supervised learning, fitting to the expert's state–action pairs; ALVINN (Pomerleau, 1989) learned to steer a van this way. The catch is distribution shift: a small mistake takes the robot to a state the expert never visited, where the policy was never trained, so mistakes compound. With per-step error on the expert's own states, the expected extra cost of a -step task can grow as (Ross & Bagnell, 2010; proved in Sequence-to-Sequence Models). DAgger (Ross, Gordon & Bagnell, 2011) removes the mismatch by collecting expert labels on the states the learner itself visits.
function DAGGER(expert π*, iterations N, episodes m):
D ← state–action pairs demonstrated by π*
π̂(1) ← TRAIN(D)
for i = 1..N:
run π̂(i) for m episodes; record every state s it visits
D ← D ∪ { (s, π*(s)) } # the expert labels the learner's states
π̂(i+1) ← TRAIN(D) # supervised learning on all data so far
return the best π̂(i) on validation runsThe original algorithm also lets the expert act with a probability that decays to 0 over the iterations. Training on the learner's own state distribution gives , where is the training error on the aggregated data and bounds the extra cost of a single mistake if the expert takes over afterwards. When mistakes are recoverable, is a small constant and the gap is linear in ; when one mistake can be fatal, can be of order , and DAgger's bound is quadratic too. The proof is in Robot Learning & Sim-to-Real.
Think first A behavior-cloned policy and a DAgger policy both err on 1% of steps, behavior cloning on the expert's states and DAgger on its own. What do the two worst-case bounds say about a 100-step task with costs in per step and ?
Behavior cloning: , the cost of failing every step, so the guarantee says nothing. DAgger: , one step's worth of cost. Doubling the horizon would quadruple the first bound and only double the second.
Language models as agents
A language-model agent puts an LLM in the agent loop. The context holds the instructions, the available tools and the history of actions and observations; the model generates text; a harness parses that text into a tool call (a search, a code execution, an API request, a click), runs it, and appends the result as the next observation. ReAct (Yao et al., 2023) interleaves free-text reasoning steps, or thoughts, with these actions, so the model can plan, track its progress and react to what the tools return. Toolformer (Schick et al., 2023) trained a model to decide for itself where an API call helps. Both were introduced in Prompting, Retrieval & Tool Use.
function REACT-AGENT(model M, task, tools, max_steps):
context ← [instructions, tool descriptions, task]
for t = 1..max_steps:
output ← M.generate(context, stop before "Observation:")
context.append(output) # "Thought: … Action: tool[args]"
if output contains "Final answer: y": return y
tool, args ← PARSE(output) # malformed output is an error too
observation ← tools[tool](args) # untrusted text from the world
context.append("Observation: " + observation)
return FAIL # step budget exhaustedThe context window is the agent's memory and its stand-in for a belief state, and everything a tool returns enters it as text. Thoughts change only the context, never the environment: in this lesson's terms, ReAct adds free internal actions to the action space.
An agent completes each step of a task correctly with probability 0.95, independently, and any error is fatal. What is the probability that it completes a 20-step task, in percent?
Show the answer
36 %
. Success decays like , so a 5% per-step error rate is ruinous over 20 steps, and even 99% per step leaves only over 100 steps. Catching errors helps multiplicatively: if 80% of mistakes are detected and repaired, the effective per-step failure falls from 5% to 1%, and 20-step success rises to . Real errors are correlated across steps, so treat this as a lens, not a law.
Benchmarks for coding, web navigation and computer use have shown rapid progress, along with high variance across runs, sensitivity to the harness and prompts, and long tasks that still fail at some step. Careful evaluation reports repeated trials, costs and confidence intervals, not a single lucky run.
Key takeaways
- Agents act on histories; a belief state, or a learned memory approximating one, restores the Markov property. Architectures range from reactive policies through model-based planners to hybrids such as Dyna and AlphaZero.
- Dyna turns a model into extra updates and MPC re-plans at every step. With a terminal value, the error of -step lookahead is at most , and planners actively exploit model errors.
- Markov games replace optima with equilibria. A mixed equilibrium makes the opponent indifferent, and independent learners face non-stationarity, which centralized critics and self-play address.
- Behavior cloning can compound errors as ; DAgger's on-policy labels give . Domain randomization trains across simulators so that reality looks like one more sample.
- LLM agents wrap a language model in an act–observe loop. Per-step reliability compounds as , tool outputs are untrusted input, and evaluation must measure reliability rather than one lucky run.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What does Dyna-Q do with its learned model?
- It plans a full action sequence before every real step and executes the first action
- Between real steps, it replays simulated transitions from the model as extra Q-learning updates
- It replaces the reward with the model's prediction error, to encourage exploration
- It uses the model only to choose
Show the answer
B. Between real steps, it replays simulated transitions from the model as extra Q-learning updates
Dyna is background planning: each real transition updates both the Q-table and the model, and then simulated transitions from previously seen state–action pairs receive the same Q-learning update. The model multiplies the value of each real sample. Decision-time planning, as in MPC, is the other way to use a model.
A planner rolls a learned model steps and then bootstraps from a learned value . In the bound , what does increasing do?
- It reduces both error terms
- It has no effect on the bound
- It shifts weight from the value function's error to the model's error
- It shifts weight from the model's error to the value function's error
Show the answer
C. It shifts weight from the value function's error to the model's error
The bound is a -weighted mixture of the value error , which carries all the weight at , and the pure-model error , which carries it all as . Longer lookahead trusts the model more and the value function less; which is better depends on which of the two is more accurate.
In the mixed equilibrium of a zero-sum game that has no pure equilibrium, how is each player's mixing probability determined?
- It makes the opponent indifferent between the opponent's two actions
- It maximizes the player's payoff against the opponent's most likely action
- It puts more weight on whichever of the player's actions has the largest entry in the matrix
- It is always 50/50
Show the answer
A. It makes the opponent indifferent between the opponent's two actions
If the opponent strictly preferred one action, it would play that action purely and exploit the mix. So in equilibrium each mix equalizes the opponent's payoffs: the kicker's comes from the keeper's indifference condition .
Why does DAgger's guarantee grow linearly in the horizon , while behavior cloning's worst case grows quadratically?
- DAgger uses a larger network
- DAgger's expert labels the states the learner itself visits, so the learner is trained on the distribution it is tested on
- DAgger discounts future costs
- DAgger never makes mistakes after the first iteration
Show the answer
B. DAgger's expert labels the states the learner itself visits, so the learner is trained on the distribution it is tested on
Behavior cloning measures error on the expert's states. Once a mistake leaves that distribution nothing bounds the learner's behavior, and each early mistake can cost up to the rest of the episode, hence . DAgger aggregates expert labels on the learner's own states, so its error is measured where it acts, and the performance-difference lemma turns that into .
An agent's per-step error rate drops from 5% to 1%, with independent errors and no recovery. Its success rate on a 50-step task goes from about…
- 95% to 99%
- 50% to 90%
- 8% to 61%
- 8% to 20%
Show the answer
C. 8% to 61%
and . A fivefold cut in the per-step error buys an eightfold gain in task success, because success decays exponentially in the number of steps. Per-step reliability is the quantity long-horizon agents live or die by.
Go deeper
- Multi-Agent Learning & Game Theory · Nash equilibria, self-play and cooperation.
- Robot Learning & Sim-to-Real · Learning control in a physical world.
- LLM Agents & Tool Use · Planning, acting and reflecting with language models.
Further reading
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 8 and 17 (MIT Press, 2nd ed., 2018).
- Y. Shoham & K. Leyton-Brown, Multiagent Systems: Algorithmic, Game-Theoretic, and Logical Foundations (Cambridge University Press, 2009).
- S. Ross, G. J. Gordon & J. A. Bagnell, "A reduction of imitation learning and structured prediction to no-regret online learning," AISTATS (2011).
- S. Yao, J. Zhao, D. Yu, N. Du, I. Shafran, K. Narasimhan & Y. Cao, "ReAct: Synergizing reasoning and acting in language models," ICLR (2023).