How LLMs Power Agents: Transformers, Tokens and Sampling
You do not need to train a model to build agents, but you do need to know how it reads, writes and fails.
A large language model (LLM) reads a sequence of tokens and predicts what comes next, one token at a time. In an agent, that prediction is used to choose actions. The model's context window, sampling settings and tendency to produce plausible errors shape almost every design decision around it.
What you will learn: how text becomes a model's decision, what attention does, how tokens and context windows limit an agent, what temperature and top-p change, and why more context is not always better.
Prerequisites: none for the beginner section. Basic Python for the sampling example.
Prediction, one token at a time
At its core, an LLM answers one question over and over: given this text, how likely is each possible next piece? It picks a piece, adds it to the text and asks again, until it produces a stop signal or reaches a length limit. A fluent paragraph, a line of code and a request to call a tool are all produced this way.
Models learn these predictions in training. A first stage, pretraining, learns patterns from very large amounts of text and often other data. Later stages tune the model to follow instructions, behave safely and use tools. The result is a general capability that you steer with the input.
From text to action
An LLM cannot open a file or send a message. What it can do is write a structured request, such as "call search_orders with this customer ID". Your program reads the request, runs the function and adds the result to the conversation. Providers train models to produce these requests in a reliable format, often called tool calling or function calling. See Message Roles, Structured Output and Function Calling.
Answer: "Your parcel is due on Thursday."
Action request: {"tool": "track_parcel", "args": {"id": "P-1042"}}
The model chose between them by predicting which continuation fits the context. Your tool descriptions and instructions strongly influence that choice.
The model starts fresh each call
In ordinary use, a model's weights do not change while you use it, and it does not remember your previous request unless the information is sent again or held by a service on your behalf. An agent's sense of continuity comes from the runtime, which supplies history, state and retrieved memory. This explains a common puzzle: if the agent "forgot" a rule, the rule was probably not in the context, or was buried where it received too little weight.
The transformer, for agent builders
Most current LLMs are based on the transformer, introduced in the 2017 paper Attention Is All You Need. You can build excellent agents without the mathematics, but five ideas explain much of their behavior.
- Attention relates everything to everything. It lets an instruction at the start influence a decision at the end. It also means irrelevant text can influence it.
- Generation looks backward only. In decoder-style models, each new token depends on earlier ones. Reasoning written out before an answer can therefore help the answer.
- Cost grows with length. Longer inputs need more computation and memory. Standard attention grows roughly with the square of the length, although many optimizations reduce this in practice.
- Prefixes can be reused. If the start of the input is identical across calls, serving systems can cache work. Keep stable material, such as instructions and tool definitions, at the front. See Reducing Tokens, Tool Calls and Spend.
- Variants differ. Many models mix experts or use other efficiency designs. The interface stays: tokens in, scores out.
Tokens and tokenization
A token is a chunk of text from the model's vocabulary: a whole common word, part of a rarer word, punctuation or a few characters of code. Tokenizers are often built with methods related to byte-pair encoding, which merges frequently occurring pairs into larger units.
A common rule of thumb for English is about four characters per token. It is only a rough guide. Other languages, code, long identifiers, numbers and structured data can differ widely, and different models use different tokenizers. For budgets and bills, use the counts the provider reports, or its token-counting tool.
| Effect on agents | Why it happens | What to do |
|---|---|---|
| Tool results are expensive | Verbose JSON repeats keys on every row | Return only needed fields; summarize large tables |
| Character-level tasks go wrong | The model sees chunks, not letters | Count, sort and compare in code |
| Arithmetic slips | Numbers are split into tokens and predicted | Give the agent a calculator or run code |
| Languages cost differently | Some scripts need more tokens per word | Measure with your real data |
Context windows and other limits
The context window is the largest number of tokens the model can handle in one request, usually covering both input and output. Everything the agent knows in a turn must fit: instructions, tool definitions, history, retrieved documents and the space for the reply.
Several limits apply at once. Check current provider documentation for each, because they change often.
- Context window: total size of one request.
- Maximum output: usually much smaller than the window. A reply that hits it is cut off, possibly in the middle of a tool request, so check the stop reason.
- Rate limits: requests and tokens per minute. Agents with many steps or parallel workers reach these quickly.
- Latency: time to the first token plus time per output token, multiplied by the number of steps.
- Knowledge cutoff: the model's training data ends at some date. For anything current, give it a tool.
A worked token budget
These are illustrative figures for a window of 100,000 tokens.
| Part | Tokens | Notes |
|---|---|---|
| Instructions | 2,000 | Stable, cacheable |
| Tool definitions | 6,000 | Thirty tools at 200 each |
| Reserved for output | 8,000 | Never fill this space |
| Safety margin | 10,000 | For surprises such as a large result |
| Left for history and documents | 74,000 | At 3,000 per step, about 24 steps |
The last row is the one that surprises people. An agent that reads a few large files can exhaust a large window quickly. What Is Context Engineering? Stack and Token Budgets shows how to manage it.
Sampling: temperature and top-p
The model produces a score for every candidate token. Scores are turned into probabilities, and sampling settings control how one is picked.
- Temperature sharpens or flattens the probabilities. Low values favor the top choice; high values give weaker choices more chance.
- Top-p (nucleus sampling) keeps only the most likely tokens whose probabilities add up to p, then picks among them.
- Top-k, offered by some systems, keeps a fixed number of top candidates.
This small program applies both to four made-up scores.
"""How temperature and top-p change the choice of the next token."""
import math
# Raw scores (logits) a model might give four candidate next tokens
LOGITS = {"search": 4.0, "answer": 3.0, "ask": 1.5, "delete": 0.2}
def softmax(logits, temperature):
scaled = {k: v / temperature for k, v in logits.items()}
top = max(scaled.values())
exp = {k: math.exp(v - top) for k, v in scaled.items()}
total = sum(exp.values())
return {k: v / total for k, v in exp.items()}
def top_p(probs, p):
"""Keep the most likely tokens until their total reaches p."""
kept, running = {}, 0.0
for token, prob in sorted(probs.items(), key=lambda kv: -kv[1]):
kept[token] = prob
running += prob
if running >= p:
break
return {k: v / running for k, v in kept.items()}
def show(label, probs):
cells = " ".join(f"{k}={probs.get(k, 0):.3f}" for k in LOGITS)
print(f"{label:22}{cells}")
for t in (0.2, 1.0, 2.0):
show(f"temperature {t}", softmax(LOGITS, t))
show("temp 1.0, top-p 0.9", top_p(softmax(LOGITS, 1.0), 0.9))
Output:
temperature 0.2 search=0.993 answer=0.007 ask=0.000 delete=0.000
temperature 1.0 search=0.679 answer=0.250 ask=0.056 delete=0.015
temperature 2.0 search=0.490 answer=0.297 ask=0.140 delete=0.073
temp 1.0, top-p 0.9 search=0.731 answer=0.269 ask=0.000 delete=0.000
Look at delete. At temperature 0.2 it effectively never appears. At 2.0 it appears about 7 times in 100. In a real model the numbers differ, but the lesson holds: higher randomness raises the chance of unusual actions.
| Agent step | Reasonable starting point |
|---|---|
| Choosing tools and filling arguments | Low temperature |
| Extracting or classifying | Low temperature, with a schema |
| Drafting varied text or ideas | Moderate or higher |
| Generating several candidates to compare | Moderate, so candidates differ |
A temperature of zero reduces variation but does not guarantee identical output on hosted systems. Changing both temperature and top-p at once makes effects hard to understand, so adjust one. And some models, particularly some reasoning models, restrict or ignore these settings: read the documentation for the one you use.
Context length versus reasoning quality
A large window makes it possible to include more. It does not make the model use all of it equally well. Research has found that models can struggle with information placed in the middle of long inputs (Lost in the Middle), and a 2025 technical report from Chroma found reliability falling as input length grew across the models it tested, an effect it called context rot. The size of the effect depends on the model, the task and how similar the distracting text is to what matters.
| Approach | Strength | Weakness |
|---|---|---|
| Send everything | Simple; nothing is missed by selection | Costly, slower, distraction |
| Retrieve what is relevant | Small and focused | Can miss what matters |
| Summarize history | Keeps long runs going | Details and caveats can vanish |
| Split across sub-agents | Each has a clean context | More calls and hand-off errors |
Do not rely on general claims. Take twenty of your own tasks, run them with a small focused context and with a large one, and compare success, cost and time. Failure patterns are described in Context Poisoning, Distraction, Confusion, Clash and Rot.
Where an agent step spends time
One step usually includes sending the input, waiting for the first token, receiving the output, running the tool and saving state. Long inputs mainly delay the first token; long outputs add time roughly in proportion to their length; tools can dominate both. Streaming shows progress sooner but does not shorten the total. Because steps run in sequence, an agent that needs ten steps feels ten times slower than one call, so measure the time of whole tasks, not only of single requests. Latency, Load Testing and Capacity Planning covers the planning.
Weaknesses that matter for agents
| Weakness | In an agent it looks like | Design response |
|---|---|---|
| Confident fabrication | Invented IDs, file names or results | Validate against real systems; require evidence |
| Instruction and data are both text | A web page's text steers the agent | Limit permissions; see Prompt Injection Attacks and Defenses |
| Variation between runs | A task passes today and fails tomorrow | Repeat tests and report success rates |
| Poor self-knowledge | High confidence on a wrong step | Use external checks over self-ratings |
| Version changes | Behavior shifts after an upgrade | Pin versions and re-evaluate before switching |
Reasoning models
Many providers offer models that spend extra tokens working through a problem before giving the final reply, often with a setting for how much effort to spend. They can plan and debug better. They also cost more and take longer. A practical pattern is to route planning and difficult recovery to a higher-effort setting and routine extraction to a faster one. Choose by evaluation, as described in Choosing Models: Reasoning, Open-Weight and Hosted and Model Routing, Fallbacks and Gateways.
Constraining the output
Many systems can force output to match a schema by allowing only tokens that keep it valid. This guarantees the shape of the output, when supported and used correctly, but not the truth of the values. A perfectly formed request can still name the wrong customer. Keep semantic checks in your code.
Log input tokens, output tokens, cached tokens, stop reason and model version for every call. Most surprises in cost and quality can be explained from those five fields.
Checklist
- You know the window and output limits of your model.
- Each request has a token budget with reserved output space.
- The stop reason is checked on every response.
- Sampling settings are chosen per step and recorded.
- Exact work such as counting and arithmetic is done by code.
- Current facts come from tools, not from model memory.
- Model versions are pinned and tested before changes.
Frequently asked questions
Does a model understand what it reads?
Researchers and philosophers disagree about the word. For engineering, judge behavior: test whether it performs your task reliably.
Does the model learn from my agent's conversations?
Calling a model does not change its weights at that moment. Whether data is stored or used for later training depends on the provider's terms and your settings, so read them.
Should I always use the largest context window?
Use what the task needs. Extra material costs money and can reduce accuracy.
Is fine-tuning needed to build agents?
Usually not at the start. Instructions, tools and retrieval solve many problems. See Fine-Tuning vs RAG vs Prompting vs Long Context.
References and further reading
- Attention Is All You Need (paper)
- Neural Machine Translation of Rare Words with Subword Units (paper on byte-pair encoding)
- The Curious Case of Neural Text Degeneration (paper introducing nucleus sampling)
- Lost in the Middle: How Language Models Use Long Contexts (paper)
- Context Rot: How Increasing Input Tokens Impacts LLM Performance (Chroma technical report)
Next steps
Message Roles, Structured Output and Function Calling
Roles, schemas and tool calls in detail.
Choosing Models: Reasoning, Open-Weight and Hosted
Pick a model by testing, not by reputation.
What Is Context Engineering? Stack and Token Budgets
Decide what goes into the window.