Skip to content

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.

15 min read0/4 questions

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.

Python
import re # A pretend vocabulary: very common English words get one token each.VOCAB = {"the", "cat", "sat", "on", "mat", "is", "if", "return", "null", "user", "id", "closed", "tram", "stop", "a"} def toy_tokenize(text): # A piece is an optional leading space plus a word, or one symbol. pieces = re.findall(r" ?\w+| ?[^\w\s]", text) tokens = [] for piece in pieces: word = piece.strip().lower() if word in VOCAB or len(word) <= 2: tokens.append(piece) else: # Unknown word: fall back to 3-character chunks. tokens += [piece[i:i + 3] for i in range(0, len(piece), 3)] return tokens samples = [ "The tram stop is closed.", "Die Straßenbahnhaltestelle ist geschlossen.", "if (user?.id !== 42) { return null; }",]for s in samples: toks = toy_tokenize(s) print(f"{len(s):>2} chars, {len(toks):>2} tokens: {'|'.join(toks)}")
Output
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.
Quick check
Which of these, all roughly 400 characters long, is likely to use the MOST tokens?
Need a nudge? A hint rules out a wrong answer.

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:

What fills the context on one turn
  1. System promptwho the model is, the rules, tool definitions
  2. Project memoryCLAUDE.md or similar, loaded every session
  3. Conversation historyevery earlier message and reply
  4. Files and tool resultsfiles read, command output, search results
  5. Your new messagethe thing you just typed

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.

1/6

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.
Three turns of a stateless chat
YouChat appModel APIWhat is a decorator?system + msg 1reply 1Show me one that timesmsg 1 + reply 1 + msg 2reply 2

You type one message.

1/6

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.

Predict the outputPython

What does this print?

history = [200, 600, 200, 600]
new_message = 200
print(sum(history) + new_message)
Need a nudge? Hints walk you through it.

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):

ModelInput per 1MOutput 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.

Python
# Prices per million tokens (dated snapshot: Claude Sonnet 5.5).INPUT_PRICE = 2.00OUTPUT_PRICE = 10.00 SYSTEM_PROMPT = 1_500 # tokens, resent every turnUSER_MSG = 200 # tokens you type each turnREPLY = 600 # tokens the model writes each turn history = 0total_in = total_out = 0print("turn input output cost so far")for turn in range(1, 21): input_tokens = SYSTEM_PROMPT + history + USER_MSG total_in += input_tokens total_out += REPLY history += USER_MSG + REPLY # this turn joins the history cost = total_in / 1e6 * INPUT_PRICE + total_out / 1e6 * OUTPUT_PRICE if turn in (1, 2, 5, 10, 15, 20): print(f"{turn:>4} {input_tokens:>5} {REPLY:>6} ${cost:.4f}") print(f"\nInput tokens: {total_in:,}")print(f"Output tokens: {total_out:,}")print(f"Turn 20 alone re-reads {SYSTEM_PROMPT + 19 * (USER_MSG + REPLY) + USER_MSG:,} tokens.")
Output
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.

Quick check
In a long chat with a coding assistant, what usually drives most of the token usage?
Need a nudge? A hint rules out a wrong answer.

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 the pairs0/5 matched

Match each term to what it means.

Choose an item, then its match on the other side.

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.

Key terms
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.