Understanding Tokens in LLMs: A Practical Guide to Billing and Context Management

    This article explains what tokens are and why they are the core unit behind large language model billing and context handling. It covers how tokenization differs between Chinese and English, why output tokens generally cost more than input tokens, and how the context window acts as a hard limit on what a model can process at once. You will also find a practical engineering checklist for counting tokens before launch, using retrieval instead of full-document prompts, compressing conversation history, controlling output length, and adding usage observability, along with common misconceptions to avoid.

    1. Why You Need to Understand Tokens First

    When building applications on top of large language models, developers usually run into confusion that has nothing to do with model capability. Three questions come up almost immediately: why does the same word count produce a different bill, why does a model “forget” the beginning of a long document, and why is output more expensive than input.

    All of these behaviors trace back to a single base unit of measurement: the token. It is both the atomic unit the model uses to process text and the basis for billing and context management. Without understanding tokens, cost estimation, performance tuning, and output quality tuning are all guesswork.

    To build intuition, it helps to picture a large model service as an “information processing shop.”

    2. The Analogy: An Information Processing Shop That Bills by the Card

    This shop has three characteristics: fast processing, high-quality semantic understanding, and a low unit price. Its operating rules are simple, but each one has a direct impact on engineering decisions.

    Rule 1: All Input Is Sliced into Uniform “Information Cards”

    The system uses a single automatic splitting algorithm — the tokenizer. Whether you submit natural language, source code, mathematical notation, or a JSON structure, it is converted in a very short time into a series of identically sized information cards. One card of this uniform size is one token.

    The key point is that the cards are uniform in size, but the amount of meaning each card carries is not equal to one character.

    The Most Common Pitfall: One Token Is Not One Chinese Character

    This is the most frequent misjudgment in Chinese-language scenarios. Because common Chinese characters are often merged into longer segments in the vocabulary, the practical ratios are:

    • In Chinese, one token roughly corresponds to 1.3–1.5 characters;
    • A 1,000-character Chinese document is about 700–800 tokens;
    • A 300,000-character industry report is about 200,000–230,000 tokens;
    • English works the opposite way: one token usually corresponds to about 4 characters or 0.75 words.

    The engineering implication is straightforward: you cannot use word count as the unit for capacity and budget estimation; you must count tokens. Code, indentation, punctuation, emoji, and Base64 content all raise token density significantly, which is why structured data is often more “expensive” than prose of the same length.

    Rule 2: Billing Is by Card Count, and Generation Costs More Than Reading

    The shop charges neither by word count nor by time spent. It settles only on the number of cards consumed, which is the standard billing model across the industry:

    • The prompt and reference material you submit → input tokens (billed);
    • The answer the model generates → output tokens (usually priced significantly higher than input).

    The reason is a difference in compute structure. Reading (the prefill stage) is mainly parallel encoding and vectorization, so computational density is relatively manageable. Generation (the decode stage) requires token-by-token autoregressive inference, where every step depends on all prior context and cannot be fully parallelized, which makes it far more compute-intensive.

    Note that unit prices, free tiers, and cache discount policies vary widely across platforms and change frequently. In engineering practice, always rely on the official pricing page of the platform you choose (for example, the model services offered by Baidu AI Cloud), and never hardcode prices in your code. A more robust approach is to make unit prices a configuration item:

    1. # Prices must be configurable so they can track official changes
    2. PRICING = {
    3. "input_per_1k": 0.0, # Read from config center / environment variables
    4. "output_per_1k": 0.0,
    5. }
    6. def estimate_cost(in_tokens: int, out_tokens: int) -> float:
    7. return (in_tokens / 1000 * PRICING["input_per_1k"]
    8. + out_tokens / 1000 * PRICING["output_per_1k"])

    Rule 3: The Workbench Has Limited Capacity, and the Context Window Is a Hard Constraint

    This is the most important and most frequently overlooked rule. A single inference pass is like a workbench of finite size: only a fixed number of cards can be spread out at once. That limit is the context window.

    The budget inside the window is usually divided among:

    • The system prompt and role definition;
    • Tool/function definitions and structured output constraints;
    • Retrieved reference material;
    • Multi-turn conversation history;
    • Space reserved for the model’s answer.

    Once the limit is exceeded, earlier content is truncated or an error is triggered, which shows up as the model “suddenly forgetting” earlier instructions. Context management is therefore not optional; it is part of application architecture.

    3. A Practical Token Engineering Checklist

    1. Count First, Then Design

    Before launch, run an offline analysis with the tokenizer that ships with your chosen model to get the real input/output token distribution, then set budgets and rate-limit thresholds accordingly. Tokenizers are not interchangeable across models, so the same text can produce noticeably different token counts under different models.

    2. Use Retrieval Instead of Full-Document Prompts

    Do not stuff an entire long document into the prompt. The common approach is to split the document, vectorize it, and store it in a vector retrieval service, then recall a small set of highly relevant fragments (Top-K) per question and place only those in the context. This solves three problems at once: lower cost, lower latency, and less attention dilution from irrelevant content.

    3. Compress History and Keep Conclusions

    Do not stack multi-turn conversations linearly. Use a sliding window plus summary compression: keep the most recent turns verbatim and roll earlier turns into structured key points (user goal, confirmed constraints, open questions).

    1. [System constraints] no more than 300 tokens
    2. [Long-term summary] user goal / confirmed facts / to-dos
    3. [Recent verbatim] last N turns
    4. [Current question]

    4. Control Output Length

    Output tokens are usually more expensive, and overly long output eats into the window available for later turns. Explicitly constrain the output format (fields, number of items, word limit) to save money and improve stability.

    5. Build Observability

    Log input/output tokens, latency, and failure reasons for every call in your logging and alerting system, and aggregate them by business dimension. Only then can you pinpoint abnormal consumption, such as a prompt being concatenated repeatedly.

    4. Common Misconceptions

    • Misconception 1: Estimating cost by word count. Count tokens instead, and leave headroom for code-heavy content.
    • Misconception 2: Assuming context can be appended indefinitely. The window is a hard limit, so you must actively evict and compress.
    • Misconception 3: Hardcoding unit prices in code. Pricing changes, so keep it configurable and verify against the official source periodically.
    • Misconception 4: Only polishing prompt wording. What really drives cost is context structure and retrieval quality.

    5. Conclusion

    Tokens are the unified yardstick linking model capability, application cost, and context design. Once you have built the “card” intuition, combining it with a configurable pricing model, retrieval-augmented context assembly, rolling summary compression of history, and solid usage observability lets you strike a controllable balance between quality and cost. If you need capabilities such as hosted model services, vector retrieval, object storage, and monitoring/alerting, you can combine the relevant general-purpose offerings from Baidu AI Cloud as needed to build an application architecture that can evolve sustainably.