---
title: "What is a token in AI? Tokenizers, BPE, and token counting"
type: "deep dive"
url: "https://aifordevs.org/articles/what-is-a-token"
markdown: "https://aifordevs.org/articles/what-is-a-token.md"
publisher: "AI for Devs"
license: "https://aifordevs.org/reuse"
attribution: "Credit AI for Devs and link to https://aifordevs.org/articles/what-is-a-token"
description: "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."
author: "AI for Devs"
published: "2026-11-18"
level: "Intro"
topics: ["models", "apis"]
---

# 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.

> **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](https://aifordevs.org/glossary#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](https://help.openai.com/en/articles/4936856-understanding-and-counting-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](https://aifordevs.org/glossary#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](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) 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](https://arxiv.org/abs/1508.07909) 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.

**Figure 1.** Applying 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](https://huggingface.co/docs/tokenizers/index) 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.

```python title="toy_bpe.py"
"""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.

**Figure 2.** More 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](https://arxiv.org/abs/1808.06226) introduced it at EMNLP 2018. Splitting on spaces fails for Chinese and Japanese, which do not put spaces between words, and the [README](https://github.com/google/sentencepiece) says the library needs no segmenter such as MeCab or KyTea.

Unigram training runs the opposite direction from BPE. [Kudo (2018)](https://arxiv.org/abs/1804.10959) starts from a large set of candidate pieces and repeatedly drops the ones whose removal costs the least likelihood. The [Hugging Face guide](https://huggingface.co/docs/transformers/tokenizer_summary) 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.

| Tokenizer | Vocabulary | English | Spanish | Hindi | Chinese | Japanese | Python | JSON, indented | JSON, minified |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Characters in sample | | 349 | 389 | 377 | 120 | 164 | 316 | 418 | 266 |
| Toy BPE, 4,000 merges | 4,256 | 95 | 179 | 969 | 360 | 492 | 121 | 147 | 111 |
| Mistral 7B v0.2 | 32,000 | 73 | 116 | 400 | 118 | 177 | 112 | 141 | 75 |
| cl100k_base (GPT-4) | 100,277 | 69 | 92 | 377 | 125 | 165 | 88 | 113 | 61 |
| DeepSeek-V4.1-Flash | 129,280 | 70 | 95 | 207 | 68 | 110 | 92 | 115 | 67 |
| o200k_base (GPT-4o, GPT-5) | 200,019 | 69 | 83 | 115 | 85 | 119 | 88 | 113 | 62 |
| Qwen3.8-27B | 248,077 | 69 | 84 | 160 | 68 | 86 | 96 | 135 | 61 |
| Gemma 4 31B | 262,144 | 69 | 81 | 102 | 72 | 85 | 108 | 137 | 65 |

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.

**Figure 3.** Larger, 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.](https://arxiv.org/abs/2305.15425) 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.

| Vendor | Published rule of thumb | Measured on this article's English paragraph |
| --- | --- | --- |
| [OpenAI](https://help.openai.com/en/articles/4936856-understanding-and-counting-tokens) | About 4 characters or three-quarters of a word per token; 100 tokens is about 75 words | o200k_base: 5.06 characters, 0.91 words |
| [Google](https://aistudio.google.com/docs/tokens) | About 4 characters per token; 100 tokens is 60 to 80 English words | Not measured; only the API counts |
| [Anthropic](https://platform.claude.com/docs/en/about-claude/glossary) | About 3.5 English characters per token before Claude 4.7; about 30 percent more tokens from 4.7 on | Not measured; only the API counts |
| [DeepSeek](https://api-docs.deepseek.com/quick_start/token_usage) | About 0.3 tokens per English character, 0.6 per Chinese character | Open 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](https://aifordevs.org/glossary#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](https://platform.claude.com/docs/en/about-claude/pricing) 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](https://aifordevs.org/data/llm-pricing), 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](https://aifordevs.org/articles/claude-api-pricing) works out for Opus 4.6 and Opus 5.5.

Context limits are token limits. Anthropic's [context window docs](https://platform.claude.com/docs/en/build-with-claude/context-windows) 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](https://aifordevs.org/articles/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](https://aifordevs.org/articles/kv-cache-explained) shows. OpenAI's [latency guide](https://developers.openai.com/api/docs/guides/latency-optimization) 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.

| Provider | How to count | Cost and limits | Watch for |
| --- | --- | --- | --- |
| [Anthropic](https://platform.claude.com/docs/en/build-with-claude/token-counting) | `POST /v1/messages/count_tokens` | Free; 5,000 to 20,000 requests per minute by tier | An estimate; rejects most server tools, the MCP connector, and images or documents by URL or file ID |
| [OpenAI](https://developers.openai.com/api/docs/guides/token-counting) | `POST /v1/responses/input_tokens`; tiktoken for plain text | Free; uses no inference quota | tiktoken 0.14.0 raised `KeyError` for `gpt-6-astra` |
| [Google](https://firebase.google.com/docs/ai-logic/count-tokens) | `models/{model}:countTokens` | Free; 3,000 requests per minute | Not supported on Live API or Gemini TTS models |
| [xAI](https://docs.x.ai/developers/rest-api-reference/inference/other) | `POST /v1/tokenize-text` | Not stated | Returns the token list; count its length |
| [DeepSeek](https://api-docs.deepseek.com/quick_start/token_usage) | Offline tokenizer package from the docs | Local | Actual counts come from each response's usage |
| Open-weight models | The model's `tokenizer.json` with Hugging Face Tokenizers | Local | Pass `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.

```python title="count_hosted.py (not run)"
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.

```bash
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
```

```python title="samples.py"
"""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=(",", ":")),
}
```

```python title="measure.py"
"""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](https://aifordevs.org/topics/models) 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.

## Sources

1. [Sennrich, Haddow, and Birch, Neural Machine Translation of Rare Words with Subword Units (ACL 2016)](https://arxiv.org/abs/1508.07909)
2. [Radford et al., Language Models are Unsupervised Multitask Learners (GPT-2, 2019), sections 2.2 and 2.3](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf)
3. [Kudo, Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates (ACL 2018)](https://arxiv.org/abs/1804.10959)
4. [Kudo and Richardson, SentencePiece: A simple and language independent subword tokenizer and detokenizer (EMNLP 2018)](https://arxiv.org/abs/1808.06226)
5. [SentencePiece README on GitHub](https://github.com/google/sentencepiece)
6. [Hugging Face Transformers docs, Tokenization algorithms](https://huggingface.co/docs/transformers/tokenizer_summary)
7. [Hugging Face Tokenizers docs](https://huggingface.co/docs/tokenizers/index)
8. [Petrov et al., Language Model Tokenizers Introduce Unfairness Between Languages (NeurIPS 2023)](https://arxiv.org/abs/2305.15425)
9. [tiktoken 0.14.0 on PyPI (released August 17, 2026)](https://pypi.org/project/tiktoken/)
10. [tiktoken, model.py (model to encoding map, main branch, read November 16, 2026)](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py)
11. [OpenAI Help Center, Understanding and counting tokens (read November 16, 2026)](https://help.openai.com/en/articles/4936856-understanding-and-counting-tokens)
12. [OpenAI API docs, Counting tokens (read November 16, 2026)](https://developers.openai.com/api/docs/guides/token-counting)
13. [OpenAI API docs, Latency optimization](https://developers.openai.com/api/docs/guides/latency-optimization)
14. [Anthropic docs, Token counting (read November 16, 2026)](https://platform.claude.com/docs/en/build-with-claude/token-counting)
15. [Anthropic docs, Glossary: Tokens (read November 16, 2026)](https://platform.claude.com/docs/en/about-claude/glossary)
16. [Anthropic docs, Pricing (read November 16, 2026)](https://platform.claude.com/docs/en/about-claude/pricing)
17. [Anthropic docs, Context windows (read November 16, 2026)](https://platform.claude.com/docs/en/build-with-claude/context-windows)
18. [Google Gemini API docs, Understand and count tokens (read November 16, 2026)](https://aistudio.google.com/docs/tokens)
19. [Google Gemini API reference, Counting tokens](https://aistudio.google.com/api-reference/tokens)
20. [Firebase AI Logic docs, Count tokens for Gemini models (read November 16, 2026)](https://firebase.google.com/docs/ai-logic/count-tokens)
21. [xAI REST API reference, Tokenize text (read November 16, 2026)](https://docs.x.ai/developers/rest-api-reference/inference/other)
22. [DeepSeek API docs, Token and token usage (read November 16, 2026)](https://api-docs.deepseek.com/quick_start/token_usage)
23. [Qwen3.8-27B tokenizer.json on Hugging Face](https://huggingface.co/Qwen/Qwen3.8-27B/blob/main/tokenizer.json)
24. [gemma-4-31B-it tokenizer.json on Hugging Face](https://huggingface.co/google/gemma-4-31B-it/blob/main/tokenizer.json)
25. [DeepSeek-V4.1-Flash tokenizer.json on Hugging Face](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/main/tokenizer.json)
26. [Mistral-7B-Instruct-v0.2 tokenizer.json on Hugging Face](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2/blob/main/tokenizer.json)

## Cite this deep dive

AI for Devs. "What is a token in AI? Tokenizers, BPE, and token counting." Published November 18, 2026. https://aifordevs.org/articles/what-is-a-token

- Page: https://aifordevs.org/articles/what-is-a-token
- Markdown: https://aifordevs.org/articles/what-is-a-token.md
- Reuse: Quote or summarize with a link to this page. Terms: https://aifordevs.org/reuse
- Publisher: AI for Devs
- Published: 2026-11-18
