Coders In Hoods
  • Courses
  • Roles
  • Blog
  • Setup

Coders In Hoods AI Academy

Every course is free. Sign in to start, and your progress, quiz scores and bookmarks follow you.

AI Academy

  • Courses
  • Paths
  • Setup guides
  • How we teach

Role roadmaps

  • AI Engineer
  • Forward Deployed Engineer
  • Machine Learning Engineer
  • All roles

Coders In Hoods

  • The agency
  • Coaching for teams
  • Blog
  • LinkedIn
  • X (Twitter)

Contact

codersinhoods@gmail.com

© Coders In Hoods · since 2019

← The BlogLLM internals· Cost

Tokens are the unit of everything

Prices, context windows, rate limits and latency are all counted in tokens, not words. What a token is, where it comes from, and how to count one.

Words
Vasile Cojusco
Published
30 November 2026
Reading time
14 min

Contents

  1. IThe short answer
  2. IIWhat a token looks like
  3. IIIWhere tokens come from: byte-pair encoding
  4. IVEverything is metered in tokens
  5. VA worked example: one support reply
  6. VIThe tokenizer is part of the price
  7. VIIWhere token counts surprise you
  8. VIIIHow to count tokens properly
  9. →Sources
  10. →Keep learning

A team ships a support assistant that drafts replies to customer emails. They planned it in words: a 1,300-word help-centre excerpt, a 300-word email, a reply of about 220 words. Then the first invoice arrives in tokens, the rate-limit errors say "input tokens per minute", and a long thread fails because it no longer fits a window measured in tokens too. Nothing they planned was in the unit the system actually counts.

The short answer

A language model never sees your text directly. It sees tokens: pieces of text, often whole common words and often fragments, from a fixed vocabulary learned from data. Price, the context window and rate limits are all counted in tokens, and response time grows with them, so measure in tokens, with the tokenizer of the model you actually call.

What a token looks like

A tokenizer turns text into a sequence of integer IDs, one per piece, and the model only ever works with those IDs. OpenAI publishes its tokenizers as a Python library, tiktoken, so we can look at real splits. Claude's splits will differ (counting those comes at the end). This is o200k_base, the tokenizer of GPT-4o:

tokens.py
import tiktoken
 
enc = tiktoken.get_encoding("o200k_base")  # GPT-4o's tokenizer
text = "Hi, I was charged twice for order #A7X-20931."
ids = enc.encode(text)
print(len(text), "characters,", len(text.split()), "words,", len(ids), "tokens")
print([enc.decode([i]) for i in ids])
45 characters, 8 words, 16 tokens
['Hi', ',', ' I', ' was', ' charged', ' twice', ' for', ' order', ' #', 'A', '7', 'X', '-', '209', '31', '.']

The ordinary words are one token each, and each carries its leading space ( charged is a different token from charged). The order number, the one string the assistant must copy exactly, is seven separate pieces. A few more from the same tokenizer:

texttokenspieces
refund1refund
REFUND2REF · UND
strawberry1 strawberry
strawberry3st · raw · berry
20262202 · 6
jane.doe@example.com6j · ane · .d · oe · @example · .com

The same word can be one token or three depending on a space or its capitals, and a year is split into 202 and 6. The Tokens and embeddings lesson goes from here to how each ID becomes a vector the network computes with.

Where tokens come from: byte-pair encoding

Nobody writes the vocabulary by hand. Most LLM tokenizers learn it with byte-pair encoding (BPE), a compression trick that Sennrich, Haddow and Birch brought into language processing in 2016. Start with single characters (byte-level tokenizers start from the 256 possible byte values), count every adjacent pair in a training corpus, merge the most frequent pair into a new symbol, and repeat until the vocabulary is the size you want.

Here it is on a tiny corpus from a support inbox: refund seen 6 times, refunds 2, refunded 3 and funded 2. Step through the merges and watch the token count fall.

Byte-pair encoding, merge by merge

1/4Start from single characters

wordseenpiecestokens
refund6r e f u n d6
refunds2r e f u n d s7
refunded3r e f u n d e d8
funded2f u n d e d6

Every word is spelled out letter by letter: 86 tokens across the corpus. The pairs f u, u n and n d each appear 13 times, more than any other. On a tie, the pair seen first wins.

