Skip to content

What is a token in AI? How models count and bill them

A token is the unit a language model reads, writes, and bills by. How tokenizers split text, why counts differ by model and language, and how to count first.

Published
Reading time
13 min read

In short

  • A token is a piece of text, usually a word, part of a word, or a punctuation mark, that a model maps to an integer ID. Models read token IDs, generate token IDs, and providers bill and limit requests in tokens.
  • Token counts depend on the tokenizer. The same sentence gives 6 tokens on OpenAI's o200k_base and 7 on cl100k_base, and Anthropic says its tokenizer for Claude 4.7 and later produces about 30% more tokens for the same text than earlier Claude models.
  • A bill has up to four token prices: fresh input, cached input, output, and reasoning tokens, which every major provider bills at the output rate. Reasoning tokens also take space in the context window and count against max_tokens.
  • Count before you send with the provider's endpoint, not a characters-divided-by-four estimate. Local tokenizers such as tiktoken miss tool definitions, images, and files, and cover only OpenAI's encodings.

A token is the unit of text a language model reads and writes: usually a short word, a piece of a longer word, a space with the word after it, or a punctuation mark. A tokenizer turns your text into a list of integer token IDs before the model sees it, and the model's output comes back as token IDs that are decoded into text. Providers count both lists, so tokens are also what you pay for and the unit that context windows and most rate limits are measured in.

That makes a token count three things at once: the size of a request, its price, and how close it is to a limit. Counts also vary with the model, the language, and the format of the text, so an estimate that works for English prose on one model can be far off for JSON, Hindi, or a newer model from the same provider.

What a token is, with a real example

A token is an entry in a fixed vocabulary that the tokenizer learned before the model was trained. Each entry is a sequence of bytes, and each has an ID. Common words get one entry. Rare words are built from several entries.

Here is one sentence run through OpenAI's tiktoken library (version 0.14.0) with two of OpenAI's encodings:

EncodingTokensPieces
o200k_base6Token izers ␣don't ␣count ␣words .
cl100k_base7Token izers ␣don 't ␣count ␣words .

The sentence is "Tokenizers don't count words." Three details show how tokenizers work:

  • "Tokenizers" is not in either vocabulary, so it is split into the subwords Token and izers.
  • The space before a word belongs to that word's token. ␣count and count are different tokens with different IDs.
  • The two encodings disagree on "don't". The larger vocabulary has a single token for it.

Case and spacing change the result too. On o200k_base, Hello is one token (ID 13225), ␣hello is another (ID 40617), and HELLO is two (HEL and LO).

1 · TEXT IN, TOKEN IDS OUTTokenizers don't count words.29 CHARACTERSToken4421izers24223␣don't4128␣count3605␣words6391.136 tokens on o200k_base7 ON CL100K_BASE: DON · 'T␣ = A LEADING SPACE2 · ONE REQUEST IN THE CONTEXT WINDOWTools, systemHistoryNew turnThinkingOutputFreeCached prefixCACHE-READ RATE ON A HITFresh inputINPUT RATEThinking + outputOUTPUT RATEMAX_TOKENS CAPS BOTHHeadroomNOT BILLED
One sentence becomes six token IDs on o200k_base. Those tokens are the new turn in a request's context window, and each part of the window is billed at its own rate.

How tokenizers split text: subwords and byte pair encoding

OpenAI's tokenizers use byte pair encoding (BPE). BPE starts from single bytes and repeatedly merges the most frequent adjacent pair in a training corpus into a new vocabulary entry, until the vocabulary reaches a target size. Sennrich, Haddow, and Birch adapted the algorithm from data compression to word segmentation in 2015, to let translation models handle rare words as sequences of subword units.

The result is a vocabulary in which frequent strings are one token and everything else is still representable. The tiktoken README lists the properties that matter in practice: BPE is reversible and lossless, it can encode any text, including text the tokenizer never saw in training, and it compresses text to about 4 bytes per token on average.

Vocabulary size is a design choice. In tiktoken, cl100k_base has 100,277 entries and o200k_base has 200,019. tiktoken maps GPT-4 and GPT-3.5 model names to cl100k_base, and GPT-4o, GPT-4.1, and GPT-5 names to o200k_base. A larger vocabulary usually means fewer tokens for the same text, which is part of why "unbelievably" is one token on o200k_base and two on cl100k_base.

Why token counts differ by model, language, and format

The same text produces a different number of tokens on each tokenizer, so a token count belongs to a model, not to the text. Three variables move it.

