Velamuvi AIAcademy
Tokenization

Lesson 4 of 5 · Tokens

Counting Tokens

Count tokens exactly with a tokenizer or an API's usage report, estimate them with rules of thumb, see how accurate 4 characters per token is, and price them.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Three ways to get a token count, from exact to rough
  • How accurate the common rules of thumb are
  • Why code, numbers and other languages break the rules
  • How to turn token counts into cost estimates

Why count?

Tokens decide three things:

  • Cost: APIs bill per token, input and output separately.
  • Limits: context windows and maximum output lengths are in tokens.
  • Speed: more tokens take longer to process and generate.

Three ways to count

1. From the API's usage report (exact, after the fact). Every response from a major LLM API includes how many input and output tokens were used, counted by the model's own tokenizer, including hidden special tokens. This is what you are billed for.

2. With a tokenizer library (exact, before sending). Libraries can count tokens locally. For OpenAI's models, the Python library is tiktoken:

import tiktoken

encoding = tiktoken.get_encoding("o200k_base")
tokens = encoding.encode("Good morning! How are you today?")
print(len(tokens))

Other providers offer token-counting functions in their libraries or a counting endpoint in their API, because their tokenizers differ. For open models, the tokenizer is downloaded with the model.

3. With a rule of thumb (instant, approximate). For English prose:

  • 1 token is about 4 characters
  • 1 token is about 0.75 words, so 100 words is about 130 tokens

You can also count live in the box below, or in the Token Counter:

Loading the tokenizer…
0 tokens · 7 words · 31 characters
Code uses more tokens per character than prose: indentation, brackets and short names each take tokens.

How good are the rules of thumb?

Here are real counts from a recent tokenizer next to the 4-characters estimate:

Try it yourselfPython
# Real token counts, measured with a recent tokenizer (o200k_base)
samples = [
    ("English", "Good morning! How are you today? I hope the weather is nice where you are.", 18),
    ("Spanish", "¡Buenos días! ¿Cómo estás hoy? Espero que haga buen tiempo donde estás.", 17),
    ("Python code", "def add(a, b):\n    return a + b\n", 12),
    ("Long number", "3.14159265358979", 7),
]

print(f"{'text':12} {'chars':>5} {'estimate':>8} {'actual':>6}")
for name, text, actual in samples:
    estimate = round(len(text) / 4)          # rule of thumb: 4 characters per token
    print(f"{name:12} {len(text):5} {estimate:8} {actual:6}")

The rule is excellent for everyday English and decent for Spanish. It underestimates code and numbers by around half: indentation, symbols and digit groups each cost tokens. For many other languages it can be far off, as the next lesson shows.

From tokens to cost

Try it yourselfPython
def estimate_cost(words, price_per_million, kind="english"):
    # Rough characters-per-token for different kinds of text
    chars_per_token = {"english": 4.0, "code": 2.7}
    characters = words * 5.5                 # about 5.5 characters per English word, with spaces
    tokens = characters / chars_per_token[kind]
    return tokens, tokens / 1_000_000 * price_per_million

for words in [500, 10_000, 1_000_000]:
    tokens, cost = estimate_cost(words, price_per_million=3.00)
    print(f"{words:>9,} words -> about {tokens:>9,.0f} tokens -> ${cost:,.4f}")

At an example price of $3 per million input tokens, a million words of input costs a few dollars. Remember that output tokens are usually priced several times higher, and that chat apps re-send the history every turn.

Common mistakes

Practice exercise

Estimate a prompt's size and how much of the context window is left for the answer.

Your solutionPython
words = 1500        # length of the prompt in English words
limit = 4096        # the model's context window in tokens

# Estimate the prompt's tokens with the rule "1 token is about 0.75 words"
# (use round), then print:
# About 2000 tokens
# Room left for the reply: 2096
Knowledge check

Which kind of text does the “4 characters per token” rule most underestimate?

Summary

  • Tokens decide cost, limits and speed.
  • Exact counts come from the API's usage report or a tokenizer library for that model.
  • Rules of thumb: 4 characters or 0.75 words per token, for English prose.
  • The rules underestimate code, numbers and many non-English languages.
  • Turn counts into cost with tokens ÷ 1,000,000 × price, separately for input and output.

Next: why the same message costs more tokens in some languages.

Finished reading? Tick it off to track your progress.