# Model Selection and Token Cost Control for AI Coding Agents

    AI coding agents can rack up surprisingly high token costs because they repeatedly re-read growing conversation history across multiple tool calls. This article explains why costs scale quadratically with session length, how to decouple model selection from your orchestration layer, how to route tasks to models by complexity tier, and practical techniques for controlling context size and improving prompt cache hit rates.

    Why Coding Agent Costs Spiral Out of Control

    The key difference between a coding agent and a simple Q&A session is that an agent repeatedly invokes tools around a task: reading files, searching code, executing commands, inspecting output, then reasoning further based on the results. Each step adds new context, and the model typically receives the full conversation history again on every turn.

    As a result, the input volume of a session isn’t just the length of your initial question—it accumulates over rounds. If each turn adds a roughly fixed amount of context, the input at round n grows proportionally to n, and the cumulative input across n rounds grows approximately proportionally to n². The longer the session, the faster costs climb. When the number of turns doubles, cumulative input usually grows by far more than 2x.

    There are four common sources of context bloat:

    • Over-scoped reads: pulling an entire directory or several large files into context just to understand one function.
    • Untruncated tool output: build logs, test output, and search results kept verbatim, consuming large chunks of the context window.
    • No pruning of conversation history: discussions irrelevant to the current goal remain in context and get re-billed on every turn.
    • Lossy summarization: compressing context to free up space can drop key constraints and confirmed decisions, forcing the model to re-explore and generating new costs.

    Understanding these mechanisms matters more than simply comparing model prices. For the same task, with proper context control, the billing gap between a low-cost model combination and a premium one can shrink considerably, while output quality stays comparable.

    Decouple Model Selection from Providers

    The optimal balance of cost and capability rarely lives on a single model. In practice, teams commonly need:

    1. Different tasks demand different capability levels—batch renaming doesn’t need a frontier model;
    2. Some models perform more reliably on specific languages or frameworks;
    3. Provider rate limits, pricing, and availability change over time;
    4. Teams need to switch to a backup provider without changing their workflow.

    To meet these needs, an agent’s architecture should separate task orchestration from model invocation. The orchestration layer only cares about the message list, tool definitions, and results; the invocation layer translates requests into each provider’s protocol and handles authentication, timeouts, and retries.

    Provider details belong in configuration, with keys injected via environment variables or a secrets management service—never committed to the repository. A configuration example (pseudocode):

    1. providers:
    2. primary:
    3. protocol: generic-chat-interface
    4. base_url: ${PRIMARY_BASE_URL}
    5. api_key: ${PRIMARY_API_KEY}
    6. model: model-large
    7. fallback:
    8. protocol: generic-chat-interface
    9. base_url: ${FALLBACK_BASE_URL}
    10. api_key: ${FALLBACK_API_KEY}
    11. model: model-small
    12. default_provider: primary

    Here model-large and model-small are placeholder names; actual values should come from your own team’s evaluation.

    Route Tasks to Models by Complexity Tier

    Tasks can be roughly grouped into three tiers:

    Tier Typical Tasks Selection Strategy
    Lightweight Renaming, formatting, boilerplate generation, explaining a single function Prefer low-cost models; prioritize response speed
    Standard Adding features on existing patterns, writing unit tests, local refactoring Balance capability against cost
    Advanced Cross-module design, hard bug triage, security-related review Use the strongest model to reduce rework

    Tiering should be based on actual measurement, not gut feeling. Prepare several representative tasks for each tier, record success rate, retry count, total time, and cost, then set default routing rules.

    Routing logic can stay simple:

    1. function select_model(task):
    2. if task.level == "light":
    3. return models.small
    4. if task.level == "standard":
    5. return models.medium
    6. return models.large

    Task tiers can be labeled manually or estimated automatically from signals such as the number of files involved, whether changes cross modules, or whether security judgment is required. Note that switching models mid-session invalidates existing context caches, and different models may interpret the same prompt differently—so switch at task boundaries whenever possible.

    Control Context Size

    4.1 Read on Demand

    Prefer symbol search or reference lookup to locate relevant code, and read only the target line ranges instead of whole files. Clarify the question you’re trying to answer before reading—this keeps a lot of irrelevant content out of the context.

    4.2 Truncate Tool Output

    Tool output often contains large amounts of redundant information. A common approach is to keep the head and tail, replace the middle with an omission marker, and prioritize preserving error messages. Example (pseudocode):

    1. function truncate_output(text, max_chars):
    2. if length(text) <= max_chars:
    3. return text
    4. head = first_part(text, max_chars * 0.6)
    5. tail = last_part(text, max_chars * 0.4)
    6. return head + "\n...[middle content omitted]...\n" + tail

    4.3 Split Sessions at Task Boundaries

    One session should pursue one clear goal. Once the goal is complete, write the conclusions into a notes file within the project; a new session can read that file to pick up where you left off, without retaining the full history.

    4.4 Maintain Persistent Notes

    Write established constraints, interface agreements, and open issues into files. After compression or a session restart, key information can be recovered from the file. This is more reliable than relying entirely on automatic summarization, and it’s easy for humans to review.

    4.5 The Trade-offs of Compression

    Compression frees up context space, but summaries are not fully reliable. After compressing, verify that key constraints are still preserved and add them manually if needed. If the same session needs frequent compression, it usually means the task is being split at too coarse a granularity—adjust your working approach first.

    Improve Prompt Cache Hit Rates

    Many providers offer cache reuse for identical prefix segments of prompts. When the prefix matches, the corresponding computation can be reused, reducing both cost and latency. Billing rules vary by provider, so defer to the official documentation.

    To improve hit rates, follow these principles:

    • Keep the system prompt and tool definitions stable—avoid random variation between turns;
    • Place dynamic content such as timestamps and random identifiers at the end of messages, not in the prefix;
    • Avoid rewriting content in the middle of conversation history; modifying history invalidates all caches after that point;
    • Keep the ordering of tool definitions fixed, so sorting changes don’t break prefix consistency.

    For monitoring, if the provider’s response includes cache-related usage fields, record them and track hit ratio per session. A sudden drop in hit rate usually indicates the prefix has changed—start by investigating recent prompt or