Reducing AI Agent Costs: Model Tiering and Call Chain Optimization
This article explains why AI agent task costs can rise quickly and how to find the largest cost sources. It covers routing tasks across model tiers by complexity with fallback on failed validation, and controlling input size through context compression. It includes a worked cost example and code samples for routing and structured context management.
1. Why Agent Costs Easily Get Out of Control
An agent differs from a single question-and-answer exchange. It works toward a goal by repeatedly planning, calling tools, reading the results, and deciding the next step. Each round of decisions usually involves one or more model calls. The more complex the task, the longer the call chain, and costs often grow faster than expected.
Cost overruns mainly come from four sources:
- Many call rounds: A task split into more than ten steps resends the prompt and context at every step.
- Growing context: Conversation history and raw tool outputs are kept in full, so input tokens accumulate with each round.
- Large models for small tasks: Work such as format conversion and field extraction does not need the strongest reasoning ability, yet it is sent to the highest-tier model.
- Wasteful retries: When a tool times out or an output fails format checks, the system retries automatically, and costs can quietly double.
These four problems compound one another. For example, a search may return large amounts of raw web content. That content is written into the context in full, so every later call pays for it, even though the model uses only a few sentences of it.
2. Break Down Costs Before Deciding What to Optimize
Before optimizing, you need to know where the money goes. The cost of a single task can be roughly expressed as:
Single task cost ≈ Σ(input tokens × input price + output tokens × output price) + Σ tool call costs
The following hypothetical example shows how each factor affects the total. Assume a task makes 8 model calls, each with an average of 3,000 input tokens and 500 output tokens. Assume an input price of 0.002 yuan per 1,000 tokens and an output price of 0.008 yuan per 1,000 tokens. These figures are for illustration only and are not actual pricing.
- Cost per call: 3 × 0.002 + 0.5 × 0.008 = 0.010 yuan
- Total task cost: 0.010 × 8 = 0.080 yuan
If context compression reduces the average input to 1,000 tokens:
- Cost per call: 1 × 0.002 + 0.5 × 0.008 = 0.006 yuan
- Total task cost: 0.006 × 8 = 0.048 yuan
In this example, context compression alone cuts costs by 40%. Actual savings depend on the task structure. Track costs separately by task type, number of call rounds, and tool category. Then find the parts that account for the largest share and decide which optimization to tackle first.
3. Tier Models by Task Complexity
The core idea of model tiering is to send simple tasks to cheaper, faster models and reserve more capable models for complex tasks. Common tiers include:
- Light tier: Classification, rewriting, format conversion, key field extraction, and simple Q&A.
- Standard tier: Multi-step summarization, routine code changes, and data organization and synthesis.
- Strong reasoning tier: Complex planning, cross-file code reasoning, and tasks that require strict logical validation.
There are three common routing strategies. The first is rule-based routing, which maps task-type labels directly to a tier. It is simple to implement, and its behavior is predictable. The second is classifier routing, where a small model first estimates task difficulty and then selects a tier. It suits scenarios with many task types that rules cannot fully enumerate. The third is confidence-based fallback, which tries the light tier first and escalates to a stronger tier when the output fails validation.
The code below combines rule-based routing with fallback. The caller provides call_model and validate, which handle model calls and output validation.
from dataclasses import dataclass@dataclassclass TaskRequest:task_type: strprompt: strneeds_reasoning: bool = FalseLIGHT_TASKS = {"classify", "rewrite", "extract_field", "format_convert"}TIER_ORDER = ["light", "standard", "reasoning"]def choose_tier(req: TaskRequest) -> str:if req.needs_reasoning:return "reasoning"if req.task_type in LIGHT_TASKS:return "light"return "standard"def run_with_fallback(req: TaskRequest, call_model, validate) -> str:start = TIER_ORDER.index(choose_tier(req))for tier in TIER_ORDER[start:]:output = call_model(tier=tier, prompt=req.prompt)if validate(output):return outputraise RuntimeError("No tier produced output that passed validation")
This code makes two points. First, the fallback depends on the validation function. Without an automated check, the system cannot tell whether the light tier’s output is usable, so fallback cannot trigger. Validation can take the form of a JSON structure check, a field completeness check, a unit test, or rule matching. Second, monitor the escalation rate. If many tasks escalate to the strong reasoning tier, the routing rules or the capability boundaries set for the light tier need adjustment.
4. Compress Context to Control Input Size
Input tokens are the most overlooked part of agent costs, because every call re-bills the repeated content. There are four common ways to control context size:
- Sliding window: Keep only the most recent few rounds of conversation in full. Older content is no longer sent verbatim.
- Summary compression: Condense earlier conversation into a summary. The light tier can generate the summary at a much lower cost than repeatedly sending the full history.
- Structured state: Organize key information into fields such as the goal, completed steps, and pending items. Fields replace lengthy natural-language history.
- Tool result trimming: Tool outputs often contain many irrelevant fields. Keep only the parts that later steps need before writing them to the context.
The code below combines structured state with a sliding window.
def render_state(state: dict) -> str:return (f"Task goal: {state['goal']}\n"f"Completed: {'; '.join(state['done'])}\n"f"Pending: {'; '.join(state['todo'])}")def build_context(state: dict, recent_messages: list, summarize, max_recent: int = 6) -> list:old_messages = recent_messages[:-max_recent]kept = rec
