Trail content
8 minEnglish narration, Portuguese subtitlesPodcast (RSS)
Chapters
  1. 0:00Opening
  2. 0:43The idea
  3. 1:46How it works
  4. 3:04A real case
  5. 4:24A challenge
  6. 5:02The common mistake
  7. 5:42Do the math
  8. 6:58In production
  9. 7:39Wrap-up
Transcript

Opening

Julia built a chat over her company's internal manuals. There are forty of them.

To be safe, her code pastes all forty manuals into every single question. It works. But every answer is slow, and the monthly bill came in ten times over the forecast.

And there's something worse. When the answer is in manual twenty-three, the bot sometimes says it found nothing.

Two concepts explain both problems: tokens, and the context window.

By the end of this lesson, you'll be able to do the math on any design before it reaches production. And you'll know why fitting in the window isn't the same as working.

The idea

The model doesn't read letters or words. It reads tokens, chunks of text cut by a tokenizer. A common English word is often one token. Long, accented or rare words become several.

Tokens matter for three reasons. Price, because you pay for every token going in and every token coming out. And the output usually costs more.

Time, because the model writes one token at a time. A long answer is a slow answer.

And the limit, because everything going in and out has to fit in one space, the context window.

One detail that surprises people. Not all text costs the same. A question in Portuguese often becomes more tokens than the same question in English. Code full of symbols, invoice files, and data with repeated field names swell even more. If your product speaks Portuguese and pastes those files, the estimate you did in your head is low.

How it works

The context window is the total number of tokens the model sees in one call. Let's look at what's inside it.

The system prompt goes into every call. A thousand extra tokens here are a thousand extra tokens on every single message.

Each tool you offer takes space too, with its name, its description and its schema.

The history grows every turn. The model has no memory, so you resend everything.

Documents and tool results are usually the biggest part.

The user's question is usually the smallest.

And the answer takes room in the window too, with its own separate limit.

Those two limits get mixed up all the time. The window is the cap for the whole call. The output limit, called max tokens, is only the cap for the answer.

Say the window is two hundred thousand tokens, and you already sent one hundred ninety-eight thousand as input. The answer gets about two thousand, at most, even if your output limit asks for eight thousand. Most APIs reject the call when the total doesn't fit. And some frameworks, to make it fit, quietly drop your oldest messages.

A real case

Back to Julia, with illustrative numbers. Say each manual is about four thousand tokens.

Pasting all forty sends about one hundred sixty thousand input tokens on every question. Her question is a tiny fraction of that. And she pays for all of it on every message, even when the answer lives in three paragraphs.

Now retrieve only three relevant passages, five hundred tokens each. That's about two thousand tokens, plus the system prompt. The question competes with far less noise, and the price drops with the size.

But that's only the bill. Remember manual twenty-three? Context windows got huge. That doesn't mean the model uses everything in them well.

There's a research paper from twenty twenty-three called Lost in the Middle. It showed that models tend to use what sits at the start and the end of the input better than what sits in the middle. Newer models improved on this. But the principle holds: every irrelevant token competes with the relevant ones for the model's attention.

That's why Julia's chat failed on manual twenty-three. The information was in the window. It was just drowned among thirty-nine other manuals, right in the middle.

A challenge

Here's one for you. Julia's team upgrades to a model with a much bigger window, two hundred thousand tokens instead of thirty-two thousand. They paste the forty manuals again. The bill stays high, and manual twenty-three still vanishes sometimes. What did the bigger window fix?

Neither problem. You still pay for every token you send. And the middle of the input is still at a disadvantage. A bigger window is slack, not a strategy. The fix is to choose passages, not to ask for more room.

The common mistake

The beginner trap is treating a big window as a reason not to choose. It fits becomes the only criterion.

The right question is different. What needs to be here for this question, and what's only taking up space?

Here's a version you'll meet in real life. On turn one, someone pastes a twenty page document into the chat. On turn fifteen, they ask for the store's address. And your code is still resending that document, on every turn, twelve turns after anyone needed it. History isn't a mandatory archive. Send what the question needs, and summarize or drop the rest.

Do the math

