What is a token in AI? Tokenizers, BPE, and token counting

What a token in AI is, how BPE and SentencePiece tokenizers build a vocabulary, why counts vary by language and model, and how to count before you send.

Published
Reading time
11 min read
Level
Intro
By
AI for Devs
TL;DR
  • A token in AI is an integer ID for a piece of text from a fixed vocabulary, such as a word, part of a word, or a few bytes. Context limits and API prices are both counted in tokens.
  • Byte-pair encoding builds a vocabulary by repeatedly merging the most frequent adjacent pair. This article's 96-line Python trainer learned 4,000 merges from CPython's bundled docs in 42 seconds on an Apple M2.
  • One paragraph took 69 tokens in English on OpenAI's o200k_base and 115 in Hindi. The older cl100k_base needed 377 for the Hindi version, 5.5 times its English count.
  • Vendor rules of thumb are English averages: about 4 characters per token for OpenAI and Gemini, and about 3.5 for Claude models before 4.7. Anthropic says 4.7 and later produce about 30 percent more tokens for the same text.
  • Count with the model's own tokenizer. Anthropic's count_tokens, OpenAI's input_tokens endpoint, and Gemini's countTokens are free as of November 16, 2026.

A token in AI is the unit a language model reads and writes: an integer that stands for a piece of text, often a common word, a fragment of a rarer one, or a few raw bytes. The tokenizer that produces those integers is fixed at training time, and every context limit and per-token price is counted in its output. This guide builds a small byte-pair encoding tokenizer in Python, measures one paragraph in five languages plus code and JSON under six production tokenizers, and lists each major provider's counting method as of November 16, 2026.

#What is a token in AI

A token is one entry in a model's vocabulary, identified by an integer. The model never sees letters. It receives token IDs, predicts the next ID, and a decoder turns generated IDs back into text. The six production vocabularies measured in this article hold from 32,000 to 262,144 entries.

OpenAI's o200k_base encoding, which tiktoken maps to the GPT-4o and GPT-5 families, keeps tokenizer and unbelievably as single tokens, leading space included. It splits the date 2026-11-18 into six pieces: 202, 6, -, 11, -, and 18. Common English words are cheap, and numbers and non-Latin scripts cost more.

A vocabulary also has special tokens, such as an end-of-text marker and the markers a chat API wraps around each message. OpenAI's help article on tokens says its counting endpoint includes formatting tokens for message roles and boundaries, so a chat request costs more than its visible text.

#How a tokenizer turns text into token IDs

A tokenizer runs a fixed pipeline: normalize the text, split it into chunks, break each chunk into vocabulary pieces, and look up each piece's ID. Decoding reverses the last two steps, and the same text always gives the same IDs under one tokenizer.

  1. Normalization rewrites characters into a standard form. Qwen3.8's tokenizer.json applies Unicode NFC, and Mistral 7B v0.2 applies none.
  2. Pre-tokenization splits text into chunks so pieces never cross a chunk boundary. GPT-2 blocked merges across character categories, with an exception for spaces, and Qwen3.8 splits every digit into its own chunk.
  3. The model step breaks each chunk into vocabulary entries. Byte-pair encoding applies learned merges, and a unigram model picks the most probable split.
  4. Each piece maps to its integer ID, and special tokens are added around messages.

Byte-level tokenizers start from the 256 possible byte values, so any UTF-8 string can be encoded without an unknown token. The GPT-2 paper chose bytes because a base vocabulary of Unicode code points would start above 130,000 symbols.

#How byte-pair encoding builds a vocabulary

Byte-pair encoding (BPE) builds a vocabulary bottom-up. It starts with single bytes, counts every adjacent pair in a training corpus, merges the most frequent pair into a new token, and repeats until the vocabulary reaches a target size. The ordered list of merges is the tokenizer.

Sennrich, Haddow, and Birch adapted BPE, a data compression algorithm, to split rare words into subword units for translation (ACL 2016). GPT-2 applied it to bytes with a 50,257-token vocabulary. All six production tokenizers measured below are BPE models, with different corpora, chunking rules, and sizes.

Encoding replays the merges in the order they were learned, as this trace from the next section's toy tokenizer shows.