wordseenpiecestokens
refund6r e fund3
refunds2r e fund s4
refunded3r e fund e d5
funded2fund e d3

Three merges build fund, because it sits inside every word. The corpus is now 47 tokens. Next, r e and e fund tie at 11, and r e comes first.

wordseenpiecestokens
refund6refund1
refunds2refund s2
refunded3refund e d3
funded2fund e d3

refund is now a single token: 25 tokens in total. Nobody told the algorithm that "refund" is a word; it fell out of the counts.

wordseenpiecestokens
refund6refund1
refunds2refund s2
refunded3refunded1
funded2fund ed2

The suffix ed becomes a token, then refunded does. Seven merges took the corpus from 86 tokens to 17. A real tokenizer runs this over a large training corpus until its vocabulary reaches the target size: about 100,000 entries for GPT-4's tokenizer and 200,000 for GPT-4o's.

Real tokenizers add one hand-written step before BPE: a regular expression that splits text into chunks that merges can't cross, keeping letters, digits and punctuation apart. GPT-4o's rule also cuts digits into runs of one to three (tiktoken), which is why A7X is three tokens and 20931 is 209 + 31. Within those chunks, the vocabulary mirrors what was frequent in the tokenizer's training data: common English words become one token, while a capitalised word or a sentence in a less represented language comes out in pieces. Hugging Face's short walkthrough runs the same algorithm on another tiny corpus:

Byte Pair Encoding Tokenization

Hugging Face · 5:23

A five-minute animation of BPE training and tokenizing new text, the same algorithm as above on a different corpus.

YouTube

Everything is metered in tokens

Once text becomes tokens, every limit and price you deal with is counted in them:

  • Price. Providers price per million input tokens and per million output tokens. As of December 2026, every current Claude model charges five times as much per output token as per input token: Claude Sonnet 5.5 is $2 per million input tokens and $10 per million output tokens (pricing). The token count can even change the rate: Claude Haiku 5.5 charges more per token for prompts over 100,000 tokens.
  • Context window. The window is a token budget shared by everything in the request and everything the model writes back, extended thinking included (context windows). The latest Claude models have a 1-million-token window and can write up to 128,000 output tokens in one request. The Context windows, KV cache and caching lesson explains why long context costs memory and money.
  • Rate limits. Claude's API limits requests per minute, input tokens per minute and output tokens per minute, per model class. Tokens read from the prompt cache don't count towards the input limit by default (rate limits). Rate limits and quotas works out which one binds first for a fleet.
  • Response time. The model reads the whole prompt before it writes anything, so a long prompt delays the first token, and it writes its answer one token at a time, so a longer answer takes longer to finish. Anthropic's latency guide advises keeping both the prompt and the expected output as short as the task allows (reducing latency). max_tokens is a hard cap on output: the response stops when it reaches that many tokens, even mid-sentence.

A worked example: one support reply

Take the support assistant on Claude Sonnet 5.5. At Anthropic's figure of about 555,000 words per million tokens, the 1,600 words of excerpt and email come to about 2,900 tokens. Add the instructions and each request sends about 3,000 input tokens, and the 220-word reply comes back as about 400 output tokens.

tokensprice per millioncost
input3,000$2$0.0060
output400$10$0.0040
per reply3,400$0.0100

At 2,000 tickets a day that's $20 a day, or $600 over 30 days. The reply is 12% of the tokens but 40% of the cost, because output tokens cost five times as much. For a single call like this one, a shorter reply saves more per token than a shorter prompt. Agents are different: they re-read their growing context on every step, so input usually dominates their bill (Token economics of an agent fleet shows why). Move the numbers to see your own case:

What a request costs
$ per million
$ per million
Cost per request
$0.0100
Share of the cost from output
40%
Cost per 30 days
$600

Starts at the worked example: Claude Sonnet 5.5 prices as of December 2026, before prompt caching.

Prompt caching changes the input line a lot when the instructions and excerpt repeat on every request; the same lesson works through it step by step.

Learn it by doing

LLM Cost Engineering

You break one agent task into its calls, count the tokens in each step, and turn per-token prices into a cost per completed case.

Free course · Certificate included · 8 lessons · 20 hours

Start free Go to the lesson: Token economics of an agent fleet

The tokenizer is part of the price

