AI ENGINEERING · LLM FOUNDATIONS · FOUNDATIONS · 2 OF 35

Tokens and Context Windows in LLMs, Explained

What a token is and how byte pair encoding learns subword pieces, with a worked split of a real sentence. The rules of thumb for counting tokens, why other languages and code cost more, input versus output pricing with a cost calculation, the context window as the model's whole working memory, budgeting it, overflow, lost in the middle, and counting before you send.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Subword tokens
  • ~4 chars each
  • output costs more
  • window = whole memory
  • budget it
  • mind the middle

Notes

The idea

A model never sees letters or words. Before your text reaches it, a tokenizer chops it into pieces called tokens, and looks up each piece in a fixed vocabulary to get an integer id. Hello world becomes two ids. The model reads that list of numbers and predicts the id of the next token. On the way out, ids turn back into text. Underneath everything, the real unit is the token.

Models read numbers
  • text is never fed in as letters or whole words
  • tokenizer: text → pieces
  • each piece → an integer id
  • from a fixed vocabulary
  • the model reads the ids and predicts the next id
  • ids → text on the way out

Why subwords

Why pieces, and not whole words or single letters? Letters give a tiny vocabulary but make every sentence very long, and long is slow and costly. Whole words make short sequences, but there are millions of them, and any new name or typo would be unknown. Subwords sit in the middle. Common words get one token, rare words are built from a few pieces, and anything can still be spelled out.

Letters, words or pieces?
  • letters: tiny vocabulary, but very long sequences
  • whole words: short, but millions of them, and new names or typos break it
  • subwords: the middle path common word → 1 token rare word → a few pieces any text can be spelled
  • vocabulary: ~30k–250k tokens

BPE by hand

Most tokenizers learn their pieces with byte pair encoding, or B P E. Split the training text into single characters. Count which neighbouring pair appears most often, and merge it into a new token. In our tiny corpus, l and o sit together five times, so they merge. Then that plus w becomes low. Now lower is low plus e plus r. Keep merging the most frequent pairs until the vocabulary reaches its target size.

Byte pair encoding, by hand
corpus: low low low lower lowest
start: single characters
  l o w | l o w e r | l o w e s t
count pairs: (l,o)=5  (o,w)=5
merge 1: l + o  → lo
merge 2: lo + w → low
now: low | low e r | low e s t
keep merging frequent pairs:
  e + r → er,  e + s → es ...
stop at the target vocab size

A real sentence

Here is a real sentence. Tokenizers split unbelievable words. A typical tokenizer might cut it into eight tokens: token, izers, split, un, believ, able, words, and the full stop. Common words are one token each, while rarer words are built from pieces. And the space usually belongs to the start of the next token, so split with a space in front is a different token from split without one.

One sentence, split
"Tokenizers split unbelievable words."

Token|izers|·split|·un|believ|able
|·words|.

36 characters, 5 words → 8 tokens
≈ 4.5 characters per token

· = a leading space, which is
    part of the token
(exact splits vary by tokenizer)

Rules of thumb

For English prose, two rules of thumb cover most budgeting. One token is about four characters, or about three quarters of a word. So a thousand tokens is about seven hundred and fifty words, a page is roughly six hundred and fifty tokens, and a three hundred page book is around two hundred thousand. Dividing characters by four is a fine first estimate. Near a hard limit, count with the real tokenizer.

English rules of thumb
1 token       ≈ 4 characters
1 token       ≈ 0.75 words
100 tokens    ≈ 75 words
1,000 tokens  ≈ 750 words
a page (~500 words) ≈ 650 tokens
a 300-page book     ≈ 200k tokens

quick estimate: characters / 4
near any hard limit: count with
the real tokenizer

Not all text is equal

That rule only holds for English prose. Many other languages need one and a half to three times as many tokens for the same meaning, because the vocabulary was learned mostly from English. Those users pay more and get less room. Code and JSON are token heavy too, with indentation, brackets and quotes. And since the model sees pieces like straw and berry, not letters, counting the letters in a word is surprisingly hard for it.

Same meaning, more tokens
English prose      the baseline
many languages     ~1.5–3× more
code, JSON         ~3 chars/token
                   or fewer
long numbers       split in chunks
emoji, rare text   several each

why letter counting is hard:
  the model sees "straw" "berry",
  not s-t-r-a-w-b-e-r-r-y