The toy BPE encoder turns the 10 bytes of ' tokenizer' into 3 tokens with seven merges; a 1,000-merge vocabulary stops at 5 tokensMerge appliedPieces of ␣tokenizer, one cell per byteTokensUTF-8 bytes␣tokenizer10merge 4␣tokenizer9merge 37␣tokenizer8merge 57␣tokenizer7merge 130␣tokenizer6merge 406␣tokenizer5merge 2,015␣tokenizer4merge 2,141␣tokenizer3A 1,000-merge vocabulary stops here, at 5 tokenssingle bytemerged tokenmade by this merge
Fig. 1Applying the earliest-learned merge that fits, the toy encoder turns the 10 bytes of ␣tokenizer (␣ is the leading space) into 3 tokens. With only its first 1,000 merges, it stops at 5.

Production libraries run far faster than pure Python. The Hugging Face Tokenizers docs say its Rust implementation tokenizes a gigabyte of text in under 20 seconds on a server CPU, and tiktoken's README claims 3 to 6 times the speed of a comparable open-source tokenizer.

#Build a toy BPE tokenizer in Python

The script below trains, encodes, and decodes a byte-level BPE tokenizer with only the Python standard library. Its corpus is the documentation that ships with CPython in pydoc_data.topics, so every Python install has it. On Python 3.15.1 that is 616,115 characters of English prose and code.

toy_bpe.py
Python
"""A toy byte-level BPE tokenizer: train merges, encode, decode. Standard library only."""
import json
import re
import sys
import time
from collections import Counter
 
# Split text into word-like chunks first, so merges never cross a chunk boundary.
# A leading space stays attached to the word after it, as in GPT-2.
PRETOKEN = re.compile(r" ?[^\W\d_]+| ?\d{1,3}| ?(?:[^\s\w]|_)+|\s+(?!\S)|\s+")
 
 
def merge(ids, pair, new_id):
    """Replace every occurrence of `pair` in `ids` with `new_id`."""
    out, i = [], 0
    while i < len(ids):
        if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
            out.append(new_id)
            i += 2
        else:
            out.append(ids[i])
            i += 1
    return out
 
 
def train(text, num_merges):
    """Learn merges in order. The vocabulary is 256 byte tokens plus one token per merge."""
    words = Counter(PRETOKEN.findall(text))
    corpus = {tuple(w.encode("utf-8")): n for w, n in words.items()}
    merges = {}  # (left_id, right_id) -> new_id; insertion order is merge order
    for new_id in range(256, 256 + num_merges):
        pairs = Counter()
        for ids, n in corpus.items():
            for pair in zip(ids, ids[1:]):
                pairs[pair] += n
        if not pairs:
            break
        best = max(pairs, key=pairs.get)  # the most frequent adjacent pair
        merges[best] = new_id
        corpus = {tuple(merge(list(ids), best, new_id)): n for ids, n in corpus.items()}
    return merges
 
 
def vocab_of(merges):
    vocab = {i: bytes([i]) for i in range(256)}
    for (a, b), new_id in merges.items():
        vocab[new_id] = vocab[a] + vocab[b]
    return vocab
 
 
def encode(text, merges, trace=None):
    """Apply the earliest-learned merge that fits, until none does."""
    out = []
    for chunk in PRETOKEN.findall(text):
        ids = list(chunk.encode("utf-8"))
        while len(ids) > 1:
            pair = min(zip(ids, ids[1:]), key=lambda p: merges.get(p, float("inf")))
            if pair not in merges:
                break
            ids = merge(ids, pair, merges[pair])
            if trace:
                trace(merges[pair] - 255, ids)
        out.extend(ids)
    return out
 
 
def decode(ids, vocab):
    return b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace")
 
 
def show(piece):
    """A token as text, or as hex when it holds only part of a UTF-8 character."""
    try:
        return piece.decode("utf-8")
    except UnicodeDecodeError:
        return "<" + piece.hex() + ">"
 
 
