Cost Control and Model Routing for AI Agents: A Practical Guide

    As AI coding agents shift the bottleneck from model capability to compute budget, costs scale with total turns, context length, and token pricing. This article presents a four-layer engineering framework for keeping agent workflows affordable: task decomposition with clear termination conditions, context engineering through retrieval and history compression, tiered model routing behind a unified gateway, and observability metrics tied to subscription or usage-based billing. It also outlines a four-week rollout plan and common pitfalls to avoid.

    1. The Problem: The Bottleneck Has Shifted from Capability to Compute Budget

    Early on, the main pain point with AI coding tools was that models were not smart enough and the generated code did not run. As toolchains matured and models became noticeably more usable on real engineering tasks, the bottleneck moved. An agent that can autonomously read files, modify code, and run tests across dozens of consecutive turns no longer has a cost determined by a single question-and-answer exchange. Instead, cost is determined by the product of three factors: total turns × context length per turn × unit price.

    A typical scenario is an automated pipeline for a “smart notes library + writing assistant”: it scans the knowledge base, extracts key points, generates a first draft, and then runs a round of polishing. Running for one hour and ending up with a bill in the tens of yuan is not unusual. This is not an anomaly; it is a consequence of the architecture. Every inference turn of an agent must carry the system prompt, tool definitions, historical messages, and retrieved snippets again. Context grows monotonically with each turn, and cost rises at an approximately superlinear rate.

    Therefore, cost governance cannot rely on “using it a few fewer times”; it requires engineering measures. The following sections describe practices at four levels.

    2. Level 1: Task Decomposition and Execution Boundaries

    The core reason agents are expensive is “unbounded autonomy.” The most effective way to control cost is to rewrite open-ended tasks into pipelines with explicit termination conditions.

    • Define acceptance criteria: Before starting a task, write down the conditions that determine “done” (for example, a specific test passes or a file has all required fields), so the model does not repeatedly self-verify.
    • Limit the per-turn tool-call budget: Set a maximum number of tool calls and a maximum number of consecutive failures for a session. After two failures, fall back to human confirmation.
    • Split stages: Break “research → design → coding → verification” into separate sessions, loading only the necessary context at each stage to avoid history accumulating in a long session.

    An illustrative way to express task constraints (pseudocode, conveying the idea of constraints only):

    1. task = {
    2. goal: "Add unit tests for the specified module",
    3. context: [file_list], # Inject only relevant files, not the entire repository
    4. max_tool_calls: 12,
    5. max_retries: 2,
    6. done_when: "line coverage of the target file in coverage_report >= 0.8"
    7. }

    3. Level 2: Context Engineering, the Main Battlefield for Cost Control

    For the same task, costs can differ by several times, and most of the difference comes from how context is organized rather than from the model itself.

    1. Use retrieval instead of full-volume feeding. First use keyword or vector retrieval to locate candidate snippets, then read specific line ranges on demand, avoiding “stuffing an entire directory into the prompt.”
    2. Compress history structurally. Distill early conversation into a short state summary (files changed, options ruled out, pending items), and carry only the summary plus increments in later turns.
    3. Trim tool definitions. Tool descriptions are billed every turn; merging tools with overlapping semantics and shortening parameter descriptions yields considerable savings in long sessions.
    4. Use a cache-friendly layout. Put stable, unchanging content (system instructions, specification notes) at the front of the prompt and volatile content at the back to better hit the inference-side caching mechanism (support varies by platform; refer to the actual documentation).
    5. Constrain the output side. Requiring “output only the patch, do not repeat the full file” can significantly reduce generated tokens.

    A reusable suggestion for context budget allocation:

    1. Total budget 100%
    2. ├─ Stable instructions and specs ≤ 15%
    3. ├─ Retrieved relevant code ≤ 50%
    4. ├─ State summary and pending items ≤ 20%
    5. └─ Reserved output space ≥ 15%

    4. Level 3: Model Tiering and Unified Routing

    Different tasks have vastly different demands on model capability. Using a flagship model for formatting, renaming, and writing comments is a common source of waste. The sensible approach is to establish tiered routing:

    • L1 lightweight tier: Format cleanup, comment completion, simple rewrites, using a small-parameter model or a local model.
    • L2 main tier: Routine business code writing and single-file refactoring, using a mid-tier model with balanced cost-performance.
    • L3 hard-problem tier: Cross-module refactoring, complex defect localization, and architecture design, which invoke the strongest reasoning model.

    In engineering, an abstraction gateway can hide the differences and decouple the “routing policy” from “business code”:

    1. def route(task):
    2. if task.risk == "low" and task.files <= 1:
    3. return "small" # Lightweight tier
    4. if task.cross_module:
    5. return "flagship" # Hard-problem tier
    6. return "balanced" # Main tier

    The gateway layer also needs to take on four responsibilities: unified authentication and key management, retry and fallback on failure, usage accounting by project, and log redaction. This way, switching the underlying model only changes configuration, not business code.

    5. Level 4: Subscription Quotas and Observability

    When unit price is no longer the only variable, the billing model itself also affects cost structure. Usage-based billing suits scenarios with low, predictable fluctuation; subscription models (a fixed monthly request quota or quota pool) suit high-frequency, continuous development scenarios, converting unpredictable marginal costs into fixed expenses. When choosing, focus on three points: whether the quota covers peak usage, whether exceeding the quota results in throttling or continued billing, and whether the quota can be shared across multiple tools.

    Regardless of the model adopted, an observability loop must be established; otherwise, there is no basis for optimization. The minimum viable metric set includes:

    • Token consumption and latency per task (aggregated by project and by model tier);
    • Cache hit rate and average context length;
    • Tool-call success rate and average number of retries;
    • Cost per unit of effective output (for example, the cost corresponding to “each commit that passes review”).

    With these data, you can determine the direction of optimization: if average context length keeps rising, the problem lies in context governance; if the retry count is high, the problem lies in prompt and tool design; if the proportion of the lightweight tier is too low, the routing policy has not been implemented.

    6. Rollout Roadmap and Common Pitfalls

    A four-week progression is recommended: in week one, integrate a unified gateway and enable usage accounting to establish a cost baseline; in week two, implement the context budget and retrieval-based feeding; in week three, launch tiered routing and failure fallback; in week four, evaluate the billing model and plan quotas.

    Three common pitfalls need to be flagged: first, blindly pursuing the strongest model, which inflates the cost of simple tasks by several times; second, long sessions that do not converge, with history growing without bound; third, looking only at unit price rather than “cost per unit of effective output,” overlooking the hidden overhead of rework.

    7. Conclusion

    The cost problem of AI coding is essentially a software engineering problem: replace free divergence with boundary constraints, replace full-volume feeding with context engineering, replace one-size-fits-all with tiered routing, and replace intuition with observable data. Baidu AI Cloud continues to invest in model services and engineering governance. Developers can combine the framework above to build cost-controlled, quality-stable agent workflows in their own environments.