Understanding LLM Token Counting: Principles and Practical Cost Control
This article explains how large language models count tokens and why token usage—not characters or bytes—is the basis for billing and rate limits. It covers the input-plus-output structure of total consumption, how tokens map to characters, bytes, and words across English and Chinese, and the key factors that change token counts, such as the tokenizer, language, context accumulation, and output length. It then outlines engineering practices for estimation and governance, including local measurement baselines, tiered quotas, input compression, output constraints, caching, asynchronous batching, and elastic capacity, along with common misconceptions and a verification checklist.
1. Why You Must Understand Tokens Before Talking About Cost
When you call a large language model, the basic unit for billing and rate limiting is not a “character” or a “word,” but a token. A token is the smallest semantic fragment the model processes, which may be a complete word, an affix, a punctuation mark, or even a single Chinese character. Understanding how tokens are counted is a prerequisite for budgeting, capacity planning, and cost control.
First, it is important to clarify a commonly overlooked fact: the token consumption of a single call consists of two parts.
- Input tokens: the prompts, system instructions, conversation history, and retrieved context you send to the model.
- Output tokens: the text the model generates and returns to you.
The total consumption is the sum of the two. For example, if the input takes 100 tokens and the model generates 200 tokens, the call consumes 300 tokens in total. This “input + output” structure means that the two main lines of cost optimization must be pursued together: compress the input and constrain the output.
2. How Tokens Map to Characters, Bytes, and Words
There is no fixed one-to-one conversion between tokens and characters; the mapping is determined by the tokenizer’s algorithm and vocabulary. Mainstream approaches in the industry mostly adopt subword segmentation, a compromise between “whole words” and “single characters”: common words become a single token, while rare words are split into smaller fragments.
A few general rules of thumb are useful:
- English text: on average, about 4 characters correspond to 1 token, and a token often contains a complete word or affix.
- Chinese text: a Chinese character usually consumes about 1 token; some rare characters or combinations may be split, but overall it is close to “1 character ≈ 1 token.”
- Punctuation, whitespace, line breaks, and code symbols also count as tokens, and consecutive spaces are often merged.
- The difference at the byte level is even larger: a Chinese character occupies 3 bytes under common encodings but counts as only about 1 token, so “estimating by bytes” significantly overestimates.
The following pseudocode illustrates the logic for calculating the “total”:
# For logic illustration only; does not represent any specific APIprompt_tokens = count_tokens(system_prompt) + count_tokens(user_input) + count_tokens(context)completion_tokens = count_tokens(model_output)total_tokens = prompt_tokens + completion_tokens# Cost and rate limiting are usually constrained by both total_tokens and the context window
3. Key Factors That Affect Token Count
- Tokenizer and vocabulary: different models have different segmentation granularity, so the same text yields different token counts under different models. Always re-measure when migrating across models.
- Language and domain: Chinese, code, JSON, regular expressions, chemical formulas, and mixed multilingual text all change the segmentation; brackets and quotes in structured data add extra tokens.
- Context accumulation: multi-turn conversations keep bringing historical messages into the input, and tokens grow roughly linearly with the number of turns, so long sessions especially need a trimming strategy.
- Output length constraints: generation length directly determines output tokens, and setting a reasonable maximum output length is the most direct cost gate.
- Hidden overhead: system instructions, tool definitions, template boilerplate, and repeated examples all consume input tokens but are often ignored in budgeting.
4. Estimation and Governance Methods for Engineering Implementation
- Build a local measurement baseline: integrate general token-counting capability on the application side, measure prompt templates and corpora offline, and form an “average token profile per request type.”
- Tiered budgeting: set input/output token quotas for different business scenarios, push cost metrics down to the API level, and combine logging services with monitoring and alerting to form an observable closed loop.
- Input compression: streamline system instructions, deduplicate examples, and rerank and truncate retrieved material to keep only highly relevant information.
- Output constraints: specify a maximum output length, require structured short answers, and avoid meaningless repetition and stacked disclaimers.
- Caching and reuse: cache results for high-frequency, stable requests, using a cache service or object storage to hold intermediate artifacts and reduce repeated generation.
- Asynchronous and batch processing: use asynchronous queues and message queues to smooth peaks for latency-insensitive tasks and improve resource utilization.
- Elastic capacity: model services typically run on container platforms; combine elastic scaling with quota management to avoid rate-limit failures caused by sudden traffic spikes.
5. Common Misconceptions and a Verification Checklist
- Misconception 1: estimating cost directly from character or byte counts. The correct approach is to use tokens as the standard, with characters serving only as a rough reference.
- Misconception 2: optimizing only the input while ignoring the output. Output tokens are also billed, and long outputs have a greater impact on latency.
- Misconception 3: assuming tokens are identical across models. After switching models, re-measure and run regression tests.
- Misconception 4: ignoring multi-turn history expansion. Set a history window and a summarization/compression mechanism.
Checklist: Have you counted input and output separately? Have you set quotas for each request type? Have you trimmed and summarized the context? Have you configured a maximum output length? Have you established a complete chain of measurement, logging, monitoring, and alerting?
6. Conclusion
The core of token counting comes down to one sentence: the total equals the sum of input and output, and the mapping between the two and characters is determined by the tokenizer and varies with language and content type. Turning this mechanism into engineering practice means building a measurement baseline, tiered quotas, input compression, output constraints, and an observability system on the application side, so that cost stays controllable while quality is preserved. For teams that need unified governance and elastic scaling, a complete token cost governance solution can be built on the general cloud capabilities offered by Baidu AI Cloud (such as container platforms, logging services, monitoring and alerting, object storage, and message queues).