if __name__ == "__main__":
    from pydoc_data.topics import topics  # English docs that ship with CPython
 
    corpus = "\n".join(topics.values())
    start = time.perf_counter()
    merges = train(corpus, int(sys.argv[1]) if len(sys.argv) > 1 else 1000)
    vocab = vocab_of(merges)
    print(f"{len(merges):,} merges from {len(corpus):,} characters in "
          f"{time.perf_counter() - start:.1f}s; vocabulary {len(vocab):,}")
    print("first 8 merges:", [show(vocab[i]) for i in list(merges.values())[:8]])
 
    encode(" tokenizer", merges, trace=lambda n, ids: print(
        f"  merge {n:>5,}: {[show(vocab[i]) for i in ids]}"))
    for text in ["The tokenizer splits text.", "def count_tokens(text):", "unbelievably", "東京"]:
        ids = encode(text, merges)
        assert decode(ids, vocab) == text
        print(f"{len(ids):2} tokens  {text!r:28} {[show(vocab[i]) for i in ids]}")
    json.dump(list(merges), open("merges.json", "w"))  # a trained tokenizer is this ordered list

Run it with python3 toy_bpe.py 4000. Tested on an Apple M2 with 16 GB of memory, macOS 26.3.1, and Python 3.15.1. Real output:

Text
4,000 merges from 616,115 characters in 42.4s; vocabulary 4,256
first 8 merges: ['  ', '--', '    ', ' t', '----', ' a', 'in', 'he']
  merge     4: [' t', 'o', 'k', 'e', 'n', 'i', 'z', 'e', 'r']
  merge    37: [' t', 'o', 'k', 'e', 'n', 'i', 'z', 'er']
  merge    57: [' to', 'k', 'e', 'n', 'i', 'z', 'er']
  merge   130: [' to', 'ke', 'n', 'i', 'z', 'er']
  merge   406: [' to', 'ke', 'n', 'iz', 'er']
  merge 2,015: [' to', 'ken', 'iz', 'er']
  merge 2,141: [' token', 'iz', 'er']
 7 tokens  'The tokenizer splits text.' ['The', ' token', 'iz', 'er', ' splits', ' text', '.']
 9 tokens  'def count_tokens(text):'    ['def', ' count', '_', 'to', 'ken', 's', '(', 'text', '):']
 7 tokens  'unbelievably'               ['un', 'be', 'li', 'e', 'v', 'ab', 'ly']
 6 tokens  '東京'                         ['<e6>', '<9d>', '<b1>', '<e4>', '<ba>', '<ac>']

The first merges are runs of spaces and dashes, because the training docs are full of indented code and ruled tables. 東京 falls back to six raw bytes, because the corpus has no Japanese to learn merges from, and it still round-trips because every byte is in the base vocabulary.

Characters per token rise from 1.00 to 3.67 on English and 2.61 on Python as the toy vocabulary grows to 4,000 merges, while Hindi stays at 0.39; o200k_base reaches 5.06 on the same English textCharacters per token on held-out text01234502505001,0002,0004,000Merges learned (vocabulary = 256 bytes + merges)o200k_base on the same English paragraph: 5.063.672.610.39English prosePython codeHindi proseo200k_base, English
Fig. 2More merges give longer tokens on text like the training corpus. Hindi stays at 0.39 characters per token, because the English corpus taught no Devanagari merges.

Each point uses the first k merges of the same 4,000-merge run, measured on held-out text written for this test. A 4,256-entry vocabulary reaches 3.67 characters per token on English prose, and o200k_base, with 200,019 entries, reaches 5.06.

#SentencePiece and unigram tokenizers

SentencePiece is a tokenizer library that trains BPE or unigram models directly on raw text, with no language-specific pre-tokenizer. It replaces each space with a visible symbol, ▁ (U+2581), keeps that symbol inside tokens, and turns it back into a space when decoding.

Kudo and Richardson introduced it at EMNLP 2018. Splitting on spaces fails for Chinese and Japanese, which do not put spaces between words, and the README says the library needs no segmenter such as MeCab or KyTea.

Unigram training runs the opposite direction from BPE. Kudo (2018) starts from a large set of candidate pieces and repeatedly drops the ones whose removal costs the least likelihood. The Hugging Face guide puts that at usually 10 to 20 percent per round. At encode time, unigram picks the most probable segmentation instead of replaying merges.

Two tokenizer.json files in this test show the SentencePiece style. Mistral 7B v0.2 uses a Metaspace pre-tokenizer that inserts ▁, and Gemma 4 uses a Replace normalizer that turns every space into ▁. Both are BPE models with byte_fallback on, so a character missing from the vocabulary becomes UTF-8 byte tokens instead of an unknown token.

#Why token counts differ by language, code, and model

Token counts differ because each tokenizer learned its merges from different data, at a different vocabulary size. Text that looks like the training corpus compresses into long tokens. Scripts, code styles, and formats that were rare in that corpus stay split into short pieces, sometimes single bytes.