Now the habit that saves you from surprises. Count tokens before you send. The provider's API has an endpoint just for that, which generates no answer and uses the same tokenizer as the model.

Then do the monthly math. Input tokens, times messages per day, times thirty. Add the average output. Multiply by the model's price per million tokens. That number tends to be scary. And it's much better to be scared before production.

Let's do one together. You measured eight thousand input tokens per question, ten thousand questions a day. The team wants to just add the vacation policy, another six thousand tokens, on every call.

Before, that's eighty million input tokens a day.

After, one hundred forty million. Your daily input nearly doubles, and the policy rides along on questions that have nothing to do with vacation.

And don't estimate by dividing characters by four. That rule sometimes works for plain English. For Portuguese, code and structured data, it undercounts. Measure a few real examples with the provider's counter.

In production

So what changes in your designs? Sending less and better beats sending everything. That's what retrieval does, instead of pasting whole manuals.

The system prompt needs a diet. When it grows unchecked, it becomes a smell called prompt bloat.

Long conversations rot. Old history confuses the model and raises the cost. That one's called context rot.

And the fixed parts at the start of the input can be reused across calls with prompt caching, which cuts both cost and latency. Just don't use caching as an excuse to paste a whole file the question doesn't need.

Wrap-up

So here's the idea to keep. The window is a budget, not a storage room. Every token you put there costs money, costs time, and competes for attention. Token math is the first thing to do in any design.

In the next lesson, we'll open up that dice roll inside the model: sampling and temperature, and what they really control. See you there.

Fundamental

Tokens and the context window

Tokens e janela de contexto

Tokens and the context window is an AI engineering fundamental for people who work with LLMs. Why everything costs tokens, why the middle of the context fades, and how to measure it.

Element
03/13
Level
Beginner
Read
4 min
Updated
On this page 5
  1. 01The situation
  2. 02The concept
  3. 03Try it
  4. 04What this changes
  5. 05Check your understanding
  6. ··Quick answers

The situation

Julia built a chat over her company’s internal manuals. To “be safe”, the code pastes all 40 manuals into every question. It works, but every answer is slow and the monthly bill came in ten times over the forecast. Worse: when the answer is in manual 23, the bot sometimes says it found nothing.

Two concepts explain both problems: tokens and the context window.

The concept

Token

The model does not read letters or words. It reads tokens, chunks of text defined by the tokenizer. A common English word is often one token; long, accented, or rare words become several. Portuguese, code, and JSON usually cost more tokens per word than plain English prose.

Tokens matter for three reasons:

  1. Price. You pay per input token and per output token, and output usually costs more.
  2. Time. The model generates one token at a time. A long answer is a slow answer.
  3. Limit. Everything going in and out has to fit in the context window.

A quick way to feel the difference: the Portuguese sentence “Qual é o prazo de troca?” often becomes more tokens than “What is the return window?”. Code with many symbols, invoice XML, and JSON with repeated keys swell further. If your product speaks Portuguese and pastes XML, the per-word estimate you did in your head is low.

Context window

The context window is the total number of tokens the model sees in one call: system prompt, history, documents, tool definitions, and the answer itself.

flowchart TD
  subgraph W["Context window of one call"]
    S["1. System prompt"]:::tool
    T["2. Tool definitions"]:::tool
    H["3. Conversation history"]:::store
    D["4. Documents and results"]:::store
    Q(["5. Current question"]):::io
    R(["6. Generated answer"]):::llm
  end
  1. The system prompt goes into every call. A thousand extra tokens here are a thousand extra tokens on every message.
  2. Each available tool takes space with its name, description, and schema.
  3. History grows every turn, because the model has no memory and you resend everything.
  4. Retrieved documents and tool results are usually the largest part.
  5. The user’s question is usually the smallest part.
  6. The answer also takes room in the window and has its own limit (max_tokens).

Two limits get mixed up all the time. The window is the cap for the whole call. max_tokens is only the cap for the output. If the window is 200 thousand and you already sent 198 thousand as input, the answer has at most about 2 thousand tokens, even if max_tokens asks for 8 thousand. APIs usually reject the call when the sum does not fit; some frameworks, to “make it fit”, drop old messages without telling you.

