Reducing Token Costs in AI Coding Assistants Without Switching Models

    This article explains why tool definitions and raw tool outputs inflate token usage in LLM-based coding agents, and how changing the interaction between the agent and its tools can cut that cost while keeping the same model. It covers on-demand tool injection, local filtering with dual-channel output, batched script execution, how to measure the results, and the security controls needed for running generated scripts.

    LLM-based programming assistants have become a daily tool for many development teams. They improve coding efficiency, but token bills grow along with them. Cross-file refactoring, large-scale log analysis, and pulling data from external systems are especially expensive. In the past, teams had limited options: wait for cheaper new models, or switch to smaller models with fewer parameters. The second option often reduces reasoning quality, which leads to more rework in code review.

    A recent approach offers a third option: keep the same model and change how the agent interacts with its tools. This article first examines where token costs come from in a traditional workflow, then explains how this approach works, and finally discusses how to verify the results and deploy the approach safely.

    1. Where Token Costs Come From in Traditional Agents

    In a default workflow, the model decides each tool call one turn at a time. Suppose an assistant needs to modify a function. It might first search for files with a Bash command, then call a read tool to view the code, and finally call an edit tool to submit the change. The output of each step returns to the model’s context so the model can decide what to do next.

    This pattern creates two main sources of cost.

    The first is the repeated transmission of tool definitions. The model needs to know which tools are available, so every request includes the names, parameter formats, and descriptions of all tools. The more tools there are, the longer this description becomes. In the first request, tool definitions alone may reach tens of thousands of tokens. The exact number depends on the number of tools, the length of their descriptions, and the tokenizer of the model in use. Teams should measure this in their own environment rather than rely on figures from other sources.

    Some platforms support prompt caching, where a repeated prefix can hit the cache and be billed at a lower rate. In that case, tool definitions that appear in every request may not be billed at the full price. However, if the cache misses or the platform does not support caching, the cost of repeated transmission is charged in full.

    The second source is that full tool outputs are kept in context. Bash logs, database query results, and JSON responses from external APIs are often long. In a turn-by-turn mechanism, this raw content enters the conversation history and is sent again with every later request. The model may need only three or five lines from it, but the entire output stays in the context.

    Together, these two sources mean that context grows faster as tasks become more complex and involve more tools. The root problem is that many intermediate results are retained by the model, and much of that content does not need to be kept long term.

    2. A New Approach: Letting Code Handle Orchestration

    To address these problems, one approach reduces how often the model directs tools one call at a time. Instead, data filtering and orchestration are handled by local scripts. The model decides what to do, the scripts run the operations in batches, and only a condensed result returns to the model.

    This approach usually involves three components.

    1. Injecting Tool Definitions on Demand

    Rather than sending the full set of tool descriptions to the model at once, the system injects only the few tools that are most relevant to the current task, based on its semantics. For example, if a task involves modifying files, only the definitions for file reading and editing are provided. This makes the first request much smaller, and later turns no longer need to carry the complete tool documentation.

    Tool selection carries its own risk. The routing layer may choose the wrong tool, leaving the model unable to complete the task. A fallback strategy is therefore needed. When the model requests a tool that was not injected, the system automatically adds that tool’s definition, retries the request, and logs the event. These events can serve as a monitoring metric for routing quality.

    2. Filtering Locally Before Returning Results

    Tool calls can be wrapped in executable scripts, such as Bash scripts, Python functions, or SQL queries. The script performs filtering, extraction, and aggregation locally and returns only the key fields to the model. The model sees the conclusion rather than the full raw data.

    To serve both programs and models, tool output can use a dual-channel design. One channel is structured JSON for later processing by programs. The other is a short text summary for the model to read. An example structure is shown below:

    1. {
    2. "status": "ok",
    3. "data": { "matched_count": 37, "refund_total": 12840.50 },
    4. "summary": "Matched 37 tickets with a total refund of 12840.50 yuan.",
    5. "truncated": false
    6. }

    The summary should have a length limit. In general, keeping the summary to about 100 tokens is sufficient, though the exact value should be adjusted to the information density of the task. The full data should be requested only when the model actually needs the details.

    3. Orchestrating Multi-Step Tasks in Batches

    For operations that span multiple files or multiple calls, the agent can first generate a script that completes all the sub-steps in one run, then return the final result. The model’s job becomes reviewing the script’s intent and final output, without observing every intermediate state. An interaction that would have taken dozens of turns may be reduced to a few.

    This approach shifts the model’s role from a step-by-step operator to a author of code, while deterministic execution is handled by a program. Code gives precise control over operations and is easier to review.

    3. Evaluating the Results: Reading Test Data Carefully

    Comparison data found online often reports specific percentages, such as a 77% saving on one task and about 23% on another. These figures can be informative, but they should not be applied directly. Teams should first clarify the following:

    • What the test tasks were, such as ticket statistics, multi-file fixes, or file search;
    • Which models, versions, and sampling parameters were used;
    • How tokens were counted, including whether input and output were both included and whether cache hits were counted;
    • Whether the control group was configured the same way as the experimental group;
    • How quality was assessed, including whether code review or spot checks of test pass rates were performed.

    A reliable evaluation method is to select real tasks from the team’s own work, run them in both traditional mode and the new mode, and record the following metrics:

    Metric Traditional Mode New Mode Notes
    Input tokens per task Measured Measured Separate the first turn from later turns
    Interaction turns Measured Measured Reflects how much orchestration reduces turns
    Task success rate Measured Measured Based on test results or manual acceptance
    Code review rework rate Measured Measured Checks whether quality has declined
    Average completion time Measured Measured Script execution may add waiting time

    In some controlled evaluations, quality did not show a clear decline. However, these results apply only to the specific tasks tested. Teams still need to spot-check quality by task type. For high-risk changes, manual review should not be skipped.

    4. Practical Points for Engineering Deployment

    1. Adding Trigger Conditions to Tool Registrations

    Label each tool with the scenarios it applies to, such as “file operations only” or “network requests only,” and build a lightweight intent router. The router can be based on keyword rules, a decision tree, or a small classification model. These options have low overhead, but they must be paired with the fallback mechanism and monitoring described earlier.

    2. Controlling Session-Level Caching and Deduplication

    Repeated system prompts, unchanging tool definitions, and stable file fragments are good candidates for caching, which avoids sending them again. Tool definitions should be updated only when their version changes.

    Caching also creates isolation risks. In multi-tenant systems or systems that handle sensitive data, cache keys must include the tenant and session identifiers so that one user’s content cannot be read by another. Cache retention periods should also be limited and aligned with the data retention policy.

    3. Supporting Script Execution Securely

    Adding “script execution” to the agent’s action space can significantly reduce the number of interaction turns, but it also introduces clear security risks. Model-generated code might delete files by mistake, read data it should not access, or be manipulated through prompt injection into performing malicious actions. A script execution environment needs at least the following controls:

    • Least privilege: the sandbox runs as a non-privileged user, mounts only the directories it needs, and is read-only by default;
    • Allowlists for commands and network access: limit which commands can be called and which domains can be accessed;
    • Sensitive data masking: keys and personal information are replaced or filtered before they enter the context;
    • Execution auditing: record the content, parameters, duration, and return code of every script;
    • Rollback on failure: run scripts that perform write operations under transactions or version control, so failures can be reverted.

    Timeouts and output limits, such as a 5000-token cap, mainly serve stability. They cannot replace the security measures above. All write, delete, and publish operations should require user confirmation before execution.

    5. Suitable Scenarios and Future Directions

    This approach works best when tool calls are frequent, each call returns a large amount of data, and the task can be split into steps that can be scripted. If a task requires frequent human judgment, or if tools return only small amounts of data, the extra routing and script layers may not be worth the cost.

    Over the longer term, the approach reflects a principle: the model should focus on information that requires judgment, while deterministic programs handle mechanical data processing. As context windows grow, token prices may continue to fall. Still, teams need to focus on keeping context smaller and more relevant. This may also reduce distraction in the model, which can help improve output quality and response speed.

    For teams building AI-assisted development tools, a sensible path is to start with a small pilot on real tasks, record token usage, turn counts, success rates, and rework rates, and then decide how far to expand. This kind of optimization may become part of a product’s competitive edge, but its value should be proven with the team’s own data.