The table is measure.py output (code below) for one paragraph written for this test, its translations into four languages, a Python snippet, and one tool definition as JSON. Counts exclude special tokens, and the run used tiktoken 0.14.0 and Hugging Face Tokenizers 0.23.3 on November 16, 2026.

TokenizerVocabularyEnglishSpanishHindiChineseJapanesePythonJSON, indentedJSON, minified
Characters in sample349389377120164316418266
Toy BPE, 4,000 merges4,25695179969360492121147111
Mistral 7B v0.232,0007311640011817711214175
cl100k_base (GPT-4)100,27769923771251658811361
DeepSeek-V4.1-Flash129,2807095207681109211567
o200k_base (GPT-4o, GPT-5)200,0196983115851198811362
Qwen3.8-27B248,077698416068869613561
Gemma 4 31B262,1446981102728510813765

English barely moves, from 69 to 73 tokens across the production tokenizers. Hindi moves the most, from 102 tokens on Gemma 4 to 400 on Mistral 7B v0.2, which is more tokens than the paragraph has characters. Qwen3.8 and DeepSeek-V4.1-Flash encode the Chinese paragraph in fewer tokens than the English one.

Chunking rules explain part of the spread. DeepSeek-V4.1-Flash isolates runs of Chinese and Japanese characters, and Qwen3.8 keeps combining marks, such as Devanagari vowel signs, attached to letters.

One paragraph in five languages: Hindi takes 400 tokens on Mistral 7B v0.2 and 377 on cl100k_base, against 115 on o200k_base and 102 on Gemma 4; English takes 69 to 73 on all fourTokens for one paragraph, same meaning in each language69, the English count on three of fourEnglish73696969Spanish116928381Hindi400377115102Chinese1181258572Japanese17716511985Vocabularies of 32,000, 100,277, 200,019, and 262,144 tokens, top bar to bottomMistral 7B v0.2cl100k_baseo200k_baseGemma 4
Fig. 3Larger, more multilingual vocabularies cut the counts for Hindi, Chinese, and Japanese, while English stays near 69. The Hindi paragraph costs almost 4 times as many tokens on Mistral 7B v0.2 as on Gemma 4.

Petrov et al. measured the same effect at larger scale for NeurIPS 2023, with tokenized lengths for the same text differing by up to 15 times between languages on some tokenizers.

Formatting costs tokens too. The same tool definition took 113 tokens as two-space indented JSON and 62 minified on o200k_base, because each newline and run of spaces is encoded. Gemma 4 spent 108 tokens on the Python snippet, against 88 on o200k_base.

#How many characters or words is a token

A token averages about 4 characters of English by OpenAI's and Google's published rules of thumb, and about 3.5 for Claude models before 4.7 by Anthropic's. Your ratio depends on the text and the tokenizer, so use vendor ratios as a sanity check and budget from real counts.

VendorPublished rule of thumbMeasured on this article's English paragraph
OpenAIAbout 4 characters or three-quarters of a word per token; 100 tokens is about 75 wordso200k_base: 5.06 characters, 0.91 words
GoogleAbout 4 characters per token; 100 tokens is 60 to 80 English wordsNot measured; only the API counts
AnthropicAbout 3.5 English characters per token before Claude 4.7; about 30 percent more tokens from 4.7 onNot measured; only the API counts
DeepSeekAbout 0.3 tokens per English character, 0.6 per Chinese characterOpen V4.1-Flash tokenizer: 0.20 and 0.57

The English paragraph uses plain, common words, which is why o200k_base beat OpenAI's 4-character estimate, while the Python snippet came in at 3.59 characters per token. The DeepSeek row uses the open-weight tokenizer from Hugging Face, which may not match the API exactly. Its Chinese figure landed close to DeepSeek's stated 0.6, and its English figure a third below 0.3.

#Why tokens set cost, context limits, and latency

Tokens are the unit of billing, capacity, and generation time. Providers bill input and output tokens at separate per-million rates, a context window caps input plus output in tokens, and a model generates one output token per step. More tokens for the same text cost more on all three.

As of November 16, 2026, Anthropic's pricing page lists Claude Sonnet 5.5 at $2 per million input tokens and $10 per million output tokens. A request with a 2,000-token prompt and a 500-token answer costs $0.004 plus $0.005, or $0.009, so one million of those requests costs $9,000.

