Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 2. What an LLM is
  4. 2.1

Lesson 2.1 · 1 of 6 · 6 min read · Reviewed 24 Nov 2026

From text to tokens

By the end, you can

  • Explain why models count tokens rather than words or characters.
  • Estimate how many tokens a passage of English text uses.

Before a language model can do anything with your text, a tokenizerTokenizer: The component that splits text into tokens and maps each token to an id the model can process. turns it into a sequence of integers. Each integer points to an entry in a fixed vocabulary of tens of thousands of pieces.

Those pieces are chosen by how often they appear in training text. Common words such as the or cat get a single tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id.. Rare or long words are split: tokenization might become token + ization. A leading space is usually part of the token, which is why the diagram shows ·cat rather than cat.

Why not just use words or letters?

Letters make sequences very long, which is slow and expensive. Whole words would need an enormous vocabulary and still fail on new words, typos and code. Word pieces are the compromise: a manageable vocabulary that can still spell anything.

What this means in practice

  • Counting. For English prose, a rough rule is three to four characters per token. Code, non-English text and unusual formatting usually use more tokens per character.
  • Limits. The context windowContext window: The maximum number of tokens a model can consider at once, counting the input and the output it generates. and max_tokens are measured in tokens, not words.
  • Cost. API pricing is per token, with input and output priced separately (chapter 3).
  • Odd behaviour. Tasks that depend on individual letters, like counting the rs in a word, are harder than they look because the model never sees the letters directly.

The exact split depends on the model’s tokenizer. Use the token countingToken counting: Measuring how many tokens a request will use before sending it, for example with a token-counting endpoint. endpoint or the usage field of a response when you need real numbers rather than estimates.

Key points

  • Models read tokens, not characters or words.
  • A token is often a word piece; English averages roughly 3 to 4 characters per token.
  • Token counts drive context limits, speed and cost.
Hands-on labRuns in the Playground

Build a toy tokenizer and measure it

Split text into word pieces and see how characters per token change for prose, code and numbers.

You will have: A toy tokenizer and a table of characters, tokens and characters per token for four samples.

Steps

  1. Split text with the regular expression in the starter so leading spaces stay with words.
  2. Break long words into 4-letter pieces and long digit runs into groups of 3.
  3. Print characters, tokens and characters per token for each sample.
  4. Compare the code sample with the prose sample.

Done when

  • Prose comes out at about 4 characters per token.
  • Code comes out well below prose, at about 2 characters per token.
  • The first prose tokens show the leading space inside each word token.

Open in the Playground No API key needed.

Starter code (Python)
import re

def toy_tokens(text):
    # TODO: split with re.findall(r" ?[A-Za-z]+| ?\d+|\s+|[^\sA-Za-z\d]", text)
    # TODO: break words longer than 7 letters into 4-letter pieces and digit runs into groups of 3
    return text.split()

samples = {
    "prose": "The cat sat on the mat and watched the rain.",
    "long words": "Internationalization is unbelievably tokenizable.",
    "code": "const total = items.reduce((a, b) => a + b, 0);",
    "numbers": "Order 1234567 shipped with 9876543 and 5551234.",
}

for name, text in samples.items():
    toks = toy_tokens(text)
    # TODO: also print chars per token for each sample
    print(f"{name:10} chars={len(text):3} tokens={len(toks):3}")
Show a solution
import re

def toy_tokens(text):
    """Short words whole (with their leading space), long words in 4-letter pieces,
    digits in groups of 3, punctuation alone. Real tokenizers learn pieces from data."""
    out = []
    for m in re.findall(r" ?[A-Za-z]+| ?\d+|\s+|[^\sA-Za-z\d]", text):
        lead = " " if m.startswith(" ") else ""
        body = m[len(lead):]
        if body.isalpha() and len(body) > 7:
            pieces = [body[i:i + 4] for i in range(0, len(body), 4)]
        elif body.isdigit() and len(body) > 3:
            pieces = [body[i:i + 3] for i in range(0, len(body), 3)]
        else:
            out.append(m)
            continue
        out.append(lead + pieces[0])
        out.extend(pieces[1:])
    return out

samples = {
    "prose": "The cat sat on the mat and watched the rain.",
    "long words": "Internationalization is unbelievably tokenizable.",
    "code": "const total = items.reduce((a, b) => a + b, 0);",
    "numbers": "Order 1234567 shipped with 9876543 and 5551234.",
}

for name, text in samples.items():
    toks = toy_tokens(text)
    print(f"{name:10} chars={len(text):3} tokens={len(toks):3} chars per token={len(text) / len(toks):.1f}")
print("prose tokens:", toy_tokens(samples["prose"])[:6])
Quick checkA 4,000-character English paragraph is about how many tokens?
How sure are you?
Pick an answer and how sure you are