Sub topic 2
LLM foundations an agent builds on
This chapter assumes you can write Python, call a web API and read JSON, and have used a chat model. It covers the model-side facts that every later design decision depends on: what a model does on each call, what a token is, what the context window limits, and which sampling settings matter.
A model call is a function of text
A language model takes a sequence of tokens and predicts a probability distribution over the next token. A chat API wraps this in a message format, but the model is still doing next-token prediction. Three consequences matter for agents:
- The model is stateless. It remembers nothing between calls. Anything it should "know" must be in the input of this call.
- The model does not run code or fetch data. It only produces text. A tool call is text in an agreed format that your program reads and acts on.
- Output is generated one token at a time, so long outputs take longer and cost more.
An agent is therefore a program that rebuilds the model's input on every step, sends it, and interprets the output. Everything in later chapters is a way of deciding what goes into that input and what to do with the reply.
Messages and roles
Chat APIs take a list of messages, each with a role.
| Role | Purpose | Typical author |
|---|---|---|
| system | Standing instructions: behavior, limits, format | Developer |
| user | The request or goal | End user or your program |
| assistant | Model output, including requested tool calls | The model |
| tool | Result of a tool your program ran | Your program |
Role names vary slightly between providers. Some put the system prompt in a separate parameter, and some call tool results "function" or place them inside a user message. The pattern is the same: you send the full list each time, and you append the model's reply and any tool result before the next call.
Tokens
A token is the unit the model reads and writes. It is usually a word fragment, a whole common word, or a piece of punctuation. For English text, one token is roughly four characters, or three quarters of a word. That ratio is a rough guide only:
- Code, JSON, and non-English text often use more tokens per character.
- Numbers and unusual identifiers can split into many small tokens.
- Whitespace and punctuation count.
Tokens matter for three reasons. Providers bill per token, with output tokens usually priced higher than input tokens. Latency grows with output length. And the context window is measured in tokens, not characters or messages.
For real budgets, count with the provider's tokenizer or the usage numbers returned in each API response. Estimates are fine for guarding against obvious overflow.
The context window
The context window is the maximum number of tokens the model can handle in one call. It covers input and output together.
context window = system prompt + message history + tool definitions + tool results + outputTool definitions count too. Each tool's name, description, and argument schema is sent on every call, so twenty verbose tools can take thousands of tokens before the user says anything.
The dotted arrow is what makes agents hard. Each step adds the model's output, and often a tool result, to the history. The input grows on every iteration, so a long run can fill the window even if each step is small.
What happens at the limit
If input plus the requested maximum output exceeds the window, most APIs return an error. The call fails and your loop must handle it. Some systems instead truncate silently, which is worse, because the agent loses instructions without any signal.
Even below the hard limit, quality can degrade. Models tend to use information at the start and end of a long input more reliably than information buried in the middle, and long inputs raise cost and latency on every step. A larger window is headroom, not a reason to stop managing context.
A minimal budget guard
This function keeps the system messages and the newest messages that fit, and reserves room for the output. It uses a rough four-characters-per-token estimate.
def estimate_tokens(text: str) -> int:
return max(1, len(text) // 4)
def fit_to_budget(messages: list[dict], window: int, reserve_for_output: int = 1000) -> list[dict]:
limit = window - reserve_for_output
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
used = sum(estimate_tokens(m.get("content") or "") for m in system)
kept = []
for message in reversed(rest):
cost = estimate_tokens(message.get("content") or "")
if used + cost > limit:
break
kept.append(message)
used += cost
kept.reverse()
return system + kept
history = [{"role": "system", "content": "You are a helpful assistant."}]
for i in range(20):
history.append({"role": "user", "content": "x" * 400})
trimmed = fit_to_budget(history, window=1500)
print(len(trimmed)) # 1 system message + 4 user messages = 5This guard is deliberately crude. Dropping old messages loses information, and it can split a tool call from its result, which some APIs reject. Chapter-level techniques such as summarizing and pinning important facts come later, in the memory chapter. For now, the point is that trimming is your program's job, not the model's.
Sampling settings
Two settings control how the next token is chosen from the distribution.
- Temperature scales randomness. Near 0, the model picks the most likely token almost every time. Higher values give more varied output.
- Top-p limits choices to the smallest set of tokens whose probabilities add up to p.
For agents, low temperature is the usual default. An agent must emit well-formed tool calls and make consistent decisions, and variety rarely helps there. Change one setting at a time, not both.
Even at temperature 0, outputs are not guaranteed to be identical across runs. Hardware, batching, and provider updates can change results. Design tests to tolerate small variation, as the evaluation chapter explains.
Prompts are the only control surface
You cannot change the model's weights in an agent project, so you steer it through input: the system prompt, the examples you include, the tool descriptions, and the data you retrieve. This has practical implications:
- Order and placement matter. Put stable instructions first and the current task last. Stable prefixes can also qualify for provider prompt caching, which lowers cost.
- Models follow what is written, not what is meant. If a rule is missing from the input, it does not exist for the model.
- Untrusted text is still input. A web page or document that a tool returns enters the same context as your instructions. The model can mistake instructions inside it for real ones, which is why the guardrails chapter treats tool output as data.
Common errors
- Assuming memory. Sending only the newest user message and expecting the model to recall earlier turns.
- Ignoring output reservation. Filling the window with input, leaving no room for a reply, and getting truncated or failed responses.
- Counting messages instead of tokens. Ten messages can be 200 tokens or 20,000.
- Forgetting tool definitions. The budget shrinks as you add tools.
- Trusting estimates near the edge. Use the token counts the API reports back and leave a margin.
Exercise
An agent has a 16,000-token window. The system prompt uses 1,500 tokens, tool definitions use 2,500, and you want to allow up to 2,000 output tokens. How many tokens are left for message history and tool results, and what should your loop do when a tool returns a result larger than that?
Show answer
16,000 - 1,500 - 2,500 - 2,000 = 10,000 tokens remain for history and tool results. If a single tool result is larger than the remaining space, the loop should not send it as is. It should truncate or summarize the result, or have the tool return a smaller page of data, and then tell the model the output was shortened so it can ask for more if needed.