How to Cut Token Costs in the Agent Era

    As AI agents take over multi-step tasks, their token bills can spiral out of control. This article breaks down where tokens are actually spent in agent workflows and presents five practical strategies to reduce costs: context engineering, tiered model routing, caching and reuse, execution path optimization, and observability with cost attribution. It also highlights common pitfalls, such as focusing only on context length while ignoring retries and loops, and explains how to balance output quality with cost through layered scheduling and on-demand loading.

    1. Why Agent Token Bills Spiral Out of Control

    Early conversational applications followed a simple pattern: the user asks a question, and the model answers. Contexts were short, turns were few, and costs stayed predictable. Once applications evolved into office-oriented agents, however, the cost structure changed fundamentally. An agent no longer waits passively for instructions. It plans autonomously in the background, calls tools, reads files, and runs validation loops until the task converges.

    The core issue is that every step an agent takes is not an isolated inference call. It is a fresh inference that carries the full history and all tool results. The first turn may involve only a few thousand tokens, but after multiple rounds of tool calls and result回填, the context snowballs. Cumulative consumption in the tens of thousands of tokens or higher is not unusual. On top of that, when “deep thinking” is enabled by default in some models, output-side costs are amplified as well.

    Reducing costs therefore cannot rely on a single trick. It requires a systematic approach that starts with understanding how consumption is generated.

    2. Cost Attribution: Where Do Tokens Actually Go?

    Before optimizing, you need attribution. Token consumption in agent scenarios can be roughly divided into four categories:

    • Input context: system prompts, tool descriptions, conversation history, retrieved snippets, and file contents.
    • Tool result backfill: file reads, API responses, and log fragments are often large and get carried into subsequent turns repeatedly.
    • Reasoning and output: regular output plus explicit thinking traces.
    • Wasted and duplicate consumption: failed retries, repeated planning, and repeated requests that miss the cache.

    The third and fourth categories are the ones most often overlooked. Many teams focus only on “the context is too long” and miss the multiplier effect of failed retries and repeated planning.

    3. Strategy 1: Context Engineering to Cut Input at the Source

    Context is the largest source of cost and the most controllable part.

    1. Layered loading. Split context into a resident layer, a task layer, and an on-demand layer. The resident layer holds only the role, constraints, and tool index. The task layer holds the current goal and key state. The on-demand layer is fetched through tools only when needed, avoiding stuffing an entire large file into the context at once.

    2. Structured compression. Summarize and structure tool outputs, keeping only field names, key values, and reference locations instead of copying the raw text. Example:

    1. def compress_tool_result(raw: dict, keep_fields: list[str]) -> dict:
    2. # Keep only necessary fields and truncate overly long text
    3. slim = {k: raw.get(k) for k in keep_fields if k in raw}
    4. for k, v in slim.items():
    5. if isinstance(v, str) and len(v) > 800:
    6. slim[k] = v[:800] + "...[truncated]"
    7. return slim
    1. Rolling history summaries. Compress early turns into a state summary that preserves decisions and references to artifacts while discarding procedural filler. When precise traceback is needed, retrieve content on demand by reference ID instead of keeping it resident in the context.

    2. Retrieval instead of full reads. Replace “read the entire file” with “search to locate, then read locally.” This is one of the most effective structural optimizations on the input side.

    4. Strategy 2: Tiered Scheduling of Models and Reasoning

    Different tasks have vastly different model capability requirements. Using the strongest model for everything is a common waste.

    • Intent routing: run a lightweight classification first. Simple Q&A and formatting extraction go to a low-cost model; complex planning and cross-file reasoning escalate to a strong model.
    • Thinking budget: make “whether to think deeply” a configurable option, enabled by task risk level, to avoid default high-intensity reasoning across the entire chain.
    • Small-model fallback: for repetitive, pattern-fixed subtasks, use a small model or a rule-based approach, reserving the strong model for key decision points.

    In engineering, a routing layer can consolidate this logic:

    1. def route(task):
    2. if task.risk == "low" and task.steps <= 2:
    3. return "light_model"
    4. if task.cross_file or task.risk == "high":
    5. return "strong_model"
    6. return "standard_model"

    5. Strategy 3: Caching and Reuse to Eliminate Duplicate Consumption

    Many agent calls are highly similar, so caching offers clear benefits.

    • Prefix caching: place stable system prompts and tool descriptions at the very front of the context to improve prefix reuse hit rates.
    • Semantic caching: build cache keys for high-frequency similar requests; on a hit, return directly and skip the entire inference round.
    • Tool result caching: set short-term caches for idempotent operations such as file reads and API queries to avoid repeatedly backfilling the same content.
    • Plan reuse: solidify successful task paths into reusable templates to reduce repeated planning overhead.

    6. Strategy 4: Execution Path Optimization to Reduce Wasted Turns

    • Parallelize independent tool calls to reduce serial waiting and turn stacking.
    • Set a maximum step count and timeout circuit breaker to prevent the agent from getting stuck in loops.
    • Use backoff for failed retries, and terminate immediately on determinable failures instead of retrying pointlessly.
    • Replace “plan first, then execute” with “small steps, fast iteration plus validation” to shorten the single-chain length.

    7. Strategy 5: Observability and Cost Attribution

    Without measurement, there is no optimization. Build a minimal viable observability loop:

    • Log input, output, cache hits, model tier, and latency for every call.
    • Attribute costs by task, by user, and by tool to locate high-consumption sources.
    • Set budget thresholds and alerts; when exceeded, automatically downgrade the model or truncate the context.
    • Use offline replay to evaluate the two-way impact of strategy changes on both quality and cost, avoiding “cutting cost while cutting quality.”

    Example metric definitions:

    1. Cost per task = Σ(input tokens × input price + output tokens × output price)
    2. Cache benefit = hit count / total request count
    3. Effective step ratio = steps that advance state / total steps

    8. Common Pitfalls

    • Compressing context only, while ignoring retries and loops, still leads to runaway costs.
    • Using the strong model for everything and overlooking the structural savings from task tiering.
    • Over-compression that loses critical information, triggers more rework turns, and ends up costing more.
    • Looking only at per-turn price and not cumulative turns, missing the multiplier effect.

    9. Conclusion

    Cost governance in the agent era is essentially about transforming “unrestrained context accumulation and full-chain strong reasoning” into an engineering system of “tiered scheduling, on-demand loading, cacheable reuse, and observable attribution.” The methods above are general technical practices that can be combined flexibly according to the capability boundaries of a specific platform. In related practices at Baidu AI Cloud, the balance between quality and cost is typically achieved through a combination of general capabilities such as model tiering, context governance, and monitoring alerts, rather than relying on a single trick.