Tokens & tokenization
Models read, limit and bill text in tokens: subword chunks from a fixed vocabulary, ~4 characters or ~0.75 words of English each. Spanish, code and non-Latin scripts need more tokens per idea.
Analogy: Like Lego: common words come as one big prebuilt brick, rare words get assembled from small bricks. The model only sees the brick numbers, never the letters painted on them.
How it works
- A tokenizer maps text to integer IDs from a fixed vocabulary (~32k–256k); the model never sees characters.
- Byte-pair encoding (BPE) merges frequent pairs: common words become one token, rare strings split into pieces.
- Context limits, rate limits and prices all count tokens; output tokens are commonly priced ~4–8× input.
- The model sees IDs, not letters: counting letters fails, and numbers split into chunks that ignore place value.
- Tokenizers differ per model: count with the real one, and budget Spanish at ~20–50% more tokens.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your support bot launches in Spanish with a translated system prompt. Same traffic, same model, same price list, yet the input bill comes in ~30% higher. Most likely cause?
Go deeper
Full explanation
A token is the unit a model reads and writes: an integer ID from a fixed vocabulary (~32k–256k entries). A tokenizer maps text to IDs and back; the model never sees characters.
Most LLMs use byte-pair encoding (BPE) or a close cousin (SentencePiece/Unigram). Training the tokenizer starts from bytes and repeatedly merges the most frequent adjacent pair, so common words ( the, Paris) end up as one token and rare strings split into pieces (tokenization → token + ization). Byte-level BPE (or byte fallback) means any input is encodable: nothing is ever "unknown".
Consequences you design for:
- Budget and billing: context limits, rate limits and prices are all in tokens; output tokens usually cost several times more than input.
- Language tax: vocabularies are fit mostly on English, so Spanish needs ~20–50% more tokens for the same text, and some non-Latin scripts several times more.
- Spelling and math blind spots: the model sees
strawberryas a few IDs, not ten letters, so counting letters fails; numbers split into chunks (often up to 3 digits) that ignore place value. - Tokenizers differ per model: count with the real one (
tiktokenfor OpenAI, the provider's token-counting API for Claude or Gemini).
Code Count tokens and see the pieces with tiktoken
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # GPT-4o-family tokenizer; use your model's own
samples = {
"en": "The quick brown fox jumps over the lazy dog.",
"es": "El veloz zorro marrón salta sobre el perro perezoso.",
"code": "for i in range(10):\n print(i ** 2)",
"num": "Order 1234567 costs $89.99",
"word": "strawberry",
}
for name, text in samples.items():
ids = enc.encode(text)
pieces = [enc.decode([i]) for i in ids] # what the model actually "sees"
print(f"{name:5} {len(text):3} chars -> {len(ids):2} tokens {pieces}")
# Budget a feature: input and output are priced separately, per 1M tokens
PRICE_IN, PRICE_OUT = 2.50, 10.00 # USD per 1M tokens, example rates only
def monthly_cost(prompt: str, out_tokens: int, calls: int) -> float:
per_call = len(enc.encode(prompt)) * PRICE_IN + out_tokens * PRICE_OUT
return per_call * calls / 1e6
print(monthly_cost(open("system_prompt.txt").read(), out_tokens=300, calls=500_000))Real example
You size a support bot whose English system prompt plus retrieved context is ~2,000 words: ~2,700 tokens per call. At 500k calls/month and $2.50 per 1M input tokens, that's ~$3,400/month. You launch in Spanish with a translated prompt and the bill lands ~30% higher (~3,500 tokens per call, ~$4,400/month), and the answers cost more tokens too, at the pricier output rate. The fix is boring: measure each locale with the real tokenizer and budget for it, keep fixed instructions in English with "answer in the user's language", and cache the stable prefix with Prompt caching.
Trade-offs +3 · −3
+ You gain
- Open vocabulary: byte-level BPE encodes any string, emoji or typo without an unknown token.
- Compact: ~4 characters per token keeps English sequences ~4× shorter than characters.
- Deterministic and cheap offline, so you can count and budget before calling the model.
− You pay
- Unfair across languages: the same content costs more money, latency and context outside English.
- Hides characters: spelling, letter counting, rhymes and digit arithmetic get harder.
- Not portable: counts, limits and prices differ between model families for identical text.
Use it when
Think in tokens whenever you size a prompt, estimate cost or latency, set max_tokens, chunk documents for RAG, or debug odd behavior with spelling, numbers, whitespace or a non-English locale.
Avoid it when
Don't hand-tune prompts to shave a few tokens before measuring volume: at low traffic the saving is noise. And never use character or word counts for hard limits; count real tokens.
Numbers to know 5
- English: ~4 characters or ~0.75 words per token; 100 tokens ≈ 75 words.
- Vocabulary sizes: GPT-2 50,257; cl100k_base ~100k; o200k_base ~200k; Llama 3 128,256.
- Spanish typically needs ~20–50% more tokens than English for the same text, depending on the tokenizer.
- Across languages the same text can take up to ~15× more tokens (Petrov et al., 2023).
- Output tokens are commonly priced ~4–8× input tokens.
Common pitfalls 4
- Estimating limits with len(text)/4 on code, JSON or Spanish: it undercounts. Use the real tokenizer.
- Counting Claude or Gemini tokens with tiktoken: different vocabularies give different counts. Use the provider's count-tokens API.
- Stray spaces in prompts or labels: " yes" and "yes" are different tokens, which skews logprob-based classification.
- Asking the model to count characters or do long digit arithmetic instead of giving it code or a tool.
Interview questions 2
Answer out loud first, then reveal.
Why can't an LLM reliably count the r's in "strawberry"?Show answer
Because it never sees letters. The tokenizer turns "strawberry" into a few subword IDs, and the model must have learned which characters each ID contains, which it only picks up indirectly. Same root cause for weak digit arithmetic: numbers are split into chunks that ignore place value. In a product I don't fight that with prompting; I route character-level and arithmetic work to code or a tool call, or have the model spell the word out first so each letter becomes its own token.
How do you estimate the token cost of a new LLM feature before building it?Show answer
I measure instead of guessing. I take ~100 realistic requests per locale and count them with the target model's tokenizer, including system prompt, tool definitions, retrieved context and the history that gets re-sent every turn. I estimate output length separately because it's priced several times higher. Then cost = (input × input price + output × output price) × calls, at p95 as well as the mean. The usual surprises are chat history growth, non-English locales and bulky JSON tool outputs. Finally I check what prompt caching or a smaller model saves.