Understanding LLM Token Billing and Cost Optimization Practices
This article explains how large language models tokenize text and why token counts, not character or word counts, drive API billing. It covers subword tokenization, the resource differences behind separate input and output pricing, prefix caching as a major billing variable, reusable cost formulas for single and multi-turn requests, six practical cost-optimization levers, and common estimation mistakes, helping readers plan capacity and control spending.
1. What a Token Really Is: The Model’s Smallest Text Unit
A token is the basic unit a large language model uses to process text, and it is also the basic scale cloud providers use to bill for model services. It is not the same as “a character” or “a word.” Instead, it is a fragment produced when a tokenizer splits raw text according to a specific algorithm. A single token may be a complete word, part of a word, a Chinese character, or even a punctuation mark.
This distinction is critical: billing is based not on character count or word count, but on the number of tokens produced after tokenization. As a result, the same passage of Chinese text can yield different token counts under different tokenization schemes, leading to different costs.
1.1 The Basic Logic of Tokenization
Mainstream tokenization schemes are usually based on the subword idea, with common implementations using byte-pair encoding–style merge strategies. The core idea is to start from the smallest character units, then merge high-frequency combinations into single units based on corpus statistics, while keeping low-frequency combinations as finer fragments.
Illustrative example (pseudocode, showing the idea only):
# Illustrates tokenization logic only; not a real APIdef tokenize(text, vocab):tokens = []for piece in split_by_frequency(text, vocab):tokens.append(piece)return tokensprint(len(tokenize("cost optimization practice", vocab))) # Outputs the number of fragments after splitting
This leads to three rules of thumb:
- Common words and high-frequency phrases are often merged into a single token, which is more cost-efficient;
- Rare characters, technical terms, and misspelled English words are more likely to be split into multiple tokens;
- Punctuation, spaces, and line breaks also count as tokens, so formatted text adds extra overhead.
1.2 Differences Between Chinese, English, and Structured Content
In general, English is split on spaces, and a longer word may be broken into several subwords. Chinese has no natural separators between characters, so tokenization results depend heavily on corpus statistics. In structured content such as JSON, code, and tables, large numbers of brackets, quotes, and indentation all turn into tokens, so a configuration snippet that “looks short” may consume more than expected.
2. Why Input and Output Are Priced Separately
LLM inference has two stages with completely different resource profiles, which is the fundamental reason for separate pricing.
- Prefill stage: reads all input tokens at once; computation can be highly parallelized, so the main pressure is on compute throughput;
- Decode stage: generates output tokens one by one, where each step depends on the previous result and is hard to parallelize, so the main pressure is on memory bandwidth and memory access.
The output stage is serial, has low compute utilization, and produces a limited amount per unit time, so its cost is naturally higher than input. The industry therefore commonly uses a dual-track structure of “input price + output price,” with the output price usually several times the input price. This design is not a marketing tactic but a direct reflection of the difference in resource profiles.
3. Cache Hits: The Biggest Variable in Your Bill
To reduce the compute overhead of repeated prefixes, the industry commonly offers prefix caching: when the beginning of a request matches a historical request, the system can reuse the already-computed intermediate results. These input tokens are billed at a significantly lower rate, while the portion that misses is billed at the standard rate.
It is worth emphasizing that whether a cache hits depends on whether the prefix is exactly identical, and platforms differ markedly in cache granularity, validity period, and invalidation policies. So when budgeting, the conservative approach is to estimate on the assumption of a “miss” and treat a hit as a bonus rather than a precondition.
4. Doing the Math: Cost Model and Estimation
Since platform prices change frequently, this article does not cite any specific prices and instead provides a reusable calculation framework. Let the input price be P_in and the output price be P_out (in units of per 1,000 tokens), the number of input tokens be N_in, and the number of output tokens be N_out. The cost of a single request is:
Cost = N_in / 1000 * P_in + N_out / 1000 * P_out
If a business session involves multiple rounds of interaction, the conversation history must be continually accumulated into the input, and the total cost is approximately:
Cost_total ≈ Σ (N_in_i / 1000 * P_in) + Σ (N_out_i / 1000 * P_out)
The key takeaway here is that the cost of multi-turn conversations grows faster than intuition suggests, because every round must re-input all the prior context. The input consumption of a ten-round long conversation can be dozens of times that of a single question-and-answer exchange.
A rough conversion reference: in common Chinese text, one Chinese character roughly corresponds to one to two tokens, with the exact figure varying by tokenizer and content domain. For capacity planning, it is recommended to first sample real corpus data to measure token counts, then multiply by the business call volume, rather than estimating directly from character counts.
5. Six Levers for Cost Optimization
- Compress context: keep only necessary background, remove redundant examples and repeated explanations, and summarize long documents before passing them in.
- Control output length: explicitly constrain the output structure and length to avoid output token inflation from the model improvising.
- Stable prefix design: place unchanging instructions, templates, and knowledge fragments at the very front of the request to improve cache reuse probability.
- Tiered routing: route simple tasks to smaller-parameter models or a rules engine, and call higher-capability models only for complex reasoning.
- Batching and asynchrony: use batch interfaces for offline tasks, which are usually more cost-effective than real-time calls.
- Observability: collect token usage for every call through logging services and monitoring alerts, attribute it by business dimension, and build a cost dashboard.
Illustrative usage-tracking structure:
{"biz": "search_summary","model_tier": "small","input_tokens": 1820,"output_tokens": 260,"cache_hit_ratio": 0.0}
6. Implementation Suggestions on Baidu AI Cloud
If you use Baidu AI Cloud’s large model capabilities, it is recommended to move cost management forward into the architecture design stage: build a unified model invocation layer that centralizes context trimming, fixed template prefixes, model tiering, and usage tracking; combine object storage to archive raw corpus, a message queue to smooth traffic peaks, and a container platform to host inference front-end services, and use monitoring alerts to set threshold reminders for token consumption. This keeps the business agile while making every unit of compute spending explainable, traceable, and optimizable.
7. Common Misconceptions
- Misconception 1: Estimating cost by character count. In reality, it should be based on tokens after tokenization.
- Misconception 2: Assuming the cache will always hit. A slight change in the prefix can invalidate the whole thing.
- Misconception 3: Looking only at input cost. In long-output scenarios, output cost often dominates.
- Misconception 4: Ignoring multi-turn accumulation. Rolling context is the main source of bill inflation.
By understanding the tokenization nature of tokens, the resource differences between input and output, and the caching mechanism, and by pairing them with reusable cost formulas and a tracking system, you can move LLM applications from “affordable” to “cost-efficient and stable.”
