Reducing Token Costs for Long-Running Tasks in AI Coding Assistants
This article explains why token costs rise sharply in long-running AI coding assistant tasks and how to control them. It covers prefix caching and prompt ordering to cut repeated computation, ways to limit context growth, goal-driven execution loops with independent review, and how subtasks, browser operations, and remote sessions help keep context manageable.
1. Why Token Costs Get Out of Control in Long Tasks
AI coding assistants usually need only a few conversation rounds to handle simple questions. The real resource drain comes from long tasks that run for dozens or even hundreds of rounds. These tasks involve reading many code files, keeping a history of operations, calling tools repeatedly, and verifying results. Each round resends the previous context to the model, so the total number of input tokens keeps growing as the task progresses.
Two factors drive this growth. First, context only accumulates. Early file contents and tool outputs are counted again in every later round. Second, the model processes the full input from scratch each time, even when most of it is identical to the previous round. Without constraints, the cost of a long task can rise nearly linearly or even faster.
Reducing the cost of long tasks depends on cutting repeated computation and controlling how much information each round must process. Switching to a model with lower per-token pricing can help, but it cannot replace managing the structure of the context.
2. Context Caching: Reducing Repeated Computation
2.1 How Caching Works
Prefix caching is a common optimization in the industry. The server stores intermediate results for the prefix that was already computed in a previous request. When the beginning of a new request matches the cached content, the server reuses those results and computes only the newly added tail.
This mechanism has two requirements. First, cache matching usually proceeds token by token from the start of the request. Once the prefix changes, every cache entry after that point becomes invalid. Second, cached tokens are billed differently from uncached tokens, and most providers charge a lower unit price for cache hits. Minimum cache length, expiration time, and pricing ratios vary by provider. Check each provider’s official documentation rather than relying on rule-of-thumb values.
2.2 Organizing Prompts to Improve Cache Hit Rates
Because the prefix determines cache hits, developers should order content from least to most frequently changing:
- System instructions and role definitions, which rarely change;
- Tool definitions and API descriptions, which stay stable within a session;
- Project-level conventions and background materials, which are mostly fixed within a single task;
- Summaries of past conversation, updated incrementally by round;
- The current user input and the latest tool results, which change every round.
The following illustrative function keeps stable content at the front of the request:
def build_request(system_prompt, tool_schemas, project_context, summary, latest_turn):# Place stable content first so the server can reuse the precomputed prefixstable_prefix = [{"role": "system", "content": system_prompt},{"role": "system", "content": tool_schemas},{"role": "system", "content": project_context},]# Only the dynamic tail below triggers new computationdynamic_tail = [{"role": "assistant", "content": summary},{"role": "user", "content": latest_turn},]return stable_prefix + dynamic_tail
This structure has a problem that developers often overlook. If the system instructions include a current timestamp, a random ID, or debug information that changes on every call, the prefix differs in each round, and the cache almost never hits. Move such information to the tail, or remove it if it does not affect the meaning.
2.3 Controlling Context Bloat
Caching lowers the cost of content that already exists, but it cannot stop the content itself from growing. Tool output is the most common source of bloat. For example, a single directory scan can return thousands of lines of file listings, while later steps may need only a few of the paths. In practice, you can:
- Set a length limit on tool output. Save anything beyond the limit to a file, and keep only the file path and a summary in the context;
- Replace the raw process logs of completed subtasks with structured summaries;
- Periodically compress historical rounds that are no longer relevant, keeping decisions and open issues.
Compression requires careful design. If a summary drops key constraints or confirmed facts, later steps may reach wrong conclusions. Each summary should explicitly keep four types of information: the goal, completed items, pending items, and known constraints.
3. Goal-Driven Long-Running Execution
3.1 From Single-Turn Q&A to Goal Loops
In ordinary chat, the user’s last message signals the end of the exchange. Long tasks need a different completion check. The system must keep working until the goal is met. This means storing the goal as a first-class part of the session state, not leaving it buried in an earlier message.
A reliable goal loop usually has four stages: define verifiable acceptance criteria for the goal, take an action, check whether the goal has been met, and plan the next step if it has not. Checking completion is the most error-prone stage. Models often declare a task finished too early because their own output looks reasonable.
3.2 The Value of Independent Review
To reduce false completion, trigger an independent review whenever the model claims the task is done. The review input should include the original goal, verifiable acceptance criteria, and the actual results, such as test output, file diffs, and run logs. The review should not rely only on the model’s own summary.
The following illustrative code shows the basic structure of this process:
def run_goal_task(goal, agent, max_rounds=30):history = []for _ in range(max_rounds):result = agent.step(goal=goal, history=history)history.append(result)if not result.claims_done:continue# Review based on actual artifacts, not the model's self-reportverdict = agent.review(goal=goal, evidence=result.artifacts)if verdict.satisfied:return resulthistory.append(verdict.feedback)raise RuntimeError("Goal not achieved within the round limit; human intervention required")
The agent object in this example is a hypothetical interface. Adjust the implementation to fit the framework you use. The design has three key points: set a maximum number of rounds to prevent infinite loops; base the review on objective evidence; and, when the review fails, write the feedback back into the history so the next round can correct the work.
3.3 Writing Acceptance Criteria
The more specific the acceptance criteria, the more reliable the review. A vague goal such as “optimize API performance” makes it hard to tell whether the work is done. A goal such as “under the same test data, the API’s P95 latency is below 200 ms, and all existing unit tests pass” can be checked item by item.
4. Combining Capabilities: Subtasks, Browser Operations, and Remote Sessions
Long tasks often involve several capabilities. Combining them well improves efficiency and keeps context size under control.
- Subtask decomposition: Assign large tasks to separate subagents. Each subagent has its own context window and returns only its conclusions to the main workflow. This keeps intermediate process details from filling the main context.
- Browser operations: Use a browser to read pages that require rendering or to run end-to-end verification. Keep the results of key steps in the operation log instead of storing every page snapshot.
- Remote session control: Allow a task started on one device to be viewed or taken over from another device. When using this capability, check the permission scope of the access credentials and enable session timeouts.
