You will not train the model at the centre of your agent, but you will spend your days at
its boundary: counting what a request costs, choosing a temperature, parsing its JSON,
retrying when it is overloaded. This module covers what happens at that boundary, at the
level of detail a builder needs. It explains what a token is and why every budget is counted
in them, how a model turns scores into text, how to make it produce output a program can
rely on, and how to write the client code that sits between your agent and the provider.
Notebooks
Notebook 2a: Tokens and BPE trains a byte-pair-encoding
tokenizer from scratch and counts what prompts and tool outputs cost.
Notebook 2b: A tiny language model trains a character
model, implements temperature, top-k and top-p sampling, and forces valid tool-call JSON
with a grammar. Notebook 2c: The LLM client builds structured
output with repair, concurrency, retries, caching and a cost budget as small layers.
Tokens
Models read and write integers, not characters. The text you send is first cut into pieces
from a fixed vocabulary, and each piece is replaced by its index.
Definition 2.1 (Token and tokenizer).
A tokenizer maps text to a sequence of integers from a fixed vocabulary and back. Each
vocabulary entry is a token: a byte sequence that may be a whole word (" agent"),
part of one ("iz"), a punctuation mark or a single byte. Context windows, output limits
and prices are all counted in tokens.
Most models use byte-pair encoding (BPE). Training starts from the 256 possible bytes,
so any string can be encoded, and repeatedly fuses the most frequent adjacent pair into a
new token until the vocabulary reaches its target size, typically 50,000 to 250,000
entries. Before merging, a regular expression splits the text into words, numbers and
punctuation, so tokens do not span word boundaries. Notebook 2a builds all of this in about
50 lines.
Three consequences of tokenization (Definition 2.1) matter when you build agents.
Cost depends on what you send, not just how much. A tokenizer compresses the kind of
text it was trained on. English prose comes to about 4 bytes per token with a modern
tokenizer; JSON, code, numbers and many other languages come to fewer, so the same number
of bytes costs more tokens.
Numbers are chopped up. Most tokenizers split digits into groups of up to three, so a
model sees 12345678 as 123, 456, 78: chunks whose boundaries have nothing to do
with place value. That is one reason long arithmetic belongs in a tool.
Everything is re-sent. An agent’s request contains its instructions, its tool
definitions and its whole history, every step (Module 1). Tool outputs, which are often
large JSON blobs, are usually the biggest part of the bill.
Providers charge separately for input and output tokens, and most offer a discount on input
tokens they have recently seen as the prefix of an earlier request (prompt caching, below).
With input tokens of which hit the cache,
output tokens, and per-token prices , a call costs
Output tokens typically cost four to five times as much as input tokens, and cached input
tokens a tenth to a half of the input price. Reasoning models add a further term: they write
hidden reasoning tokens before the visible answer, billed as output, and an “effort”
setting controls how many. The usage table at the end of every notebook applies equation
without the cache term, at a round reference price of USD 1 per million input
tokens and USD 4 per million output tokens.
From scores to text
Definition 2.2 (Language model).
A language model assigns a probability to every token in the vocabulary as the next
one, given the tokens so far: . It generates text
autoregressively: choose a next token, append it, and repeat until a stop token or a
length limit.
The network inside a language model (Definition 2.2) outputs one score per vocabulary entry, called a logit. The softmax turns scores into probabilities, and the temperature reshapes
them on the way:
With the distribution in sharpens towards the top token;
with it flattens; as it puts all its mass on the top token
(greedy decoding). Two filters are usually applied as well. Top-k keeps only the
most likely tokens. Top-p (nucleus sampling) keeps the smallest set whose probabilities
add up to , so it keeps few tokens when the model is confident and many when it is not.
Both cut off the long tail of unlikely tokens, which is where most nonsense in a sample comes
from.
contexttokens so farmodelone logit eachtemperaturetop-k, top-pgrammar maskvalid onlysamplenext tokenappend and repeat
Agents mostly want low temperatures for tool calls and structured output, where there is one
right answer, and moderate ones for open-ended writing. Two cautions apply.
Remark 2.1 (Low temperature is not determinism).
Greedy decoding is not a safe default. On a small model it falls into loops (Notebook 2b
shows a model repeating the model the model ...), and even large models degrade into
repetition on long outputs. And temperature 0 on a hosted API does not guarantee identical
outputs: batching and floating-point order vary between calls. Build agents that tolerate
variation, and evaluate them over several runs (Module 10).
The caution in Remark 2.1 also explains why evaluation of agents talks about
success rates rather than pass or fail: the same request can lead to different
trajectories.
Output a program can rely on
An agent parses what the model writes: a tool name and its arguments, a category to route
on, a score to compare. Free-form generation gets this wrong some of the time. The tiny
model in Notebook 2b produced a usable tool call only a quarter of the time. Large models
fail far less often, but a long run makes many calls, and one failure in a hundred will
happen. There are two remedies, and robust systems use both.
Validate and repair. Describe the expected shape as a schema (in Python, a Pydantic
model), validate every reply against it, and when validation fails, send the error message
back and ask again. The error is a precise correction written by a machine: priority: Input should be less than or equal to 3. This works with any model, and Notebook 2c builds
it in 15 lines.
Make invalid output impossible.
Definition 2.3 (Constrained decoding).
Constrained decoding applies a grammar at every generation step: tokens that cannot
continue a valid output get probability zero, and the rest are renormalised before
sampling. Where the grammar allows only one continuation, it is emitted without consulting
the model at all.
Model APIs expose constrained decoding (Definition 2.3) as “structured outputs” or “strict” tool schemas;
open-source inference servers implement it with libraries such as Outlines and XGrammar,
which compile a JSON Schema into a mask over the vocabulary. The hard part in practice is
that one token can cover several grammar positions (a single token might be ", "), so the
mask has to be computed over token strings, not characters.
Remark 2.2 (Form is not content).
A grammar guarantees that the output parses. It does not make it right. In Notebook
2b, the constrained model writes a valid tool call every time, and picks the tool by how
often it appeared in training rather than by the question, because its short context
cannot see the question. A strict schema on a real model guarantees a well-formed
{"city": ...}; only the model’s reading of the request makes it the right city.
So keep validating values even when the format is guaranteed (Module 3 on tool arguments),
and measure behaviour, not just parse rates (Module 10). Remark 2.2 is the
structured-output version of a general rule in this course: checks on shape are cheap and
worth having, and they are not evidence that the agent works.
The client between agent and model
Remark 2.3 (The model remembers nothing).
Each call is independent. A model knows only what is in the request: the instructions,
the conversation so far, the tool definitions. A chat that seems to remember you is a
client that re-sends the whole history every turn.
Two of the course’s big topics follow from Remark 2.3. Memory and context engineering
(Module 6) is the problem of choosing what to re-send. Cost grows with each step, because
every turn pays again for all the turns before it.
The rest of the client is engineering for an unreliable remote service. Each concern is
best written as a thin layer that wraps the model client and presents the same interface,
so layers stack:
layer
guards against
the rule that matters
structured output
unparseable or invalid replies
validate every reply; feed the error back
concurrency
slow sequential calls
asyncio.gather, with a semaphore to cap calls in flight
retries
rate limits (429), overload (529, 503), timeouts
exponential backoff with jitter; never retry 400 or 401
exact cache
paying twice for the same request
key on everything that affects the reply
budget
runaway cost
estimate before sending; refuse past the limit
One interface, many providers. Providers differ in wire format: where the system prompt
goes, how tool calls are encoded, what the usage fields are called. LiteLLM translates a
single OpenAI-style call into each provider’s format, so the provider becomes a string such
as anthropic/claude-sonnet-5-5 or ollama/qwen3. Everything in this course talks to the
BaseLLM interface instead (await llm.generate(request)), so the offline policy model, a
recorded replay, the tiny model of Notebook 2b and a live model are interchangeable.
Prompt caching is different from the exact cache in the table. The provider keeps the
computed state of a request’s prefix, and a later request that starts with the same tokens
is billed at the cached rate in . Agents benefit greatly, because each step
re-sends the same instructions and tools followed by a growing history. Prompt caching only
helps if the prefix is byte-for-byte stable: put instructions and tool definitions first,
append new content at the end, and keep timestamps and random ids out of the system prompt.
Choosing a model. For an agent, the criteria are mostly not the ones on general
leaderboards. In rough order: how reliably it calls tools and follows a schema; how well it
uses a long context full of tool output; latency per step, since an agent makes many; price
per step, by equation ; and for hard multi-step tasks, whether a reasoning
mode helps enough to pay for its hidden tokens. The only reliable way to choose is to run
your own tasks through each candidate several times (Module 10).
Try this
In Notebook 2a, train the tokenizer on the notes plus a few hundred lines of JSON. How
much cheaper do tool definitions become, and what happens to prose?
In Notebook 2b, raise the n-gram order to 30 so the context reaches back into the
question. Does the constrained model now choose the right tool? What happens for a city
that is not in the training data, and what does that suggest about memorisation?
Use equation to price a 30-step agent run: a 3,000-token prefix of
instructions and tools, 600 tokens added per step, 150 output tokens per step, at USD 3 and
USD 15 per million input and output tokens. Then assume the prefix and all earlier history
hit the cache at a tenth of the input price. How much does caching save?
Readings
Hur and Song, Build an AI Agent (From Scratch), Manning 2026, chapter 2.
Stanford CS329Z, Engineering AI Agents, Lecture 2: LLMs for builders
(slides).