At the same per-token price, sending the Hindi paragraph as input costs 1.67 times the English one on o200k_base and 5.46 times on cl100k_base. To compare models in the LLM pricing dataset, multiply each rate by that model's own count for your text.

Tokenizers also change within one model family. Anthropic says Claude 4.7 and later produce about 30 percent more tokens for the same text than earlier models, so a lower list price can still bill more, as the Claude API pricing guide works out for Opus 4.6 and Opus 5.5.

Context limits are token limits. Anthropic's context window docs give Claude Opus 5.5 and Sonnet 5.5 a 1M-token window, and the system prompt, messages, tool definitions, and generated output, thinking included, all count against it. A document that tokenizes 30 percent larger takes 30 percent more of that window, so plan the budget per model, as context engineering describes.

Latency follows output tokens. A model reads the whole prompt in one parallel prefill pass, then runs one decode step per generated token, as the KV cache explainer shows. OpenAI's latency guide lists fewer output tokens and fewer input tokens as separate fixes, and says a long prompt can delay the first token.

#How to count tokens before you send a request

Count tokens with the provider's own endpoint, or with the exact tokenizer file for an open-weight model. A local library gives exact counts only when it implements that model's tokenizer. Methods are as documented on November 16, 2026.

ProviderHow to countCost and limitsWatch for
AnthropicPOST /v1/messages/count_tokensFree; 5,000 to 20,000 requests per minute by tierAn estimate; rejects most server tools, the MCP connector, and images or documents by URL or file ID
OpenAIPOST /v1/responses/input_tokens; tiktoken for plain textFree; uses no inference quotatiktoken 0.14.0 raised KeyError for gpt-6-astra
Googlemodels/{model}:countTokensFree; 3,000 requests per minuteNot supported on Live API or Gemini TTS models
xAIPOST /v1/tokenize-textNot statedReturns the token list; count its length
DeepSeekOffline tokenizer package from the docsLocalActual counts come from each response's usage
Open-weight modelsThe model's tokenizer.json with Hugging Face TokenizersLocalPass add_special_tokens=False for text only

Anthropic's docs show one get_weather tool definition plus a short question counting as 403 input tokens on Claude Opus 5.5, so count requests with their tools attached, against the model ID you will call.

The three hosted calls below were not run, because no API keys were used for this article. Their shapes follow each provider's docs.

count_hosted.py (not run)
Python
import anthropic
import openai
from google import genai
 
prompt = open("prompt.txt").read()
 
claude = anthropic.Anthropic().messages.count_tokens(
    model="claude-opus-5-5", messages=[{"role": "user", "content": prompt}]
)
print("Claude Opus 5.5:", claude.input_tokens)
 
gpt = openai.OpenAI().responses.input_tokens.count(model="gpt-6-astra", input=prompt)
print("gpt-6-astra:", gpt.input_tokens)
 
gemini = genai.Client().models.count_tokens(model="gemini-4-argon", contents=prompt)
print("Gemini 4 Argon:", gemini)

The local measurement did run. It reuses merges.json from toy_bpe.py and needs two packages in a virtual environment; tiktoken downloads its encoding files on first use.

Shell
python3 -m venv .venv && . .venv/bin/activate
pip install tiktoken==0.14.0 tokenizers==0.23.3
mkdir -p hf
curl -sL -o hf/qwen3.8-27b.json https://huggingface.co/Qwen/Qwen3.8-27B/resolve/main/tokenizer.json
curl -sL -o hf/gemma-4-31b-it.json https://huggingface.co/google/gemma-4-31B-it/resolve/main/tokenizer.json
curl -sL -o hf/deepseek-v4.1-flash.json https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/resolve/main/tokenizer.json
curl -sL -o hf/mistral-7b-v0.2.json https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2/resolve/main/tokenizer.json
python3 measure.py hf
samples.py
Python
"""One paragraph in five languages, plus code and JSON. Written for this test."""
import json
 
