01 / 27 · Agents and Environments
What an agent is
How an agent perceives an environment and acts on it in a loop: the agent function and program, performance measures and rationality, the properties of task environments, five kinds of agent, where language-model agents fit, and the plan of the course.
On this page 8
The NLP course ended with a loop around a language model: the model emits a tool call, a runtime executes it, the result goes back into the context, and the model decides again. That loop is one instance of an idea much older than language models. Artificial intelligence has described its systems as agents since the 1990s: something that perceives an environment and acts on it, over and over, so that the environment ends up in states someone wants. This course builds agents in that sense, from the classical ones that search a known world, through reinforcement learning, to the language-model agents that write code and operate computers. This note sets up the vocabulary that every later note uses: the loop, what it means for an agent to act well, how environments differ, and what kinds of agent program exist.
Notation. At step the environment is in state ; the agent receives a percept (observation) and emits an action . The percept sequence up to is . and are the sets of percepts and actions. A performance measure assigns a number to a sequence of environment states. For a random quantity, is its expectation, as in the Probability course.
Baseline: a program that answers once#
A classifier, a translation model or a chat model answering one question is a function: it receives an input, returns an output, and is done. Whether the output is good can be judged on its own, against a label or by a reader. Nothing the function returns changes the next input it will see.
That stops being true as soon as a system acts. A robot that moves sees a different room. A program that deletes a file cannot read it afterwards. An assistant that runs a test learns something it did not know before the run. In each case the output is an action, the action changes the world, and the next input depends on it. The quality of one action can no longer be judged alone: moving away from a dirty square is a mistake if nothing else needs cleaning and a good idea if something does. To reason about such systems we need three things the single-answer view does not have: a loop, a way to score a whole history rather than one output, and a description of the world the loop runs in.
The agent–environment loop#
An agent is anything that perceives its environment through sensors and acts on it through actuators (Russell and Norvig, 2021, chapter 2). The environment is everything outside the agent that its actions affect or its percepts depend on. They interact in discrete steps:
One turn of the agent–environment loop
- Percept. The environment is in state ; the agent’s sensors report a percept , often only part of the state. In the example, a vacuum cleaner in a world of two squares, A and B, sees where it is and whether its own square is dirty: . It does not see B.
- Update. The agent program folds the new percept into whatever it keeps from the past, here a counter of steps since it arrived in A.
- Choose. The program picks an action from : the square is dirty, so Suck.
- Act. The actuators carry out the action and the environment moves to a new state, possibly at random: . Here A becomes clean, and the clean square B may get dirty.
- Score. A performance measure, outside the agent, rates the sequence of states the environment goes through.
Two objects describe what the agent does, and they should not be confused. The agent function is the mathematical description of the behaviour: a map from every possible percept sequence to an action,
where is the set of finite sequences of percepts. The agent program is the code that runs on the agent’s hardware and implements . It sees only the current percept and its own memory, and it must produce the action in the time available.
The distinction matters because the obvious program, a lookup table indexed by the whole percept sequence, is hopeless. Worked example. The vacuum world has percepts: two locations times clean or dirty. A table that covers a lifetime of steps needs a row for every sequence of length 1 to :
A camera with a few million pixels has more possible percepts than there are atoms in the universe, so the table cannot even be written down. The design problem of this course is to find small programs that produce good agent functions: four rules for the vacuum cleaner, a search procedure, a value function, a neural network, a language model in a loop.
Performance measures and rationality#
What counts as acting well? The answer belongs to whoever designs the agent, and it is written as a performance measure : a number assigned to the sequence of environment states that the agent’s behaviour produced. Two choices in this definition are deliberate. The measure scores states of the environment, not the agent’s opinion of how it did; an agent that could change the measure would simply declare success. And it scores the outcome, not the behaviour; Russell and Norvig’s advice is to write the measure for what one wants in the world rather than for how one thinks the agent ought to behave, because an agent will find ways to satisfy a behavioural rule that miss its purpose. The same problem returns with language models as reward hacking, in Alignment and oversight of agents.
An agent is rational if, for every percept sequence, it chooses the action that maximizes the expected value of the performance measure, given the percepts so far and what it knows in advance (Russell and Norvig, 2021, section 2.2). In terms of the whole agent function:
where the expectation is over the randomness of the environment and over whatever the agent does not know about it. Three consequences follow.
- Rational is not omniscient. The expectation is taken with the information the agent has. An agent that sucks a square that turns out to have been clean, because its sensor was noisy, can still have acted rationally.
- Rationality is relative to the measure. The same behaviour can be rational under one measure and irrational under another, as the example below shows.
- Rational agents gather information. If looking costs less than acting blindly, a rational agent looks: checking the other square is an action whose value is the information it brings.
Worked example: one step, two measures. The vacuum world gives one point for each clean square at each step. The agent stands in A, A is dirty, B is clean. Suck scores for the step. Moving right scores , because A stays dirty. If a move also costs , the move scores . Suck wins under both measures here. The difference shows over time. After each step, each clean square gets dirty with probability . The reflex rule “if dirty then Suck, else move to the other square” makes the agent shuttle between two clean squares, paying for a move at almost every step. When moves are free this costs nothing and the rule is nearly the best one can do. When a move costs the agent earns about per step while the world is mostly clean, and an agent that waits steps before going to check the other square does better:
Average score per step in the two-square world
At , the reflex agent averages points per step when moves cost , against when they are free. The waiting agent with the best waiting time, , averages . At dirt returns faster, the best wait shrinks to , and the advantage to . The numbers are exact long-run averages, computed from the stationary distribution of the Markov chain of (location, dirt in A, dirt in B, counter), as in the Code section; a simulation of 200,000 steps agrees with them to within 0.003.
The waiting agent is better because its counter carries information. When the agent left B, B was clean; after more steps it is dirty with probability , which for grows from to at . Going to look is worth its cost only when that probability is high enough. The reflex agent, which keeps no state, cannot make this trade-off at all.
The properties of task environments#
The environment, together with the performance measure, the actuators and the sensors, is the task environment of the agent. Before choosing an agent design, it pays to classify the task environment along a few axes, because each axis decides which methods apply (Russell and Norvig, 2021, section 2.3):
| property | the easy end | the hard end | what the hard end demands |
|---|---|---|---|
| observable | fully: the percept shows the whole relevant state | partially: noisy or missing parts, as B for the vacuum cleaner | memory and a belief about the hidden state |
| deterministic | deterministic: and fix | stochastic: outcomes have probabilities | expected values, plans that branch |
| episodic | episodic: each decision stands alone, as one image to classify | sequential: an action changes what comes later | looking ahead, credit for delayed results |
| static | static: the world waits while the agent thinks | dynamic: it changes meanwhile, as traffic | deciding in time, acting before thinking is done |
| discrete | discrete: finitely many states, percepts, actions, steps | continuous: positions, speeds, time | function approximation, control |
| agents | single agent | multi-agent: others act too, competing or cooperating | game theory, communication |
A seventh distinction concerns the designer rather than the world: whether the rules of the environment are known (the outcomes of actions, or their probabilities, are given to the agent) or unknown, so that the agent must learn them by acting. Known and fully observable is not the same as easy: chess is both and still hard.
Three examples:
| vacuum world above | chess with a clock | an agent fixing a bug in a repository | |
|---|---|---|---|
| observable | partially | fully | partially: it reads files one at a time |
| deterministic | stochastic (new dirt) | deterministic, but the opponent is unpredictable | mostly deterministic; flaky tests and network calls are not |
| episodic | sequential | sequential | sequential |
| static | dynamic in a mild way | semidynamic: the clock runs, the board waits | static, unless other people push commits |
| discrete | discrete | discrete | discrete, with an enormous action space: any command, any edit |
| agents | single | multi-agent, competitive | single, or several cooperating |
The hardest combination, partially observable, stochastic, sequential, dynamic, continuous and multi-agent, is the ordinary world of a self-driving car. The first notes of the course work at the easy ends on purpose: Search and planning assumes a fully observable, deterministic, known world; Markov decision processes adds stochastic outcomes and, at its end, partial observability; Games and Monte Carlo tree search adds an opponent; the reinforcement-learning section removes the assumption that the world is known.
Five kinds of agent program#
Agent programs can be ordered by how much they compute about the world before they act (Russell and Norvig, 2021, section 2.4). Each kind adds one component to the previous one.
Simple reflex agents choose the action from the current percept alone, with condition–action rules: “if the square is dirty, suck”. They are fast and tiny, and they are correct only when the right action can be read off the current percept, which in practice means a fully observable environment. Without memory they can loop forever: a vacuum cleaner that sees dirt but not its location, with the rule “if clean, move right”, reaches the right wall and keeps bumping into it. Randomizing the rule, “if clean, move in a random direction”, breaks such loops at some cost.
Model-based reflex agents keep an internal state that summarizes what they cannot see now. To update it they need two pieces of knowledge: a transition model, how the world changes by itself and in response to actions (dirt reappears with probability ), and a sensor model, how the state shows up in percepts. The waiting agent above is one: its counter is all it needs to know about B.
Goal-based agents are told which states are desirable and work out how to get there, by imagining sequences of actions with the transition model. This is search and planning, the subject of the next note. A goal-based agent adapts to a new goal without new rules: give a navigation agent a different destination and it computes a different route.
Utility-based agents replace the yes-or-no goal by a utility, a number that ranks outcomes, and with uncertain outcomes they choose the action with the highest expected utility. They can trade off goals that conflict (speed against safety) and goals that may not be reached. A Markov decision process is the formal setting for this kind of agent.
Learning agents improve any of the above from experience. They have four parts: the performance element, which is one of the four programs above and chooses actions; a critic, which compares the outcomes with the performance standard and produces feedback such as a reward; a learning element, which uses the feedback to change the performance element; and a problem generator, which proposes exploratory actions that may be bad now but teach something. Reinforcement learning, the second section of the course, is the study of learning agents whose feedback is a reward.
| agent | keeps state | uses a model of the world | ranks outcomes | improves from experience |
|---|---|---|---|---|
| simple reflex | no | no | no | no |
| model-based reflex | yes | to update its state | no | no |
| goal-based | yes | to look ahead | goal or not | no |
| utility-based | yes | to look ahead | by expected utility | no |
| learning | any of the above | possibly learned | possibly learned | yes |
Where a language-model agent fits#
A language-model agent fits the same frame, with each part made of text (Sumers et al., 2024):
- Percepts are whatever enters the context: the user’s request, the output of a tool, the text of a web page, a screenshot for a model that reads images.
- Actions are what the model writes, read by a runtime: a call to a tool with arguments, an edit to a file, a command for a shell, a message to the user, or a final answer.
- The agent program is the loop of the NLP course with the model inside it. The model plays the role of the agent function, , where is the context: the instructions, the percepts and the model’s own earlier actions. The language model as a policy makes this precise.
- The internal state is the context window, plus any memory outside it: files, a database, notes the agent writes for itself, the subject of Context and memory.
- The task environment is, for most interesting tasks, at the hard end of almost every axis of the table above: partially observable, stochastic (the model samples, and so may the tools), sequential, often dynamic, discrete but with an unbounded action space, and increasingly multi-agent.
- The performance measure is task success, such as tests passing or a question answered correctly, plus costs: time, money, and actions that should never be taken. Writing it down well is as hard as for any other agent, and harder when it also becomes the reward used for training.
Two simplifications are common and worth keeping apart. A workflow is a fixed program that calls a model at predefined points: the code decides the next step. An agent, in the narrower sense used by practitioners, lets the model decide the next step and when to stop (Anthropic, 2024). Both are agents in the sense of this note; they differ in how much of the agent program is written by people and how much is generated by the model at run time. Workflows, frameworks and protocols returns to the choice.
The plan of the course#
The course has seven sections. Each one uses the frame of this note and adds what the previous ones could not do.
- Agents and Environments. The classical agent, in worlds whose rules it knows. Search and planning finds a sequence of actions to a goal in a deterministic world, with A* and planning languages. Markov decision processes handles random outcomes: values, the Bellman equations, value and policy iteration, and belief states when the world is partly hidden. Games and Monte Carlo tree search adds an opponent and the sampling-based search that, with neural networks, became AlphaGo, AlphaZero and MuZero.
- Reinforcement Learning. The world is no longer known; the agent learns from rewards. Q-learning and temporal-difference learning estimate the values of the MDP note from experience; deep Q-networks replace the table by a neural network, as trained in the Machine Learning and Deep Learning courses; policy gradients and actor–critic methods, up to PPO, optimize the policy directly; model-based RL learns the transition model and plans with it, the line from MuZero to Dreamer.
- Language Models as Agents. A pretrained, instruction-tuned language model from the NLP course becomes a policy over text. Chain of thought lets it compute before it answers; tool use gives it actuators through function schemas; ReAct interleaves reasoning and acting into the agent loop, with its stopping rules and failure modes.
- Memory, Planning and Reflection. What an agent needs when a task outgrows one context window: memory that it writes and retrieves, building on retrieval-augmented generation; planning with language models, which brings back the search of the first section (tree search over thoughts, a model that writes a plan for a classical planner); reflection on its own failures; and the choice between fixed workflows and open-ended agents, with the protocols that connect agents to tools, such as MCP.
- Agents at Work. Four kinds of task environment, with their percepts, actions and benchmarks: coding agents in a repository and a shell, web and computer-use agents on screens, research agents that search and read, and systems of several agents that divide the work.
- Training Agents. The policy gradients of the second section applied to language models: RLHF, GRPO and reinforcement learning with verifiable rewards; reasoning models that spend more computation at inference time; and training agents on whole multi-step tasks.
- Evaluation and Safety. How to measure an agent with benchmarks and statistics that survive randomness; how an attacker steers an agent through what it reads, and what isolation and least privilege do about it; how agents exploit flawed performance measures, and how people keep oversight. The last note collects the open problems and the course in one paragraph.
What changed#
| a program that answers once | an agent | |
|---|---|---|
| interaction | one input, one output | a loop of percepts and actions |
| what is judged | the output | the sequence of environment states |
| criterion | accuracy, a label, a reader | the expected performance measure |
| what the system needs | a function of the input | a program with memory, a model, goals or utilities |
| when its output is wrong | one bad answer | consequences that change everything that follows |
Limitations#
- The boundary is a choice. Where the agent ends and the environment begins is decided by the designer. For a language-model agent, is the runtime that executes tools part of the agent or of the environment? Different answers lead to different measures and different responsibilities.
- Performance measures are hard to write. Every measure leaves out something its designer cares about, and an optimizing agent finds the gap. The course meets this as reward misspecification and reward hacking.
- Rationality ignores the cost of thinking. The definition asks for the best action, however long it takes to compute. Real agents must decide in time, which is why the course cares about search budgets, the number of simulations and test-time compute. Choosing the best program for the available computation, rather than the best action, is called bounded optimality (Russell and Subramanian, 1995); the idea goes back to Simon’s bounded rationality (Simon, 1955).
- The frame does not say how. It classifies agents and environments; it does not build an agent. The algorithms start in the next note.
What you should remember#
- An agent perceives and acts in a loop; its percepts depend on its earlier actions.
- The agent function maps percept sequences to actions; the agent program implements it with limited memory and time. A table is never the answer.
- A rational agent maximizes the expected performance measure given what it has perceived and what it knows. The measure scores environment states and outcomes, not the agent’s behaviour.
- Task environments are classified as fully or partially observable, deterministic or stochastic, episodic or sequential, static or dynamic, discrete or continuous, single- or multi-agent, and known or unknown; each hard end calls for a specific capability.
- Agent programs grow from simple reflex to model-based, goal-based, utility-based and learning agents. A language-model agent is a trained policy over text inside a loop, in an environment at the hard end of almost every axis.
Code#
The vacuum world as an environment class, the reflex and waiting agents as programs, the agent-environment loop, the size of a lookup table, and the exact long-run scores from the stationary distribution of the chain. Seeds are fixed; exact numbers can differ slightly across platforms and library versions. The script runs in about a second.
import numpy as np
# 1. the environment: two squares A = 0 and B = 1; the agent sees only its own square
class Vacuum:
def __init__(self, p, move_cost, rng):
self.p, self.c, self.rng = p, move_cost, rng
self.loc, self.dirt = 0, [1, 1]
def percept(self):
return self.loc, self.dirt[self.loc] # (location, is my square dirty?)
def step(self, action):
if action == 'Suck': self.dirt[self.loc] = 0
elif action in ('Left', 'Right'): self.loc = 0 if action == 'Left' else 1
score = (2 - sum(self.dirt)) - (self.c if action in ('Left', 'Right') else 0)
for j in (0, 1): # dirt appears on clean squares
if not self.dirt[j] and self.rng.random() < self.p: self.dirt[j] = 1
return score
# 2. agent programs: each maps the current percept (and its own state) to an action
def reflex(percept, state):
loc, dirty = percept
return ('Suck' if dirty else 'Right' if loc == 0 else 'Left'), state
def waiting(K): # model-based: counts the steps since it arrived
def program(percept, k):
loc, dirty = percept
if dirty: return 'Suck', k + 1
if k >= K: return ('Right' if loc == 0 else 'Left'), 0
return 'NoOp', k + 1
return program
def run(program, p, c, steps=200_000, seed=0):
env, state, total = Vacuum(p, c, np.random.default_rng(seed)), 0, 0.0
for _ in range(steps): # the agent-environment loop
action, state = program(env.percept(), state)
total += env.step(action)
return total / steps
# 3. the agent function as a table: one row per percept sequence
percepts = [(l, d) for l in (0, 1) for d in (0, 1)]
print(len(percepts), sum(len(percepts) ** t for t in range(1, 11))) # 4 1398100
# 4. the exact long-run score: the stationary distribution of the Markov chain (location, dirt A, dirt B, counter)
def exact(p, c, K=None):
Kmax = 0 if K is None else K
states = [(l, a, b, k) for l in (0, 1) for a in (0, 1) for b in (0, 1) for k in range(Kmax + 1)]
ix = {s: i for i, s in enumerate(states)}
P, r = np.zeros((len(states), len(states))), np.zeros(len(states))
for (l, a, b, k) in states:
d = [a, b]
act = 'Suck' if d[l] else ('Move' if K is None or k >= K else 'NoOp')
if act == 'Suck': d[l] = 0
nl = 1 - l if act == 'Move' else l
nk = 0 if (act == 'Move' or K is None) else min(k + 1, Kmax)
r[ix[(l, a, b, k)]] = 2 - sum(d) - (c if act == 'Move' else 0)
for na in ((d[0],) if d[0] else (0, 1)):
for nb in ((d[1],) if d[1] else (0, 1)):
pr = (1 if d[0] else (p if na else 1 - p)) * (1 if d[1] else (p if nb else 1 - p))
P[ix[(l, a, b, k)], ix[(nl, na, nb, nk)]] += pr
M = np.vstack([(P.T - np.eye(len(states)))[:-1], np.ones(len(states))]) # pi P = pi, sum pi = 1
pi = np.linalg.solve(M, np.r_[np.zeros(len(states) - 1), 1.0])
return pi @ r
for p in (0.05, 0.2):
best = max(range(9), key=lambda K: exact(p, 0.5, K))
print(p, round(exact(p, 0.0), 4), round(exact(p, 0.5), 4), best, round(exact(p, 0.5, best), 4),
round(run(reflex, p, 0.5), 4), round(run(waiting(best), p, 0.5), 4))
# 0.05 1.9451 1.4938 4 1.7594 1.4935 1.7596
# 0.2 1.7339 1.4073 2 1.4768 1.4068 1.4743
# (p; reflex with free moves; reflex with move cost 0.5; best K; waiting agent; then the two simulated)
Next#
The vacuum cleaner never had to look further ahead than one step. Most tasks are not like that: reaching a destination, solving a puzzle or assembling a plan takes many actions, and only the whole sequence achieves the goal. When the world is fully observable, deterministic and known, a goal-based agent can find such a sequence before acting, by searching the space of states it can reach. The next note formulates that search problem and solves it with breadth-first search, uniform-cost search and A*.
References#
- S. Russell, P. Norvig. Artificial Intelligence: A Modern Approach, 4th ed. Pearson, 2021. Chapter 2 (intelligent agents): section 2.2 (rationality), section 2.3 (task environments and their properties), section 2.4 (the structure of agents).
- R. S. Sutton, A. G. Barto. Reinforcement Learning: An Introduction, 2nd ed. MIT Press, 2018. Section 3.1 (the agent–environment interface).
- T. R. Sumers, S. Yao, K. Narasimhan, T. L. Griffiths. Cognitive architectures for language agents. Transactions on Machine Learning Research, 2024.
- Anthropic. Building effective agents. December 2024. Workflows against agents.
- L. Weng. LLM powered autonomous agents. Blog post, June 2023.
- S. Yao, J. Zhao, D. Yu, N. Du, I. Shafran, K. Narasimhan, Y. Cao. ReAct: synergizing reasoning and acting in language models. ICLR, 2023.
- H. A. Simon. A behavioral model of rational choice. The Quarterly Journal of Economics, 69(1):99–118, 1955.
- S. J. Russell, D. Subramanian. Provably bounded-optimal agents. Journal of Artificial Intelligence Research, 2:575–609, 1995.
- CS188, Introduction to Artificial Intelligence. University of California, Berkeley. Course materials; the order of the first section of this course follows it.