The model's tokenizer. Providers change tokenizers between model generations. Anthropic's pricing page states that Claude 4.7 and later models use a newer tokenizer that produces approximately 30% more tokens for the same text, and its token counting guide tells you to recount prompts against the model you plan to use. A migration at the same price per token can still raise the cost of every request.

The language. Text in languages other than English often splits into more pieces. Petrov et al. found that the same text translated into different languages can differ in tokenized length by up to 15 times. A small test on the same question shows the direction:

TextCharacterso200k_basecl100k_base
How many tokens is this sentence?3377
¿Cuántos tokens tiene esta frase?3389
この文は何トークンですか?131011
यह वाक्य कितने टोकन का है?261225

The Hindi sentence costs 12 tokens on the newer encoding and 25 on the older one, where many Devanagari characters fall back to individual bytes. One short sentence is an illustration, not a benchmark. Measure your own traffic per language before you set a per-request budget.

The format. Code, JSON, numbers, and identifiers break into more tokens per character than prose. {"user_id": 48213, "status": "active"} is 38 characters and 14 tokens on both encodings, about 2.7 characters per token, against about 4.8 for the English sentence above. The number 48213 alone is two tokens, 482 and 13.

That is why rules of thumb hold only for English prose. OpenAI's key concepts page gives about 4 characters or 0.75 words per token. Google's token guide gives about 4 characters per token and 60 to 80 English words per 100 tokens.

Input, output, cached, and reasoning tokens

A response reports its tokens in several buckets, and each bucket can carry its own price. The names differ by provider, and so does whether one bucket is included in another, which is where most token accounting bugs come from.

BucketClaude API (usage)OpenAI Responses API (usage)Gemini API (usage)
Inputinput_tokens, after the cache onlyinput_tokens, cache includedtotal_input_tokens
Cache readscache_read_input_tokensinput_tokens_details.cached_tokenstotal_cached_tokens
Cache writescache_creation_input_tokensinput_tokens_details.cache_write_tokensNo separate field
Outputoutput_tokensoutput_tokenstotal_output_tokens
ReasoningInside output_tokensoutput_tokens_details.reasoning_tokens, inside output_tokenstotal_thought_tokens

Google's guide lists its fields as separate categories without saying whether they overlap, so check one response's total_tokens against the sum of the others before you build cost reports on them.

Input tokens are everything you send: the system prompt, the messages, tool results, images, documents, and tool definitions. On Claude, input_tokens covers only the tokens after the last cache breakpoint, so total input is cache_read_input_tokens + cache_creation_input_tokens + input_tokens. On OpenAI, the prompt caching guide treats cached_tokens and cache_write_tokens as parts of input_tokens, so uncached input is input_tokens - cached_tokens - cache_write_tokens. Adding the cache fields on OpenAI, or forgetting them on Claude, gives the wrong total.

Cached tokens are a repeated prompt prefix that the provider has already processed. They cost a fraction of the input price, and writing them can cost more. Prompt caching covers how the prefix has to be laid out for a hit.

Output tokens are the tokens the model generates, and they carry the highest price on the bill.

Reasoning tokens, also called thinking tokens, are output the model generates before its answer. All three providers bill them at the output rate. OpenAI's reasoning guide says reasoning tokens are not visible through the API, still occupy space in the context window, and can run from a few hundred to tens of thousands per request. Anthropic's context window guide says thinking tokens are a subset of max_tokens, are billed as output, and count toward rate limits. Google's pricing page labels its output prices as including thinking tokens.

How providers bill tokens

A request's cost is each bucket's token count times that bucket's price, summed. Prices are quoted per million tokens (MTok), separately for input and output, with multipliers for cache reads and writes.

Claude Sonnet 5.5 on the Claude API, as listed on Anthropic's pricing page in November 2026, makes a concrete example:

BucketPrice per MTokTokens in one requestCost
Cache read$0.10 (0.05x input)20,000$0.0020
Fresh input$2.002,000$0.0040
Output, including thinking$10.00800$0.0080
Total22,800$0.0140

The 800 output tokens are 3.5% of the request's tokens and 57% of its cost. Without the cache hit, the 20,000 prefix tokens would cost $0.04 at the input rate, and the request would cost $0.052.