EN = (
    "A language model reads text as tokens, not letters or words. Before a request "
    "reaches the model, a tokenizer splits the text into pieces from a fixed vocabulary "
    "and maps each piece to an integer. The provider counts those integers to enforce "
    "the context limit and to compute the bill, so the same sentence can cost more on "
    "one model than on another."
)
ES = (
    "Un modelo de lenguaje lee el texto como tokens, no como letras ni palabras. Antes "
    "de que una solicitud llegue al modelo, un tokenizador divide el texto en fragmentos "
    "de un vocabulario fijo y asigna a cada fragmento un número entero. El proveedor "
    "cuenta esos enteros para aplicar el límite de contexto y calcular la factura, así "
    "que la misma frase puede costar más en un modelo que en otro."
)
HI = (
    "एक भाषा मॉडल पाठ को अक्षरों या शब्दों के रूप में नहीं, बल्कि टोकन के रूप में पढ़ता है। "
    "अनुरोध मॉडल तक पहुँचने से पहले, एक टोकनाइज़र पाठ को एक निश्चित शब्दावली के टुकड़ों में "
    "बाँटता है और हर टुकड़े को एक पूर्णांक से जोड़ता है। प्रदाता संदर्भ सीमा लागू करने और बिल "
    "की गणना करने के लिए इन पूर्णांकों को गिनता है, इसलिए एक ही वाक्य की लागत एक मॉडल पर "
    "दूसरे मॉडल से अधिक हो सकती है।"
)
ZH = (
    "语言模型把文本当作词元来读取,而不是字母或单词。请求到达模型之前,分词器会把文本切分成"
    "来自固定词表的片段,并把每个片段映射为一个整数。服务商通过统计这些整数来执行上下文限制"
    "并计算费用,因此同一句话在一个模型上的费用可能比在另一个模型上更高。"
)
JA = (
    "言語モデルはテキストを文字や単語ではなく、トークンとして読み取ります。リクエストがモデル"
    "に届く前に、トークナイザーがテキストを固定の語彙に含まれる断片に分割し、それぞれの断片を"
    "整数に対応付けます。プロバイダーはその整数を数えてコンテキストの上限を適用し、料金を計算"
    "するため、同じ文でもモデルによって費用が高くなることがあります。"
)
CODE = '''def count_tokens(text: str, enc) -> int:
    """Return how many tokens `text` uses under encoding `enc`."""
    if not text:
        return 0
    return len(enc.encode(text))
 
 
for path in sorted(Path("prompts").glob("*.txt")):
    n = count_tokens(path.read_text(), enc)
    print(f"{path.name:30} {n:6,d} tokens")
'''
TOOL = {
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "input_schema": {
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "City name, such as Lisbon"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
        },
        "required": ["city"],
    },
}
SAMPLES = {
    "English": EN,
    "Spanish": ES,
    "Hindi": HI,
    "Chinese": ZH,
    "Japanese": JA,
    "Python": CODE,
    "JSON, indented": json.dumps(TOOL, indent=2),
    "JSON, minified": json.dumps(TOOL, separators=(",", ":")),
}
measure.py
Python
"""Count the same samples under the toy BPE and several production tokenizers."""
import json
import sys
from pathlib import Path
 
import tiktoken
import tokenizers
from tokenizers import Tokenizer
 
import toy_bpe
from samples import SAMPLES
 
learned = [tuple(p) for p in json.load(open("merges.json"))]  # written by toy_bpe.py
toy = lambda k: {p: 256 + i for i, p in enumerate(learned[:k])}  # the first k merges
 
print("toy BPE, characters per token")
for k in [0, 250, 500, 1000, 2000, 4000]:
    print(f"{k:5} merges  " + "  ".join(
        f"{name} {len(SAMPLES[name]) / len(toy_bpe.encode(SAMPLES[name], toy(k))):.2f}"
        for name in ["English", "Python", "Hindi"]))
 
count = {"toy BPE, 4,000 merges": (4256, lambda t, m=toy(4000): len(toy_bpe.encode(t, m)))}
for name in ["cl100k_base", "o200k_base"]:
    enc = tiktoken.get_encoding(name)
    count[name] = (enc.n_vocab, lambda t, enc=enc: len(enc.encode(t)))
for path in sorted(Path(sys.argv[1]).glob("*.json")):  # tokenizer.json files from Hugging Face
    tok = Tokenizer.from_file(str(path))
    count[path.stem] = (tok.get_vocab_size(), lambda t, tok=tok: len(tok.encode(t, add_special_tokens=False).ids))
 
