How Token Usage Is Calculated: From Model Calls to AI Agent Cost Governance

    This article explains how token usage is calculated in generative AI applications, why agent workflows tend to consume more tokens than single-turn chat, and which factors drive input and output costs. It then outlines practical approaches to token budgeting, monitoring, and optimization so teams can govern AI agent costs more effectively.

    In generative AI applications, when a user enters a question, uploads a document, or asks the system to complete a complex task, the model must first read the context and then generate a response. During this process, the text is split into basic units that the model can recognize and count. These units are commonly called tokens.

    In the past, tokens appeared mainly in API documentation, billing pages, and model service backends. As large language models enter office work, education, coding, and business automation scenarios, more ordinary users are beginning to ask questions such as “How many tokens are left?”, “How many tokens will this task consume?”, and “Why does the same question cost more over time?” This means that tokens are shifting from a technical parameter into a new kind of digital resource.

    1. What Exactly Is a Token?

    A token is not fully equivalent to a word count, nor is it equivalent to a character count. A model typically uses a tokenizer to split input text into segments. A Chinese character, a word, an English word, a punctuation mark, or even a special symbol in code may correspond to one or more tokens.

    For example, a short text may be split as follows:

    1. please / help / summarize / this / document / .

    English and code may be split differently. Long words may be broken into multiple segments, and indentation, brackets, variable names, and operators also participate in counting. Therefore, token counts cannot be estimated simply by multiplying word count by a fixed ratio.

    A complete model call usually contains at least two parts:

    1. Total tokens = input tokens + output tokens

    Input tokens include the user question, system instructions, conversation history, retrieval results, tool return content, and text processed from uploaded files. Output tokens are the answer, code, structured data, or tool-call parameters generated by the model.

    For agent tasks, multiple rounds of calls must also be considered:

    1. Total task consumption = Σ (input tokens per round + output tokens per round)

    In other words, although the user appears to have issued only one instruction, multiple model calls may have already occurred in the background.

    2. Why Agents Are More Likely to Consume Tokens

    Ordinary chat is usually a “question-and-answer” interaction, while an agent is closer to a loop of “plan—execute—observe—correct.”

    When a user asks to “prepare a sales analysis report,” the agent may perform the following steps in sequence:

    1. Understand the user’s goal and break down the task;
    2. Query business data or read files;
    3. Generate intermediate analysis results;
    4. Call calculation, search, or database tools;
    5. Check whether the results are complete;
    6. Modify tables or generate charts;
    7. Write the final report;
    8. Format and quality-check the final content.

    Each of these steps may invoke the model once or multiple times. More importantly, later calls often need to carry context produced earlier. If the context continues to accumulate, input tokens will keep increasing.

    Therefore, an agent’s token consumption depends not only on the length of the final answer, but also on task decomposition depth, the number of tool calls, the scale of historical information, and the number of error retries.

    This can be represented with a simplified model:

    1. Task cost ≈
    2. base instruction cost
    3. + historical context cost
    4. + tool return data cost
    5. + reasoning and planning cost
    6. + final output cost
    7. + retry cost

    Retry cost is often overlooked. If a tool call fails, the format does not meet requirements, or validation does not pass, the system may regenerate the result. For complex workflows, even a small number of exceptions can create significant additional consumption.

    3. Which Factors Significantly Affect Token Usage

    3.1 Context Length

    The longer the context, the more content the model must read on each call. Many applications pass the full conversation history, all documents, and all tool results directly into the model. Although this approach is simple, it causes a large amount of repeated computation.

    More reasonable approaches include:

    • Summarizing earlier conversations;
    • Keeping only historical information relevant to the current task;
    • Retrieving documents in segments instead of injecting the full text;
    • Removing duplicate system prompts and invalid tool outputs;
    • Filtering fields in structured data.

    3.2 Output Limits

    The longer the generated content, the more output tokens are used. There is no need to make the model produce lengthy explanations for simple tasks, nor should every request be given an excessively high maximum output length.

    For example, for tasks such as classification, field extraction, and pass/fail validation, the model can be asked to return only a short structured result rather than a full natural-language explanation.

    3.3 Documents and Code

    Documents, logs, and code often have high information density. Large numbers of repeated fields, whitespace characters, comments, and redundant formatting all increase token counts.

    Before entering the model, preprocessing can be performed:

    1. raw file
    2. ↓
    3. remove irrelevant formatting and duplicate content
    4. ↓
    5. split by section or semantics
    6. ↓
    7. retrieve relevant segments
    8. ↓
    9. submit to the model for analysis

    Splitting does not mean simply truncating by a fixed number of characters. A better strategy is to combine natural boundaries such as headings, paragraphs, functions, classes, and log time ranges, so that each segment remains as semantically complete as possible.

    3.4 Multi-Turn Interaction

    The convenience of continuous conversation comes from context memory, but each round of requests may repeatedly carry part of the historical content. If a user uses the same session for a long time, token consumption may gradually increase.

    From an engineering perspective, context management strategies can be set, for example:

    • Automatically summarize after a threshold is reached;
    • Store long-term preferences separately from temporary tasks;
    • Keep only the most recent several rounds of conversation;
    • Place reusable knowledge in a retrieval library;
    • Archive completed tasks.

    3.5 Tool Calls and Failed Retries

    Every time a database is queried, a file is read, code is executed, or an external system is called, new intermediate results are produced. If the returned content is not filtered, the model may receive a large amount of information unrelated to the final task.

    Tool interfaces should return only necessary fields where possible and provide clear error messages and status codes. For failed tasks, reasonable retry limits should also be set to avoid resource waste caused by infinite loops.

    4. How to Establish a Token Budget

    Before launching an AI application, an enterprise should first establish task-level budgets rather than looking only at the total bill.

    A basic budget table can include:

    Task type Average input Average output Daily calls Estimated daily consumption
    Simple Q&A Low Low High Medium
    Document summarization Medium Medium Medium Medium
    Code generation Medium High Medium High
    Multi-step automation High Medium to high Low High

    In actual measurement, both average values and long-tail values should be considered. Average consumption can be used for daily budgeting, while high-percentile data such as P95 or P99 is suitable for capacity planning and risk control.

    The following estimation method can be used:

    1. Monthly token budget =
    2. daily active users
    3. × average tasks per user per day
    4. × average tokens per task
    5. × days in the month
    6. × safety factor

    The safety factor covers business growth, an increase in complex tasks, and abnormal retries. A budget is not meant to restrict all usage; rather, it lets teams know which scenarios are worth optimizing and which tasks need limits.

    5. What Token Monitoring Should Record

    Recording only whether a call succeeded or failed is far from enough. It is recommended to record at least the following information for each model call:

    • Request time and business scenario;
    • User or tenant identifier;
    • Model invocation type;
    • Input token count;
    • Output token count;
    • Total token count;
    • Response latency;
    • Whether a retry occurred;
    • Number of tool calls;
    • Final task status.

    On this basis, multiple layers of metrics can be built:

    User Layer

    Observe the daily, weekly, and monthly consumption of individual users to identify abnormal growth or high-frequency usage behavior.

    Application Layer

    Compare the token share of different functions such as Q&A, document processing, coding assistance, and data analysis to determine where resources mainly flow.

    Workflow Layer

    Track how many rounds of calls a task went through, which steps consumed the most, and where failures mainly occurred.

    Cost Layer

    Connect token usage with business outcomes, such as how many tokens are required to complete a report, process a ticket, or generate a piece of code, so as to evaluate the real input-output ratio.

    6. Common Token Optimization Methods

    6.1 Streamline Prompts

    System instructions should clearly define the goal, input format, output format, and exception handling, but should not stack a large number of repeated descriptions. Centralizing rules that remain unchanged over time can reduce repeated content in each request.

    6.2 Use Retrieval Instead of Full-Text Injection

    For knowledge bases or long documents, relevant segments should be retrieved first and then provided to the model. When the retrieval scope is too large, ranking, deduplication, and relevance filtering can also be added.

    6.3 Control Output Format

    For results consumed by programs, structured output should be preferred. For example, return only fields, status, and conclusions, avoiding large amounts of process explanation. When content needs to be shown to users, the application layer can add formatting afterward.

    6.4 Introduce Caching

    For identical or highly similar requests, model results can be cached. Scenarios suitable for caching include fixed knowledge Q&A, repeated summarization, common template generation, and stable classification tasks.

    Caching needs to consider data freshness and permission isolation. Tokens should not be saved by returning outdated data or data that does not belong to the current user.

    6.5 Differentiate Task Complexity

    Simple classification, keyword extraction, and format conversion do not necessarily require the most capable and most expensive model. A tiered strategy can be adopted based on task difficulty: simple tasks are processed quickly, while complex tasks enter multi-round reasoning and tool collaboration workflows.

    6.6 Set Limits and Circuit Breakers

    Set reasonable token limits for individual users, individual applications, and individual tasks. When a task exceeds the budget, it can be paused, the user can be asked whether to continue, or the task can be handed over to manual processing. For abnormal loops, protection should be provided through maximum steps, timeouts, and retry limits.

    7. From “Buying Resources” to “Managing Call Efficiency”

    The value of tokens lies not in stockpiling quantity, but in whether they can be converted into stable and controllable business outcomes. For individual users, understanding tokens helps with reasonably planning long-document analysis, code generation, and automation tasks. For enterprise teams, token management is part of model governance, cost control, and service stability.

    In the future, competition in AI applications will not be reflected only in how well a model answers questions. It will also be reflected in the following areas:

    • Whether the same task can be completed with fewer calls;
    • Whether existing context can be reused accurately;
    • Whether invalid retries can be reduced in complex tasks;
    • Whether resource consumption can be measured transparently;
    • Whether a balance can be achieved among cost, speed, and quality.

    Therefore, development teams should treat tokens as a computing resource that requires continuous optimization and establish a complete loop covering request design, context management, tool orchestration, cache reuse, and monitoring and auditing. Only by bringing every call into an observable, explainable, and controllable engineering system can large language models and agents truly move from “usable” to “affordable, stable, and sustainable.”