Some prices depend on the size of the request, which makes the token count a price tier as well as a quantity:

  • Long prompts. On the Gemini API, Gemini 3.1 Pro Preview charges $2.00 per MTok of input for prompts up to 200,000 tokens and $4.00 above, and output rises from $12.00 to $18.00. Claude Haiku 5.5 charges more for prompts over 100,000 tokens, counting cache reads and writes toward that threshold.
  • Cache writes. Anthropic bills a five-minute cache write at 1.25 times the base input price and a one-hour write at 2 times. OpenAI bills cache writes on GPT-5.6 and later at 1.25 times the uncached input rate for the default 30-minute lifetime.
  • Batch. Anthropic's Batch API halves input and output prices for asynchronous work.

Tools add input tokens you never typed. Anthropic adds a tool-use system prompt whenever a request includes tools: 286 tokens on Claude Opus 5.5 and Sonnet 5.5, on top of the tool names, descriptions, and schemas themselves. Its computer-use toolset adds about 4,500 input tokens per request. Anthropic also estimates a 10 kB web page at about 2,500 tokens when its web fetch tool reads one. Every one of these is billed again on every turn of a conversation unless it is cached. LLM cost optimization ranks the ways to cut each line.

Context windows and max tokens

A context window is the maximum number of tokens a model can hold for one request, counting the input and the output it generates. max_tokens is the cap you set on the output part. Both are counted in the model's own tokens.

The providers draw the boundary differently:

  • OpenAI. The key concepts page says the prompt and the generated output combined must be no more than the model's maximum context length. In the Responses API, max_output_tokens caps reasoning and visible output together.
  • Anthropic. Claude Opus 5.5, Sonnet 5.5, Haiku 5.5, and other current models have a 1M-token context window and can generate up to 128,000 output tokens per request. Cached tokens still occupy the window, since caching changes what you pay for them, not whether they count.
  • Google. Gemini 4 models share one 1,048,576-token window across input, thinking, and output, with a default output cap of 65,536 tokens. Gemini 3 and 2.5 models have separate budgets of 1,048,576 input tokens and 65,536 output tokens.

What happens at the limit also differs. On Claude, input that already exceeds the window returns a 400 "prompt is too long". On Claude 4.5 and newer models, a request whose input plus max_tokens exceeds the window is accepted, and generation stops with stop_reason: "model_context_window_exceeded" if it reaches the limit. On OpenAI, a reasoning request that reaches max_output_tokens returns status: "incomplete", possibly before any visible output, after billing the input and reasoning tokens.

Set max_tokens to the largest useful answer plus the reasoning budget, not to the model's maximum. OpenAI recommends reserving at least 25,000 tokens for reasoning and output when you start with its reasoning models, then adjusting from measured usage. Treat any stop at the cap as a failed answer, not a short one.

How to count tokens before you send a request

Count with the provider's endpoint when you need the number a request will actually use, and with a local tokenizer when you need speed on plain text and the model uses an OpenAI encoding.

MethodCoversNotes
tiktokenPlain text, OpenAI encodingsLocal and offline. Misses tools, images, files, and request formatting
OpenAI POST /v1/responses/input_tokensThe full Responses API inputReturns the exact count, including tools, images, and files
Claude POST /v1/messages/count_tokensThe full Messages API inputFree, rate limited per minute, and documented as an estimate
Gemini count_tokensThe request's inputReturns input tokens only
count_tokens.py
import tiktoken
import anthropic
import openai
from google import genai
 
text = "Tokenizers don't count words."
 
# Local: plain text on an OpenAI encoding. No network call.
enc = tiktoken.get_encoding("o200k_base")
print(len(enc.encode(text)))  # 6
 
# OpenAI: the exact input count for a Responses API request.
oa = openai.OpenAI()
print(oa.responses.input_tokens.count(model="gpt-6.2-astra", input=text).input_tokens)
 
# Anthropic: an estimate for a Messages API request, under that model's tokenizer.
an = anthropic.Anthropic()
print(an.messages.count_tokens(
    model="claude-sonnet-5-5",
    messages=[{"role": "user", "content": text}],
).input_tokens)
 
# Google: input tokens only.
gc = genai.Client()
print(gc.models.count_tokens(model="gemini-4-neon", contents=text).total_tokens)