print(f"\ntiktoken {tiktoken.__version__}, tokenizers {tokenizers.__version__}, Python {sys.version.split()[0]}")
print(f"{'':22}{'vocab':>8}" + "".join(f"{k[:9]:>10}" for k in SAMPLES))
print(f"{'characters':22}{'':>8}" + "".join(f"{len(v):>10}" for v in SAMPLES.values()))
for name, (vocab, n) in count.items():
    print(f"{name:22}{vocab:>8,}" + "".join(f"{n(v):>10}" for v in SAMPLES.values()))

Real output:

Text
toy BPE, characters per token
    0 merges  English 1.00  Python 1.00  Hindi 0.39
  250 merges  English 1.91  Python 1.48  Hindi 0.39
  500 merges  English 2.13  Python 1.61  Hindi 0.39
 1000 merges  English 2.62  Python 1.98  Hindi 0.39
 2000 merges  English 2.98  Python 2.14  Hindi 0.39
 4000 merges  English 3.67  Python 2.61  Hindi 0.39
 
tiktoken 0.14.0, tokenizers 0.23.3, Python 3.15.1
                         vocab   English   Spanish     Hindi   Chinese  Japanese    Python JSON, ind JSON, min
characters                           349       389       377       120       164       316       418       266
toy BPE, 4,000 merges    4,256        95       179       969       360       492       121       147       111
cl100k_base            100,277        69        92       377       125       165        88       113        61
o200k_base             200,019        69        83       115        85       119        88       113        62
deepseek-v4.1-flash    129,280        70        95       207        68       110        92       115        67
gemma-4-31b-it         262,144        69        81       102        72        85       108       137        65
mistral-7b-v0.2         32,000        73       116       400       118       177       112       141        75
qwen3.8-27b            248,077        69        84       160        68        86        96       135        61

This run exercised the toy tokenizer, two tiktoken encodings, and four open-weight tokenizer.json files, locally. It did not exercise any Claude, Gemini, xAI, or DeepSeek API tokenizer. The translations are the author's, and a native speaker's may count differently.

After a request returns, log the usage the provider billed: usage.input_tokens and usage.output_tokens on Anthropic and the OpenAI Responses API, and usage_metadata.prompt_token_count and candidates_token_count on Gemini's generateContent. Compare those numbers with your pre-send counts on real traffic, and recount whenever you change models. The models topic page collects related guides.

#Questions

What is a token in AI?

A token is the unit of text a language model reads and generates. The tokenizer maps each piece of text, such as a common word, part of a rarer word, or a few bytes, to an integer ID from a fixed vocabulary. Providers count those IDs to apply context limits and to bill input and output, so tokens are the unit of both capacity and cost.

How many words is 1,000 tokens?

OpenAI's rule of thumb gives about 750 English words, and Google's gives 600 to 800 for Gemini. On a plain 63-word English paragraph measured for this article, o200k_base produced 69 tokens, which works out to about 910 words per 1,000 tokens. Code, JSON, and other languages give far fewer words per token, so count real text.

Can I use tiktoken to count tokens for Claude or Gemini?

No. tiktoken implements OpenAI's encodings, and Claude and Gemini use their own tokenizers. Anthropic and Google document API methods for counting, not a local tokenizer file, so a tiktoken count for their models is a guess. Call Anthropic's count_tokens endpoint or Gemini's countTokens method with the exact model ID. Both are free and count under that model's tokenizer.

Why does the same text use more tokens in some languages?

A tokenizer learns merges from its training data, so scripts that were rare in that data stay split into short pieces or single bytes. In this article's test, a Hindi paragraph took 377 tokens on cl100k_base and 115 on o200k_base, against 69 for the English original. Larger, more multilingual vocabularies shrink that gap but do not close it.

Do spaces and formatting count as tokens?

Yes. Whitespace, newlines, and punctuation are encoded like any other text. The same tool definition took 113 tokens as two-space indented JSON and 62 tokens minified on o200k_base, an 82 percent difference. Chat APIs also add formatting tokens for roles and message boundaries, which a plain-text count of your prompt does not include.

Are output tokens more expensive than input tokens?

Usually, yes. As of November 16, 2026, Claude Sonnet 5.5 costs $2 per million input tokens and $10 per million output tokens, a 5x ratio. Output tokens are also slower, because a model generates them one at a time, while it processes the whole prompt in one parallel prefill pass. OpenAI bills reasoning tokens as output tokens too.