Token Counting and Cost Optimization for Large Language Models: A Practical Guide
Understand what tokens are, how tokenizers split text, where your LLM bill actually goes, and the engineering practices that reduce token usage across chat history, file reads, tool calls, and long outputs.
1. Start Here: The Token Is the Unit of Measurement for Language Models
To understand LLM cost, the first thing to look at is not the price per unit but what is actually being billed. A token is the discrete unit in which a model processes text. It is neither a character nor a “word” in the human sense. It plays three roles at once: the model’s input interface, the basic granularity of computation, and the smallest unit of metered billing in cloud services.
A useful analogy is buying fuel: you pay for liters, not for the number of liquid molecules in the tank. Likewise, you pay for tokens, not for the number of Chinese characters. The analogy stops at measurement, though. There is no fixed exchange rate between tokens and price. Unit price is determined together by model tier, context length, and the provider’s billing policy, so you have to check the official pricing page of the service you use rather than estimating from experience.
2. Tokenization: Why Models Don’t Read Text Character by Character
A model does not scan text character by character. The string first passes through a tokenizer that maps it to integer IDs in a vocabulary, and only then does computation begin. Tokenization aims to balance sequence length against semantic completeness: split too finely and sequences grow longer while attention cost rises; split too coarsely and the vocabulary explodes while low-frequency fragments go uncovered.
The mainstream approach is subword tokenization, with common strategies including merging high-frequency fragments by frequency and falling back to bytes so that any input can still be encoded. This produces several rules that directly affect cost:
- Common words and frequent collocations are often merged into a single token, giving the best value for money.
- Rare characters, typos, and newly coined words get split into multiple fragments, and the token count rises noticeably.
- Punctuation, spaces, line breaks, and emoji each consume tokens on their own; they are not free.
- Code has dense indentation and symbols, so token consumption per character is usually higher than for natural language.
- Different languages and different tokenizers produce different splits, so old estimates cannot be carried over when migrating across models.
Illustration (the split below is for explanation only; the tokenizer you use is authoritative):
Source: 你好,我是太阳鸟Split: [你][好][,][我][是][太阳][鸟] → 7 tokens
The correct engineering practice is not to guess. Most model services provide token counting or return a usage field. Wire that counting into your telemetry and you get a conversion factor that reflects your own corpus distribution. The rule of thumb “roughly 1 Chinese character ≈ 1.5 tokens” is only good enough for rough capacity planning, not for reconciling a bill.
3. Billing Structure: Three Kinds of Tokens and Their Real Share
The cost of a single call usually consists of input tokens and output tokens, which often carry different unit prices, with the output side more expensive. What really makes a bill spiral is the hidden third item: context.
Cost per call ≈ input tokens × input price + output tokens × output priceInput tokens this call = system prompt + tool definitions + conversation history + retrieved snippets + current question
The key point is that the conversation history is counted into the input again on every turn. This is not waste but an inherent constraint of autoregressive models: the model has no server-side session memory, so what we call “multi-turn conversation” is the client replaying the history every time. Cost therefore grows roughly quadratically with the number of turns:
50 turns × 200 characters per turn × 1.5 ≈ 15,000 tokens (history alone)Input for turn 50 ≈ 50 × 300 ≈ 15,000 tokensCumulative input ≈ 1 + 2 + ... + 50 turns ≈ on the order of 380,000 tokens
4. Where the Cost Goes: Four Frequent Sources of Consumption
Context accumulation. Long sessions are the most easily overlooked amplifier. The strategy is to set dual thresholds on turn count and token count, and when either is exceeded, compress with a summary instead of truncating outright: keep conclusions and constraints, drop pleasantries and intermediate trial and error.
File and knowledge base reads. Letting the model “take a look at” a large file means stuffing the entire content into the input. Switch to retrieval-based reading: locate first, then fetch fragments, using chunking plus vector retrieval so that only relevant passages enter the context.
Tool calls and loops. For coding assistants and automation agents, every tool return, error stack, and log flows back into the context. A single debugging session can trigger multiple rounds of “read file → edit code → run tests,” and consumption multiplies. Always set a maximum iteration count and a per-task token budget.
Verbose output. Output costs more per token and cannot be reused. Constraining the format (structured output, limited fields) and avoiding requests to restate the input are among the highest-value optimizations available.
5. Engineering Techniques for Driving Cost Down
- Tiered model routing: send simple intent classification and format conversion to a small model, and escalate to a larger one only for complex reasoning. This usually cuts most of the overhead.
- Prompt prefix caching: put the stable system prompt and tool definitions at the very front and keep them byte-for-byte identical. A cache hit can significantly reduce the cost of repeated input (check the provider’s documentation for support and discounts).
- Context engineering: sliding window plus rolling summary, with key facts externalized to structured storage and filled back in on demand.
- Batching and async: use the batch API for offline jobs to avoid peak hours and get better pricing.
- Observability: record input/output tokens, cache hits, and latency per call at the trace level, aggregate by business line, and build budgets and alerts on top.
- Output throttling: set a max tokens limit to prevent runaway generation in abnormal cases.
6. Running It in the Cloud: Govern Tokens as a Resource
When building applications on a platform such as Baidu AI Cloud, treat tokens as a resource under the same management discipline as CPU and memory: consume model capability on demand, retain call details through a logging service, set alert thresholds against a daily budget, distribute keys and quotas from a unified configuration center, and keep knowledge bases and long documents in object storage for retrieval on demand. Cost then shifts from “known only at the end of the month” to “attributable in real time.”
In one sentence: a token is not a consumable that gets wasted but the pricing scale of automated labor; what you can optimize is never the unit price but how much content you actually send in each time.