Each endpoint has edges worth knowing:

  • OpenAI's token counting guide lists why local tokenizers fall short: they do not handle images and files, tools and schemas add tokens that are hard to count locally, and model-specific behavior can change tokenization. The endpoint's count includes the formatting tokens that represent the request's structure.
  • Anthropic's endpoint accepts system prompts, client tools, images, and PDFs, but returns an error for server tools such as web search, for the MCP connector, and for images or documents passed by URL or file ID. Send those as base64. The count can include tokens Anthropic adds for system optimizations, which are not billed, and it ignores cache_control, since caching happens only when a message is created. Its rate limit is separate from message creation: 5,000, 10,000, or 20,000 requests per minute depending on usage tier.
  • Non-text input has its own rates. Google's guide counts an image of 384 pixels or less in both dimensions as 258 tokens, tiles larger images into 768 by 768 tiles of 258 tokens each, and counts audio at 32 tokens per second.

After the call, read usage from the response. It is the number you were billed for. Record it per request, with the model and the cache fields, so cost per feature can be computed later.

Token optimization: where tokens go and how to cut them

Token optimization starts with measurement: break usage down by bucket and by prompt section, then cut the largest line first. On most applications, that order looks like this:

  1. Cache the stable prefix. Put tools, the system prompt, and fixed documents first and keep them byte-identical across requests. On Claude Sonnet 5.5, a cache hit costs 5% of the input price.
  2. Cap and shape output. Set max_tokens, lower the reasoning effort where the task allows, and ask for the fields you need instead of prose around them.
  3. Trim tool definitions. Remove tools a route never calls, and shorten long descriptions. Their tokens are paid on every turn.
  4. Retrieve less, and smaller. Send the passages that answer the question, not whole documents. Chunking strategies covers sizing chunks in tokens rather than characters.
  5. Compact data formats. Drop indentation and repeated keys in JSON you send, and strip boilerplate from fetched HTML.
  6. Budget per language and model. Set token budgets from measured counts for each language you serve, and recount when you change models.

Context engineering covers how to decide what belongs in the window at all, which removes more tokens than any of the cuts above.

Frequently asked questions

What is a token in AI?

A token is a piece of text, often a word, part of a word, or a punctuation mark, that a language model treats as one unit. A tokenizer converts text into a list of integer token IDs before the model reads it, and the model's output is a list of token IDs decoded back into text. Providers bill, limit, and size requests in tokens.

How many words is 1,000 tokens?

For English prose, about 750 words, by OpenAI's rule of thumb of 0.75 words per token. Google's guide gives 60 to 80 English words per 100 tokens. Code, JSON, numbers, and most non-English text use more tokens per word, so count with the provider's endpoint when the number matters.

What does max tokens mean?

Max tokens is the cap you set on how many tokens a model may generate in one response. On Claude it is max_tokens, and on OpenAI's Responses API it is max_output_tokens. On reasoning models the cap covers thinking tokens and visible output together, so a low cap can end a response before any answer appears.

Are reasoning tokens billed?

Yes. OpenAI, Anthropic, and Google all bill reasoning or thinking tokens at the output rate, even though OpenAI does not return them and Anthropic may return a summary instead of the full thinking. They also take space in the context window. Check output_tokens_details.reasoning_tokens on OpenAI and total_thought_tokens on Gemini.

Why do different models count the same text differently?

Each model family uses its own tokenizer with its own vocabulary, and providers change tokenizers between generations. "Tokenizers don't count words." is 6 tokens on OpenAI's o200k_base and 7 on cl100k_base, and Anthropic says Claude 4.7 and later produce about 30% more tokens than earlier Claude models for the same text. Recount prompts on the model you plan to use.

Is tiktoken accurate for Claude or Gemini?

No. tiktoken implements OpenAI's encodings, so it estimates OpenAI token counts for plain text only. For Claude, use the /v1/messages/count_tokens endpoint, and for Gemini, use count_tokens, each with the model ID you plan to call.

Sources

  1. 01Neural Machine Translation of Rare Words with Subword UnitsSennrich, Haddow, and Birch, ACL 2016
  2. 02Language Model Tokenizers Introduce Unfairness Between LanguagesPetrov et al., NeurIPS 2023
  3. 03tiktokenGitHub, openai/tiktoken
  4. 04Key conceptsOpenAI API docs
  5. 05What are tokens and how to count them?OpenAI Help Center
  6. 06Counting tokensOpenAI API docs
  7. 07Reasoning modelsOpenAI API docs
  8. 08Prompt cachingOpenAI API docs
  9. 09Token countingClaude API docs
  10. 10Context windowsClaude API docs
  11. 11Prompt cachingClaude API docs
  12. 12PricingClaude API docs
  13. 13Understand and count tokensGoogle AI Studio docs
  14. 14Gemini API pricingGoogle AI Studio docs