Token Cost Optimization for LLM Agent Tasks: Practices and Checklist

    This article examines why LLM Agent tasks consume more tokens than single-turn Q&A and identifies four major cost drivers: cache hit rate, output length, over-reasoning, and execution framework design. It presents a practical workflow for measuring token usage, engineering context, routing models by task complexity, constraining output, controlling retries, setting termination safeguards, balancing cost against quality, and establishing ongoing monitoring and governance.

    1. Background: Cost Structure of Agent Tasks

    Single-turn Q&A involves one input and one output. An Agent task goes through multiple rounds of planning, tool calls, and result backfilling. At each step, a longer context must be resubmitted to the model. As a result, for the same task goal, different Agent implementations can differ by several times in token consumption.

    The cost of a single task can be roughly broken down as:

    1. Total cost = Σ(uncached input tokens × input unit price)
    2. + Σ(cached input tokens × cache unit price)
    3. + Σ(output tokens × output unit price)

    Input tokens often account for the largest share in multi-step calls. System prompts, conversation history, and raw tool returns accumulate as steps increase. Output token unit prices are usually higher than input token unit prices, so redundant model-generated content also needs focused control.

    Pricing rules, caching strategies, and multiplier settings vary by provider. Actual values should be based on the relevant platform documentation and billing statements. From an engineering perspective, what is truly controllable is the call structure itself.

    2. Four Key Factors Affecting Token Consumption

    2.1 Cache Hit Rate

    Most inference services reuse computation results for identical prefix content. Caching takes effect only when the prefix is exactly the same. Therefore, an Agent prompt structure should follow two principles:

    1. Put stable content first: System role definitions, tool descriptions, and fixed specifications should be placed at the beginning of the prompt and remain byte-for-byte identical.
    2. Put dynamic content last: Changing content such as the current time, user ID, and random identifiers should be placed at the end to avoid breaking the prefix.

    A common anti-pattern is inserting a timestamp on the first line of the system prompt. As a result, the prefix differs on every call, and cache hits become almost impossible.

    2.2 Output Length

    In intermediate steps, an Agent often only needs a structured result, such as a tool name and parameters, but it tends to output full explanatory text. Solutions include:

    • Requiring JSON or fixed-format instructions in intermediate steps to reduce natural-language descriptions.
    • Setting reasonable maximum output lengths for different steps.
    • Explicitly prohibiting repetition of user input and restatement of historical content in the prompt.

    2.3 Over-Reasoning

    Complex reasoning modes can improve accuracy on difficult problems. However, for tasks such as format conversion, field extraction, and simple summarization, the additional thinking process only increases consumption. A reasonable approach is to decide reasoning depth based on task difficulty rather than enabling the strongest reasoning mode uniformly for all requests.

    2.4 Execution Framework Design

    The execution framework refers to the Agent’s scheduling logic, including task decomposition, tool scheduling, result compression, failure retries, and termination conditions. Framework design often has a greater impact on cost than model selection itself. For example:

    • A loop without termination conditions can lead to repeated calls.
    • If raw web pages or database records returned by tools are all placed into the context, input tokens can grow rapidly.
    • Rerunning the entire chain from the beginning after a failure can consume several times more than retrying only the failed step.

    3. Measure First, Then Optimize

    Metrics must be established before optimization; otherwise, it is difficult to determine whether a change is effective. At a minimum, track the following metrics:

    Metric Meaning Purpose
    Input tokens per task Total input across the full task workflow Detect context bloat
    Cache hit ratio Share of input tokens that hit the cache Validate prefix structure
    Output tokens per task Total output across the full task workflow Detect redundant generation
    Average steps Number of model calls per task Detect loops and repeated calls
    Retry rate Share of steps that require retry Detect tool or format issues
    Cost per task Average cost by task type Evaluate optimization gains

    The following example code summarizes the cost of a single task:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class StepUsage:
    4. input_tokens: int
    5. cached_tokens: int
    6. output_tokens: int
    7. def estimate_task_cost(steps, price_input, price_cached, price_output):
    8. """Price parameters are passed by the caller according to the pricing rules of the service used, in price per token."""
    9. total = 0.0
    10. for s in steps:
    11. uncached = s.input_tokens - s.cached_tokens
    12. total += uncached * price_input
    13. total += s.cached_tokens * price_cached
    14. total += s.output_tokens * price_output
    15. return total

    Logs should record the task ID, step number, token usage, and cache information for each model call. With this data, comparative analysis can be performed by task type, user segment, and version number.

    4. Main Optimization Strategies

    4.1 Context Engineering

    The core of context engineering is to keep only the information truly needed by subsequent steps. Common methods include:

    • Sliding window: Keep only the most recent several rounds of conversation.
    • Stage summaries: After each subtask is completed, compress the process into a short conclusion and replace the original records.
    • Tool result trimming: After a tool returns, extract only the fields relevant to the current goal and discard unrelated content.
    1. def build_context(system_prompt, summary, recent_messages, max_recent=6):
    2. """Stable prefix first, summary in the middle, recent messages last, balancing cache hits and information completeness."""
    3. return [system_prompt, summary] + recent_messages[-max_recent:]

    The order here has a clear intent: system prompts and summaries change less often and are placed earlier to form a cacheable prefix more easily; recent messages change frequently and are placed at the end.

    4.2 Tiered Model Routing

    Not all subtasks require the same model. Routing by task characteristics can significantly reduce cost while keeping quality under control.

    1. def route_model(task):
    2. if task.estimated_steps <= 2 and not task.needs_tool_chain:
    3. return "light" # Simple extraction, format conversion, short text generation
    4. if task.requires_long_reasoning:
    5. return "strong" # Multi-condition reasoning, complex planning, code review
    6. return "standard" # Other routine office tasks

    Routing rules need to be validated with an evaluation set. If the success rate of a lightweight model drops significantly on a certain task type, that task type should be moved up one tier rather than downgraded based on experience alone.

    4.3 Output Constraints

    Output constraints include format constraints and length constraints. Format constraints are implemented through JSON Schema or explicit field lists, so the model outputs only the content needed for parsing. Length constraints are implemented by setting a maximum number of output tokens, but sufficient space must be reserved to prevent truncated results from triggering retries.

    4.4 Retry Granularity Control

    Retries should be performed per step, not per task. In practice, this can be achieved by:

    • Saving an input snapshot and output result for each step.
    • Rerunning only the failed step when a step fails.
    • Setting idempotency identifiers for tool calls to avoid side effects from duplicate execution, such as sending messages twice or writing records twice.

    4.5 Termination Conditions and Loop Protection

    The Agent framework should set explicit termination conditions: maximum number of steps, maximum token budget, and goal achievement judgment. When the budget is exceeded, the task should be stopped and the completed part returned rather than continuing to try.

    5. Balancing Cost and Quality

    Cost reduction must not come at the expense of results. It is recommended to establish a fixed evaluation set covering common task types and edge cases, and to record two categories of metrics:

    • Quality metrics: Task success rate, key field accuracy, and human acceptance rate.
    • Cost metrics: Cost per task, average tokens, and average steps.

    Every optimization should be compared on the evaluation set. The ideal outcome is a significant reduction in cost metrics while quality metrics remain basically unchanged. If quality drops beyond an acceptable range, the change should be rolled back or enabled only for low-risk task types.

    6. Monitoring and Governance

    Cost governance needs to run continuously rather than as a one-time effort. Recommended practices include:

    1. Tiered quotas: Set token budgets by team, project, or user, and issue alerts when they are exceeded.
    2. Cost dashboard: Use logging services and monitoring alerting systems to show unit cost trends by task type.
    3. Anomaly detection: Automatically flag and notify developers when the number of steps or tokens for a single task spikes.
    4. Version comparison: After each prompt or framework change, compare cost and quality metrics between the previous and new versions.

    7. Implementation Checklist

    • Stable content is placed first in prompts, and dynamic content is placed last.
    • Token usage and cache hits are recorded for every model call.
    • Intermediate steps use structured output and set maximum output lengths.
    • Tool return results are trimmed by field before entering the context.
    • Tiered routing is enabled for simple subtasks and validated with an evaluation set.
    • Retries are performed per step, and tool calls have idempotency protection.
    • Step limits and token budgets are set, and tasks are stopped when exceeded.
    • A joint cost and quality evaluation set is established, with before-and-after comparisons for every change.