How LLM API Tokens Are Actually Counted
This article explains what tokens really are in large language model APIs and why they are not characters or words. It covers how tokenizers such as BPE split text, why Chinese and English produce different token counts, and how to measure token usage accurately. It also outlines the impact of tokens on context windows, cost, latency, and output stability, along with practical strategies for reducing token consumption and clearing up common misconceptions.
How LLM API Tokens Are Actually Counted
1. Why a Token Is Not a Character or a Word
Developers who are new to LLM APIs often assume that a token means a “character count” or a “word count.” This intuition is especially misleading in Chinese-language scenarios: a sentence may look like a dozen characters on screen and a sequence of encoded bytes in a database, but on the model side it is split into a variable number of processing units.
A more accurate definition is: a token is the basic unit the model uses to process text, and the smallest semantic fragment produced when a tokenizer splits input text according to a given vocabulary. It is neither a character count nor a word count, but the result of a vocabulary match.
Take a Chinese sentence as an example: “今天天气不错,适合出去走走。” Humans see a complete sentence, a program sees a sequence of Unicode code points, and the model sees a sequence of token IDs. The model does not scan the text character by character. Instead, it first maps the text to a sequence of IDs and then runs the rest of the computation. That mapping step is what truly determines the token count.
This leads to a key conclusion: the number of tokens is not an inherent property of the text, but a result determined jointly by the “text + tokenizer.” The same passage may produce different token counts under different models, and the same model may produce different results under different vocabulary versions.
2. How Tokenizers Split Text: BPE-Style Algorithms as an Example
A common family of approaches in the industry is BPE (Byte Pair Encoding) and its variants. The core idea can be summarized as “start fine-grained, then merge according to the vocabulary”:
- In the initial stage, split the text into fine-grained units (characters or bytes).
- Repeatedly merge high-frequency adjacent combinations identified during training into larger fragments.
- Once the vocabulary is fixed, apply the same rules during inference to greedily split the input.
The following illustrative code only conveys the idea and does not represent any specific product API:
# Pseudocode: illustrating the intuition of "splitting by vocabulary"vocab = {"Hello": 1, " world": 2, "!": 3, "今天": 4, "天气": 5}def tokenize(text):tokens, i = [], 0while i < len(text):# Try to match a longer fragment from the vocabulary at the current positionfor length in range(len(text) - i, 0, -1):piece = text[i:i+length]if piece in vocab:tokens.append(vocab[piece])i += lengthbreakelse:raise ValueError("No vocabulary match")return tokens
This pseudocode highlights two details that are often overlooked:
- Spaces participate in splitting. In many tokenizers, the space before a word is merged with the word itself into a single token, so “world” and “ world” may be two different tokens.
- Punctuation and symbols are likely to become standalone tokens. Exclamation marks, commas, and newline characters often each occupy one token.
As a result, “Hello world!” may be split into three tokens under some tokenizers: Hello, world, and !. With a different vocabulary, the result may be two or four tokens. This shows that the splitting method depends on the vocabulary, and the vocabulary depends on the model.
3. Why Chinese and English Differ Significantly
Chinese has no natural space boundaries, so tokenizers rely more heavily on the vocabulary and merge rules. A common outcome is that “common words are merged, while rare characters are split apart.” English uses spaces as strong boundaries, but the spaces themselves may be absorbed into tokens. The token density of the two languages therefore differs:
- Common two-character Chinese words and four-character idioms may each occupy one token.
- Rare characters, proper nouns, and number strings may be split into multiple tokens.
- Long English words that miss the vocabulary may be split into several subword fragments.
- Structured text such as code, JSON, and URLs is symbol-dense, and its token count is often higher than intuition suggests.
The practical engineering rule is: do not extrapolate token counts linearly from character counts. Instead, rely on actual tokenization results and leave a safety margin.
4. How to Count Tokens Accurately
There are three reliable layers:
- Prefer the official counting or tokenization tools. Most platforms provide a token-counting API or a local tokenizer library, and the results are closest to actual billing.
- Use offline approximate estimation. When there is no network access or when doing capacity planning, a general-purpose tokenizer library can provide an approximation, which can then be corrected using a historical deviation factor.
- Build a local baseline. Run batch statistics on high-frequency prompt templates to create a “template -> token range” reference table for cost forecasting and rate-limit configuration.
Illustrative call logic:
# Pseudocode: counting the tokens in a piece of textdef count_tokens(client, text):# client is a wrapper around the platform's counting capabilityreturn client.count_tokens(text)
It is important to emphasize: counting results from different models and different versions must not be mixed. Applying the statistics from model A directly to model B is a common cause of inaccurate cost estimation.
5. Four Impacts of Tokens on Engineering Practice
5.1 Context Window
Input and output share the same window budget. System prompts, conversation history, retrieved fragments, and user input all consume tokens. Without trimming, long conversations quickly hit the limit.
5.2 Cost Control
Billing usually measures input and output tokens separately. The output side often has a higher unit price, so “making the model write less filler” is just as important as “making the input more compact.”
5.3 Latency and Throughput
More tokens mean longer prefill and decoding time. In batch tasks, compressing the input can significantly increase the amount processed per unit of time.
5.4 Output Stability
Improper truncation can break semantic completeness and lead to irrelevant answers. Trimming strategies should aim to “preserve key information” rather than mechanically cutting off the tail.
6. Practical Strategies for Optimizing Token Usage
- Streamline system prompts: remove repeated constraints, merge synonymous requirements, and avoid piling up lengthy background.
- Compress retrieved fragments: rerank and deduplicate first, keeping only the passages strongly related to the question.
- Control history length: use a sliding window or summary-based memory instead of concatenating everything.
- Constrain structured output: use concise schema descriptions instead of lengthy examples to reduce output tokens.
- Batch processing and caching: cache and reuse repeated prefixes to reduce repeated computation.
- Monitoring and alerting: incorporate token usage into logging and monitoring/alerting systems, set threshold alerts, and avoid abnormal amplification.
7. Clearing Up Common Misconceptions
- Misconception 1: 1 token = 1 Chinese character. Not true. Common words may be merged, and rare characters may be split.
- Misconception 2: 1 token = 1 English word. Not true. Spaces and subword splitting both change the result.
- Misconception 3: The token count is fixed. Not true. It changes with the model and vocabulary version.
- Misconception 4: Character counts can be linearly converted to tokens. Not true. They can only serve as a rough lower-bound reference for capacity.
8. Conclusion
The essence of a token is “the result of splitting text under a fixed vocabulary.” Understanding this explains why the same passage yields different counts under different models, and why spaces, punctuation, and line breaks all affect the count. For developers, the right approach is not to memorize conversion formulas, but to rely on actual tokenization results, build a local statistics baseline, and incorporate tokens into a unified framework for cost, latency, and context management. In practice on platforms such as Baidu AI Cloud, combining token counting with logging, monitoring, and rate limiting is a foundational engineering capability for keeping LLM applications stable and controllable.
