How LLM API Token Calculation Works: From Tokenization to Cost Control

    This article explains what tokens actually are and why they, rather than characters or words, are the unit used for LLM API billing and context limits. It walks through the full path from raw text to token IDs and back, outlines the main tokenization approaches and why the same text yields different token counts across models, and covers practical estimation, optimization, and troubleshooting techniques for keeping token usage under control.

    1. A Token Is Not a Character or a Word

    The most common misconception when calling an LLM API is treating tokens as character counts or word counts. A token is the basic unit of computation a model uses to process text. It is neither the smallest symbol humans write with nor a word in the linguistic sense. It is a fragment that a tokenizer cuts out of text according to a specific algorithm.

    A sentence a user types, such as “Nice weather today, good day for a walk,” is natural language to a human, an encoded sequence of characters at the machine level, and a sequence of token IDs to the model. The model does not interpret meaning character by character. It maps each token to a vector and then performs attention computation and parameter operations in that vector space. This is why billing, context length limits, and input/output statistics are all measured in tokens.

    2. From Text to Tokens: The Full Pipeline

    Processing the text in a single request typically involves these stages:

    1. Encoding and normalization: The text is converted into a byte stream under a unified encoding, with differences in line breaks, whitespace, and full-width versus half-width characters handled.
    2. Tokenization: The tokenizer splits the byte or character sequence into fragments based on its vocabulary and merge rules, then maps them to integer IDs.
    3. Concatenation and markers: Control tokens such as role markers, separators, and end-of-sequence tokens are added to distinguish system instructions, user input, and model output.
    4. Model computation: The token sequence enters the model, which produces a probability distribution over the next token.
    5. Detokenization: The generated token IDs are converted back into readable text.

    The code below is illustrative only. It shows the flow and does not represent any specific API:

    1. ids = tokenizer.encode(text) # text -> sequence of token IDs
    2. logits = model(ids) # forward pass of the model
    3. next_id = sample(logits) # sample the next token
    4. text_out = tokenizer.decode(ids) # token IDs -> text

    3. How Text Gets Split: Mainstream Algorithm Approaches

    Different models use different tokenizers, so splitting results naturally differ. This is the root cause of the token count discrepancies you see for the same text across platforms. Three approaches are common in the industry:

    • Byte-level splitting: Uses bytes as the smallest unit, naturally supporting multiple languages and emoji, but a single Chinese character often requires several tokens.
    • Subword splitting: Merges high-frequency fragments first, so common words become single tokens while rare words are broken into subwords, balancing vocabulary size against coverage.
    • Statistical merge-based splitting: Starts from characters and repeatedly merges frequent pairs based on co-occurrence frequency in the corpus, ending with a fixed-size vocabulary.

    A few stable patterns follow from this. Common words and frequent collocations tend to be more token-efficient. Rare characters, typos, random strings, code symbols, and Base64 content tend to consume more tokens. The token-to-character ratio for Chinese is generally much higher than the token-to-word ratio for English.

    4. Why Billing and Context Are Both Measured in Tokens

    Tokens became the unified unit of measurement for three reasons:

    1. Roughly linear correlation with compute: The model’s computation and memory usage grow with sequence length, so tokens track real resource consumption more closely than characters.
    2. Cross-language comparability: Character density varies enormously between languages, and tokens provide a relatively consistent scale.
    3. Separate input and output accounting: Most platforms count input tokens and output tokens separately, because the computational characteristics of the generation phase differ from those of the input phase.

    Note that specific unit prices, tiered rules, and cache-hit policies are commercial terms set by each platform. Refer to the official documentation for those, as this article makes no numerical assumptions.

    5. Engineering Practice: Estimating and Optimizing Token Usage

    When you cannot call the tokenizer directly, use a conservative estimate: roughly “word count × 1.3” for English, “character count × 1.5–2” for Chinese, and a further markup for code and structured text. Before going live, calibrate against a small sample using the tokenization scheme of your target model.

    Optimization options include:

    • Compress the system prompt: Remove repeated constraints and turn long rules into a bullet list.
    • Trim conversation history: Keep only the turns relevant to the current task, and summarize when necessary.
    • Control output length: Specify the output format and length explicitly to avoid unconstrained expansion.
    • Structure the input: Replace verbose natural-language descriptions with concise fields.
    • Batch and cache: Put stable, unchanging prefixes at the front to improve prefix reuse and cache hit rates.
    • Monitor and alert: Use logging services and monitoring alerts to track input and output tokens per call and pinpoint abnormal growth.

    Example: rewriting a verbose prompt as a bullet list can significantly cut wasted tokens.

    1. # Before
    2. You are a highly professional assistant and must strictly follow the many rules below... (long repetitive description)
    3. # After
    4. Role: backend review assistant
    5. Rules: 1) flag risks only 2) give a fix suggestion for each 3) no more than 5 items
    6. Output: Markdown list

    6. Common Misconceptions and a Troubleshooting Checklist

    • Misconception 1: Token count equals character count. Count based on tokenization results; mixed Chinese and English text shows an even larger gap.
    • Misconception 2: All models split text the same way. Different vocabularies and algorithms inevitably produce different results.
    • Misconception 3: Longer output means better results. Output tokens count toward both cost and latency.
    • Misconception 4: More context means more accuracy. Overly long context introduces noise and raises cost.

    For troubleshooting, hold three things fixed: the same text, the same set of parameters, and the same tokenization basis. Only then can you compare model behavior and reach reproducible conclusions.

    7. Conclusion

    Understanding tokens is essentially understanding how a model “sees the world.” Once you treat text as a sequence of tokens rather than a sequence of characters, differences in billing, context limits, and generation behavior all become explainable. In practice, build a loop of estimate first, calibrate next, monitor after, and use general-purpose capabilities such as logging services, monitoring alerts, and object storage on cloud platforms like Baidu AI Cloud to accumulate call data. That is how you keep token costs under control, evaluate quality, and spend a limited budget on high-quality output.