Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
What you will learn
- Turn text into token ids and back with tiktoken
- See how a space or a capital letter changes the tokens
- Explain why a model miscounts the r's in strawberry, and the two fixes
- Compare token counts for the same text across languages and tokenizers
Before you start
- Basic Python
You may have seen a language model miscount the r's in the word "strawberry". By the end of this article you'll know exactly why, because you'll see what the model actually receives when you type. We'll use tiktoken 0.11 on our own machine. No model and no API key are needed.
Three sealed envelopes
You type the word strawberry. Before the model sees anything, the word is cut into pieces, and each piece goes into a sealed envelope with a number on the front. Here, three envelopes: 302, 1618 and 19772.
That's the whole idea: a model reads token ids, not letters.
Text in, ids out
A tokenizer is a fixed vocabulary of text pieces, and every piece has a number. o200k_base is one of these vocabularies, the one used by the GPT-4o model family. Common words get one piece of their own, and rare words are built from several smaller pieces. Each model family ships its own tokenizer, so the same text can split differently from one provider to another.
Here's the small helper the project uses:
"""Small helpers around tiktoken, shared by the demos."""
import tiktoken
ENCODING = "o200k_base" # the tokenizer of the GPT-4o model family
def pieces(text, encoding=ENCODING):
"""the token ids and the text piece each id stands for"""
enc = tiktoken.get_encoding(encoding)
ids = enc.encode(text)
return ids, [enc.decode([i]) for i in ids]
def show(text, encoding=ENCODING):
ids, parts = pieces(text, encoding)
print(f"{text!r}: {len(ids)} tokens")
print(" pieces:", " | ".join(repr(p) for p in parts))
print(" ids: ", ids)
encode takes text and gives back a list of integer ids. To see what each id stands for, we decode them one at a time; that gives the pieces. show prints the token count, the pieces and the ids. (The first time you use an encoding, tiktoken downloads it, a few MB.)
The same word, three ways
from tokens import show
show("strawberry")
show(" strawberry") # with a space in front
show("Strawberry") # capital S
show("How many r's are in strawberry?")
'strawberry': 3 tokens
pieces: 'st' | 'raw' | 'berry'
ids: [302, 1618, 19772]
' strawberry': 1 tokens
pieces: ' strawberry'
ids: [101830]
'Strawberry': 3 tokens
pieces: 'Str' | 'aw' | 'berry'
ids: [3504, 1134, 19772]
"How many r's are in strawberry?": 8 tokens
pieces: 'How' | ' many' | ' r' | "'s" | ' are' | ' in' | ' strawberry' | '?'
ids: [5299, 1991, 428, 885, 553, 306, 101830, 30]
- strawberry on its own is three tokens:
'st','raw'and'berry'. - Put a space in front and it's one token, id 101830. Words in the middle of a sentence usually come with a space in front, so this is the common form.
- With a capital S the pieces change again:
'Str','aw','berry'. Three tokens, different ids. - Inside a real question, the word is that single token
' strawberry'again, 101830.
Keep this in mind when a prompt behaves differently after a small change in spacing or case. The model didn't get "the same thing, slightly different". It got different numbers.
The strawberry problem
Look at what is inside each piece. There is one r inside 'raw' and two inside 'berry'. The letters are there, but the model doesn't receive them. To count them, it has to recall how each id is spelled and add up the r's. Sometimes it gets that right, and sometimes it doesn't.
Here are two fixes:
from tokens import pieces, show
word = "strawberry"
# 1. the problem: the model gets these pieces, not ten letters
ids, parts = pieces(word)
print("the model sees:", parts)
print("letters inside each piece are not visible to it")
# 2. fix in the prompt: spell the word out, one letter per token
show(" ".join(word))
# 3. fix in code: count letters with Python, not with the model
print("Python counts r:", word.count("r"))
the model sees: ['st', 'raw', 'berry']
letters inside each piece are not visible to it
's t r a w b e r r y': 10 tokens
pieces: 's' | ' t' | ' r' | ' a' | ' w' | ' b' | ' e' | ' r' | ' r' | ' y'
ids: [82, 260, 428, 261, 286, 287, 319, 428, 428, 342]
Python counts r: 3
- Fix in the prompt: spell the word out with spaces. Now it's 10 tokens, one per letter, and three of them are
' r', the same id 428 each time. The letters are finally visible as separate inputs. - Fix in code: let Python count.
word.count("r")says 3. Always, and for free.
This goes well beyond strawberry. Reversing a word, counting characters, checking that a code has exactly eight letters: anything that depends on single letters is a job for code, not for the model. As an AI engineer, you decide which part goes to the model and which part stays in Python. (For the wider list of what a model does well and badly, see What an LLM Can and Cannot Do.)
Same meaning, different counts
Tokens matter for one more reason. Here's the same refund question in English, German and Hindi, plus a line of Python and a card number, counted with two tokenizers: the older cl100k_base and the newer o200k_base.
import tiktoken
texts = {
"English": "Where is my refund? I ordered on Monday.",
"German": "Wo ist meine Rückerstattung? Ich habe am Montag bestellt.",
"Hindi": "मेरा रिफंड कहाँ है? मैंने सोमवार को ऑर्डर किया था।",
"Python": "def total(items): return sum(i.price for i in items)",
"Number": "4111111111111111",
}
for name in ("cl100k_base", "o200k_base"):
enc = tiktoken.get_encoding(name)
counts = {k: len(enc.encode(v)) for k, v in texts.items()}
print(f"{name:12}", " ".join(f"{k} {n}" for k, n in counts.items()))
cl100k_base English 10 German 17 Hindi 49 Python 13 Number 6
o200k_base English 10 German 13 Hindi 17 Python 13 Number 6
The English sentence is 10 tokens with both. German goes from 17 to 13. Hindi is the big one: 49 with the older tokenizer, 17 with the newer one. The Python line is 13 with both, and the card number 6.
Numbers get chopped into chunks too. Pass your own text to the project's tokenize demo, for example python demo.py tokenize "Refund for order 1004", and you get 6 tokens: 'Refund' | ' for' | ' order' | ' ' | '100' | '4'.
Models charge by the token, and the context window is measured in tokens too. So count tokens on your own text instead of guessing from the number of words, and if your users write in many languages, test with their real messages. How those tokens fill the context window and turn into a bill is the subject of LLM Tokens, Context Windows and Cost.
Common mistakes
- Thinking the model sees letters. It sees ids. Letters hide inside the pieces.
- Asking a model to count, reverse or measure characters and trusting the answer. Do it in code, or at least spell the word out.
- Treating small spacing or case changes as harmless.
"strawberry"," strawberry"and"Strawberry"are three different inputs. - Estimating tokens from word counts, especially for other languages, code or numbers.
- Assuming every model splits text the same way. Each model family has its own tokenizer.
Quick recap
| Idea | Example |
|---|---|
| Text becomes ids before the model sees it | strawberry -> [302, 1618, 19772] |
| A space changes the ids | ' strawberry' -> [101830], one token |
| A capital changes the ids | 'Str' | 'aw' | 'berry' |
| Letters hide inside pieces | one r in 'raw', two in 'berry' |
| Character work goes to code | word.count("r") -> 3 |
| Counts depend on language and tokenizer | Hindi: 49 (cl100k_base) vs 17 (o200k_base) |
Try it yourself
- Run
showon your own name and count its tokens. - Add a sentence in your language to the counts script.
- Run the project's tests: you should see
4 passed.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.
Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
An LLM replies with a string. Pydantic turns that string into a typed object or a clear error. Validate a User, generate its JSON Schema, then follow one customer e-mail through a Ticket model where the first reply says refund, fails the check, and the retry fits.