09 / 27 · Language Models as Agents
The language model as a policy
How a pretrained, instruction-tuned language model becomes the policy of an agent: tokens, turns and actions as a POMDP over text, the prompt as conditioning, temperature as a behavioural knob, why the pretrained prior makes acting possible, and what it still lacks.
What an agent is · Markov decision processes · GPT and autoregressive language modeling · Instruction tuning and alignment
On this page 7
The reinforcement-learning section ended with agents that learn a model of their world and plan inside it (previous note). Every agent in that section, from tabular Q-learning to Dreamer, starts from a policy that knows nothing about its task and improves it from rewards, over thousands or millions of episodes. A language model arrives with something none of them had: a policy that has already been trained, on a large share of what people have written, to produce a plausible next move in almost any situation that can be described in text. This note writes the language-model agent in the vocabulary of the first two sections. It defines what the state, the action and the policy are when everything is text, how the prompt and the temperature change the policy without any training, why the pretrained model is a good starting policy, and what it still lacks before it can act well.
Notation. A vocabulary of tokens . The model gives , the probability of the next token after a prefix, through logits and a softmax with temperature , as in the GPT note. At environment step the environment is in a hidden state and emits an observation , a string. The context is the token sequence the model reads at that step: the instructions, then , rendered by the chat template. An action is a string that ends with an end-of-turn token; a parser maps it to an element of the environment’s action set or to invalid. The reward , the discount and the belief are those of the Markov decision processes note; is the belief at step .
Baseline: a policy that starts from nothing#
The agents of the reinforcement-learning section begin with a uniform or random policy and explore: -greedy action choice, an entropy bonus, random initial weights. Exploration works because their action sets are small. A grid world has four actions; an Atari game has at most eighteen. Random actions find a reward sooner or later, and learning takes over from there.
Text is a different action space. Worked example. With the GPT-2 vocabulary of 50,257 tokens, the number of strings of 8 tokens is
A uniformly random policy emits one particular 8-token action, such as search[Dunmore] followed by the end of the turn, with probability . Even if a million different strings were all acceptable actions, a random string would be one of them with probability . An agent that had to discover by trial and error that search[ opens a call would never see its first reward. A policy over text has to start with most of its probability on sensible strings, or reinforcement learning has nothing to work with.
Tokens, turns and actions#
The model generates one token at a time, but the environment sees only whole actions. Two levels of description are therefore useful, and the course uses both.
The turn level is the agent of the first note. The environment has a hidden state , a transition and an observation that shows only part of : a partially observable MDP, or POMDP (Kaelbling, Littman and Cassandra, 1998). The agent receives and emits . The policy is a distribution over strings, the product of the token probabilities,
and the environment receives only what the parser makes of the string. The policy over the environment’s actions adds up every string that parses to the same action:
The invalid mass is a property of the model, the prompt and the parser together. A strict parser that accepts only Suck makes suck and Suck. invalid; a lenient one maps them to Suck and moves that probability to a valid action.
The token level is the view used when a language model is trained with reinforcement learning. The state is the prefix , the action is the next token, the transition is deterministic (append the token), and the reward arrives only when a whole response has been judged. This MDP has actions in every state and episodes as long as the response; Reinforcement learning for language models works in it.
Between the two levels lies the question of what the agent conditions on. In a POMDP the information available at step is the history , and an optimal policy can be written as a function of the belief , which summarizes the history (Markov decision processes). A language-model agent never computes a belief. Its context is the history itself, written as text, , and whatever the model infers about the hidden state stays implicit in its activations. This is the most general form of a POMDP policy, a function of the whole history, with one practical limit: the context window. When the history no longer fits, the runtime drops or summarizes part of it, and the policy then conditions on less than . Context and memory is about that limit.
| MDP or POMDP | language-model agent |
|---|---|
| hidden state | what the agent cannot see: files, a web page it has not opened, a database |
| observation | text returned by the environment: a tool result, an error, a user message |
| history or belief | the context : the history written into the chat template |
| action | a generated string, parsed into a tool call, a command or a final answer |
| policy | : token probabilities, then the parser |
| transition | the runtime and the world: tools, programs, people |
| reward | usually zero until the end, then task success: tests pass, the answer is right |
| episode | one task, ended by a final answer or a budget |
| discount | usually , in an episode bounded by a step budget |
Worked example: the vacuum world as text. The two-square world of the first note becomes a text environment once its percepts are written as sentences and its actions read from strings. The runtime renders the observation as You are in square A. Square A is dirty.; the model generates Suck and the end-of-turn token; the parser maps the string to the action Suck. One environment step is one turn of the conversation and, here, two generated tokens. A coding agent’s turn may be several hundred tokens of reasoning followed by a command; the turn level stays the same and only the token level grows.
The language model as a policy: one step of the agent
- Render. The chat template writes the system prompt, the earlier turns and the new observation into the context .
- Score. The model reads and the tokens generated so far in this turn, and produces logits for the next token.
- Sample. A token is drawn from the softmax of ; steps 2 and 3 repeat until the end-of-turn token, giving the string .
- Parse. The parser maps to an action , or reports it as invalid.
- Act and observe. The environment executes , moves to and returns ; the turn is appended to the history, and the loop starts again at step 1.
The model runs only in steps 2 and 3. The template, the parser and the loop belong to the agent program around it, written by people, and they decide as much about the agent’s behaviour as the weights do.
Prompting as conditioning#
The policy is , and includes text that the designer writes. Changing that text changes the policy without changing . Three parts of the context do most of the work.
The system prompt states the task, the role, the rules and the available actions. It is the cheapest lever on behaviour and the most fragile: it is only more tokens in the context, and the model follows it to the extent that training taught it to follow such text.
Demonstrations, or few-shot examples, show the model whole solved cases, here whole trajectories of observations and actions. This is the in-context learning of GPT-3, described in the GPT note. Two findings tell what the examples contribute. Xie et al. (2022) model a prompt as evidence about a latent task: if the pretraining text is a mixture of documents generated under different latent tasks , the model’s prediction behaves like
and each example sharpens the posterior . Worked example. Two candidate tasks start at , and each example is 4 times as likely under as under . After one, two and three examples, Bayes’ rule gives
so a few examples settle which behaviour is wanted. The second finding is empirical. In classification and multiple-choice tasks, replacing the labels of the examples by random labels barely hurt accuracy, across 12 models including GPT-3; the format, the set of possible labels and the kind of inputs mattered more (Min et al., 2022). Demonstrations tell the policy what kind of action is expected more than they teach it the mapping.
The chat template marks who said what. The instruction-tuning note shows the template of one model family; for an agent, the context is a sequence of roles. Written with simplified role tags, the context of the vacuum agent after one step reads
<system> You control a vacuum cleaner in squares A and B. Reply with one action: Suck, Left, Right or NoOp.
<user> You are in square A. Square A is dirty.
<assistant> Suck
<user> You are in square A. Square A is clean.
<assistant>
and the model continues after the last tag. Real templates use special tokens and often a separate tool role for observations. The role tokens are the only thing that separates the designer’s instructions from the text that the environment returns. Both condition the same policy, so an observation that contains instructions can steer the agent as well as the system prompt can: the root of the prompt injection of Agent security and prompt injection.
Worked example: an instruction becomes a different agent program. The Code section runs the vacuum world with a scripted stand-in model. With the plain system prompt and it behaves like the reflex agent of the first note: 1.495 points per step at with moves costing , against the reflex agent’s exact 1.494. Adding one sentence, Moving costs energy: wait when the square is clean, and check the other square every few steps, makes the same model wait four steps before it moves, reading the count from the turns in its context. It scores 1.760, the waiting agent’s 1.759. The context served as the agent’s memory, and the prompt selected the program. Whether the new program is better is decided by the environment’s performance measure, not by the prompt: the same instruction would lower the score if moves were free.
Sampling: temperature and behaviour#
The temperature divides the logits before the softmax, , as in the GPT note: approaches greedy decoding, is the model’s own distribution, and flattens it. For an agent, the question is what it does to the distribution over actions. For an action of one token, followed by the end of the turn, the answer is exact: its probability is proportional to , so low temperatures sharpen the policy towards its mode and high temperatures move mass from the head to the tail. For actions of several tokens the sharpening happens token by token, which is not the same as raising to the power .
Worked example: the tail is large. In square A, clean, a model gives the first token of its reply the logits Right , NoOp , Suck and Left ; each of 1,000 other tokens, which would make the reply invalid, gets . At , the normalizer is
so Right has probability and the invalid tail . At every logit is halved, the tail becomes , and
One token with probability is negligible; a thousand of them are not, once the temperature lifts them. At Right has and the tail is below .
The distribution of the first token of the reply, against temperature
The three regimes matter for agents in different ways.
- Low temperature gives a nearly deterministic policy. Runs are reproducible and invalid actions rare, but the policy has no exploration, and in an unchanged context it repeats the same action: an agent that failed once with greedy decoding tends to fail the same way again. The ReAct authors trace one of their failure modes, repeating the same thought and action, to greedy decoding (Yao et al., 2023, footnote on repetitive loops).
- Temperature around 1 samples the model’s own policy. Methods that need several different attempts at the same problem, such as self-consistency in the next note and the reinforcement learning of the training section, sample here, because their signal comes from the differences between samples.
- High temperature mostly breaks the format. In the Code section, the plain-prompt agent scores 1.495 points per step at , 1.570 at and 1.055 at , where 81 % of its replies are invalid. The gain at is an accident: random NoOps sometimes make the agent wait, which happens to pay when moves cost something. Temperature changes behaviour in ways that have nothing to do with the task, and its value should be chosen with the environment’s measure, like any other parameter of the agent.
Temperature does not make a served model deterministic either. Floating-point addition is not associative, and the order of the reductions inside a GPU kernel can depend on how many requests share a batch. Asked the same prompt 1,000 times at temperature 0, Qwen3-235B-A22B-Instruct-2507 gave 80 different completions, the first difference at the 103rd token; with kernels rewritten to be independent of the batch size, all 1,000 were identical (He and Thinking Machines Lab, 2025).
Why pretraining and instruction tuning give a usable prior#
Pretraining maximizes the likelihood of human-written text, over a corpus (Maximum likelihood). Read as reinforcement learning, this is behaviour cloning: imitation of the policy that produced the data, a mixture of millions of writers. The text includes descriptions of procedures, dialogues, questions followed by answers, code followed by its output and logs of commands. The cloned policy therefore already maps situations described in words to the moves people made in them. Instruction tuning continues the imitation on curated demonstrations of an assistant, including demonstrations of tool calls (Instruction tuning and alignment); preference optimization and reinforcement learning with verifiable rewards then improve the policy while a KL penalty keeps it near what it imitated.
In the terms of the reinforcement-learning section, these stages provide a prior policy with good coverage. A sample from it is a sensible action with high probability, so exploration reduces to sampling, and later training reweights actions the prior already proposes. The KL-regularized objective of RLHF makes this exact: its optimum is
a reweighting of the prior by the exponentiated reward, as derived in the DPO section of the instruction-tuning note. Worked example. Three actions with , rewards and give the weights , and , so . The second action wins because the prior gave it enough probability to start with. An action to which the prior gives zero probability stays at zero, whatever its reward: the prior decides which behaviours are reachable at all.
The prior is not a grounded policy, though. Huang et al. (2022) asked GPT-3 175B to write step-by-step plans for household tasks in the VirtualHome simulator. The free-form plans read well, but only 7.79 % of them were executable in the simulator, because their steps did not name actions the simulator had. Mapping each generated step to the most similar admissible action, with a better choice of example and step-by-step correction, raised executability to 73.05 % (Codex 12B: from 18.07 % to 78.57 %). The model knew what to do; it did not know which actions existed.
What is still missing#
A language model wrapped in a loop is a policy. Three things separate it from a good agent, and the following notes add them.
Grounding. The actions must be ones the environment accepts, and they must refer to its actual state. The parser of the Code section accepts four strings and rejects everything else. Two remedies keep the model’s knowledge and add the environment’s constraints. One maps or restricts generated text to admissible actions, as Huang et al. did and as tool schemas and constrained decoding do in Tool use and function calling. The other scores each admissible action with the model and multiplies the score by what the environment allows. SayCan (Ahn et al., 2022) chooses a robot’s next skill by maximizing : the language model says what would help, a learned value function says what can succeed from where the robot stands.
Feedback. A plan written in one pass is open loop. The agent improves only if observations of the results come back into the context, as in ReAct and the agent loop, or if outcomes are turned into rewards and used for training, as in Training agents with reinforcement learning. Feedback in the context changes behaviour within one episode and is forgotten after it; feedback in the weights persists.
Memory. The context is the agent’s only state. It is finite, every token in it is read again at every step, and what is dropped from it no longer exists for the model. The Code section keeps the last 12 turns; real agents keep files, notes and retrieval indexes, the subject of Context and memory.
One more ingredient sits inside the policy rather than around it. The model computes each token with a fixed number of layers, so an action that needs several steps of reasoning has to fit inside the forward passes of a few tokens. Letting the model write those steps out is the subject of the next note.
What changed#
| a policy learned from scratch | a language-model policy | |
|---|---|---|
| starting point | random or uniform | a pretrained, instruction-tuned prior |
| what it conditions on | the state , or a belief | the context: the history written as text |
| action space | a small fixed set | any string, read by a parser |
| how it is changed | gradient steps on rewards | the prompt, without training; or fine-tuning |
| exploration | -greedy, entropy bonus | the sampling temperature |
| grounding | built in: its actions are the environment’s | added by the program: parser, schemas, admissible actions |
| memory | a state or belief update | the context window, plus whatever the program stores |
Limitations#
- Likelihood is not value. The prior proposes what a writer would plausibly do next, not what maximizes the performance measure. Text over-represents confident statements and successful outcomes, and the policy inherits both.
- The agent reads its own actions as evidence. A model trained to imitate experts who knew things it cannot see may treat its own earlier actions as information about the hidden state, and so confirm its own guesses. Ortega et al. (2021) call this an auto-suggestive delusion and argue that actions must be treated as interventions, not observations.
- Invalid actions and brittle parsing. Every free-text action can fail to parse, and a lenient parser may map a string to an action the model did not mean.
- Prompt sensitivity. Small changes in wording, in the order of examples or in the model version change the policy, often in ways no one predicted. Every prompt is a parameter that has to be evaluated.
- The context is expensive memory. It is re-read at every step, and it is bounded.
- Temperature is a crude knob. It reshapes every token distribution at once: the choice between two actions and the spelling of their arguments.
What you should remember#
- A language-model agent is a POMDP agent whose policy is : the probabilities of the generated tokens, summed over the strings that the parser maps to each action, with an invalid remainder.
- The context is the history written as text. It replaces the belief state, up to the length of the window.
- The token level, with one token per action and a reward at the end, is the MDP used for training; the turn level is the one the environment sees.
- The prompt conditions the policy: the system prompt states the task, demonstrations select the kind of behaviour, the chat template separates roles. Instructions and observations condition the same policy.
- Temperature sharpens or flattens the policy. Low temperature repeats itself; temperature near 1 is for methods that need diverse samples; high temperature mostly produces invalid actions. Temperature 0 is not bitwise deterministic on a shared server.
- Pretraining is behaviour cloning of human writers and instruction tuning is behaviour cloning of an assistant. Together they give a prior with good coverage, which later reward training can only reweight.
- Missing: grounding in the actual actions and state, feedback from results, and memory beyond the window.
Code#
The vacuum world of the first note, with its Vacuum class unchanged, driven by a scripted stand-in for a language model: next-token logits over a toy vocabulary of four action words, an end-of-turn token and 1,000 junk tokens, computed by rules from the rendered context. The chat template, sampling with temperature until the end of the turn, the parser and the agent program are written out. With a real model only toy_logits changes, to a forward pass of a transformer over the rendered tokens; the template, the sampling, the parser and the loop stay as they are. Seeds are fixed; exact numbers can differ slightly across platforms and library versions. The script runs in about six seconds.
import re
import numpy as np
# 1. the environment of the first note: 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]
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):
if not self.dirt[j] and self.rng.random() < self.p: self.dirt[j] = 1
return score
# 2. a scripted stand-in for a language model: next-token logits over a toy vocabulary, given the context
ACTIONS = ['Suck', 'Left', 'Right', 'NoOp']
VOCAB = ACTIONS + ['<eot>'] + [f'w{i:03d}' for i in range(1000)] # 1,000 tokens that make no valid action
EOT, JUNK = 4, slice(5, None)
def steps_since_move(context):
acts = re.findall(r'<assistant> (\S+)', context)
k = 0
for a in reversed(acts):
if a in ('Left', 'Right'): break
k += 1
return k
def toy_logits(context, generated):
z = np.full(len(VOCAB), -8.0) # the long tail: implausible tokens
if generated: # after one word: end the turn if the word is an action
z[EOT] = 6.0 if generated[-1] in ACTIONS else 0.0
return z
last = context[context.rfind('<user>'):] # the newest observation
here = 'A' if 'in square A' in last else 'B'
if 'is dirty' in last:
z[:4] = [4.0, 0.5, 0.5, 1.0] # Suck, Left, Right, NoOp
else:
go = 'Right' if here == 'A' else 'Left'
z[:4] = [1.0, 0.5, 0.5, 1.5]
z[ACTIONS.index(go)] = 3.0
if 'wait when the square is clean' in context and steps_since_move(context) < 4:
z[3] += 2.5 # the instruction shifts mass to NoOp ...
z[ACTIONS.index(go)] -= 2.5 # ... away from moving, until four steps have passed
return z
# 3. the chat template, sampling with temperature until <eot>, and the parser
def render(system, turns):
return f'<system> {system}\n' + ''.join(f'<user> {o}\n<assistant> {a}\n' for o, a in turns[:-1]) + f'<user> {turns[-1][0]}\n<assistant>'
def softmax(z, tau):
e = np.exp((z - z.max()) / tau)
return e / e.sum()
def sample_action(context, tau, rng, max_tokens=3):
out = []
for _ in range(max_tokens):
w = VOCAB[rng.choice(len(VOCAB), p=softmax(toy_logits(context, out), tau))]
if w == '<eot>': break
out.append(w)
return ' '.join(out)
def parse(text):
return text if text in ACTIONS else None # anything else is an invalid action
# 4. the language model wrapped as an agent program: percept in, action out, the context as its state
def lm_agent(system, tau, rng, window=12):
def program(percept, turns):
loc, dirty = percept
obs = f'You are in square {"AB"[loc]}. Square {"AB"[loc]} is {"dirty" if dirty else "clean"}.'
turns = (turns + [(obs, None)])[-window:] # the context keeps the last 12 turns
text = sample_action(render(system, turns), tau, rng)
action = parse(text)
turns[-1] = (obs, text)
return (action or 'NoOp'), turns, action is None # an invalid action does nothing
return program
def run(program, p=0.05, c=0.5, steps=20_000, seed=0):
env, state, total, invalid = Vacuum(p, c, np.random.default_rng(seed)), [], 0.0, 0
for _ in range(steps):
action, state, bad = program(env.percept(), state)
total += env.step(action); invalid += bad
return total / steps, invalid / steps
SYS = 'You control a vacuum cleaner in squares A and B. Reply with one action: Suck, Left, Right or NoOp.'
WAIT = SYS + ' Moving costs energy: wait when the square is clean, and check the other square every few steps.'
for name, system in (('plain', SYS), ('wait', WAIT)):
for tau in (0.3, 1.0, 2.0):
score, bad = run(lm_agent(system, tau, np.random.default_rng(1)))
print(name, tau, round(score, 3), round(bad, 3))
# plain 0.3 1.495 0.0
# plain 1.0 1.57 0.011
# plain 2.0 1.055 0.81
# wait 0.3 1.76 0.0
# wait 1.0 1.704 0.008
# wait 2.0 0.995 0.806
# (prompt; temperature; points per step at p = 0.05 with moves costing 0.5; share of invalid replies)
# 5. the action distribution at the first token, square A clean, plain prompt, against temperature
ctx = render(SYS, [('You are in square A. Square A is clean.', None)])
for tau in (0.5, 1.0, 2.0):
q = softmax(toy_logits(ctx, []), tau)
print(tau, ' '.join(f'{a}={q[i]:.3f}' for i, a in enumerate(ACTIONS)), f'invalid={q[EOT:].sum():.3f}')
# 0.5 Suck=0.017 Left=0.006 Right=0.930 NoOp=0.046 invalid=0.000
# 1.0 Suck=0.093 Left=0.056 Right=0.686 NoOp=0.153 invalid=0.011
# 2.0 Suck=0.059 Left=0.046 Right=0.161 NoOp=0.076 invalid=0.658
# 6. why reinforcement learning from scratch cannot find an action in text
print(f'{50_257 ** 8:.2e}', f'{1 / 50_257 ** 8:.1e}') # 8-token strings over the GPT-2 vocabulary
# 4.07e+37 2.5e-38
# 7. few-shot examples as evidence about a latent task: two tasks, each example 4 times likelier under task 1
post = [1 / (1 + 4.0 ** -k) for k in range(4)]
print([round(x, 3) for x in post])
# [0.5, 0.8, 0.941, 0.985]
Next#
The policy of this note maps its context to an action in a single pass of a few tokens. For a question whose answer takes several steps of computation, such as a word problem or a chain of facts, that leaves the model a fixed number of layers to do all of the work before the first token of the answer. The next note lets the model write the intermediate steps first: chain-of-thought prompting, why the extra tokens add serial computation, self-consistency as a vote over reasoning paths, and what is known about whether the written reasoning is the reasoning the model actually did.
References#
- S. Yao, J. Zhao, D. Yu, N. Du, I. Shafran, K. Narasimhan, Y. Cao. ReAct: synergizing reasoning and acting in language models. ICLR, 2023. The context as the sequence of observations and actions; repetitive loops under greedy decoding.
- T. R. Sumers, S. Yao, K. Narasimhan, T. L. Griffiths. Cognitive architectures for language agents. Transactions on Machine Learning Research, 2024.
- L. P. Kaelbling, M. L. Littman, A. R. Cassandra. Planning and acting in partially observable stochastic domains. Artificial Intelligence, 101(1–2):99–134, 1998.
- T. B. Brown et al. Language models are few-shot learners. NeurIPS, 2020.
- S. M. Xie, A. Raghunathan, P. Liang, T. Ma. An explanation of in-context learning as implicit Bayesian inference. ICLR, 2022.
- S. Min, X. Lyu, A. Holtzman, M. Artetxe, M. Lewis, H. Hajishirzi, L. Zettlemoyer. Rethinking the role of demonstrations: what makes in-context learning work? EMNLP, 2022.
- L. Ouyang et al. Training language models to follow instructions with human feedback. NeurIPS, 2022.
- W. Huang, P. Abbeel, D. Pathak, I. Mordatch. Language models as zero-shot planners: extracting actionable knowledge for embodied agents. ICML, 2022. Table 1: executability in VirtualHome.
- M. Ahn et al. Do as I can, not as I say: grounding language in robotic affordances. CoRL, 2022. SayCan.
- P. A. Ortega et al. Shaking the foundations: delusions in sequence models for interaction and control. DeepMind technical report, arXiv, 2021.
- H. He and Thinking Machines Lab. Defeating nondeterminism in LLM inference. Blog post, September 2025.
- R. S. Sutton, A. G. Barto. Reinforcement Learning: An Introduction, 2nd ed. MIT Press, 2018. Section 17.3 on partial observability; chapter 13 on policies as distributions.
- L. Weng. LLM powered autonomous agents. Blog post, June 2023.