A bill for the 40 manuals

The numbers below are illustrative. Suppose each manual is about 4 thousand tokens. Pasting 40 into every question sends about 160 thousand input tokens, plus the system prompt and the question.

Design Input tokens per question What the model sees
Paste all 40 manuals about 160 thousand Everything, including 39 irrelevant ones
Retrieve 3 passages of 500 tokens about 2 thousand, plus the system prompt Only what search picked

In the first row, Julia’s question is a tiny fraction of the input. In the second, it competes with far less noise. The price gap tracks the size gap: you pay for those 160 thousand on every message, even when the answer lives in three paragraphs.

In 2023, Samsung employees pasted confidential source code into ChatGPT. The leak is a policy and tooling problem. The design problem is the same as Julia’s: whatever enters the window, the model reads, and you pay.

Fitting is not the same as working

Context windows got huge. That does not mean the model uses everything in them well. Research like “Lost in the Middle” (Liu et al., 2023) showed that models tend to use what sits at the start and end of the input better than what sits in the middle. Newer models improved on this, but the principle holds: every irrelevant token competes with the relevant ones for the model’s attention.

That is why Julia’s chat failed on manual 23. The information was in the window, drowned among 39 other manuals. Manual 1 and manual 40 had a better chance of being used than the one in the middle.

The beginner trap is treating a large window as a reason not to choose. “It fits” becomes the only criterion. The right criterion is: what needs to be here for this question, and what is only taking up space.

Check +20 XP on first tryJulia's bot pastes 40 manuals into every question. The right answer is in manual 23 and the model says it found nothing. Which diagnosis comes first?

Try it

Count a prompt’s tokens before you send it. The API has an endpoint just for that, which generates no answer.

import anthropic

client = anthropic.Anthropic()

system = open("system_prompt.txt").read()  # your project's system prompt

count = client.messages.count_tokens(
    model="claude-opus-5-5",
    system=system,
    messages=[{"role": "user", "content": "What is the return window?"}],
)
print(count.input_tokens)

Now do the monthly math: input tokens times messages per day times 30. Add the average output. Multiply by the model’s price per million tokens from the provider’s pricing page. That number tends to be scary, and it is better to be scared before production.

Then repeat the count with a 20-turn history pasted into messages. The question did not change; the input did. The gap between the two counts is the price of never compacting the conversation.

Check +20 XP on first tryYou measured 8,000 input tokens per question, 400 output, 10,000 questions a day. The team wants to 'just add the vacation-policy PDF' (another 6,000 tokens) on every call. What happens to the input bill?

What this changes

  • Sending less and better beats sending everything. RAG retrieves the right passages instead of pasting whole manuals.
  • The system prompt needs a diet. When it grows unchecked, it becomes Prompt Bloat.
  • Long conversations rot: old history confuses the model and raises the cost. That is the Context Rot smell.
  • Fixed parts at the start of the input can be reused across calls with prompt caching, which cuts cost and latency.
  • max_tokens that is too short cuts the answer in half. A window that is too full rejects the call or pushes the framework to delete the start of the conversation.

Token math is the first thing to do in any design. It goes deeper in Cost and latency.

Check your understanding

Check +20 XP on first tryAn HR assistant gets 'how many vacation days do I have?' and returns an answer cut off mid-sentence. The stop_reason is max_tokens. Which limit did it hit?

Check +20 XP on first tryThe team raises the model window from 32 thousand to 200 thousand tokens and pastes the 40 manuals again. The bill stays high and manual 23 still vanishes sometimes. What did the larger window fix?

Check +20 XP on first tryOn turn 1 the user asks about the return window. On turn 15 they ask for the store address. The code resends the previous 14 turns, including a 20-page PDF pasted on turn 3. What is the most useful next step?

Check +20 XP on first tryYou need to estimate tokens for a classifier that takes a ticket title and body in Portuguese, with no documents. Which order of work avoids a surprise bill?

Quick answers

What is Tokens and the context window?

Tokens and the context window is an AI engineering fundamental for people who work with LLMs. Why everything costs tokens, why the middle of the context fades, and how to measure it.

Go further

Relations

Part of the tracks 1
Search