A per-token price only means something next to the tokenizer that does the counting. Anthropic's pricing page notes that Claude 4.7 and later models use a newer tokenizer that produces about 30% more tokens for the same text than earlier models. That's an average: Anthropic's own words-per-token figures imply nearer 35%, and your text may differ again.

Say the support assistant moves from Claude Sonnet 4.6 ($3 and $15 per million) to Sonnet 5.5 ($2 and $10). The per-token price falls by a third, but the same emails and replies now come to about 1.3 to 1.35 times as many tokens. The bill changes by a factor of about ⅔ × 1.3 ≈ 0.87 to ⅔ × 1.35 = 0.90: roughly 10–13% cheaper, not 33%. That's before any difference in how long each model's replies are, which is why you compare models on cost per completed task, measured on your own traffic.

Where token counts surprise you

Languages. Here is one reply translated into five languages, counted with two of OpenAI's tokenizers (o200k_base for GPT-4o, cl100k_base for GPT-4):

languagesentenceGPT-4o tokensGPT-4 tokens
EnglishYour refund has been approved and will arrive within five working days.1313
SpanishTu reembolso ha sido aprobado y llegará en un plazo de cinco días hábiles.1824
GermanIhre Rückerstattung wurde genehmigt und wird innerhalb von fünf Werktagen eingehen.1925
Japanese返金が承認されました。五営業日以内に反映されます。1826
Hindiआपका रिफ़ंड स्वीकृत हो गया है और पाँच कार्यदिवसों के भीतर पहुँच जाएगा।2475

This Hindi sentence takes 1.85 times as many tokens as the English one with GPT-4o's tokenizer, and nearly six times as many with GPT-4's. Petrov et al. measured gaps of up to 15 times for the same translated text, and Ahia et al. found speakers of many languages pay more through a commercial API while getting worse results. Every extra token also uses up context and adds time. Claude's counts will differ from these: measure your own languages with your own model.

Numbers and identifiers. GPT-4o's tokenizer cuts digits into groups of up to three from the left, so 1234567 becomes 123 · 456 · 7. Order numbers, prices, dates and email addresses break into fragments that rarely line up with their meaning. Singh and Strouse showed that how numbers are chunked changes arithmetic accuracy: making GPT-3.5 and GPT-4 chunk from the right, by writing numbers with commas, improved results substantially.

Letters. The model receives strawberry as one token, not ten letters. To count its r's it has to have learned the spelling of that token from training data, because the letters themselves aren't in its input. Spelling, counting characters and reversing strings are harder for a model than they look for the same reason.

Rules of thumb. OpenAI's guidance for English is about four characters, or three-quarters of a word, per token, and it calls these estimates. Anthropic's own figure for Claude's current tokenizer is that a million tokens holds about 555,000 words, against about 750,000 on earlier models (models overview). That is closer to 55 words per 100 tokens than 75. A rule of thumb belongs to one tokenizer, and usually to English.

Glitch tokens. The tokenizer is trained on different text from the model, so a few tokens can end up in the vocabulary that hardly ever appear in the model's training data. Their embeddings stay barely trained, and Land and Bartolo found such under-trained tokens across many models, where they can trigger odd behaviour.

Don't count with someone else's tokenizer

tiktoken is right for OpenAI models and wrong for Claude, and the same is true the other way round. Even two generations of one provider's tokenizer disagree by a factor of three on the Hindi sentence above, and tokenizers from different providers can differ as much. Count with the provider's own counter, for the model version you use.

How to count tokens properly

For Claude, use Anthropic's token-counting endpoint. It takes the same input as a real request and returns the number of input tokens. It's free, though rate-limited, and its count is an estimate that can differ from the real request by a small amount.

count.py
import anthropic
 
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
 
count = client.messages.count_tokens(
    model="claude-sonnet-5-5",
    system="You draft replies for a customer support team.",
    messages=[{"role": "user", "content": "Hi, I was charged twice for order #A7X-20931."}],
)
print(count.input_tokens)

Then rely on the bill's own numbers. Every response carries a usage object. Your total input is three fields, each at its own price: input_tokens (the uncached part), cache_creation_input_tokens and cache_read_input_tokens. output_tokens includes any reasoning, and output_tokens_details.thinking_tokens says how much. Log them per request, per customer and per step: they are what you pay for, and they tell you where the tokens go.

