Lesson 2 of 40How AI works
Tokens and Context
Learn what tokens are, what fills a context window, how API pricing works, and why long conversations get slower, pricier and worse.
Every AI tool you use has two hidden budgets: how much text the model can see at once, and how much you pay for each piece of it. Both are measured in tokens, not words or characters. If you understand tokens and the context window, you can explain why a long chat starts forgetting things, why a coding agent gets slower over an afternoon, and why a feature that costs a cent in testing costs thousands in production. This lesson builds that understanding with numbers you can run yourself.
Tokens, not words
In the How LLMs Work lesson you saw that a model predicts "the next word". More precisely, it predicts the next token: a chunk of text from a fixed vocabulary the model was built with. A tokenizer splits your text into those chunks before the model sees it, and turns the model's output back into text.
Common English words are usually a single token, often including the space in front of them: " the", " return". Rare words get split into several pieces. Symbols, digits and unusual characters are often a token each. As a very rough rule of thumb, English prose averages about four characters per token, but the real number depends on the model's tokenizer and on what you are writing.
This toy tokenizer imitates the idea. Common words are in its small vocabulary; everything else is chopped into three-character chunks. Run it and compare the three lines.
Press Run (⌘ Enter) to see what happens.The English sentence is 6 tokens. The German sentence means the same thing and costs almost three times as many, because its long words are not in the vocabulary. The line of code is short but full of symbols, so it costs 16. Real tokenizers have vocabularies of many thousands of entries and are far smarter than this, but the pattern holds:
- Code costs more tokens than prose of the same length, because of brackets, operators, indentation and invented names like
getUserByIdOrThrow. - Non-English text often costs more, especially in languages that were less common in the tokenizer's training text, and in scripts other than the Latin alphabet.
- JSON, logs and minified files are token-hungry. Pasting a 5,000-line log is rarely a good idea.
The context window
The context window is everything the model can see when it produces a reply: the maximum number of tokens it can take in for one request. Current Claude models have a context window of 1 million tokens (a dated snapshot; check the docs for current limits). That sounds endless until you see what goes into it.
A model has no memory between requests. Each reply is produced from whatever is in the context for this request, and the context is built fresh every time from several sources:
The system prompt comes first. A chat app or coding tool writes it for you; via the API you write it. It is resent on every request.
Stateless: the history is resent every time
This surprises almost everyone. The model does not "remember" your conversation. The API is stateless: each request is independent, so the app sends the whole conversation again, every single turn. When you call the Claude API yourself, you build that list of messages and resend it on each call.
messages = [
{"role": "user", "content": "What is a Python decorator?"},
{"role": "assistant", "content": "A decorator is a function that wraps..."},
{"role": "user", "content": "Show me one that times a function."},
]
# Turn 2 sends all three messages, not just the last one.You type one message.
Two consequences follow. First, chat feels like memory but is really re-reading: if the app trims old messages to save space, the model genuinely loses them. Second, cost grows faster than you expect, because every turn pays again for everything before it.
What does this print?
history = [200, 600, 200, 600] new_message = 200 print(sum(history) + new_message)
Input, output and price per million
API pricing is quoted per million tokens, with separate prices for input tokens (everything you send) and output tokens (everything the model writes). Output is more expensive, because generating each token is a full run of the model, while input can be processed in parallel. From the Claude API's current price list (a dated snapshot; prices change):
| Model | Input per 1M | Output per 1M |
|---|---|---|
| Claude Fable 5.1 | $10 | $50 |
| Claude Opus 5.5 | $4 | $20 |
| Claude Sonnet 5.5 | $2 | $10 |
| Claude Haiku 5.5 | $0.10 | $0.50 |
The formula is simple: input_tokens / 1,000,000 × input price + output_tokens / 1,000,000 × output price. What is not simple is how fast input tokens pile up in a conversation. This calculator simulates a 20-turn chat with Sonnet 5.5. Each turn you type 200 tokens and get a 600-token reply, and a 1,500-token system prompt rides along every time.
Press Run (⌘ Enter) to see what happens.The model wrote 12,000 tokens but read 186,000. Output is five times pricier per token, yet input is most of the bill here, because the history is paid for again on every turn. Total input grows roughly with the square of the number of turns. Now imagine a coding agent where each "turn" includes a 3,000-token file read. Change USER_MSG to 3000 and run it again.
A few half-cent conversations do not matter. A feature that runs this conversation for 50,000 users a day does. Tools like prompt caching cut the cost of a repeated prefix, which the Token Budget lesson covers.
Context rot: more is not better
A 1 million token window does not mean you should fill it. Context rot is the drop in quality as the context fills up, especially with noise. Every token competes for the model's attention. With a long history of abandoned attempts, stale file versions, and 2,000 lines of test logs, the model is more likely to miss the one instruction that matters, follow an old plan you already rejected, or mix up two versions of a file.
You will see the symptoms in real use: a coding session that was sharp an hour ago now "forgets" a rule from your first message, repeats a fix that already failed, or edits the wrong function. The model did not get worse. Its context did.
The practical habits are short:
- Start a fresh conversation for each new task.
- Give the model the right three files, not the whole repository.
- Paste the relevant 20 lines of a log, not all of it.
- In long sessions, summarise and restart rather than pushing on.
The Context Engineering and Working on a Token Budget lessons turn these habits into a system.
Match each term to what it means.
Counting tokens before you send
Guessing is fine for intuition, but for real budgets count. The Claude API has a token counting endpoint that tells you exactly how many input tokens a request would use, without running the model:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
system = "You are a concise code reviewer."
messages = [{"role": "user", "content": "Review this function: ..."}]
count = client.messages.count_tokens(model="claude-opus-5-5", messages=messages, system=system)
print(count.input_tokens)After a real call, response.usage.input_tokens and response.usage.output_tokens tell you what that call actually used. Log both for every request in anything you ship; it is the only way to know what a feature really costs. Tokenizers differ between model families, so always count with the model you will actually use.
- token
- A chunk of text, often a word or part of one, that a model reads and writes.
- tokenizer
- The component that splits text into tokens and turns tokens back into text.
- context window
- The maximum number of tokens a model can take in for one request, including its reply.
- stateless
- Keeping no memory between requests, so the full conversation is resent each time.
- input vs output tokens
- Tokens you send versus tokens the model writes. They are priced separately.
- context rot
- The drop in output quality as the context fills with long, noisy or stale content.