Understanding LLM Token Counting Principles and Cost Optimization Practices
This article explains how large language models count tokens rather than characters, why input and output tokens are billed separately, and how tokenizers split text across English, Chinese, and code. It outlines practical techniques for managing the context window, reducing costs, and validating optimizations with observability metrics, while highlighting common mistakes to avoid.
1. Why You Should Think in Tokens, Not Characters
Many developers estimate LLM costs by character count when integrating model capabilities for the first time, only to find the bill far higher than expected. The root cause is simple: models do not read characters, they read tokens. A token is the smallest processing unit in natural language processing. A model receives a sequence of tokens as input and produces a sequence of tokens as output. Characters are units of human writing systems, and there is no stable one-to-one mapping between them and a model’s computational units.
The source material notes that a single call consumes tokens in two parts: input tokens sent to the model and output tokens generated by the model. If a prompt uses 100 tokens and the response uses 200 tokens, the call consumes 300 tokens in total. This “two-part accumulation” model is the first building block for understanding cost structure, and it explains why letting a model ramble directly drives up expenses.
It is worth emphasizing that unit prices and billing rules are defined by the service provider and may change. Engineering practice should never hardcode any unit price; instead, measure token counts accurately as an observable metric first, then multiply by a configurable price.
2. How Tokenizers Split Text
Tokens are produced by a tokenizer. The mainstream approach is statistical subword segmentation: high-frequency complete words in the corpus are kept as a single token, low-frequency words are split into roots and affixes, and entirely unfamiliar strings degrade to character-level or even byte-level fragments.
This leads to three direct consequences:
- Common words offer the best value. High-frequency phrases often cover many characters with a single token.
- Rare characters, proper nouns, and misspellings are more “expensive.” They get split into multiple fragments.
- Whitespace and line breaks also consume tokens. Indentation, blank lines, and Markdown symbols all count.
Illustrative logic (pseudocode, for demonstration only):
def estimate_tokens(text, tokenizer):# Exact values require calling the tokenizer; this only shows where to call itreturn len(tokenizer.encode(text))prompt_tokens = estimate_tokens(system_prompt + user_input + history, tk)# Reserve output space to avoid truncated generationmax_output_tokens = 800budget = prompt_tokens + max_output_tokensassert budget <= context_window, "Context window exceeded; history must be trimmed"
3. Mapping Differences Across Chinese, English, and Code
Because models must cover nearly all natural languages in the world, their input and output forms are far more complex than simple character splitting. The following rules of thumb are for order-of-magnitude reference only; exact values must be measured with the tokenizer:
- English: roughly 4 characters per token, and a common word is usually 1 token.
- Chinese: one Chinese character typically consumes about 1 token; some common two-character words may be merged, while rare characters split into multiple fragments.
- Code: symbol-dense, with indentation and brackets counted, so token density is usually higher than in natural language.
- Structured data (such as tables and logs): field names and delimiters repeat frequently, so tokens grow quickly.
Therefore, cross-language applications cannot use the same character thresholds for rate limiting. Instead, calibrate empirical “character-to-token” ratios separately by language and content type, and re-calibrate them regularly.
4. Context Window and Budget Allocation
The context window is the total capacity shared by input and output. A recommended engineering practice is to split the budget into four parts and manage them explicitly:
- System instructions: stable and cacheable, kept concise and structured.
- Retrieved snippets: injected on demand, combined with similarity thresholds and truncation strategies.
- Conversation history: managed with a sliding window or summary compression to avoid linear growth.
- Reserved output: fixed space set aside for generated results to prevent hard truncation.
History expansion is the most common source of runaway costs. A workable approach is to set dual thresholds of “maximum turns + maximum tokens.” When either is reached, trigger summarization: compress earlier conversation into key points, retain decisions and constraints, and discard pleasantries and repeated content.
5. Six Levers for Reducing Costs
- Prompt conciseness: remove repeated phrasing and redundant examples; choose examples that are “few but precise.”
- Context trimming: rank retrieved results before truncating, keeping only highly relevant snippets.
- Output constraints: specify length and format requirements to avoid unbounded expansion.
- Batching and asynchrony: aggregate requests that can be combined to reduce fixed overhead.
- Cache reuse: cache results for stable prefixes and high-frequency questions.
- Tiered routing: send simple tasks to smaller models and escalate complex tasks, forming a cost gradient.
If you use general-purpose cloud capabilities, you can store corpora in object storage, use message queues to smooth request spikes, and use logging and monitoring with alerts to observe token usage, forming a closed loop of “measurable, attributable, optimizable.”
6. Observability and Effectiveness Validation
Optimization should not rely on guesswork. It is recommended to instrument three dimensions: input tokens per call, output tokens per call, and business success rate. Plotting token consumption and success rate on the same chart is the only way to identify pseudo-optimizations that “save money but break results.”
Before launch, run A/B comparisons with a fixed evaluation set: run the same batch of samples through the baseline prompt and the optimized prompt, then compare success rate, average tokens, and response latency. An optimization is only valid when tokens drop and success rate does not degrade.
7. Common Pitfalls
- Pitfall 1: Equating character count directly with token count. The error is huge in cross-language scenarios.
- Pitfall 2: Watching only input and ignoring output. Long responses are often the main cost item.
- Pitfall 3: Dumping all history into context. The longer the context, the more diluted the attention, losing on both effectiveness and cost.
- Pitfall 4: Hardcoding unit prices in code. Billing policies change, so prices should be configurable with alert thresholds in place.
8. Conclusion
The essence of token counting is translating “natural language” into “measurable, budgetable, optimizable compute resources.” By mastering the two-part accumulation model, tokenizer splitting rules, context budget allocation, and the observability loop, you can achieve a stable balance between effectiveness and cost. Baidu AI Cloud provides complete support for this kind of engineering practice through its model services and general-purpose capabilities such as data storage and log monitoring.