A short checklist:

  • Plan in tokens: budgets, window sizes and rate limits, never in words or pages.
  • Measure real traffic, in every language and format you serve, with the model you'll run.
  • Recount when you change model: a new tokenizer changes the bill even at the same price.
  • Watch both sides: output costs five times as much on Claude and it's what users wait for, while input is what agents re-read on every step.
  • Set max_tokens to a ceiling you can afford, knowing it cuts the response off rather than shortening it.

Learn it by doing

LLMs for Engineers

You build a byte-level BPE tokenizer from scratch, stress-test it on code, numbers and other languages, and see how each token becomes the vector the model computes with.

Free course · Certificate included · 9 lessons · 18 hours

Start free Go to the lesson: Tokens and embeddings

Questions people ask

How many words is a token?

For English with OpenAI's tokenizers, about three-quarters of a word. For Claude 4.7 and later, Anthropic's figure is about 555,000 words per million tokens, or 55 words per 100. Measure your own text rather than trusting either.

Can I count Claude tokens with tiktoken?

No. tiktoken implements OpenAI's tokenizers. Use Anthropic's free token-counting endpoint, or the usage field returned with every response.

Do thinking tokens count?

Yes. Reasoning is billed as output at its full length, even when you only see a summary, and it counts within max_tokens. On current models, earlier turns' thinking stays in context and is billed again as input.

Why does the same prompt come to more tokens on a newer Claude model?

Claude 4.7 and later use a newer tokenizer that produces about 30% more tokens for the same text, so compare models on cost per completed task, not price per token.

■

Sources & further reading

  • Neural Machine Translation of Rare Words with Subword UnitsPaper · Sennrich, Haddow, Birch · 2016The paper that brought byte-pair encoding into NLP. Section 3.2 states the whole merge algorithm in a few lines of Python.
  • Language Model Tokenizers Introduce Unfairness Between LanguagesPaper · Petrov, La Malfa, Torr, Bibi · 2023NeurIPS 2023. Measures how the same text, translated, tokenizes to very different lengths across languages (up to 15 times), and what that does to cost, latency and usable context.
  • Do All Languages Cost the Same? Tokenization in the Era of Commercial Language ModelsPaper · Ahia et al. · 2023EMNLP 2023. Prices the same information in 22 languages through a commercial API; read the introduction and the cost analysis.
  • Tokenization counts: the impact of tokenization on arithmetic in frontier LLMsPaper · Singh, Strouse · 2024How splitting numbers into 3-digit chunks from the left or the right changes arithmetic accuracy. The figures in the first half are enough.
  • Fishing for Magikarp: Automatically Detecting Under-trained Tokens in Large Language ModelsPaper · Land, Bartolo · 2024EMNLP 2024. Why some tokens exist in a vocabulary but were barely trained, and how to find them. The introduction explains the "glitch token" story.
  • Models overviewLab research · AnthropicCurrent Claude models, their context windows and output limits, and Anthropic's own words-per-token figures for the old and new tokenizers.
  • PricingLab research · AnthropicPer-token prices for every Claude model, prompt-caching multipliers, and the note that Claude 4.7 and later use a tokenizer producing about 30% more tokens for the same text.
  • What are tokens and how to count them?Lab research · OpenAIThe source of the "one token is about four characters of English" rule of thumb, and its caveat that it is only an estimate.
  • Token countingDocs · AnthropicThe free endpoint for counting a request's input tokens before you send it, with examples in every SDK.
  • Context windowsDocs · AnthropicHow input, output and extended thinking share one window, and the current window and output sizes.
  • Rate limitsDocs · AnthropicLimits in requests, input tokens and output tokens per minute, and which tokens count towards each.
  • ThinkingDocs · AnthropicHow reasoning tokens are billed (as output, at full length) and which models keep earlier turns' thinking in context.
  • Reducing latencyDocs · AnthropicWhy fewer tokens in and out means faster responses, and what max_tokens does to a long answer.
  • tiktokenDocs · OpenAIOpenAI's open-source tokenizers. The encoding definitions show the pre-splitting rules, including GPT-4o's digit runs of one to three.

Keep learning · free in the AI Academy

  • LLMs for Engineers9 lessons · 18 hoursCourse →
  • LLM Cost Engineering8 lessons · 20 hoursCourse →
← PreviousWelcome to the Coders In Hoods blog