AI Agent Token Costs: Diagnose Waste Before You Optimize

    High token usage in AI agents often comes from repeated context, oversized tool results, and retries—not a single response. Learn how to attribute usage to individual actions, prioritize cost-saving changes, preserve validation, and compare platforms by cost per successfully completed task.

    1. Seven Million Tokens May Not Mean One Response

    A seven-digit token count on a bill can make it look as though a model is spending recklessly. Before drawing that conclusion, check what the number measures.

    Most platforms report cumulative usage: the sum of all model calls within a session or task lifecycle. That is not the amount of content generated in a single response.

    The difference can be substantial. An agent typically completes a real task through a loop: reason, call a tool, read the result, and reason again. Each iteration may resend system instructions, message history, and tool output.

    The first step is therefore not optimization but attribution: break usage down by turn and action.

    2. Four Mechanisms That Amplify Token Usage

    Repeated Context Across Multiple Turns

    Let the input length at turn n be L(n). If history grows through linear appending, cumulative input is approximately ΣL(n), approaching O(n²).

    Increasing a task from 5 turns to 20 can therefore increase input usage by roughly an order of magnitude rather than just four times. This is a major reason long-running tasks become progressively more expensive.

    Tool Results Fed Back into Context

    A directory listing, full log, or web page can contain thousands or tens of thousands of tokens. Once added to history, that material may be carried into every subsequent call.

    The agent reads the source once, but the same content can be counted as input N times.

    Retries with Nearly Identical Context

    When a tool times out, parameters are invalid, or an assertion fails, an agent may retry with almost unchanged context. That means paying again for the most expensive part of the input—sometimes several times in succession.

    Increasing Reasoning Length

    As a complex task progresses, the reasoning itself may become longer. This increases output usage and, when retained in history, subsequent input usage.

    Some of this is necessary work. It should not be treated in the same way as avoidable context repetition, oversized tool results, or ineffective retries.

    3. Keep Four Metrics Separate

    • Input tokens: Instructions, history, and tool results. These are often the dominant cost in long tasks and can account for more than 90% of token usage.
    • Output tokens: Content generated by the model. In input-heavy workflows, these may account for only a single-digit percentage.
    • Cached tokens: Reused prefixes, generally billed at a substantial discount. Discounts can bring the rate to 10% of the standard price or less, but the applicable service’s current pricing rules determine the actual rate.
    • Actual cost: The weighted total after applying the relevant prices to uncached input, cached input, and output.

    A high input share is not inherently abnormal. Many tasks need extensive context to produce a correct result.

    A more useful warning sign is a low cache hit rate. If system prompts or historical prefixes change on every turn, content that could qualify for discounted reuse may instead be charged at the standard rate.

    4. Diagnose Usage by Mapping It to Actions

    Add lightweight instrumentation to the call chain and record usage by turn and action type:

    1. def traced_call(agent, messages, action):
    2. before = len(messages)
    3. resp = agent.call(messages) # The response must include usage data
    4. u = resp.usage
    5. record = {
    6. "action": action, # plan / tool / reflect / retry
    7. "turn": resp.turn_index,
    8. "input": u.prompt_tokens,
    9. "output": u.completion_tokens,
    10. "cached": u.prompt_cache_hit_tokens,
    11. "delta_ctx": len(messages) - before,
    12. }
    13. ledger.append(record) # Send to a logging service for aggregation
    14. return resp

    With this usage ledger, focus on four questions:

    1. Turn distribution: How many turns does each task take? Are any loops exceeding the expected threshold?
    2. Input spikes: Which turns show a step increase in input, and which tool calls caused it?
    3. Repeated reads: Are the same files or log sections being included in full multiple times?
    4. Retry amplification: What share of total input comes from calls marked action=retry?

    5. Optimize in Order of Expected Value

    First: Narrow the Retrieval Scope

    Use keyword or vector retrieval to locate relevant files and line ranges. Send only the matching excerpts into context rather than entire directories or files.

    This is often the highest-value change, with little impact on quality when relevant material is preserved.

    Second: Extract Relevant Sections Instead of Full Results

    For logs, include error lines and a fixed window around them. For long documents, first extract their structure—headings, exception stacks, or key fields—then decide which sections need to be expanded.

    Third: Compress Task Progress, Not Source Material

    For long-running tasks, replace completed history with a structured summary containing:

    • The objective
    • Confirmed facts
    • Ruled-out hypotheses
    • Remaining work

    Preserve reusable conclusions while removing process noise:

    1. def compact(messages, keep_last=3, summary_prompt=SUMMARY):
    2. head, tail = messages[:-keep_last], messages[-keep_last:]
    3. if len(head) <= 1:
    4. return messages
    5. summary = llm(summary_prompt, head) # Compact once, not on every turn
    6. return [{"role": "system", "content": summary}] + tail

    Trigger compaction infrequently, such as every K turns or when context exceeds a threshold. Running it on every turn introduces additional model calls and can increase costs.

    Fourth: Limit Retries and Enforce Budgets

    Set retry limits and backoff policies. When a retry requires context changes, replace only the failed portion rather than rewriting the entire context.

    Also set per-task token and spending budgets. When a task reaches its limit, fall back to reporting the current findings and a list of unfinished items instead of continuing indefinitely.

    Fifth: Design Cache-Friendly Prefixes

    Place stable system instructions, tool definitions, and long-term rules at the beginning of the prompt, and keep them byte-for-byte unchanged.

    Move variable content—timestamps, random IDs, and current-turn notes—to the end.

    A more stable prefix improves the opportunity for cache reuse. The resulting discount reduces cost without removing useful context.

    6. Do Not Remove Validation to Save Tokens

    One tempting “optimization” is to eliminate tests, checks, or secondary confirmation.

    That may reduce the immediate bill, but incorrect results can create larger downstream rework costs. Those failures may also be difficult to detect.

    Keep validation and optimize what it returns to the model. Run the necessary checks, but feed back failure summaries rather than the complete test output.

    7. Compare Subscriptions and Usage-Based Pricing Fairly

    Dividing total tokens by a subscription allowance does not establish whether a plan offers good value. The two pricing models may measure consumption differently.

    Use comparable operational metrics instead:

    • Cost per successful task: Total spending during the period divided by the number of tasks that passed validation.
    • Allowance usability: Whether peak-time rate limits interfere with work or long contexts are truncated.
    • Completion and rework rates: A lower price offers little benefit if tasks fail or must be repeated.

    Compare these metrics in the same table. They usually provide a more reliable basis for selection than price per million tokens alone.

    8. Close the Observability Loop

    For a deployment on Baidu AI Cloud, this approach can be organized around general infrastructure categories: write call traces and usage details to a logging service; use monitoring and alerts to set thresholds for per-task tokens, cache hit rates, and retry rates; store long documents and tool artifacts in object storage and pass references instead of repeatedly embedding full content; and schedule batch attribution analysis on a container platform or serverless functions.

    The specific component matters less than the feedback loop:

    Measure → Attribute → Optimize → Retest

    After each change, compare the cost per successful task. Keep only changes that genuinely reduce it without undermining task acceptance.

    Conclusion

    High agent token usage is often driven less by the model itself than by the combination of repeated loops, full tool-result feedback, and blind retries.

    Start by attributing cumulative usage to individual actions. Then narrow retrieval, extract relevant content, compact history infrequently, constrain retries, and stabilize prompt prefixes.

    Finally, evaluate platforms by cost per successfully completed task, not token price alone. This is a more reliable approach than simply imposing a shorter context limit.