A common pattern in LLM application code is to use actual token usage reported by the server when available and count locally with tiktoken when it isn't. Some projects integrate models from several providers and still estimate them all using the same tiktoken encoding.
That raises a question: isn't tiktoken a tokenizer? How did it become a usage estimator, and how reliable are the numbers?
After reading 程序员小jobleap's A quick introduction to tiktoken, OpenAI's efficient text encoding tool, I wanted to go one level deeper: understand how BPE produces tokens, then see where estimation errors actually come from.
A clarification up front: counting tokens is a legitimate use for tiktoken. OpenAI's Cookbook specifically explains how. The point requiring care is treating a count from one encoding as the actual usage for any model or request.
Tokens aren't a character count, and they aren't necessarily words
Before processing text, a model needs a sequence of token IDs. A token may represent a whole word, part of a word, punctuation, a fragment including whitespace, or just some of the bytes in a Unicode character.
So “How many tokens are in this text?” is missing a condition: which tokenizer and which encoding are we using?
We can write it as:
文本 x + 编码规则 E → token ID 序列 → 序列长度 T_E(x)
The subscript E matters. Change the vocabulary, merge rules, or pre-tokenization method and the same text can have a different length. The official tiktoken description calls it a fast BPE tokenizer for OpenAI models and offers several encodings. tiktoken
How BPE turns text into tokens
BPE stands for Byte Pair Encoding. Originally a compression method, it was later applied to subword tokenization. Sennrich, Haddow, and Birch showed how subword units could handle rare words in machine translation: represent a word using smaller units without allocating a separate vocabulary entry for every complete word. Paper
Distinguish learning merge rules from applying them.
During tokenizer training, start with small symbols, count frequencies of adjacent pairs, merge frequent pairs, then count and merge again until a stopping condition such as the target vocabulary size is reached. For new text, apply the learned merge rules in priority order. The tokenizer doesn't retrain for each user input. Hugging Face BPE tutorial
Here's a simplified character-level example. Suppose the training material contains only two words with the following frequencies, and merges cannot cross word boundaries:
low × 5
lower × 2
初始:l o w × 5
l o w e r × 2
Both l o and o w occur 7 times. Suppose the tie goes to l o first:
第 1 条规则:l + o → lo
lo w × 5
lo w e r × 2
Now lo w occurs 7 times and can also be merged:
第 2 条规则:lo + w → low
low × 5
low e r × 2
If training stops here, low is one token under these toy rules and lower is three. Continue training and you might get a different result.
Frequent fragments can thus become larger units, and tokens don't have a fixed length. The “pair” in BPE refers to merging two adjacent existing units at a time. It doesn't mean every resulting token is just two bytes long.
tiktoken uses byte-level BPE
The toy example starts with characters. Byte-level BPE starts with bytes. A Chinese character often occupies several bytes in UTF-8, so character and token boundaries needn't coincide. tiktoken first pre-splits the text according to the encoding's rules, then applies BPE. Hugging Face BPE tutorial, tiktoken encoding implementation
This explains why “one Chinese character equals one token” doesn't hold. Some characters may span several tokens, while common fragments may form one. Spaces, letter case, and punctuation also affect the split.
One detail in the introductory article deserves correction. Its example uses AutoTokenizer.from_pretrained("bert-base-uncased"), but BERT uses WordPiece. It illustrates text being converted into IDs, but isn't a direct example of the BPE algorithm. Hugging Face BERT documentation
Is tiktoken counting or estimating?
Consider this minimal example:
import tiktoken
encoding = tiktoken.encoding_for_model("gpt-4o")
text = "你好,BPE!"
token_ids = encoding.encode_ordinary(text)
print(encoding.name)
print(token_ids)
print(len(token_ids))
There's no character-count guess and no model call. tiktoken actually tokenizes using the selected encoding, then takes the length of the list. encode_ordinary treats the input as ordinary text. Strings resembling special token markers aren't interpreted as protocol controls. Constructing a real model protocol requires handling the corresponding special tokens separately. tiktoken API implementation
In tiktoken 0.9.0's mapping, for example, gpt-4o maps to o200k_base and gpt-4 to cl100k_base. These are model-name mappings maintained by the library. They don't automatically detect what tokenizer a remote model uses. Model mapping source
The distinction between a count and an estimate depends on the question you're answering:
| Question | Meaning of the number |
|---|---|
| How many tokens does this ordinary text produce under a specified encoding? | An exact count for that encoding. |
| If the target model uses that encoding, how many tokens are in this text? | An exact count provided both the text and processing rules match. |
| The other model's tokenizer is unavailable. Can I substitute this encoding? | An approximation for the target model. The error can go in either direction. |
| If I count each chat message body, do I have the whole request's usage? | Message structure, tool definitions, and other overhead may be missing. |
| If I retokenize the visible reply, do I have all output usage? | Not necessarily. It depends on what the server returned and how it accounts for usage. |
OpenAI's documentation distinguishes string counts from API usage: chat formatting adds tokens, and actual call usage comes from the response's usage field. Advanced usage
Saying “tiktoken wasn't made for this, but people use it for token estimates” conflates two issues. It is made for counting. The result becomes an estimate when you go beyond the encoding and text you actually know.
Why a cross-model fallback can still help
Applications often need to decide before sending a request how much retrieved material will fit, whether to trim chat history, and roughly how much budget a task will need. Since the call hasn't happened yet, there's no usage for it.
If the target tokenizer isn't available, a ready-made BPE encoding at least captures more structure than treating all characters as equal. It splits common fragments, spaces, and symbols by its own rules. That makes it an engineering option. Whether it's closer to the target model than a simple ratio needs testing on your own data.
In symbols, the fallback assumes:
目标编码的计数 T_target(x) ≈ 替代编码的计数 T_proxy(x)
BPE supplies a substitute count. It doesn't guarantee that the two counts will be close. Even two BPE tokenizers can have different vocabularies, training material, pre-tokenization rules, and special tokens.
The OpenAI Cookbook shows the same text under different encodings:
| Ordinary text | r50k_base | cl100k_base | o200k_base |
|---|---|---|---|
antidisestablishmentarianism | 5 | 6 | 6 |
2 + 2 = 4 | 5 | 7 | 7 |
These numbers come from the Cookbook's encoding comparison, not a local measurement for this article. A larger vocabulary doesn't mean every input has fewer tokens.
How do character- and byte-count fallbacks relate to BPE?
A lighter approach uses a ratio:
估计 token 数 ≈ 字符数 ÷ 某个经验系数
The intuition behind the common “divide by 4” rule is to estimate how much text a token covers on average. The tiktoken README says a token corresponds to around four bytes on average in practice. That's an average, not a rule for every input, and certainly not “four Chinese characters.” tiktoken README
BPE merges depend on the text and encoding. A fixed divisor compresses that variation into one average. Chinese, code, URLs, random identifiers, Base64, and emoji can all break the average. Measure the size of those deviations rather than assigning a precise ratio because the text “looks more complex.”
Specify the length unit too. Python's len(text) counts Unicode code points. JavaScript string .length counts UTF-16 code units. In Python, len(text.encode("utf-8")) counts UTF-8 bytes. Put different units into the same formula and you get different results.
Can byte length provide a conservative upper bound?
For byte-level BPE that starts with a complete set of individual bytes, only merges, doesn't expand the original text, and inserts no extra tokens, there's a simple derivation:
初始单元数 = UTF-8 字节数
每次合并减少一个单元
所以:普通文本 token 数 ≤ UTF-8 字节数
This algorithmic upper bound is usually loose. For example, "你好" is six UTF-8 bytes. It doesn't necessarily produce six tokens; under those conditions, it cannot produce more than six.
The bound covers only the corresponding ordinary text encoding. It doesn't cover added chat templates, tool definitions, images, or audio, and can't be generalized to any unknown tokenizer. If preprocessing expands the text or the model uses another mechanism, check the assumptions again.
So bytes ÷ 4 is an average-based heuristic; bytes is a conservative bound under specific conditions. They serve different purposes.
An implementation that labels its fallback
The example below handles ordinary text only and deliberately requires the caller to say whether the target encoding is confirmed. It demonstrates application-level fallback logic, not complete chat request billing.
from functools import lru_cache
import tiktoken
@lru_cache(maxsize=None)
def load_encoding(name):
return tiktoken.get_encoding(name)
def count_text(text, *, confirmed_encoding=None):
# confirmed_encoding 必须来自已核实的模型配置,不能靠名称猜测。
if confirmed_encoding is not None:
encoding = load_encoding(confirmed_encoding)
return {
"tokens": len(encoding.encode_ordinary(text)),
"method": "matched_encoding",
"encoding": encoding.name,
"exact_for_text": True,
}
# 无法取得目标编码时,显式采用替代编码。
encoding = load_encoding("cl100k_base")
return {
"tokens": len(encoding.encode_ordinary(text)),
"method": "proxy_encoding",
"encoding": encoding.name,
"exact_for_text": False,
}
print(count_text("你好,BPE!", confirmed_encoding="o200k_base"))
print(count_text("你好,BPE!"))
Here cl100k_base merely demonstrates a substitute encoding. It isn't universally more accurate or more conservative for unknown models. Similarly, exact_for_text means exact only for the caller-confirmed encoding and ordinary-text handling. It doesn't promise exact usage for a complete request.
The example doesn't swallow arbitrary exceptions and dress them up as successful estimates. A misspelled encoding configuration should surface as a configuration problem. To support environments entirely without a tokenizer, add a separate character-ratio or byte-bound path, recording the method and its assumptions.
Prepare the encoding resources as well. tiktoken may download data the first time certain encodings are loaded. Cache them in advance for offline deployments. Cookbook encoding loading notes
Put the fallback in the overall budgeting process
I separate managing context before a call from recording usage afterward:
flowchart TD
A["调用前:需要控制输入长度"] --> B{"目标 tokenizer 可用?"}
B -->|是| C["按目标编码统计普通文本"]
B -->|否| D["替代编码或经校准的长度估算"]
C --> E["计入消息与工具开销,预留输出及误差空间"]
D --> E
E --> F["发起请求"]
F --> G{"返回实际 usage?"}
G -->|是| H["记录服务端用量,检查估算偏差"]
G -->|否| I["保留估计值与估算方法标签"]
For context control, start with this budget relationship:
估计输入 token + 预留输出 token + 误差余量 ≤ 上下文窗口
The input budget should cover the actual system prompt, history, retrieved material, tool definitions, and protocol overhead sent. The reserved output budget must also respect the target model's per-call output limit. Counting only the last user message is insufficient. Tokenizing the whole HTTP JSON payload doesn't necessarily reproduce server formatting either. OpenAI Advanced usage
There's no universally correct fallback margin. Collect real workload samples and compare estimates with actual usage by target model, language, and content type. If your goal is avoiding overruns, pay particular attention to underestimates as well as average error. Recheck when models, prompt templates, or tool definitions change.
Suppose a sample has an estimated 1,000 input tokens for the complete input and actual usage of 1,250. The estimate missed 250 tokens. That might reflect the substitute encoding or omitted message structure. It doesn't immediately establish a universal correction factor of 1.25. First confirm the scope of the counts and examine samples of different types and lengths.
After a call, record input, output, and other provider-supplied usage categories from usage separately. If actual usage is missing, estimates may still reveal trends, but mark them so they won't later be mistaken for exact records. For cost reconciliation, follow the service's pricing and billing definitions.
Understanding BPE makes the boundary clear. tiktoken determines how a particular encoding splits a text. Whether that result tells you about another model or a whole request depends on additional matching conditions and validation. A good fallback preserves those assumptions and the remaining uncertainty.
References
- 程序员小jobleap (2025-04-12). A quick introduction to tiktoken, OpenAI's efficient text encoding tool. The starting question for this article. The BERT example's algorithm is clarified above.
- Sennrich, R., Haddow, B., & Birch, A. (2016). Neural Machine Translation of Rare Words with Subword Units.
- Hugging Face. Byte-Pair Encoding tokenization.
- OpenAI. tiktoken; 0.9.0 model mapping; 0.9.0 encoding interface.
- OpenAI. How to count tokens with Tiktoken.
- Hugging Face. BERT tokenizer documentation.
- OpenAI. Advanced usage.
Filed under April 15, 2025. Sources checked and organized on November 13, 2026. The examples use models and encodings available before the archive date. Online documentation may continue to change. The code is illustrative; no real API calls were made for this article.