Models, Harnesses, Agents, Environments
The first most important thing you'll need to understand in order to work with AI agents is what an agent even is, what its component parts are, and how they relate to each other.
There are four key elements to understand:
- The environment - The outside world your agent interacts with
- The model - The thinking engine
- The agent - The model harnessed in an environment
- The harness - What connects the model to the environment
Diagram showing the four components: environment, model, agent, and harness
The Model: The Thinking Engine
The model is the engine in the car. It's the thinking brain inside the whole setup.
Examples of models include:
- Claude Opus
- Claude Sonnet
- GPT 5.5
- Grok
These models usually sit on some server somewhere, and they charge you for access to make requests to them.
On its own, the model doesn't really do much. You pass it text, and it gives you back some text. To make it actually useful in the world, you need some kind of harness around it.
The Harness: Connecting Model to World
The harness connects that model (that text-producing stateless thing) to the outside world. That outside world is represented by the environment.
The harness is tied to the environment it's in. It's designed around that environment.
For example:
- Code editors and IDEs have an environment of the file system. They use tool calls to interact with the file system, save files, edit files, and search the web.
- Chat interfaces like ChatGPT or Claude.ai have their own environments. In Claude.ai, you can save documents and search the web. It's a slightly different virtual environment from the file system.
Defining an Agent
An agent is a model harnessed in an environment.
The agent isn't really a separate thing. It's just a name for what we call the harness and the model together. When we talk about Claude Opus running in an IDE on the file system, that is an agent. It's also a harness wrapping a model.
Here are some concrete examples of agents:
- Opus running in an IDE on the file system
- Grok (the model) on Pi (the harness) operating on the file system (the environment)
- GPT 5.5 on ChatGPT in the ChatGPT environment, where it can create documents, search the web, and connect to MCP servers
The Blurry Lines
Like every analogy, this isn't a perfect one. The harness and the environment blur together a little bit.
For instance, if you have an NPM script, is that an aspect of the harness? Is it something the harness can call, or is it something in the environment? It's in the environment, but other people might say it's in the harness. There's a little bit of bleed there.
Improving Performance Beyond Just the Model
People go crazy for the model. Everyone wants to swap in the latest and greatest model and expects everything to become amazing.
But the model is just one aspect in a larger ecosystem. It's just the engine of the car.
If you want your agent to perform better, you can do more than just swap out the model. You can think about:
- Improving the harness
- Improving the environment in which the harness and model operate
Training a new model is unbelievably expensive and out of reach for most people and companies. So your work is going to be in improving the harness and improving the environment that the agent works in.
What is an agent?
- A model harnessed in an environment
- A model trained on your own codebase
- A set of tool calls wrapped in a script
- A chat interface that can search the web
Your agent keeps underperforming on your project. Where is most of your leverage to fix it?
- Improve the harness and the environment it works in
- Swap in the newest and most capable model you can find
- Train a new model on the code your team has written
Non-Determinism
The model is just one part of the agent. There's also the harness and the environment. Understanding how these components work together is key to influencing the outcome of your AI coding agent.
Let's focus on the model itself, because understanding it will help us grasp the core of everything that's going on.
Next Token Prediction
The main thing to understand about models is that they're doing next token prediction. However you try to change it, however you try to manipulate it, it's always non-deterministic.
How Token Prediction Works
Models work by taking a sequence of tokens as input. Think of it like completing a sentence:
my space favorite space color space is space
These are all candidates for the next token. The model has to guess what comes next.
The important part is that the model is asking itself to choose the next token. It has a set of candidates already in its training weights.
The model looks across all possible tokens and identifies the most likely candidates. From there, it assigns a probability to each one.
| Candidate | Probability |
|---|---|
| red | 32% |
| blue | 28% |
| orange | 14% |
Visual representation of token candidates and their probability distributions
The Sampling Process
At this point, the prediction goes into the sampler. The sampler takes a sample of each candidate and essentially picks one.
You might think: "Why wouldn't it always just pick the most likely option?" That makes the most sense, right?
What's interesting about large language models is that sometimes they pick the most likely option, sometimes they pick a less likely one, and sometimes they will even pick a relatively unlikely possibility.
This is because the sampler is usually tuned to be random or relatively random, a sort of weighted randomness. There are lots of different sampling algorithms, many of which are non-deterministic, and a couple which are deterministic. But most agents pick non-determinism.
Temperature Control
There's also a concept called temperature that you can pass to most samplers. Most models will accept a temperature setting.
- High temperature: The model chooses more randomly
- Low temperature: The model chooses less randomly and will always pick the most likely option
So your question probably is: "Why wouldn't I always set temperature to zero?" Surely when coding, there's always a correct answer that's best, and you should be able to get the model to choose it every time.
Temperature scale showing relationship between temperature, diversity, and output quality
The Likelihood Trap
This is actually a well-known trap in language modeling. It's called the likelihood trap, from a paper called "Trading Off Diversity and Quality in Natural Language Generation."
Here's what the research shows:
As you decrease temperature and remove diversity from the output, always making the model choose the same thing, the quality actually drops.
You can see this in the paper's data. As temperature increases initially, they get better quality, reaching a peak point. But as they continue reducing temperature even further, the responses start getting worse again.
This scale is based on human judgment. Humans actually judge these really deterministic responses to be worse.
Graph showing the likelihood trap with quality peaking at moderate temperature, not at zero
Non-Determinism Is a Feature
This means that non-determinism is a feature, not a bug.
If you get the agent to choose the most likely candidate every time, you fall into the likelihood trap, and your responses are going to get worse.
And by the way, even if you do turn temperature to zero, because of the way that models do their work (massively in parallel, with the order of computation mattering), even on the same GPU with the same model, it's going to return different responses each time. It's very strange.
This means non-determinism is baked into the pie here. We cannot get rid of it.
What This Means for AI Coding
When you watch exercises being performed, your agent is probably going to do something different. That difference and the variance here is something we need to get used to and get better at dealing with.
Non-determinism echoes down into permissions as well. There's always a non-zero chance that the agent will do something really weird and really bad, even if it's very smart.
Keep this in your mind all the time: non-determinism is baked in. You cannot remove it. You can get your systems to perform more reliably, but there's always this non-deterministic engine at the base of it.
You want your coding agent to give the same good answer every time, so you set the temperature to zero. What do you actually get?
- Lower quality output: this is the likelihood trap
- The highest quality answer it can give, every run
- An identical response on every single run you make
Your agent runs a very capable model and has behaved well all week. How should that change the way you think about its permissions?
- Not at all: a smart agent can still do something bad
- Loosen them, because a smart model has earned the trust
- Loosen them, but only after you set the temperature to zero
Turns And Model Provider Requests
One thing that many AI-powered developers lack is a way to describe what an actual turn with an agent looks like.
How does the harness, which is usually running locally, communicate with the model, which is usually sitting in the cloud? Understanding this is essential for the optimizations and thinking you'll do later.
Setting Up the Request Logger
To understand this communication, you'll use the request logger. Run:
npm run request-logger
It asks which coding agent you use, and which model provider if your agent can use more than one. It can remember your answer, so it only has to ask once. It then prints the exact command to start that agent through the logger.
Copy and paste that command into a new terminal and run it. Now instead of pointing at the model provider's servers, your agent is pointing at your local request logger.
Next, open the side panel and navigate to the ./request-logger/logs directory. It should currently be empty except for a .gitkeep file.
File explorer showing empty logs directory with git keep file
Seeing Your First Model Provider Request
Say hello to the agent. It responds with something like "hello, what would you like to work on today?"
Now refresh the logs directory. A new file has appeared tracking the request made to v1/messages on the Anthropic API.
Request logs showing model provider request with XML tags and metadata
Inside the Request
This file contains everything sent to and received from the model. There are different XML tags showing what was in the request.
At the top, you'll see meta information and headers. Further down around line 50, you'll see the system prompt with all the text sent to the agent.
Scroll down to find where you said hello. Then find the agent's response. At the very bottom, you'll see:
Hello, what would you like to work on today?
This entire huge request and the tiny response you got back - this is a model provider request.
| Concept | Meaning |
|---|---|
| Model Provider Request | One request sent to the model, plus one response back |
| Model Provider | The service handling the request (Anthropic, Ollama, etc.) |
Following the Conversation
Go back to the agent and ask a follow-up:
tell me my hair looks nice
The agent responds with something like "your hair looks nice," and another model provider request is created in the logs.
Multiple Hidden Requests
Refresh the logs directory. You'll notice there are actually multiple new requests, not just one. The agent doesn't just respond to your message - it's doing other work behind the scenes.
To figure out which request is which, click on one and scroll to the bottom. You'll see a title describing what that request was for, like "compliment request about hair."
Request logs showing multiple requests with descriptive titles
Suggestion Requests
Other requests might have titles like "now let's get to work on proxy.ts." These are running in SuggestionMode - they generate what you might naturally type next into the agent.
Request log showing SuggestionMode generating next prompt suggestions
Every time you see something that looks AI-generated in the interface, that's the result of a model provider request. Even the suggestions are coming from the model.
The Full Conversation History
As you look through the logs, you'll notice something important: every time you send a request to the agent, your entire conversation history is passed along with it.
The request includes:
- Your previous messages
- The agent's previous responses
- All context accumulated so far
This file gets longer and longer as your conversation grows.
Triggering Tool Use
Now ask the agent to do something more complex:
I would like you to write a file containing a list of compliments to me in a markdown file in the repository root.
Check the logs - there are now several requests. The first one is properly dated to when you sent your message.
Inside, find where you sent your request. The agent processes it and then something different happens. Instead of just responding with text, you see a tool use section.
Request log showing JSON tool use with file path and content parameters
Rather than plain text, the model is passing a file_path and content.
What Is a Tool?
A tool is something the harness provides to the model to let it interact with the environment. In this case, there's a write tool that takes:
- A
file_pathparameter - A
contentparameter
Request log showing write tool definition with JSON schema
Looking further back in the request, you'll see where the tool was defined. It passes JSON schema telling the model how to call it.
The Tool Call Response
In this single model provider request, the harness sent:
- Instructions on how to call a tool
- Your request to write a file
The model responded: "OK, let's use this tool."
That tool use part is then interpreted and executed by the harness.
Request log showing tool result indicating file created successfully
Looking at the next request, you'll see a tool result message. The harness then sends this result back to the model in another request, and receives a new response:
Done, I created compliments.md in the repo root.
Defining a Turn
This entire flow is called a turn.
Both of these model provider requests were sent in a single turn:
- First request: You sent a message and received instructions to call a tool
- Second request: You sent the tool result and received a message back
Diagram or view showing a complete turn with multiple model provider requests
A single turn can last hours and contain hundreds of model provider requests.
| Element | Definition |
|---|---|
| Model Provider Request | One round trip to the model (request + response) |
| Tool Call | The model's instruction to use a tool (not the execution) |
| Tool Result | The output of executing that tool |
| Turn | The entire cycle from user message to agent response, including all tool calls and results |
This is the engine that powers everything.
Next Steps
Continue your conversation with your agent and watch the requests build up in the logs. Play around and see what you can find. The language of model provider requests, turns, tool calls, and tool results should now make sense for understanding how agents work.
You ask the agent to write a file. It calls the write tool, gets the result back, and tells you it is done. How does that flow break down?
- Two model provider requests inside a single turn
- Two turns, one for each model provider request
- One model provider request, making up one turn
The model's response contains a tool use block with a file_path and content. Who actually writes that file to disk?
- The harness interprets the tool use and runs it
- The model writes the file as part of its response
- The model provider runs the tool on its own servers
What does the harness send to the model on each new model provider request in a conversation?
- The entire conversation history so far, every time
- Only your newest message, since the model recalls the rest
- A short summary of everything said earlier in the session
Sessions And The Context
Looking at the request logs from our previous lesson, we need to introduce a key term: the agent's context.
All of this text, the instructions on how to use Git, the parameters, the scope, all of these different tool calls, these are what we call the agent's context. It's the available information that the agent has access to.
Request logs showing Git instructions, parameters, scope, and tool calls
This text gets turned into tokens so the agent can then do next token prediction. After all of this context, the agent is simply producing a little piece of text in response.
Context Window Limits
You probably also know that there's a maximum amount of context that any model can receive.
Arena.ai leaderboard showing LLM context window specifications
Let's look at a leaderboard for LLMs. You can see it lists scores, price per million tokens, and context window on the right side:
| Model | Context Window |
|---|---|
| GPT 5.6 Sol | 1.1 million tokens |
| Gemini 3 Pro | 1 million tokens |
| GPT 5.2 Chat Latest | 128k tokens |
This context window is a somewhat arbitrary number. It's picked by the developers based on how much context they think their model and infrastructure can handle.
If you send the model provider too many tokens in a single request, the request will fail. It won't produce any output tokens.
Managing Context and Costs
Managing the text that's in your context is really, really important.
Every time you send a request to a model provider, you are going to get billed for that text. You need to make sure that:
- The stuff you're sending is worth sending
- The stuff you're sending is relevant to the task at hand
If you send models a ton of text, they can get confused and distracted in the same way that humans can.
System Prompts and Harnesses
Whenever you're using a harness (an agentic framework or wrapper), the context window never starts at zero.
The harness wraps the agent and gives it custom instructions right from the start:
- It tells the agent what tools are available
- It gives high-level instructions for what the agent is supposed to do
- It specifies what role the agent is supposed to inhabit
This is often called the system prompt. Here's an example:
You are Claude Code, Anthropic's official CLI for Claude.
<!-- cache_control breakpoint -->
You are an interactive agent that helps users with software engineering tasks.
IMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.
The harness you choose has a lot of influence over the text that's sent to the agent. Different harnesses send different amounts of text.
Sessions and Turns
We need a term for what happens when we build up the context over multiple turns: a session.
Over multiple turns with the agent, you build up stuff in the context so the agent can see every single thing that's happened in that session.
For instance, in a conversation:
- Turn 1: five model provider requests
- Turn 2: three requests
- Turn 3: four requests
On that last model provider request, when you send the entire conversation history so far and get back the response, that is the latest stuff in the context. This whole thing is the session.
Diagram showing multiple turns building up context within a session
This is important because you can:
- Clear the context and start a new session
- Compact the session
- Move to a separate session and come back later
Having a word for this is very important when we're thinking about and navigating our interactions with agents.
Key Terms
| Term | Definition |
|---|---|
| Context | All the available information that the agent has access to, including instructions, parameters, scope, and tool calls |
| Context Window | The maximum amount of context (in tokens) that a model can receive in a single request |
| System Prompt | The initial instructions given to the agent by the harness, defining its role and behavior |
| Session | A continuous conversation with an agent, where context builds up over multiple turns |
Next Steps
Continue exploring these logs, this time looking specifically at the system prompt to see what's in there.
Your agent probably looks very different from what we've shown, and even if you're using Claude Code, they change these things all the time. So there are probably different tweaks here from what's shown on screen.
You send a model provider more tokens than the model's context window allows. What happens?
- The request fails and gives you no output tokens
- The oldest messages are dropped and the rest is sent
- It goes through, but you are billed at a higher rate
You open a brand new session in a harness and have not typed anything yet. How much context is already in it?
- Some: the harness has already sent a system prompt
- None: the context window starts at exactly zero
- None until the agent makes its first tool call
Why does it matter to keep irrelevant text out of your context?
- You pay for it each request, and it distracts the model
- It only matters once you get near the context window
- It slows the harness down when it saves the session
Smart Zone / Dumb Zone
Looking at logs with thousands of tokens might seem overwhelming. A typical agent interaction uses around 18k tokens, but modern models can handle up to a million tokens in their context window. You could send 950,000 tokens and get back 50,000.
But there's a natural skepticism here: Can the model really reason about all this text at once?
Attention Relationships
To understand what's happening under the hood, let's think about how a model processes tokens.
When you send a single token, like the word "the", there's no relationship to track. It's just one thing.
But add a second token, like "frog," and something changes. Now the model needs to:
- Remember both tokens
- Track the relationship between them
Even with just two tokens, you're tracking three things: token one, token two, and their relationship.
Diagram showing two tokens with one relationship between them
Add a third token, and the problem multiplies. Now you need to track:
- All three tokens
- The relationship between tokens 1 and 2
- The relationship between tokens 1 and 3
- The relationship between tokens 2 and 3
That's three tokens and three relationships.
Diagram showing three tokens with three relationships connecting them
The pattern scales quadratically. Every time you add a token, the number of relationships explodes:
| Tokens | Relationships |
|---|---|
| 2 | 1 |
| 3 | 3 |
| 4 | 6 |
| 5 | 10 |
Diagram showing five tokens with ten relationships
This is like adding a football team to a league. It sounds simple, but suddenly the number of games that league has to play scales massively.
Look at the scale at a thousand tokens: 1 million relationships. 10,000 tokens: 100 million. 100,000 tokens: around 10 billion.
AI coding dictionary showing token to relationship scaling
These attention relationships are how the model finds connections in text, jumps around it, and understands it. The more relationships it has to track, the worse it performs. It's like lots of people shouting for attention in a crowded room.
Attention Degradation
This has a direct consequence: the more text you send to a model, the worse it performs.
It's less able to pay attention to what matters. This is called attention degradation. The attention mechanism, the system for understanding relationships between tokens, gets worse as it has more to handle.
In practice, as you pass more context, your agent starts doing progressively dumber things.
Smart Zone vs. Dumb Zone
Diagram showing smart zone and dumb zone in context window
Agents have two zones:
Smart Zone - Early in the context window, the agent performs complex tasks well:
- Planning
- Building complex software
- Strategic decisions
Dumb Zone - As context fills up, the agent struggles:
- Simple file writes
- Closing issues
- Writing basic specs
You might still get results in the dumb zone, but you're not getting the best out of your agent.
And there's a cost penalty too: every request sent into the dumb zone involves sending massive amounts of tokens at once, costing you more.
Where Does The Dumb Zone Start?
This is heavily debated and moves per model. At the time of recording, the consensus for state-of-the-art models is that the dumb zone starts around 150,000 tokens.
This has moved up significantly. The previous recording of this course put it at around 100k to 120k tokens. As models improve, expect the dumb zone to move further back, giving you more smart zone to work with.
Text showing 150,000 tokens as the current dumb zone threshold
That 150k number might sound really low when model providers advertise one million token context windows. Why do they claim something they can't really use?
First, it's a nice headline. Second, not all use cases need the smart zone. If you're just retrieving text over a long body of work, not building software, you don't need peak performance. That's why the million-token window exists.
For coding work, you want to stay in the smart zone. If you're doing a lot of work in the dumb zone, you'll produce lower quality code that you then need to spend tokens cleaning up.
It's A Slope, Not A Cliff
The dumb zone isn't a cliff edge where you drop off immediately. It's a slow decline.
Use the 150k token mark as a signal. When your session reaches that point, start thinking about how to bail out. How can you hand off the work? How can you change your approach to get back into the smart zone?
This paranoia is extremely useful for getting high quality work at the lowest token price.
The entire approach should be designed around making the most of the smart zone.
The Underlying Mechanism Doesn't Change
By the time you see this, the numbers might have moved. Different models might have different thresholds. But the mechanism underneath, attention degradation, isn't going away.
It's the constraint that underpins all LLMs right now. It happens because of how attention relationships scale up as you add tokens.
Understanding this mechanism is key to getting the best results from your agent.
For today's state-of-the-art models, roughly where does the dumb zone start?
- Around 150,000 tokens
- Around 110,000 tokens
- Around 1,000,000 tokens
What is the mechanism that makes a model perform worse as you send it more text?
- Attention relationships grow quadratically with tokens
- The harness truncates the oldest part of the context
- The sampler raises temperature as the context grows
Your session has just passed 150,000 tokens and the coding work is not finished. What now?
- Start working out how to hand the work off and reset
- Carry on, because quality drops off a cliff much later
- Move to a model advertising a million token window
Statelessness
A session is composed of multiple turns, each of which contains model provider requests. This builds up a context over time. Every model provider request retains the state of the previous conversation in that session.
Diagram showing session composed of turns with model provider requests
But here's the critical part: all of that state lives in the harness, not in the model itself. The model is totally stateless.
Diagram highlighting the harness containing session state while model remains stateless
The Harness vs The Model
| Concept | Stateful? | Scope | Responsibility |
|---|---|---|---|
| Model | Stateless | N/A | Processes a single request based on provided context |
| Harness | Stateful | Within one session | Remembers all messages and session history |
| Environment | Stateful | Indefinite | Persists files, changes, and data on disk |
The harness is responsible for remembering all of the session—remembering all of the messages so far. It communicates all of that in one big chunk to the model. Because the model doesn't remember anything, doesn't retain any state.
The harness carries information forward, but only through the duration of the session. It remembers everything that happened in that session throughout the different turns. But as soon as you clear it, then it forgets everything again.
Why This Matters
Many people see the statelessness of the agent as a bad thing. They want the agent to be stateful, to remember things about them, to improve over time.
Discussion of agent statelessness and desire for memory
This is why you see lots of people building memory systems. They're trying to bring state into a stateless system to get the agent to remember stuff over time.
The Real Solution: Save to the Environment
The way to get the agent to have memory is to save things in the environment. The file system and the environment that the agent is in is really important for retaining state.
If you save a file in the file system and then clear the session, that state is still going to be there. The file is still going to be saved.
Breaking this down:
- Model: Totally stateless
- Harness: Stateful within the same session only
- Environment: Always stateful
You can always save stuff in the environment. Then the harness and the model can work together to pull things out of the environment.
Memory systems are ways to augment the environment to help it remember more stuff. This lets the agent remember things across sessions. You'll sometimes see harnesses trying to retain a bit more state across sessions as well.
Default to Statelessness
As Mario Zechner, creator of Pi, says:
i get asked what memory system i use often. my answer has always been: my codebase is my memory system.
Mario Zechner quote about codebase as memory system
Just like Mario, the preference is to default to statelessness where possible and save the stuff that's important for memory inside the codebase.
The reason is pure simplicity. It's found to work better. By default:
- The model is totally stateless
- The harness is stateful within a session
- The environment is always stateful because you can save stuff in it
A lot of people want to bolt on a memory system onto the agent itself. But be suspicious about that. Just modifying the codebase tends to be enough.
You clear the session. Which part of the setup still holds what happened before?
- The environment: files on disk stay where they are
- The harness: it remembers the messages you sent it
- The model: it retains what it learned about you
You want your agent to remember a decision after this session ends. What do you reach for first?
- Write it into the codebase for the agent to read back
- Bolt a memory system onto the agent so it can store it
- Keep the session open so the harness holds onto it
How Much Did It Cost?
Understanding how you get billed for the work that agents do is very important, and it's a lot harder than you might think. The cost is spread out over sessions, turns, and model provider requests.
The usual experience of paying for agent work is watching your bill climb higher and higher without being able to attribute it to anything specific. You can see your bill climbing, but you're not quite sure what the optimization surface is. How do you improve it? How do you get things cheaper, or fix the bad habits that are causing sessions to become expensive?
The numbers do exist
Well, the numbers that explain it do exist. The provider returns them on every model provider request.
Every time you send a model provider request during a turn, you are sending input tokens, and then you are getting back output tokens from the response.
- Input tokens are what you send: the current state of the repo, the current state of what the agent knows in the environment
- Output tokens are what the agent produces
And output tokens are billed at a much higher rate than input tokens.
Claude API pricing page showing input tokens at $10 per million and output tokens at $50 per million
Pricing comparison
For instance, if we look at Claude Haiku 4 on the API rates, we can see that input tokens are $10 per million tokens sent, whereas output tokens are five times that - they're $50 per million tokens.
Input tokens are usually by far the larger number. The request output is often just a few hundred tokens, either producing a tool call or replying to something you just sent it, whereas the input is the entire session so far.
Every single model provider request you're building up state, which is then going into input tokens, whereas the output tokens stay relatively static.
Exploring the request logger
To take a look at this, we can examine the request logger. Start it, then copy and paste the command it prints into a new terminal to start an agent through it.
We'll send a simple message and then go into the logs to look at the first request that comes back.
If we go all the way down to the response tag, we can see a usage output with some really interesting numbers. We can see that there were only two input tokens used and the output tokens were 14.
Request logger showing usage statistics with input tokens, output tokens, and cache token counts
So it came back with its typical "hello, what can I help you with today?" message. The interesting question is: why were the input tokens only two here? Because we know that it sends the full system prompt along with it.
Well, we can see that we have cache_creation_input_tokens and then cache_read_input_tokens. In other words, some of these input tokens were cached in the prefix cache.
Request logger showing cache_creation_input_tokens and cache_read_input_tokens fields
How the prefix cache works
Most providers keep a prefix cache. When a request begins with the same set of tokens as a recent request, then the provider reuses the work that it did on that stretch and bills it as cached input tokens instead.
If we go back to the pricing page, we can see that cache hits and refreshes are billed at 10 times lower than base input tokens.
However, what we did wasn't a cache read - it was a cache write. The logs show cache_creation_input_tokens: 22214. In other words, we have now created the cache, which we're then going to hit on the subsequent request.
Warming up the cache
Let's go into our agent again and send another message. Then if we look at the log that it creates, we can see in the response it pulled in 504 input tokens, created a cache output of 59, but then read 22,000.
In other words, now we have warmed up the cache and we are now hitting the cache. So in effect, we were only billed for around 500, maybe approaching 600 input tokens here, plus the 46 output tokens that were produced.
Request logger showing second request with majority of tokens from cache_read_input_tokens
We can see there are output tokens but there are also thinking tokens, which are billed the same as output tokens since they're essentially the same.
This means that subsequent requests do get cheaper because your input tokens write to a cache, which are then cached as input tokens, and these cached input tokens are billed significantly lower.
Sessions and the cache
This is, of course, suited to the way that sessions work because they grow by appending. Every request is the previous request with just a bit more at the end.
That's why you notice that the request is designed in the way that it is - it has the stuff that rarely changes at the start of the request and stuff that does change more often further down, often actually delivered inside user messages.
The complexity of session billing
That's why figuring out the billing for a session is so complicated, because there are so many variables here.
Sure, you've written to the cache in the first model provider request, but then you've mostly read from the cache on the second. But maybe on the third, you've produced lots of output tokens, which are very expensive.
Maybe you took an hour's break between turn 2 and turn 3, and so the cache was totally exhausted - it had timed out by that point.
Context management matters
Now most of this, of course, is the harness's concern. It's the harness's job to make sure that information is organized in the context window so that you get the best out of your cache.
But one thing I want you to notice here is that every input token you provide to the agent gets re-added into the session every single request. In other words, it's very easy to build up sediments in this very first model provider request that then gets taken through and is continually built every single model provider request.
This means that keeping context small and keeping context relevant is not only good for the agent, but it's also good for your wallet.
And helping you navigate the difference between input tokens, cached input tokens and output tokens will hopefully help this whole thing feel a bit less opaque.
The provider reuses a stretch of your request from its prefix cache. How is that stretch billed?
- At ten times lower than base input tokens
- At ten times higher than base input tokens
- At exactly the same rate as base input tokens
- Not at all, since the work was already done once
You send a message, take an hour's break, then send another. The second message bills far more input tokens than the messages before the break. What happened?
- The prefix cache timed out, so nothing could be read from it
- The session restarted, so the system prompt was sent a second time
- The break pushed the session into the dumb zone, forcing a retry
- The thinking tokens from the last turn were re-billed as input
Why does keeping the context small save you money, rather than only improving what the agent produces?
- Every input token is re-sent on every model provider request
- Output tokens are charged at a lower rate in shorter sessions
- A small context skips the prefix cache and its write cost
- A small context makes the harness send fewer turns per session
Hallucination
In a previous lesson, we talked about the dumb zone and the smart zone, where attention degradation kicks in as the session gets longer and the model gets progressively worse. But we didn't really talk about what those "dumb things" actually are - what symptoms you're likely to see inside the dumb zone and sometimes even in the smart zone itself.
The Core Problem: Hallucination
Hallucination definition displayed on screen
The big one, and the one we're always working to prevent at any cost, is hallucination - confidently wrong model output.
A hallucination can be absolutely disastrous when you're coding. It can:
- Produce broken code
- Take you down a direction in the product you didn't want
- Recommend that you use an API that's no longer secure
- Do all sorts of really dangerous stuff
Often what we're trying to do is provide an environment that gives the model things to work with that lessen the likelihood of hallucinations.
In this lesson, we're going to create a dictionary for hallucinations - a way of understanding how to prevent them and what they really are.
Two Main Flavors of Hallucination
There are two main flavors of hallucination: factuality and faithfulness.
Factuality Hallucination
A factuality hallucination is invented or simply wrong facts about the world. Examples include:
- A function that doesn't exist
- A wrong API signature
- A citation to an article that doesn't exist
These happen because of a lack of parametric knowledge.
Understanding Parametric Knowledge
When the model is trained initially, the information in its training is stored in its parameters. Every model's brain, its memory essentially, is stored in these huge arrays of numbers, sometimes billions and billions of numbers.
These are sometimes called weights. Parametric knowledge is the knowledge encoded in these parameters, and it's encoded once at the time the model is trained.
The reason the model is stateless is that these parameters never change after that. They're literally frozen after the training process.
The Problem With Parametric Knowledge
However, think about this: if you take all of the terabytes and terabytes of training data and compress them down into a couple of billion numbers, a lot of stuff going to get lost.
When you have a really detailed image and compress it down to a tiny size, you sometimes can't see the finer detail.
Not only that, but parametric knowledge has a cutoff to it. The model was trained at a certain time, and data that came after that - new events, new libraries, new APIs - has escaped the model. Models often need to be continually updated to make sure they've got the new stuff.
Knowledge Cutoff
All models have a knowledge cutoff. And the way training works is you can't just patch more information into the model - you have to retrain it from scratch.
Knowledge cutoff concept displayed
This means factuality hallucinations can come from two places:
- You're asking for information that's after its knowledge cutoff
- You're asking for information about stuff before the knowledge cutoff, but it's only got a kind of fuzzy JPEG - a blurry image to reference
The model isn't going to be very good at retrieving information from its parametric knowledge because of the way it's stored. It's not stored like a database of facts. It's just stored as fuzzy vibes.
A Real Example: The X API Pricing
Here's a hallucination from Claude Opus. When asked "How expensive is the X API? Don't search for information, just tell me based on what you know," it replied:
Based on my knowledge, which may be outdated, here are the rough tiers for the X Twitter API from my training:
- Free: very limited
- Basic: $100/month
- Pro: $5,000/month
- Enterprise: custom pricing
Agent response showing outdated X API pricing
This is actually not true. The pricing has gone down massively relatively recently. When we then ask it to search for the information, it goes off and searches - using web search - and checks whether its parametric knowledge was correct.
Agent performing web search
The search reveals that the pricing model changed significantly in February. This was actually before this current model's knowledge cutoff, so what we had there was a factuality hallucination - invented or wrong facts about the world.
Corrected X API pricing after web search
The Fix: Contextual Knowledge
The fix column shows us: load in the contextual knowledge. Contextual knowledge is knowledge that is in the context window of the model.
From research, hallucinations are much less common when the agent works from contextual knowledge. The answer is right in front of it, not dredged up from blurred memory.
However, contextual knowledge is not a cure for hallucinations because we also have faithfulness hallucinations.
Faithfulness hallucination definition
Faithfulness Hallucination
A faithfulness hallucination is where even if you've passed the information to the LLM in its context, it will:
- Ignore it
- Drift away from it
- Do something slightly strange with it
This is the thing that the dumb zone makes really, really bad because of attention degradation. Because you have so much information in the context, the model can't find the relevant stuff. There are so many attention relationships to keep track of that it doesn't know which ones are the important ones.
This means that you can pass the agent all the relevant information. You can set things up perfectly. But if there's just too much in its context window, then it won't be able to follow instructions as well, and it will hallucinate more.
That means it will produce worse code, open you up to security risks, and do really strange stuff.
A Decision Tree for Hallucinations
Decision tree flowchart for diagnosing hallucinations
Here's a decision tree you can use when you see a hallucination:
First question: Was the information available in the model's context window?
| Scenario | Problem Type | Solution |
|---|---|---|
| No | Factuality problem | Load the information into context |
| Yes | Faithfulness problem | Clear your context window to reduce attention degradation |
If It's a Factuality Problem
If the information wasn't in the context, it's a factuality problem. The model is looking at its parametric knowledge and coming up short.
The fix: Never trust an unsourced LLM. Always make sure the agent is working from sourced information, from contextual info.
However, you might end up right back with another hallucination. And if the information is in context, then you've got a faithfulness problem.
If It's a Faithfulness Problem
The agent is not being faithful to the information you've provided to it.
This can happen in the smart zone, but most of the time you've just got to get out of the dumb zone. Clear your context window. Make sure the attention degradation goes down. Let the agent relax a little bit.
It usually doesn't happen in the smart zone, but because models are non-deterministic, you will very occasionally get a faithfulness error in the smart zone.
The Long Game
The hope is that model providers improve models to the point where we don't have to worry about hallucinations so much. Factuality and faithfulness errors are things they test for, but we can't really see a world in which we're not having to deal with these sometimes.
Knowing about how they work and understanding them at a deep level is a really important part of AI coding. During the rest of this course, keep an eye out for factuality errors and faithfulness errors - and now you'll know how to deal with them.
You pasted the exact file the agent needed into the context, and it still used a function from somewhere else. What do you do first?
- Clear the context window, then hand it the file again
- Paste in the surrounding files as well, to be thorough
- Ask it to search the web for the correct signature
- Send the same prompt again and see if it lands
The agent states an API's pricing that it was never given and that turns out to be wrong. What is the problem, and what is the fix?
- A factuality problem - load sourced information into the context
- A faithfulness problem - clear the context window and ask again
- A factuality problem - wait for the model to be retrained on it
- A faithfulness problem - the model drifted away from its training
A model's knowledge cutoff sits before a library you use. How does new information get into its parametric knowledge?
- The model has to be retrained from scratch
- The provider patches the new facts into the parameters
- Anything you put in the context is written back to it
- A web search the model runs updates its parameters
Effort
Effort is a dial you can adjust on the model that is provided by pretty much every model provider now. In Claude Code here you can specify /effort and then choose the effort level you want.
Claude Code showing the /effort command with different effort levels displayed
The dial ranges from faster effort levels on the left to smarter effort levels on the right. This video explores how to decide what effort level to use for your work.
Comparing Low vs Max Effort
Let's see what the difference looks like in practice. Setting effort to max and asking the agent to explore a codebase and tell you about it produces very different results compared to setting it to low.
Terminal showing max effort run with 41,000 tokens used and 2 minutes 15 seconds elapsed
When running the same prompt with different effort levels:
| Metric | Low Effort | Max Effort |
|---|---|---|
| Time taken | 1 minute 11 seconds | 2 minutes 15 seconds |
| Tokens used | 11,000 | 41,000 |
| Analysis depth | Basic facts, tech stack | Deeper exploration, features, file structure, potential issues |
The low effort version captured the basic facts about the repo - it figured out the request logger subproject and the tech stack.
The max effort version went deeper, exploring actual features, authentication implementation details, and file structure. It even found some documentation drift that the low effort version missed.
The max effort approach put in more work and got slightly better feedback, but it spent four times as many tokens to do so. That's the core trade-off: more thinking for more cost.
So what is happening here? Why is it putting more effort in? What mechanism is it using to do that?
How Reasoning Tokens Work
Models can produce three types of outputs: text, tool calls, and reasoning. Those reasoning tokens are the model's own train of thought, a kind of stream of consciousness for what the model is thinking.
In some interfaces, these reasoning tokens are displayed to the user. Some agents show them directly. But in Claude Code, you only see the text and tool calls - the reasoning happens behind the scenes.
The theory behind this comes from an older technique called Chain of Thought Prompting. The research showed that when you ask a model to show its working, it does a better job.
Chain of Thought paper showing standard prompting example with incorrect answer
For example, with standard prompting:
The cafeteria had 23 apples. If they used 20 to make lunch
and bought 6 more, how many apples do they have?
Answer: 27
This answer is wrong. But if you get the model to go through the steps:
They had 23 apples originally
They used 20 to make lunch: 23 - 20 = 3
They bought 6 more apples: 3 + 6 = 9
Answer: 9
By showing its reasoning, the model gets the right answer.
When you increase effort, you're essentially telling the model: produce more reasoning tokens, show more of your thinking.
Effort Levels and Benchmark Performance
This approach is proven across benchmarks to increase performance. DeepSWE is a reputable benchmark that shows how different models perform at different effort levels.
DeepSWE benchmark graph showing performance vs cost for different effort levels
Looking at the performance data:
| Model | Low | Medium | High | Extra High | Max |
|---|---|---|---|---|---|
| Claude | 60% | 65% | 69% | 70% | 70% |
| GPT 5.6 | 45% | 61% | 69% | - | - |
As effort increases, so does the cost per task.
DeepSWE graph showing Claude Sonnet 5 cost and performance metrics
Claude Sonnet 5, for instance, starts at 31% quality on low effort but costs $26 per task. To get better performance, you might switch to GPT 5.6, which only costs $1.86 to outperform that baseline.
The critical insight: effort is not just a quality trade-off. It's also a latency trade-off. The more tokens you use, the sooner you hit the dumb zone, where the model's reasoning becomes degraded. More effort means you're burning through your token budget faster, leaving less room for actual work.
Choosing Your Effort Level
The first point: avoid max effort. Max and even extra high are extremely wasteful uses of tokens. Model providers include these settings mainly to push their benchmark scores higher by a few percentage points. If they can squeeze out 2% improvement on benchmarks, that might rank them higher than competitors.
But your concern is different: day-to-day cost, latency, and quality.
For a model like GPT 5.6, the difference between low, medium, and high can feel like you're using different models entirely. It's a genuinely impactful difference. However, don't over-optimize your setup by constantly tweaking effort levels per task.
Instead, pick one setting and stick with it. The author uses Claude Opus 4.8 with medium effort and doesn't change it task by task. The reasoning is simple: consistency matters more than optimization.
When you change and tune your model and its effort level, you're modifying one part of your system. But when you change the harness and environment, you can swap out models and improve the entire system. By staying model agnostic and keeping your effort level consistent, you preserve flexibility.
This is a subjective take - different approaches work for different workflows. You can share your own experiences and discuss which models work best for you in the Discord. The key is making a deliberate choice and measuring the results rather than constantly adjusting knobs.
What to Consider When Choosing Effort
When deciding on an effort level, you need to balance multiple factors:
| Factor | Low Effort | Medium Effort | High Effort | Max Effort |
|---|---|---|---|---|
| Cost | Cheapest | Moderate | Higher | Most expensive |
| Speed | Fastest | Fast | Slower | Slowest |
| Quality | Basic | Good | Better | Marginally better |
| Dumb zone risk | Lowest | Low | Higher | Highest |
| Best for | Mechanical edits, simple tasks | Everyday work | Genuinely hard problems | Benchmarking only |
The sweet spot for most work is medium effort. It provides a good balance of cost, speed, and quality without burning through your token budget unnecessarily.
Final Recommendations
The effort setting dramatically changes both the cost and quality of the model you're using. Before settling on an approach:
- Check the benchmarks - Look at performance graphs for the models you use on sites like DeepSWE. They show token spend ratios and differences between low, medium, and high.
- Remember benchmarks are flawed - The work you do day-to-day is probably very different from what benchmarks test. The only way to know what works for you is to try different effort levels in your actual workflow.
- Avoid constant min-maxing - Pick a model and effort level that feels right, and stick with it. The time you spend tuning is time you're not shipping.
- Be consistent - A stable, predictable setup beats endlessly optimized one-offs.
The goal is to make an informed choice and move forward, not to find the perfect setting. Your setup should serve your workflow, not constrain it.
You sit down to a normal day of feature work and open the effort menu. What do you pick?
- Medium, and leave it there for the next task too
- Max, because this feature matters more than the last one
- Whichever fits each task, changed as the work changes
- Low, and raise it only once the output looks wrong
Raising the effort level costs you more money. What else does it cost?
- Token budget, so you reach the dumb zone sooner
- Quality, since the extra reasoning confuses the model
- Tool calls, since reasoning tokens are produced instead
- Nothing else, since the token bill is the only cost
Why do model providers ship a max effort level at all?
- To push their benchmark score up a couple of points
- To give day to day work the best possible output
- To let heavy users buy a faster answer on hard tasks
- To keep a long session inside the smart zone for longer
Choosing A Model
One of the questions I get asked most often is: what model should I use? Does it make sense to swap models for certain situations?
My business partner Joel once observed the way I sigh on stream when chat tells me to use a different model and I have to explain it again. I do get a little bit annoyed by the constant barrage of people saying "try this model, try this model. This new model beats the rest of the models hands down. You have to try it or you're being left behind."
Twitter conversation about model switching
Model, Harness, and Environment
In my mental model, the model is just one part of a larger ecosystem. There's the harness that surrounds it, and then the environment that the harness plus model operates in.
Diagram showing model, harness, and environment
I consider the model to be about 50-50 equal with the harness plus environment. In other words, the model is a very consequential part of the whole operation. If you switch out to a crap model, then you are not going to get anywhere.
But if you have a model that's working very well, then there's often things that you can do in your harness and your environment to improve the outputs that you get from the model.
I do want to talk about how you choose a model in this lesson, but I also want to de-emphasize it as an important consequential thing.
As long as you're using one of the models in the top tier, you will probably be okay.
Graph showing models in top right corner
At the time of recording, I'm currently on Claude Opus 4.8 medium. There is probably some optimization I could do with my model, but first I'm more interested in optimizing my harness and the environment my code runs in.
All the time I see low-hanging fruit that I can grab. And crucially, if I put the effort in to improve the environment and the harness, then that means I can swap out to any model and it should be okay.
I kind of think of the model as an employee in your company, and employees come and go. So if you can invest in your company infrastructure to make sure that any employee who comes in can succeed, then you're going to be in a good spot.
Efficiency: Cost Per Task
However, with all that said, I do want to give you a mental model so that you can choose the right model in the right situation.
One thing I love about the DeepSWE benchmark is that it has average cost per task at the bottom.
If we go up here to its output tokens filter you can see that if we choose output tokens then it's quite a different picture. For instance, Gemini 3.5 Flash spends a ton of tokens to not achieve very much.
But if we actually look at the cost per token, you can see it's actually relatively cheap and pulls it far back over this side of the picture. So some model providers simply charge more per token than others.
Not only that, but for instance, these tokens are presumably billed at API token level, whereas if you purchase a subscription, it is much, much cheaper.
And so you're not only choosing a model, you're also choosing a pricing structure along with it.
So whenever you're doing these comparisons, you need to think about the fact that efficiency is the key. It's not just raw cost in tokens, it's what are you getting for those tokens.
DeepSWE graph showing models grouped in top right corner
While this graph is fantastic because we can see everything grouped up towards the top right corner, which is the most efficient, this is still a pretty abstract benchmark that might not correspond to your actual work.
For more on subscription versus API pricing, see Anthropic's plan comparison.
Matching Quality to Task Needs
The next thing to say is that different tasks require different levels of quality.
Graph showing GPT 5.6 SOL effort levels
For instance, if we look at a model like GPT 5.6 SOL, there might be situations where we only need to use the low effort level. For instance, exploration, research and summarization might only need a low effort level.
Whereas detailed planning or code review it might be tempting to go up to the high effort level that really takes a big old jump. And so there's an element here of picking the right tool for the job.
That could mean using one model for planning for difficult stuff and another model for implementation.
Assess Models With Your Own Data
Now, throughout this, I've been pointing at this graph as if it's the thing that you should trust here, but really I'm using this as an analogy for your own assessments.
What you need to be doing is watching your own usage, watching the bill like a hawk, and also just getting a sense for a model. Models really are like employees and the only way you can get the best out of your employees is by getting to know them.
And so you will develop your own personal hierarchy of models and effort levels. However, what I would say again is don't spend too much time min-maxing between all of these different choices.
I prefer to pick one I like and then stick with it. And what I find is that the more I work with the same model and the same effort level, the better I get at prompting it.
Later in the course, we will take a look at a more empirical way to assess models. That really is pretty simple, which is you take the same inputs and you set up two different models, or maybe the same model with different effort levels, or even the different harness, let's say, you just get two different setups to perform the same task.
Then you assess which one's better, maybe note that down somewhere, maybe run that experiment a few different times, and you've got some pretty good data. That's going to be better than looking at these graphs because these graphs don't correspond to the actual tasks that your agents are going to be doing in your company every day.
Key Takeaways on Model Selection
So to sum up then, models are just one part of the overall picture. They are an important part but it's about 50-50.
When you're choosing models, you're not just choosing output tokens or output tokens versus quality, it's also the cost per task.
As you start using a few different models, then you will get a sense for what your favourites are in certain situations. And in my opinion, you should probably stick to one model, one effort level and get to know it really, really well.
Everyone has an opinion about model selection. I would love to hear from you what your opinions are when it comes to this stuff and how you assess different models and different effort levels.
Join the conversation in the AI Hero Discord.
You are on a top tier model and the output your agent gives you is still not good enough. Where do you spend the next hour?
- On the harness and environment, which any model benefits from
- On swapping to whichever model tops the newest benchmark
- On raising the effort level of the model you already run
- On rewriting the prompt until this model gets the task right
A teammate insists a different model is better for your codebase. How do you settle it?
- Give two setups the same task and judge which result is better
- Read the benchmark graph and take the model nearest the top right
- Take whichever model shows the lowest average cost per task
- Switch model every week until one of them starts to feel best
You are comparing two models on cost. What does the raw price per token miss?
- Cost per task, and whether you pay API or subscription rates
- Context window size, which caps how much one task can hold
- Time per task, which is the real cost of a slow model
- Effort level, which is chosen separately from the model
Subagents
Now we understand some of the constraints of models, like smart zone and dumb zone, and about how context window fills up and slowly degrades. Let's look at a really common technique that harnesses use to mitigate those downsides.
Visualizing Agent Context Usage
I've got a little visualization of the context of the agent here.
Visualization showing agent context divided into colored sections
Each section represents different tasks that the agent needs to do in that session.
- Grey section: The stuff that's always in the system prompt - the request logger
- Yellow section: Exploration
- Green section: Implementation
The Token Optimization Problem
The dream for any harness would be to make these chunks smaller. We want to spend fewer tokens. This has two benefits:
- We spend less money
- We have more space in the context window, less attention degradation, more space in the smart zone
Context visualization showing desire to reduce chunk sizes
However, there's a trade-off. If we do less legwork in the exploration phase, we're going to end up with worse exploration, which means our implementation might suffer because of bad information. It feels like we're locked in for spending this amount of tokens in our exploration phase.
How do you bridge this divide? How do you make the exploration cheaper, or a certain phase cheaper, so that other phases can benefit?
Delegating Work to Subagents
Lots of harnesses employ a really smart solution: they delegate it to another agent.
Visualization showing a subagent being spawned from the main agent
The main agent spawns another agent, and that agent can spend lots of tokens really in-depth exploring the code base, then summarize that information back to the main agent. This is kind of like a senior developer going to a junior developer and saying: "Just research something for me and then report your findings."
Parallel Subagent Work
The main agent (the orchestrator) can also spawn multiple subagents at the same time in parallel to do different tasks. Maybe it needs to research two things at the same time while those two junior developers can go and work in parallel and report their findings.
Visualization showing multiple subagents spawned in parallel
Flexible Subagent Configuration
These subagents can be spawned with different configurations:
- Different system prompts
- Different models
- Different effort levels
Recursive Subagents
You can even have a subagent spawn its own subagents. Some harnesses support this, some don't. Some only allow you to go one level deep, but this means subagents can act just as powerful as the agents above them.
Visualization of nested subagents spawning their own subagents
We're going to leave the exploration at the theoretical level for now because we're going to be using subagents a lot more when we get into the fundamentals.
Nice work and I will see you in the next one.
Your main agent hands a deep codebase exploration to a subagent. What does the main agent get out of that?
- It receives the summary, not the tokens spent finding it
- It gets the exploration done faster than it could alone
- It pays nothing for the tokens the subagent burns
- It has its own context window emptied back to the start
What can a subagent be spawned with that differs from the agent that spawned it?
- Its own system prompt, model, and effort level
- Its own system prompt, but the parent's model
- Its own model, but the parent's system prompt
- Nothing, since a subagent inherits the whole setup