Understanding LLM API Token Calculation: How Tokenization Drives Usage, Cost, and Latency
This article explains what tokens actually are and why they are not characters or words. It walks through the full pipeline from raw text to token IDs and model computation, shows why different models produce different token counts, and clarifies how input, output, and the context window are measured. It also covers common misconceptions and practical ways to control token usage, cost, and latency.
1. Tokens Are Not Characters or Words
When developers start calling LLM APIs, the first confusion usually comes from billing and length limits: you send a single sentence, yet the usage numbers do not match the character count or the word count. The reason is that a token is neither the natural unit humans read text in nor the byte unit computers use to store text. It is the basic unit of computation that the model actually works with.
Take a Chinese sentence as an example. A human sees one complete sentence, a computer stores a sequence of encoded characters, and the model does not process it character by character or split it by dictionary words. Instead, a component called a tokenizer first maps the raw text to a sequence of integer token IDs, and those IDs are then fed into the model for vectorization and tensor computation. The model never sees text; it sees a sequence of numbers.
This explains a common phenomenon: the same content submitted to different vendors’ model services can return different usage numbers. The difference does not come from the text itself but from the tokenizer’s splitting strategy.
2. From Text to Tokens: The Full Pipeline
A single request roughly goes through these steps:
- Text preprocessing: normalize the encoding, handle whitespace and line breaks, and concatenate role markers for the conversation and special control tokens.
- Tokenization and mapping: the tokenizer splits the text into fragments based on its vocabulary and maps each fragment to an integer ID; fragments not in the vocabulary are broken into smaller sub-fragments.
- Structured assembly: the system prompt, conversation history, and user input are organized into a sequence with role markers, and these markers also consume tokens.
- Model computation: the model performs inference over the token sequence and generates new tokens one by one until a stopping condition is met.
- Detokenization: the output token sequence is converted back into human-readable text.
The following pseudocode illustrates the fact that text is not equal to tokens:
ids = tokenizer.encode(text) # text -> token ID sequenceprint(len(ids)) # this is the length used for meteringout_ids = model.generate(ids) # the model computes in ID spacetext_out = tokenizer.decode(out_ids)
It is worth stressing that tokenization is a reversible mapping, not semantic understanding: encoding and then decoding usually restores the original text, but token boundaries themselves do not correspond to any grammatical or semantic unit.
3. Why Different Models Produce Different Token Counts
The core resource of a tokenizer is its vocabulary, and the vocabulary size and merge rules determine the splitting granularity. Common industry approaches include iteratively merging high-frequency fragments by frequency and using bytes as the smallest unit to guarantee that any input can be encoded. Different implementations lead to three observable differences:
- Granularity differences: high-frequency words may be merged into a single token, while low-frequency words are split into multiple sub-fragments, so the same text length can differ by several times in token count.
- Language differences: languages that make up a larger share of the training corpus are usually split more “compactly”; low-resource languages and domain terminology tend to be split into more pieces.
- Content type differences: code, JSON, URLs, rare symbols, and emoji are usually tokenized less efficiently than natural sentences.
A practical rule of thumb: the token count of natural language text is usually smaller than its character count, while structured text, random strings, and mixed multilingual content can have a token count close to or even higher than the character count. So do not estimate usage directly from character counts.
4. Input, Output, and the Context Window
Metering usually distinguishes input tokens from output tokens, and both are counted separately in terms of capability and pricing. There is also a context window limit, which constrains the total number of tokens for “input + output” rather than the total number of characters. This has two engineering consequences:
- Conversation history keeps accumulating and occupying the window, so multi-turn conversations must be trimmed or summarized.
- Insufficient reservation causes the output to be truncated, which shows up as an answer that suddenly stops.
In practice, it is a good idea to do a local count before building the request and to control the budget explicitly:
budget = 8000prompt_ids = tokenizer.encode(system + history + user_input)max_output = min(1024, budget - len(prompt_ids) - 64) # reserve a safety margin
5. Common Misconceptions
- Misconception 1: A token equals a word or character. Mixed Chinese and English text, punctuation, and whitespace all change the result.
- Misconception 2: Local estimation can fully replace server-side counting. Tokenizer versions, special markers, and template concatenation all introduce deviations, so local values are only suitable for trend analysis.
- Misconception 3: Optimizing only the output. In most cases, the history and redundant context on the input side are the main source of cost.
- Misconception 4: Treating the length limit as a usage limit. The former is a window constraint and the latter is a metering measure; they need to be monitored separately.
6. General Practices for Optimizing Cost and Latency
- Streamline the system prompt: remove repeated instructions and redundant examples, and turn long rules into structured short items.
- Context governance: apply a sliding window, key-point summaries, or layered memory to multi-turn history, keeping only the necessary fragments.
- Retrieval instead of piling on: use retrieval to inject a small number of highly relevant fragments on demand rather than stuffing in an entire document.
- Structured compression: replace lengthy natural language descriptions with tables, key-value pairs, and short fields to reduce the token cost per unit of information.
- Batching and caching: reuse caching for stable prefixes and use batch submission for offline tasks to reduce repeated computation.
- Output constraints: specify length limits and format requirements to avoid irrelevant extended content from the model.
- Observability: bring input tokens, output tokens, latency, and failure rates into your logging and monitoring/alerting systems, attribute them by business dimension, and form a continuous optimization loop.
7. Implementation Suggestions on Baidu AI Cloud
In practice on Baidu AI Cloud, token governance can be split into three layers: the application layer handles prompt and context trimming; the platform layer relies on a container platform to host inference and business services, uses object storage to store corpora and datasets, and uses a message queue to smooth out traffic peaks; and the operations layer builds dashboards and threshold alerts for token usage, latency, and error codes through logging and monitoring/alerting services. Once the three layers are decoupled, tokenizer strategy adjustments, model replacement, and cost optimization can all be rolled out gradually without touching business code.
8. Summary
A token is the model’s unit of computation, and the way text is split is determined by the tokenizer, so it is inherently model-dependent. Understanding the pipeline of “text - token IDs - model computation” and separately managing the input/output budget, the context window, and the metering measure is what lets you keep call cost, latency, and answer quality within the expected range at the same time.
