Optimizing Agent Task Token Costs: Engineering Practices and Approaches

    AI agents incur significantly higher costs than single-turn Q&A due to multi-round planning, tool calls, and cumulative context resubmission. This article explores the composition of token consumption in agent tasks and identifies key factors affecting costs, including cache hit rates, output length, over-reasoning, and context bloat. It further outlines optimization strategies at the execution framework level, such as task decomposition, model routing, and early stopping, while emphasizing the importance of a robust cost measurement system and practical landing precautions.

    1. Background

    AI agents and single-turn Q&A have different cost structures. Single-turn Q&A typically involves a single model call, while agents require multi-round planning, tool calling, result reading, and plan revision around a specific goal. Each round resubmits the context, causing total consumption to often be multiples of a single call. Estimating costs solely based on model unit price usually leads to significant deviations.

    Even with the same model and task, consumption differences between implementations remain significant. These differences primarily stem from the execution framework’s design—namely, the agent’s scheduling logic, context management, and tool orchestration strategies—rather than the model’s unit price.

    2. Composition of Token Consumption

    A single agent task’s token consumption can be broken down into four parts:

    • Input Tokens: System prompts, conversation history, tool definitions, retrieval results, etc.
    • Output Tokens: Model-generated answers, planning text, and tool call parameters.
    • Reasoning Tokens: The internal thinking process generated by the model when deep reasoning is enabled; billing methods vary by service.
    • Tool Return Values: External tool execution results written back into the context, which are repeatedly counted as input in subsequent rounds.

    The fourth part is the most easily overlooked. A tool returning extensive logs without truncation will have its output repeatedly billed across the next dozen or so rounds.

    3. Key Factors Affecting Consumption

    3.1 Cache Hit Rate

    Most model services offer cached pricing for identical input prefixes, with hit portions significantly cheaper than missed ones. The prerequisite for caching is a byte-for-byte identical request prefix. Therefore, stable content (system instructions, tool definitions, fixed examples) should be placed at the beginning of the prompt, while dynamically changing content per round (current state, new user input) should be placed at the end.

    Common practices that break caching include embedding timestamps in system prompts, randomly shuffling tool list order each request, and regenerating history summaries with inconsistent formats. These minor changes can drastically reduce the hit rate.

    3.2 Output Length

    The unit price of output tokens is typically higher than that of input tokens. Agents often generate large paragraphs of explanatory text during intermediate steps, which offers almost zero value for machine parsing. Measures to compress output include:

    • Outputting only structured parameters (e.g., JSON) during tool call stages without appending explanatory text.
    • Setting clear output limits for intermediate steps.
    • Separating the final user-facing response from internal planning, generating complete text only in the final step.

    3.3 Over-reasoning

    Complex reasoning modes suit difficult problems, but for tasks like format conversion, field extraction, or simple judgments, the extra thinking process only increases consumption. A sound approach is to grade by task difficulty: use low reasoning intensity or disable reasoning for simple steps, and enable deep reasoning only for complex planning.

    3.4 Context Bloat

    As rounds increase, historical messages continuously accumulate. Without cleanup, input in later rounds will far exceed early ones. Common strategies include:

    • Summarizing intermediate processes of completed subtasks, keeping only conclusions.
    • Truncating or paginating excessively long tool outputs while retaining location information for re-reading when needed.
    • Setting round or token budget limits, triggering a convergence process and outputting intermediate results when exceeded.

    4. Execution Framework Optimization Strategies

    The execution framework determines how the above factors are combined. A mature framework typically features the following capabilities:

    1. Task Decomposition: Breaking the goal into independently verifiable subtasks to reduce single-context scale.
    2. On-demand Tool Loading: Injecting only the tool descriptions potentially needed for the current step into the context, rather than all definitions at once.
    3. Model Routing: Selecting different scale models based on subtask types. Assigning classification and extraction tasks to small models, and comprehensive analysis tasks to large models.
    4. Early Stopping on Failure: Terminating and reporting promptly when consecutive tool calls make no progress, avoiding continuous consumption of the budget by invalid loops.

    Below is a pseudocode snippet illustrating the control logic:

    1. def run_agent(task, budget):
    2. context = build_stable_prefix() # Place stable content at the front
    3. spent = 0
    4. for step in plan(task):
    5. model = route_model(step.kind) # Select model based on subtask type
    6. effort = "low" if step.kind == "extract" else "high"
    7. result = call_model(context, step, reasoning=effort, max_output=512)
    8. spent += result.usage.total
    9. if spent > budget:
    10. return summarize_partial(context)
    11. context = compact(context, result.observation, limit=2000)
    12. if no_progress(context, window=3):
    13. break
    14. return finalize(context)

    This code demonstrates four control points: prefix stability, step-based model selection, output limits, and budget/early stopping. Specific parameters should be adjusted based on business data and not applied directly.

    5. Establishing a Cost Measurement System

    Before optimizing, a baseline must be established. It is recommended to record each task’s consumption across the following dimensions:

    • Task type (e.g., data processing, document generation, code modification).
    • Input, output, reasoning, and cache-hit token counts.
    • Number of tool calls and average rounds.
    • Task success rate and manual correction ratio.

    Looking only at averages easily masks problems. Pay attention to percentiles, such as P90 consumption, because a few long-tail tasks often account for the majority of costs. After each change, run regression tests on a fixed task set, comparing both cost and success rate. If cost drops but success rate drops simultaneously, the change cannot be retained.

    6. Landing Precautions

    • Cost optimization cannot come at the expense of correctness. Compressing context and losing key constraints may cause silent task failures, inadvertently increasing manual costs.
    • Caching and summarization strategies introduce consistency risks. Key states should retain original records for troubleshooting.
    • Billing parameters, pricing tiers, and quota rules change frequently; design them as configurable items rather than hardcoding them.
    • If tool outputs contain user data, desensitize them before entering the context.