How to Account for LLM Token Usage and Costs

    As AI applications shift from single-turn chat to autonomous agents, token consumption has become harder to predict and more expensive. This article explains why tokens are a context-dependent unit of measurement, breaks down the four layers that drive consumption, and outlines how to build usage accounting, reconcile bills, and enforce budget guardrails across teams.

    1. From Technical Parameter to Consumer Product: Why Tokens Are Being Stockpiled

    Tokens used to appear mainly in technical documentation and API bills, serving as an abstract unit for developers during debugging and capacity planning. Today they are packaged into prepaid plans that sit in shopping carts alongside everyday goods and become a recurring topic during major sales events.

    The deeper reason for this shift is that AI applications are moving away from single-turn “one question, one answer” conversations toward agents that can decompose tasks on their own and call models repeatedly. Agents effectively give models “hands and feet,” multiplying both the number of calls and the context length behind a single task. Token consumption rises accordingly.

    For users, the motivation to buy a plan is straightforward: lock in future inference usage ahead of time and avoid sudden capacity expansion and price fluctuations. Once the hype fades, however, the real questions surface—can this prepaid quota be measured accurately, can it be reconciled line by line against the bill, and can it be used safely within budget?

    2. What a Token Really Is: A Context-Dependent Unit of Measurement

    A token is the basic unit by which large models process and generate information. It is not equal to a character count or a word count: a piece of Chinese text may be split into a varying number of fragments after tokenization, and punctuation, spaces, and code symbols all affect the result. As a result, the same semantic content produces different token counts on the input side and the output side.

    More importantly, token consumption is strongly context-dependent. In multi-turn conversations, historical messages repeatedly participate in computation as context; retrieval-augmented generation splices retrieved document fragments into the prompt; and at each step, an agent may feed the previous step’s observations back into the model. This means there is no fixed answer to “how many tokens does one question cost”—it must be calculated based on the calling pattern, context strategy, and task chain.

    Illustrative pseudocode helps clarify what makes up input-side tokens:

    1. messages = [system_prompt] + history + retrieved_docs + user_query
    2. input_tokens = tokenize(messages)
    3. output_tokens = 0
    4. loop:
    5. resp = model.generate(messages)
    6. output_tokens += tokenize(resp.output)
    7. if resp.tool_call:
    8. messages += [resp.output, tool_result]
    9. continue
    10. break
    11. total_tokens = input_tokens + output_tokens

    3. Where Consumption Comes From: A Decomposable Cost Chain

    To get the accounting right, the first step is to accept that token consumption is not a single-point action but a chain. It can be broken into four layers:

    • Prompt layer: system prompts, role settings, and output format constraints, which are billed repeatedly on every call.
    • Context layer: conversation history, retrieved fragments, and knowledge base content, the main source of increase in long-text scenarios.
    • Inference layer: the content the model generates itself, where output tokens usually carry a higher unit price.
    • Orchestration layer: the agent’s planning, tool calls, result backfilling, and retries, which often bring several times the number of calls of a single-turn conversation.

    Once these four layers stack up, a task that “looks simple” may actually consume several times what intuition suggests. Cost governance therefore has to start from the chain perspective rather than focusing only on individual requests.

    4. Getting the Numbers Right: Building Usage Accounting and Cost Attribution

    The goal of accounting is to make every unit of consumption traceable and explainable. At least three mechanisms are recommended:

    1. Unified instrumentation and tagging. Tag every call with a business identifier, scene identifier, and user identifier so that consumption can be aggregated by business line, functional module, and tenant.
    2. Itemized measurement. Record input tokens, output tokens, cache hits, and retry counts separately, avoiding the use of a total figure to mask structural problems.
    3. Unit-based conversion. Convert tokens into business-readable metrics such as “cost per thousand tasks” and “cost per active user,” making them easy to compare against revenue or efficiency gains.

    An illustrative usage record structure:

    1. {
    2. "trace_id": "t-20240101-0001",
    3. "scene": "document_summary",
    4. "tenant": "team-a",
    5. "input_tokens": 3200,
    6. "output_tokens": 450,
    7. "cached_tokens": 1800,
    8. "retries": 1,
    9. "latency_ms": 2600
    10. }

    With structured records in place, it becomes possible to answer management questions such as “which scene is the money going to” and “which type of request is the least cost-effective.”

    5. Reconciling the Bill: Making Bills and Usage Verifiable in Both Directions

    The difficulty in reconciliation lies in inconsistent measurement standards on the two sides: the business side sees task counts, while the bill side sees tokens and call volumes. Three workable practices:

    • Aligning standards: take the measurement fields returned by the API as authoritative; the business side only maps them and does not perform secondary estimation.
    • Two-way verification: periodically compare internal usage summaries with bill details by cycle and by identifier, with any discrepancy traceable to a specific call.
    • Auditable trails: retain raw request and response summaries, measurement results, and the billing cycle together to form a closed-loop evidence chain.

    It is worth emphasizing that different services may differ in measurement details; the specific rules should follow the public documentation of the chosen service. This article does not assume any unified parameters.

    6. Trustworthy and Controllable: Budget Guardrails and Optimization Strategies

    Once the accounting is clear, consumption has to be controlled. Budget guardrails should be built into the architecture layer in advance rather than chased after the fact:

    • Quotas and rate limiting: set call limits and concurrency limits by tenant and scene to prevent abnormal tasks from amplifying consumption.
    • Context governance: compress history, summarize memory, control the number of retrieved fragments, and prioritize reusing cacheable content.
    • Model tiering: route simple tasks to lightweight models and escalate to stronger ones only for complex reasoning, avoiding the use of a sledgehammer to crack a nut.
    • Circuit breaking and degradation: automatically degrade or queue when failures are consecutive or budget is exceeded, keeping core paths available.

    In engineering implementation, guardrails can be built as a unified gateway capability and work with common cloud product categories such as logging services, monitoring and alerting, and message queues to form a closed loop of “observability—alerting—intervention.” In related practice, Baidu AI Cloud also emphasizes that cost governance needs to be built in step with the observability system rather than as a single-point optimization.

    7. Action Checklist for Different Roles

    • Developers: instrument first, then optimize; use itemized measurement to locate waste; put prompts and context under version control so changes can be traced back.
    • Architects: treat the token budget as one of the capacity metrics and incorporate it into rate limiting, degradation, and capacity reviews.
    • Managers: replace anxiety over totals with unit-based metrics, evaluate input against output based on business returns, and set phased budget red lines.
    • Procurement and finance: use bill details as the sole basis for reconciliation, retain the usage evidence chain, and review discrepancies by cycle.

    Conclusion

    Tokens becoming a consumer product has only exposed a long-standing measurement problem to everyone earlier than expected. The real solution is not mysterious: break consumption into a chain, turn usage into data, turn bills into reconcilable evidence, and turn budgets into guardrails in the architecture. With these four points in place, the stockpiled quota will not turn into a muddled account, but into a predictable, optimizable, and sustainable compute asset.