How LLM API Token Counting Works and How to Optimize Costs

    This article explains why character counts cannot be converted directly into tokens, how tokenizers turn text into tokens, and which factors most affect token counts. It clarifies the relationship between input tokens, output tokens, context windows, and billing, then shows how to reliably estimate and verify token usage before and after a request. Finally, it covers engineering methods for reducing token costs and handling multimodal input, so you can treat tokens as an estimable, verifiable, and manageable engineering metric rather than a vague billing term.

    1. Why Character Counts Don’t Convert Directly into Tokens

    When developers integrate an LLM API, they usually run into three questions at once: how many tokens a piece of text occupies, how much content fits into a single request, and how much the request will ultimately cost. These questions are related, but none of them can be answered by string length alone.

    Characters are a concept at the text-representation level, words are a concept at the language level, and tokens are the discrete units the model actually processes. Before text enters the model, it is encoded by a tokenizer into a sequence of integer IDs, where each ID maps to one token in the vocabulary. The model computes primarily over these IDs rather than over the raw text you see on screen.

    A more accurate way to think about it is:

    The token count of a piece of text is the length of the token sequence produced when a specific tokenizer encodes a specific input.

    This definition carries two key conditions: you must specify which tokenizer is used, and you must specify which part of the input is being counted. Saying only “how many tokens is this text” without naming the model or encoding rules often has no single answer.

    The same text can produce token sequences of different lengths under the tokenizers used by different models. Even when model names are similar, you cannot assume their counting rules are identical without verifying.

    2. How a Tokenizer Turns Text into Tokens

    2.1 A Token May Map to Text Fragments of Different Lengths

    A single token might represent a common word, a word root, a punctuation mark, or even part of the byte representation of a character. It does not necessarily carry a complete linguistic meaning.

    For example, a common English word may be encoded as a whole, while a rarer long word may be split into several fragments. Common Chinese characters or phrases may also tokenize differently, so you cannot mechanically apply a rule like “one Chinese character equals one token.”

    The following only illustrates the concept of tokenization and does not represent the output of any real model:

    1. Original text: Let's discuss the API billing.
    2. Illustrative fragments: [Let's] [discuss] [the] [API] [billing] [.]
    3. Encoded result: [id1, id2, id3, id4, id5]

    A real tokenizer may split things in a completely different way, so this kind of illustration cannot be used for precise budgeting.

    2.2 The Basic Idea Behind Common Tokenization Methods

    Common industry approaches include byte pair encoding and subword modeling. They typically rely on statistical patterns in the training corpus to balance vocabulary size against text-representation efficiency.

    Taking byte pair encoding–style methods as an example, the core idea is to iteratively merge frequently occurring adjacent units so that common fragments can be represented with fewer tokens. However, specific implementations may also involve text pre-tokenization, byte mapping, and special-token recognition, so not all tokenizers should be understood as the same algorithm.

    The vocabulary and encoding rules usually stay fixed during model inference. A tokenizer will not automatically learn to compress a sentence you send repeatedly into a new token within the current request.

    2.3 Unfamiliar Characters Still Have to Be Encoded

    Many tokenization schemes can handle content not directly covered by the vocabulary through byte-level representation or fallback mechanisms. This lets the model accept a wide range of text, but it also means rare characters, complex symbols, or text in certain languages may be split into more tokens.

    So “the text can be input” does not mean “the text is encoded compactly.”

    3. Factors That Significantly Affect Token Counts

    3.1 Language and Text Distribution

    Different languages are written differently, and tokenizers cover different languages to different degrees.

    English has explicit spaces between words, but tokens still do not equal words; Chinese has no natural word boundaries, but tokens do not equal characters either. Mixed Chinese and English, technical terms, abbreviations, and rare names all change the tokenization result.

    The idea that “one token corresponds to roughly a few characters” is at best a rough rule of thumb for a specific text type. It does not apply to all languages and is even less suitable as a direct basis for production billing.

    3.2 Spaces, Line Breaks, and Punctuation

    Spaces are not necessarily ignored. Some tokenization schemes encode a leading space together with the following word; line breaks, indentation, and consecutive punctuation can also affect splitting.

    As a result, two visually similar pieces of text may have different token counts:

    1. Status: OK
    2. Status:OK
    3. Status:
    4. OK

    Full-width versus half-width symbols, line-break positions, and changes in spacing can all introduce encoding differences. However, you cannot further conclude that “removing all spaces always saves tokens,” because tokenization involves merging relationships, and the full modified text must be recounted.

    3.3 Code, Numbers, and Structured Content

    Variable names, brackets, indentation, and operators in code, along with field names, quotes, and delimiters in structured data, are all part of the input.

    A piece of structured data that expresses only a few business fields may still consume a fair number of tokens because of repeated key names and formatting symbols. Long numbers, random identifiers, and dense timestamps often do not fit the character ratios of ordinary natural language either.

    If this content does not help the task, you can consider extracting the relevant fields at the application layer. But if the task depends on precise identifiers, field hierarchy, or code structure, you cannot delete things arbitrarily just to reduce tokens.

    3.4 Text Normalization and Encoding Differences

    Text that looks identical to the human eye does not necessarily have an identical underlying character sequence. For example, different character composition methods, invisible characters, or special spaces introduced during copying can change the count.

    Whether to unify line breaks, clean up invisible characters, or apply character normalization should be decided based on business needs. For natural language, moderate cleanup is reasonable; for signatures, original evidence, code, or exact-match data, you must preserve the requirements at both the semantic and byte levels.

    4. API Input Is More Than Just the Last Question

    Developers often count only the last message the user sent, then find the input usage returned by the API is noticeably higher. The cause is usually not a tokenization error but an incomplete counting scope.

    A single conversational request may include:

    • System instructions and role constraints;
    • The user’s current question;
    • Previous user messages and model replies;
    • Reference material retrieved by the system;
    • Tool descriptions, parameter schemas, and tool return results;
    • Message roles, boundary markers, and other serialized content the model actually uses.

    If a request carries conversation history, earlier replies re-enter the model as input for this turn. What was output in the previous turn may be input in the next, and you cannot assume it no longer occupies context or no longer incurs charges just because it was already generated.

    Also, you should not treat the length of the entire network request payload as the input token count. How transport-layer field names, request metadata, and text are organized into model input on the server side is a separate question. Some content participates in model processing; some is merely interface control information.

    Precise counting must be based on how the API actually constructs the model input.

    5. The Relationship Between Input, Output, Context, and Billing

    5.1 Input Tokens and Output Tokens

    Input tokens are the usage corresponding to the prompt and related context the model processes; output tokens are the usage corresponding to the content the model generates.

    But whether “output usage” includes only the user-visible reply depends on the specific API documentation. Some models or endpoints may also report other generation-related usage, so you cannot assume the bill is wrong just because you counted only the text displayed on the page.

    5.2 The Context Window Is Not Simply Input Capacity

    The context window describes the sequence size a model can handle in a single pass. For common autoregressive text-generation models, the budget usually needs to account for both the input and the space reserved for generation:

    1. input tokens + reserved generation tokens <= available context capacity

    This is a common planning principle, not a universal parameter constraint across all endpoints. A real service may separately limit maximum input, maximum output, or set additional budgets for other processing stages.

    For example, suppose a system allows 24,000 available context tokens and the application wants to reserve 3,000 tokens for generation, then the input should not simply fill all 24,000 tokens. These numbers are only budgeting examples and do not represent the capability of any specific model.

    5.3 Costs Must Be Calculated by Actual Billing Category

    In the simple case where input and output are priced separately, you can estimate with the following formula:

    1. cost = input tokens / pricing unit * input price
    2. + output tokens / pricing unit * output price

    The pricing unit may be per thousand tokens or per million tokens and must match the price sheet.

    If the service distinguishes cache reads, cache writes, other generation usage, or multimodal processing, calculate each category separately. A cache hit may change the price or computation overhead, but it does not mean this content necessarily stops occupying context.

    Counting method, billing method, and context limits are three related but distinct dimensions and should not be conflated.

    6. How to Reliably Calculate and Verify Tokens

    6.1 Before the Request: Use Matching Encoding Rules

    If the service provides a tokenizer or counting capability that matches the target model, prefer it and confirm its version and supported scope.

    Using only some general-purpose tokenizer to count text can help with a rough capacity judgment, but you cannot assume it matches server-side counting by default. Multi-turn messages, tool definitions, and special markers in particular may carry additional overhead.

    The following is conceptual pseudocode and does not correspond to any specific API:

    1. messages = assemble_actual_request_messages()
    2. input_estimate = count_actual_serialized_content(messages)
    3. generation_budget = set_budget_by_task()
    4. safety_margin = set_margin_by_historical_error()
    5. if input_estimate + generation_budget + safety_margin > available_context:
    6. trim_history()
    7. filter_reference_material()
    8. recount()

    The safety margin should not be set arbitrarily as a fixed universal ratio; it should be adjusted based on the actual request structure and historical error.

    6.2 After the Request: Record Server-Side Usage

    After a request completes, save the usage information returned by the API, including the available input, output, and other categorized data. The server-side usage fields are an important basis for verifying processing volume, but final billing should still be confirmed against the billing documentation, invoice, or usage details.

    If you use streaming responses, also confirm whether usage information is returned only in the final event. When a connection drops or the client stops early, the text the client receives may be less than what the server already generated, so the locally visible character count may not explain the entire charge.

    6.3 Build Estimation-Error Monitoring

    It is recommended to record the following:

    • Model and endpoint version;
    • Local input token estimate;
    • Server-reported input and output usage;
    • Number of historical turns and reference-material size;
    • Whether tool definitions or multimodal input are included;
    • Whether the request ended normally;
    • The corresponding price version and billing category.

    When the estimation deviation suddenly widens, first investigate model switches, tokenizer version mismatches, message-template changes, and hidden context newly added to the request.

    Logs should capture the necessary statistics while avoiding the long-term storage of full sensitive prompts just for token analysis.

    7. Engineering Methods for Reducing Token Costs

    7.1 Remove Irrelevant Information First, Then Consider Compressing Expression

    The most effective optimization is often not trimming a few punctuation marks but stopping the transmission of entire sections of content unrelated to the task.

    In retrieval scenarios, filter for fragments directly relevant to the question and avoid stuffing an entire document into the context. Repeated instructions, repeated history, and redundant tool output should also be handled first.

    However, trimming must not break the evidence chain. If the task requires citing sources, comparing multiple clauses, or checking original text, you must keep the necessary context and locating information.

    7.2 Manage History Instead of Appending Endlessly

    Depending on the task, you can keep the last few turns, extract key facts, or summarize earlier conversation.

    A summary should preserve the user’s goal, confirmed conditions, important numbers, and unresolved questions, avoiding replacing key constraints with a vague general description. For content with high precision requirements such as legal clauses or numerical calculations, the necessary original text should also be retained.

    Generating a summary itself incurs call costs, so an overall benefit is possible only when it is reused across many subsequent turns.

    7.3 Control the Scope and Format of the Answer

    Clearly specifying which fields the answer should contain, whether derivation is needed, and whether examples are needed can reduce ineffective output. For a task that only needs a single judgment result, there is no need to generate a long explanation by default.

    But too small an output budget leads to truncated answers, incomplete structure, or missing key explanations. Budget optimization should be constrained by task success rate rather than simply pursuing the fewest tokens.

    7.4 Avoid Mechanical Compression

    Removing all spaces, renaming fields to obscure abbreviations, or turning natural language into dense symbols does not guarantee fewer tokens and may reduce the model’s comprehension quality.

    Compressing a file for transmission also does not automatically reduce the tokens of the decompressed text the model reads. Network transfer size and model context usage should be optimized separately.

    Any compression scheme should verify both the token change and the task quality.

    8. Multimodal Input Cannot Be Calculated by Text Rules of Thumb

    When an API receives images, audio, or video, usage may depend on factors such as image dimensions, processing detail, audio duration, and video sampling method. Different services may use different units or conversion rules, so “file bytes divided by some constant” is not a universal method.

    If the input is text recognized from an image, you can count that text using text tokenization rules; if you submit the image directly, you should estimate based on the endpoint’s documentation for image processing.

    Tool calls require attention to the full chain as well. Tool descriptions, the call parameters generated by the model, and the returned tool results may all occupy tokens at their respective stages. You cannot count only the natural-language answer the user ultimately sees.

    9. Building a Reproducible Token Budget System

    A reliable engineering workflow should form a closed loop of “estimate before the request, control during execution, verify after the request, and optimize over the long term.”

    Before the request, confirm the actual input scope and leave room for generation; during execution, handle over-limit conditions, truncation, and abnormal termination; after the request, record actual usage and reconcile billing; over the long term, analyze the cost-quality relationship by task type.

    What you ultimately need to remember is not some character conversion ratio but three principles:

    First, the token count is determined by the encoding result of a specific tokenizer over the actual input.

    Second, API usage may cover the full message structure, not just the last sentence the user typed.

    Third, cost optimization should be premised on completing the task, achieved by reducing irrelevant context and ineffective output rather than blindly compressing text.

    Mastering these three points is what turns tokens from a vague billing term into an estimable, verifiable, and manageable engineering metric.