Optimizing Cost and Efficiency for Long-Horizon AI Agent Tasks: Reducing Token Usage and Execution Time
Long-running AI agent workflows can become expensive and slow as context accumulates, outputs grow, and ineffective loops consume additional model calls. This article explains how to measure task performance, manage context, and structure execution to reduce token consumption and latency without sacrificing completion quality.
1. Why Long-Horizon Tasks Become More Expensive
When an AI agent handles a complex task, it typically goes through multiple stages, such as reading files, breaking down objectives, writing code, calling tools, and checking results. Each stage may require one or more model calls. A complete workflow can take tens of minutes. During that time, the model may repeatedly inspect the same file or accidentally reintroduce an issue that was already fixed.
Cost increases mainly for three reasons.
The first is the continuous accumulation of input context. Each model call typically includes previous conversation history, tool results, and file contents. If every call contains the output of all previous steps, the input size of the nth call grows linearly with n. As a result, the total input volume across the task grows approximately in proportion to n². The more rounds a task requires, the faster the cost increases.
The second is overly verbose output. When the model provides excessively long explanations, reasoning, or status reports, the output token count increases, and response times become longer.
The third is ineffective looping. Repeatedly reading the same files, running identical checks, or failing to perform regression validation after a change can add multiple rounds without producing meaningful progress.
A simplified model can be used to estimate total cost:
Total cost ≈ Σ (input tokens in round i × input price+ output tokens in round i × output price)
This formula shows that optimization should target both the size of each round and the total number of rounds. Compressing output alone has limited value if the task still takes twenty rounds to complete.
2. Define Metrics Before Optimizing
Optimization cannot be evaluated without measurement. At minimum, track the following metrics:
- Task completion rate: The proportion of tasks completed according to the acceptance criteria.
- Cost per task: The cost calculated from the input and output tokens consumed by each task.
- End-to-end latency: The time from task intake to result delivery.
- Average number of rounds: The number of model calls required to complete a task.
- Rework rate: The proportion of tasks that fail again after modification or require a rollback.
Cost should not be the only metric. If cost decreases while the completion rate also declines, the optimization has weakened the system’s capabilities. A more useful metric is the completion rate per unit cost, calculated as completion rate divided by cost per task. Optimization is genuinely effective when this value improves.
It is also helpful to establish a fixed benchmark task set. After changing prompts, context strategies, or model configurations, replay the same tasks and compare the metrics above.
3. Context Management: Keep Only What the Current Decision Requires
Context is a major source of cost. It can generally be controlled in three ways:
- Summary compression: When the history exceeds a threshold, compress earlier steps into a structured summary that preserves the goal, completed work, key conclusions, and unresolved issues.
- On-demand retrieval: Instead of placing entire files into the context, retrieve relevant sections by file path or keyword.
- Externalize state: Store task state in an external structure so that the model reads only the fields required for each round.
An example implementation is shown below:
from dataclasses import dataclass, field@dataclassclass TaskState:goal: strdone: list[str] = field(default_factory=list)open_issues: list[str] = field(default_factory=list)key_facts: dict[str, str] = field(default_factory=dict)def build_context(state: TaskState, recent_messages: list[str],max_recent: int = 6) -> str:"""Build each round from a state summary and recent messagesinstead of including the entire history."""parts = [f"Goal: {state.goal}","Completed: " + "; ".join(state.done[-10:]),"Open issues: " + "; ".join(state.open_issues),"Key facts: " + "; ".join(f"{k}={v}" for k, v in state.key_facts.items()),"Recent messages:",*recent_messages[-max_recent:],]return "\n".join(parts)
The key idea is to move memory from the complete conversation history into structured state. The model does not need to reread the entire process; it only needs the goal, current progress, and unresolved issues.
Summary quality directly affects results. If a summary omits a critical constraint, later steps may drift away from the original objective. User requirements, interface agreements, and confirmed root causes should receive higher retention priority. After generating a summary, perform a completeness check.
