Token Counting in LLM APIs: Principles and Practical Strategies
Learn how tokenizers convert text into model inputs, why token counts differ across models, and what contributes to API usage. This article explains how to budget complete requests, reserve output capacity, validate estimates against actual usage, and reduce token consumption without losing essential information.
Token Counting in LLM APIs: Principles and Practical Strategies
When calling a large language model (LLM) API, developers regularly encounter terms such as token usage, context window, and maximum output tokens. Tokens are more than billing units: they are the discrete units a model uses to process text.
Understanding how tokens are produced and counted—and why the same text can yield different counts across models—is fundamental to reliable API integration, cost control, and context management.
1. What Is a Token?
People read natural language, while computers store characters or bytes. Models generally do not process that text character by character. Instead, a tokenizer converts the text into tokens, which are mapped to token IDs before entering the model.
A token is a discrete unit in the model’s vocabulary. It may represent:
- A complete word.
- Part of a word.
- A common Chinese character or a combination of characters.
- A punctuation mark.
- Whitespace or indentation.
- A numeric fragment.
- A special marker.
- A sequence of bytes representing text in a particular language.
For example, consider this sentence:
The weather is nice today, so it is a good time for a walk.
A conceptual token sequence might look like this:
[The] [ weather] [ is] [ nice] [ today] [,] [ so] [ it] [ is][ a] [ good] [ time] [ for] [ a] [ walk] [.]
This is only an illustration. Actual segmentation depends entirely on the target model’s tokenizer, vocabulary, and tokenization rules. It cannot be used to infer another model’s token count.
Formally, if a model’s tokenizer is T and the input text is s:
tokens = T.encode(s) = [t1, t2, ..., tn]ids = [id(t1), id(t2), ..., id(tn)]token_count = n
The model receives ids. An embedding layer converts each token ID into a vector for subsequent computation. During generation, the model also produces tokens one at a time, which are then decoded into text.
Token counts therefore affect context length, generation steps, response latency, and cost.
2. From Raw Text to Token IDs
Text typically passes through the following stages before reaching a model. The exact pipeline varies by tokenizer.
Text Normalization
A tokenizer may normalize text by adjusting whitespace, handling full-width and half-width characters, processing letter case, or retaining or combining certain control characters.
Normalization policies differ across models. Some tokenizers preserve finer distinctions between special symbols.
Preliminary Segmentation
The tokenizer may initially separate text based on spaces, punctuation, language boundaries, or character categories.
This is not necessarily the final tokenization result. These units may subsequently be merged or split.
Subword Segmentation and Vocabulary Matching
Modern LLMs commonly use subword-level or byte-level approaches. Frequent text fragments enter the vocabulary as individual tokens. Rare words, uncommon characters, complex identifiers, and long numeric strings are split into smaller pieces.
This approach limits vocabulary size while supporting broad text coverage.
Byte Fallback
When a character or combination is not represented in the vocabulary, a tokenizer may fall back to smaller byte-level or basic character representations.
This helps support arbitrary text, but token counts can increase substantially. Uncommon characters, complex emoji, special symbols, and mixed-language identifiers may require several tokens.
Mapping to Token IDs
Each token has a corresponding vocabulary ID. Special markers may also have their own IDs, including markers for conversation roles, message boundaries, tool descriptions, or sequence endings.
These markers may not appear in user-visible text, yet they can consume tokens when the request is serialized using the model’s template.
Applying the Conversation Template
An LLM API request usually contains more than the current user message. It may include system instructions, conversation history, role information, tool definitions, and structured output requirements.
The service serializes these components according to the model’s conversation template. As a result, reported token usage may include template overhead that users do not directly see.
Counting only the user’s text is therefore often inaccurate. The relevant quantity is the sequence length produced from the complete request, including any template content added by the service. The API’s usage reporting and billing documentation determine the applicable accounting rules.
3. Why Token Counts Differ Across Models
There is no universal conversion between text length and token count. Several factors explain why the same text can produce different counts:
- Different vocabularies: Models differ in vocabulary size, included fragments, and language distribution.
- Different merge rules: Training and tokenization rules determine which fragments become tokens and which combinations are merged first.
- Different language coverage: Models trained on different data distributions may tokenize Chinese, English, code, numbers, and symbols with different efficiency.
- Different normalization policies: Whitespace, case, character width, and control characters may be handled differently.
- Different special markers: Conversation templates, role markers, tool-call markers, and safety-related markers may differ.
- Different model versions: Versions of the same named model may use different tokenizers or request templates.
A character-to-token ratio measured for one model should not be applied to another. Nor should developers assume that one Chinese character or one English word always equals one token.
The practical rule is simple: estimate tokens using the target model’s published tokenizer or counting capability. If the platform provides token counting or usage reporting, use the complete request and treat the service’s reported results as authoritative for its accounting.
Cost-sensitive applications should also recalibrate estimates regularly using representative production content.
4. What Contributes to Token Usage?
Chinese, English, and Multilingual Text
Chinese text may be segmented into individual characters, words, or combinations spanning multiple characters. English words may remain whole or be split into roots, affixes, or other subword fragments.
Common expressions are more likely to match frequent vocabulary entries. Rare terms, proper nouns, and mixed-language text may be split more finely. Punctuation handling and whitespace retention also affect counts.
Code and Structured Data
Indentation, line breaks, brackets, operators, variable names, comments, JSON quotation marks, and colons can all consume tokens.
A long, uncommon variable name may require multiple tokens. Pretty-printed JSON improves readability, but keys, indentation, and repeated fields still use context capacity.
Redundant fields and repeated explanations can be removed where doing so preserves meaning and parsing requirements. Token reduction should never make the data invalid.
Numbers, URLs, Hashes, and Identifiers
Long numeric strings, random IDs, hashes, complex URLs, and email addresses often lack the frequent patterns found in natural language. They may therefore split into many fragments.
Applications that must include such content should use conservative budgets rather than estimates based on ordinary prose.
Emoji and Special Characters
An emoji may contain multiple Unicode code points, and tokenizers handle these sequences differently. A single visible emoji can consume multiple tokens.
Control characters, bidirectional text characters, and uncommon scripts may also trigger finer-grained encoding. Character-based estimates are especially unreliable for these inputs.
Conversation History and Message Templates
In multi-turn conversations, each request typically includes system instructions, earlier messages, the current user input, and necessary tool definitions. Longer histories increase input token counts.
Some platforms offer context caching or related optimizations. Their effect on context occupancy and billing must be checked in the relevant API documentation.
Tool Definitions and Structured Output Requirements
Tool descriptions, parameter schemas, and output format requirements may become part of the prompt. More complex tools and longer descriptions generally consume more tokens.
How tool definitions are processed and billed on each request depends on the platform.
Output Tokens
Both input and output need to be budgeted. Generating long prose, code, tables, or JSON increases output usage.
Streaming changes how responses are delivered and displayed; it does not eliminate token consumption. If generation reaches its output limit, the response may be truncated, leaving structured output incomplete.
5. Context Windows, Output Limits, and Token Budgets
A context window generally describes the token capacity available for a model call. A maximum output token setting limits generation length.
The relationship between these limits varies by API, so consult the target service’s documentation. A conservative planning model is:
context_window >= system_instructions + conversation_history + user_input+ tool_definitions + retrieved_content + format_template+ reserved_output + safety_margin
This can be simplified to:
prompt_budget = context_window - reserved_output - safety_margin
The safety_margin accommodates template overhead, tool-description overhead, encoding differences, and version changes.
For multi-turn applications, budget management can follow this pseudocode:
function prepare_request(system, history, user, tools, context_window, max_output, margin):request = build_chat_request(system, history, user, tools)prompt_tokens = count_tokens(target_model, request)budget = context_window - max_output - marginwhile prompt_tokens > budget and history is not empty:history = summarize_or_remove_oldest(history)request = build_chat_request(system, history, user, tools)prompt_tokens = count_tokens(target_model, request)if prompt_tokens > budget:user = compress_input(user)request = build_chat_request(system, history, user, tools)prompt_tokens = count_tokens(target_model, request)if prompt_tokens > budget:return error_or_split_task()return request, prompt_tokens, max_output
The important principles are:
- Calculate the budget from the complete request.
- Reduce low-value history first.
- Preserve system constraints, essential task information, and required output formatting.
- Split or summarize inputs that cannot fit, rather than silently truncating them and losing meaning.
6. Token Estimation and Operational Management
Use the Target Model’s Counting Capability
The most reliable approach is to use the target model’s tokenizer or the platform’s token-counting service.
If a preflight counting API is available, count the complete request in the form required by the service—not just the user text. For offline estimates, verify that the tokenizer version matches the deployed model.
Count the Complete Request
Include system prompts, history, user input, tool definitions, retrieved passages, formatting constraints, and applicable template overhead.
For a multi-turn application, recalculate the context for every call. Do not simply add the latest message count to the previous request total.
Record Actual Usage
Many LLM APIs return usage information. Record reported input and output usage, retain full-request estimates, and compare them.
Build separate calibration samples for content types such as Chinese question answering, English documentation, code generation, JSON output, and long-document summarization. Their token characteristics can differ substantially.
Allocate Budgets by Content Type
Assign limits to system prompts, retrieved context, conversation history, and reserved output. Per-component budgets help prevent one part of the request from consuming all available context.
Retrieval-augmented generation requires particular care. Rather than inserting every candidate document into the request, filter, deduplicate, and compress the retrieved content first.
Keep a Safety Margin
Local estimates may miss service-side template overhead, and model versions may change. Production systems should retain spare capacity and trigger fallback behavior when thresholds are exceeded.
Possible responses include reducing history, shortening retrieved passages, splitting the task, lowering the output limit, or selecting a workflow better suited to the available context capacity.
7. Practical Ways to Reduce Token Consumption
Simplify Prompts Without Weakening Constraints
Remove repeated instructions, vague background information, and examples unrelated to the current task.
Keep necessary role definitions, output formats, boundary conditions, and acceptance criteria. A small number of representative examples is often preferable to many redundant ones.
Compress Conversation History
Keep recent turns in their original form and summarize older history. Clearly identify summaries as summaries rather than original statements.
Explicitly preserve important entities, user preferences, and unfinished tasks so that compression does not remove essential constraints.
Control Retrieved Context
In retrieval-augmented generation, retrieve candidates, filter them, remove duplicates, rerank them, and then assemble the context within budget.
Keep enough surrounding information to make each passage understandable. Avoid cutting sentences in half. Remove repeated paragraphs, navigation text, and irrelevant metadata.
Optimize Structured Data
Reduce redundant fields and repeated descriptions while preserving application parsing requirements.
Tool definitions should be clear and concise. Output requirements should be explicit without repeating the same instruction in several forms.
Set Appropriate Output Limits
Choose output limits based on the task. Long-form generation can be organized into stages, such as summaries, outlines, and full sections.
Validate structured responses for completeness and syntactic correctness. An output limit should establish a manageable balance between quality, latency, and cost—not force every response into the smallest possible form.
Use Suitable Context Management Features
If the platform offers context caching, batch processing, or other optimizations, review the relevant rules before using them.
These features do not remove the need for context management or capacity planning. Evaluate optimizations on representative samples to identify any loss of quality.
8. Common Misconceptions and a Troubleshooting Checklist
Misconception 1: Character Count Is a Reliable Token Estimate
There is no fixed character-to-token ratio. Chinese, English, code, emoji, numbers, and random strings can behave very differently.
Misconception 2: Splitting on Spaces Gives the Token Count
Models use tokenizers, not simple whitespace-based word splitting. Subword fragments, punctuation, and special markers all affect the result.
Misconception 3: Every Model Counts the Same Text the Same Way
Vocabularies, training data, normalization, and templates differ. Estimates must be tied to the target model and version.
Misconception 4: Only the Current User Message Matters
System instructions, conversation history, tool definitions, retrieved content, and formatting requirements may all occupy context.
Misconception 5: Maximum Output Tokens Means Total Context Capacity
Parameter definitions vary across services. Confirm the relationship between the context window, input limit, and output limit.
Misconception 6: Streaming Reduces Token Usage
Streaming changes response delivery, not the number of generated tokens being measured.
Misconception 7: Structured Syntax Does Not Consume Tokens
Brackets, quotation marks, colons, indentation, and repeated keys can all consume tokens. Large JSON documents and complex code require explicit budgeting.
Troubleshooting Checklist
- Identify the target model, version, and tokenizer rules.
- Serialize the complete request as required by the service.
- Count system instructions, history, user input, tools, retrieved content, and template overhead.
- Reserve capacity for output and unexpected overhead.
- Compare API-reported usage with estimates.
- Compress, summarize, chunk, or apply fallback handling to oversized requests.
- Build regression tests using representative application content.
- Recalibrate budgets after model or template upgrades.
9. Conclusion
Tokens connect text representation, context capacity, model computation, and API cost. They are neither characters nor words: their count is the length of the sequence produced by the target tokenizer’s vocabulary and rules.
Understanding tokenization, hidden conversation-template overhead, and complete-request budgeting helps reduce estimation errors, context overflows, truncated outputs, and uncontrolled spending.
The most reliable engineering approach is to count for the target model, budget the full request, calibrate against actual usage, and make token management part of API operations, cost analysis, and capacity planning. The same principle applies to LLM API workloads on Baidu AI Cloud: token budgets should be a foundational operational metric, not an issue addressed only after deployment.