Input vs output

Tokens come in two kinds. Input tokens are everything you send. The model reads them all in one parallel pass, called prefill, which mostly sets the wait for the first token. Output tokens are the reply. They are generated one at a time, each appended and fed back in before the next. That phase is called decode, and it sets the total time. A long answer is a slow answer, so cap the output length.

Two kinds of tokens
  • input tokens (the prompt) read in one parallel pass (prefill): sets the wait for the first token
  • output tokens (the reply) written one at a time, each fed back as input (decode): sets total time
  • long answer = slow answer
  • cap it: max output tokens

Paying per token

Providers bill per token, with separate prices for input and output. Output usually costs about three to five times more. Take made up prices of one dollar per million input tokens and four per million output. A call with two thousand tokens in and five hundred out costs two tenths of a cent for each side. Four thousand dollars for a million calls. Output was a fifth of the tokens, and half the bill.

A cost calculation
made-up prices, per million tokens:
  input 1 USD     output 4 USD

one call: 2,000 in, 500 out
  in : 2,000 × 1 / 1M = 0.002
  out:   500 × 4 / 1M = 0.002
  total               0.004 USD

× 1M calls a month = 4,000 USD
output: 20% of tokens, 50% of bill

The context window

The context window is the most tokens the model can handle in one call, and it is the model's entire working memory. Everything shares it: the system prompt and tools, the conversation so far, retrieved documents, tool results, the new question, and the reply being written. Input plus output must fit. The model keeps nothing between calls, so if a fact is not in the window, for the model it does not exist.

One window, shared by all
  • system prompt + tool list
  • conversation history
  • retrieved documents
  • tool results
  • the new question
  • + the reply being written
  • input + output ≤ window
  • nothing outside it exists
  • for the model

Budget the window

Treat the window like a budget. Say it holds a hundred and twenty eight thousand tokens. The system prompt and tools take three thousand, recent history twenty five thousand, documents twenty thousand, the question one thousand, and you reserve four thousand for the answer. Fifty three thousand in total. Always reserve the output first. And note that the maximum output is its own, smaller limit, often a few thousand to tens of thousands.

Budget for a 128k window
system prompt + tools     3,000
history (recent turns)   25,000
retrieved documents      20,000
the question              1,000
reserved for the output   4,000
                         ------
total                    53,000

headroom ~75k. Note: max output
is its own, smaller limit

When it overflows

What happens when it does not fit? Depending on the provider and framework, the call is rejected with an error, or the oldest text is silently cut. Silent is worse, because the model may lose its instructions unnoticed. So manage it yourself. Keep a sliding window of recent turns, fold older turns into a running summary, retrieve only the chunks that matter, trim large tool results, and keep the system prompt pinned.

When it does not fit
  • the API rejects the call, or old text is cut silently
  • manage it yourself:
  • sliding window: keep the last N turns
  • summarise older turns into a short running summary
  • retrieve only what matters
  • trim big tool results
  • pin the system prompt

Chats resend history

Here is a cost trap. The model is stateless, so a chat app resends the whole history every turn. Say the system prompt is one thousand tokens and each turn adds five hundred. Turn one sends one thousand, turn twenty sends ten and a half thousand. Across twenty turns that is a hundred and fifteen thousand input tokens, growing with the square of the turns. Summaries and prompt caching keep it in check.

Every turn resends everything
system 1,000 + history grows 500/turn

turn 1   input   1,000
turn 2   input   1,500
turn 10  input   5,500
turn 20  input  10,500

20 turns, total input: 115,000
grows with the square of the turns
summaries + prompt caching help

Lost in the middle

Even inside the window, position matters. Research on long prompts found a U shape. Models use facts at the start and end well, but often miss facts buried in the middle, an effect called lost in the middle. Newer models handle it better, but it has not gone away. So put key instructions and the question at the end, send fewer and more relevant documents, and place the best ones near the edges.

Position matters
how well a fact is used, by where
it sits in a long prompt:
  start   ########   good
  middle  ####       weaker
  end     ########   good

• instructions + question at the
  end (or repeat at both ends)
• fewer, more relevant documents
• best chunks near the edges

Count before sending

