Sub topic 1
What a Token Is and Why Counts Differ by Model
A language model does not read characters or words. It reads tokens, and every price, limit, and usage figure for a coding agent is stated in tokens. This chapter explains what a token is, why two models count different numbers for the same text, and how to get counts you can trust.
Prerequisites
This chapter assumes you can:
- Read basic Python (functions, dictionaries, f-strings).
- Use an AI coding assistant or agent and have seen it read files and run commands.
- Describe a large language model at a high level: text goes in, text comes out.
- Read JSON and use the command line.
No earlier chapter is required. Later chapters build on the vocabulary introduced here.
What a token is
A token is a chunk of text that a model treats as one unit. Before the model sees your prompt, a program called a tokenizer splits the text into chunks and replaces each chunk with an integer ID. The model works only with those IDs. When it answers, it produces IDs one at a time, and the tokenizer turns them back into text.
Most current tokenizers are subword tokenizers. They hold a fixed vocabulary of chunks, often tens of thousands to a few hundred thousand entries. Common words are usually one chunk. Rare words are split into several pieces. Anything missing from the vocabulary falls back to smaller pieces, down to single bytes.
A common method for building the vocabulary is byte pair encoding (BPE). It starts from single bytes and repeatedly merges the most frequent adjacent pair in a training corpus into a new chunk. You do not need the algorithm for daily work. What matters is the result: the vocabulary reflects whatever text the tokenizer's builders trained it on.
Why counts differ by model
The same text produces different token counts for three reasons.
- Different vocabularies. Each model family ships its own tokenizer. A string that is one chunk in one vocabulary may be three in another. Two models from the same provider can also differ if one generation changed the tokenizer.
- Different content. Even within one tokenizer, the characters-per-token ratio changes with the kind of text.
- Different framing. Chat requests add special tokens that mark message boundaries and roles. Tool definitions are serialized into the prompt as well. The provider's count includes all of this, and your own count of the visible text does not.
Content type matters
Tokenizers are trained mostly on prose, so prose compresses best. Rough, commonly observed patterns:
- English prose: often around 4 characters per token.
- Source code: fewer characters per token. Identifiers like
get_user_by_idsplit into several pieces, and indentation and punctuation add more. - JSON and logs: usually worse still. Quotes, braces, repeated keys, UUIDs, and hashes tend to split into many small tokens.
- Numbers: often split into short digit groups, so long numbers cost many tokens.
- Non-English text: often needs more tokens per character than English, depending on the tokenizer.
These ratios are heuristics, not guarantees. The exact figures depend on the tokenizer, so measure them for your own content.
For a coding agent this matters because most of what it sends is code, command output, and JSON from tools. Counting that material at the English rate will undercount it.
Whitespace and formatting
Whitespace is text too. Deeply indented code, long runs of spaces, and blank lines are tokenized. Some tokenizers merge runs of spaces into one token, and others do not. Reformatting a file, such as switching tabs to spaces, can change its token count without changing its meaning.
Counting tokens in practice
There are three ways to get a count, in order of reliability.
- The usage field in the API response. Every response reports the tokens the provider counted and billed for that request, typically as input and output counts, with extra fields for cached or reasoning tokens. Field names vary by provider. This is the number that appears on your invoice.
- A provider's token-counting endpoint or tokenizer library. Many providers offer one. It counts a request before you send it, using the real tokenizer. Use the tokenizer that matches the model you will call.
- A character-based estimate. This is quick and needs no network. It is only good for rough planning.
Here is a small estimator and a calibration step. The ratios are placeholders. Replace them with values you measure.
import json
import math
# Placeholder characters-per-token ratios. Measure your own.
CHARS_PER_TOKEN = {"prose": 4.0, "code": 3.0, "json": 2.5}
def estimate_tokens(text, kind):
"""Rough token estimate from character count."""
return math.ceil(len(text) / CHARS_PER_TOKEN[kind])
def measured_ratio(text, input_tokens):
"""Characters per token, from a real usage figure."""
return len(text) / input_tokens
source = "a" * 3000
print(estimate_tokens(source, "code")) # 1000
# A usage block as returned by an API (field names vary by provider).
response = json.loads('{"usage": {"input_tokens": 1600, "output_tokens": 85}}')
prompt = "b" * 4800
print(measured_ratio(prompt, response["usage"]["input_tokens"])) # 3.0The second function is the useful habit. Log the characters you sent and the input tokens the provider reported. Over a few dozen requests you get a ratio for your own workload, which beats any general rule of thumb.
Why this changes cost comparisons
Prices are quoted per million tokens, but a token is not a fixed unit. It is defined by each model's tokenizer. If Model B has a lower price per million tokens but its tokenizer splits your code into more pieces, it can cost more for the same file.
To compare fairly, convert both to a common unit such as cost per 1,000 characters of your actual content.
def cost_per_1k_chars(price_per_million, chars_per_token):
tokens = 1000 / chars_per_token
return tokens * price_per_million / 1_000_000
# Placeholder prices and ratios, not real rates.
a = cost_per_1k_chars(price_per_million=3.0, chars_per_token=4.0)
b = cost_per_1k_chars(price_per_million=2.7, chars_per_token=3.2)
print(f"{a:.6f}") # 0.000750
print(f"{b:.6f}") # 0.000844Model B has the lower sticker price, yet it is about 12% more expensive on this content. The gap here is small, but it can go either way. Tokenizer efficiency is one input to model choice, and later chapters add capability, latency, and success rate.
Common errors
- Treating tokens as words. A token is often less than a word, and code has many tokens per visible "word".
- Using one tokenizer to budget for another model. A count from a library built for a different model gives the wrong number. Treat it as a rough guide only.
- Forgetting hidden input. The system prompt, tool schemas, and role markers all count. A request with a short user message can still carry thousands of tokens.
- Ignoring output tokens. Output is counted and billed separately, usually at a higher rate. The next chapters cover this.
- Assuming a stable count across model versions. A new model version may ship a new tokenizer. Re-measure after you upgrade, because the same prompt can cost more or less than before.
- Trusting estimates for limits. If you are near a context limit, use the real counter. A 10% estimation error can decide whether a request fits.
Edge cases worth knowing
- Tokenization is not additive. The count for
A + Bcan differ from count(A) plus count(B), because merges can happen across the boundary. Budget with a small margin when you assemble prompts from parts. - Non-text inputs. Images and documents are converted to tokens by provider-specific rules, not by a tokenizer over characters. Check the provider's documentation for the formula.
- Unusual strings. Base64 blobs, minified code, long hashes, and random identifiers tokenize poorly. A 10 KB base64 string can cost far more than 10 KB of prose.
- Special-token text. Some tokenizers treat strings that look like control tokens specially. Pasting such text into a prompt can behave unexpectedly, depending on the library settings.
Summary
A token is a vocabulary chunk defined by a model's tokenizer, so counts belong to a model, not to the text. Code, JSON, numbers, and non-English text usually need more tokens per character than English prose. The provider's reported usage is the authoritative figure, and character-based estimates are for rough planning. When you compare models, convert to cost on your own content before trusting the price per million tokens.
Exercise
A model quotes 3.0 USD per million input tokens and its tokenizer averages 3.0 characters per token on your code. A second model quotes 2.4 USD per million input tokens and averages 2.4 characters per token on the same code. Which is cheaper for 1,000 characters of input, and by how much per 1,000 characters? Then name one reason the figure you computed could still be wrong for your real workload.
Show answer
The first model uses 1000 / 3.0 = 333.3 tokens, costing 333.3 3.0 / 1,000,000 = 0.001000 USD. The second uses 1000 / 2.4 = 416.7 tokens, costing 416.7 2.4 / 1,000,000 = 0.001000 USD. They cost the same, even though the second looks 20% cheaper per token. The figure could be wrong because the characters-per-token ratios are averages for one sample. Your real prompts also include system prompt text, tool schemas, role markers, and JSON tool output, which tokenize at different ratios. The fix is to measure with the usage field from real requests.
Exercise
You log the characters sent and the input_tokens reported for five requests: (4,500 chars, 1,500 tokens), (6,000, 2,000), (3,000, 1,200), (9,000, 3,000), (1,500, 600). Compute the overall characters-per-token ratio for the five requests. Then estimate the input tokens for a new 12,000-character request of similar content.
Show answer
Total characters are 4,500 + 6,000 + 3,000 + 9,000 + 1,500 = 24,000. Total tokens are 1,500 + 2,000 + 1,200 + 3,000 + 600 = 8,300. The overall ratio is 24,000 / 8,300, which is about 2.89 characters per token. A 12,000-character request is about 12,000 / 2.89, which is about 4,150 tokens. Pooling totals is better than averaging the five individual ratios because it weights larger requests more heavily. The estimate is still approximate. Confirm it with the provider's counter or the usage field.