Count tokens before you send, not after the call fails. Use the tokenizer for your model family, or the provider's count tokens endpoint. Tokenizers differ between families, so the same text gives a different count when you switch models. The chat format also adds a few hidden tokens per message. After each call, log the real input and output counts the response returns. That feeds your cost dashboards.

Count before you send
  • use the tokenizer for your model family, or the provider's count-tokens call
  • tokenizers differ: same text, new model, new count
  • chat formatting adds a few tokens per message
  • log the usage the response returns: real in + out
  • alert on budget, not crash

Common mistakes

The common mistakes. Budgeting in words or characters, then being surprised by the token count. Forgetting the reply needs room too. Filling a huge window just because it is there, which makes calls slower, pricier and often less accurate. Letting a framework silently cut the start of the prompt, where the instructions live. Leaving output uncapped. And assuming English ratios for every language.

Mistakes to avoid
  • budgeting in words or characters, not tokens
  • no room left for the reply
  • filling a big window just because it is there
  • silent truncation that drops the system prompt
  • no cap on output length
  • English ratios for every language

Numbers worth knowing

Numbers worth knowing, all ballparks. About four characters per token in English. Vocabularies of thirty thousand to a quarter of a million tokens. Frontier context windows from about a hundred thousand to over a million tokens, smaller for small models. Output priced about three to five times input. Generation at roughly fifty to two hundred tokens per second. And attention cost grows faster than prompt length.

Numbers worth knowing
chars per token (English)  ~4
words per token            ~0.75
vocabulary size            ~30k–250k
frontier context window    ~128k–1M+
small-model window         ~8k–128k
max output tokens          ~4k–tens of k
output vs input price      ~3–5×
generation speed           ~50–200 tok/s
attention cost grows faster than
prompt length (naive: O(n²))

Say it like this

How to say it. Text is split into subword tokens by a byte pair encoding tokenizer, about four characters each in English. We budget the window: three thousand tokens of system prompt, twenty five thousand of history, twenty thousand of documents, four thousand reserved for the answer. Older turns are summarised, and we count with the real tokenizer and log usage on every call. Cost and quality, managed together.

In the interview
  • "Text is split into subword tokens by a BPE tokenizer, about 4 chars each. We budget the 128k window: 3k system, 25k history, 20k documents, 4k reserved for the answer. Old turns are summarised, we count with the real tokenizer and log usage on every call."

Interview questions

Q1What is a token in an LLM?

A token is a piece of text, often a subword, that the tokenizer maps to an integer id from a fixed vocabulary. The model reads and predicts token ids, not characters or words. In English a token averages about four characters, or three quarters of a word.

Q2How does byte pair encoding work?

Start with text split into bytes or characters, repeatedly find the most frequent adjacent pair in the training corpus and merge it into a new token, and stop when the vocabulary reaches a target size. Common words end up as single tokens; rare words are spelled from a few pieces, and byte-level BPE means no input is ever unknown.

Q3Why do non-English text and code cost more tokens?

Tokenizer vocabularies are learned mostly from English text, so other languages are split into smaller, more numerous pieces, often 1.5 to 3 times as many for the same meaning. Code and JSON spend tokens on whitespace, brackets and quotes.

Q4Why are output tokens priced higher and slower than input tokens?

Input tokens are processed in one parallel pass (prefill), while output tokens are generated one at a time, each needing its own step through the model (decode). That sequential work is more expensive, so output is usually priced around 3 to 5 times input and dominates response time.

Q5What is a context window?

The maximum number of tokens a model can process in one call, covering the system prompt, tools, history, documents, the question and the generated reply together. It is the model's only working memory; anything outside it is invisible to the model.

Q6What happens when a conversation exceeds the context window, and how do you handle it?

The API rejects the request or the oldest content is truncated, possibly dropping instructions. Handle it before it happens: keep a sliding window of recent turns, summarise older ones, retrieve only relevant chunks, trim tool results and keep the system prompt pinned.

Q7What is the "lost in the middle" effect?

In long prompts, models use information at the start and end more reliably than information in the middle. Mitigate by placing key instructions and the question at the end, sending fewer and more relevant documents, and putting the most important ones near the edges.

Q8How do you count tokens and control cost in production?

Count with the tokenizer for the specific model family or the provider's token-counting endpoint, since tokenizers differ. Reserve output space, cap max output tokens, log the input and output usage returned on every call, and remember chat apps resend history each turn, so summaries and prompt caching matter.