Low-Cost Code Agent Architecture: Design and Implementation Practices
This article explains how to estimate the per-call cost of a code agent, including token pricing, cache-hit effects, and budget margins. It then compares MoE and attention optimizations, discusses when long-context models are appropriate, and outlines workflow design choices such as code indexing, chunking, and retrieval for stable, cost-aware operation.
I. Start with the Numbers: Estimating the Cost of a Single Call
The first step in cost estimation is to clarify the billing basis. Most model providers split costs into several parts: regular input tokens, output tokens, and cache-read tokens after a cache hit. Some providers also bill cache writes separately, and the write price may be higher than the regular input price. These items should be calculated separately during budgeting rather than relying on a single blended unit price.
The prices below are hypothetical values used to explain the calculation method. They are in CNY and do not represent any provider’s actual quote. For actual budgeting, use the prices published on the provider’s official website on the day of the query and record the query date.
Assume a code review task for a medium-sized project. The agent needs to read about 500,000 tokens of code context per call and output about 20,000 tokens of change suggestions and code. Set the unit prices as follows:
- Input: 0.5 CNY / million tokens
- Output: 1.5 CNY / million tokens
The cost of a single call is:
(0.5 × 0.5) + (0.02 × 1.5) = 0.25 + 0.03 = 0.28 CNY
Under this assumption, 1,000 reviews per month cost about 280 CNY. Real consumption will increase because of retries, tool feedback, and multi-turn conversation history, so it is advisable to reserve a margin in the budget. The margin ratio should be based on your own project’s call logs; start with a conservative estimate and calibrate it gradually.
The impact of caching on cost is linear. Let the cache-read price be r times the regular input price, and let the cache hit rate be h. The input cost proportion is:
1 - h + h × r
For example, when r is 0.1 and the hit rate is 60%, the input cost is about 0.46 of the original, a reduction of about 54%. This result does not include the cost of cache writes.
The hit rate depends on whether the context prefix is stable. If the prefix content changes on every request, the cache will almost never hit. In practice, place system instructions, repository structure, and other rarely changing content at the front of the prompt, and place current task-related code and issues at the back.
II. Model Architecture: What MoE and Attention Optimization Each Solve
Low-cost models usually rely on two types of architecture optimization. They solve different problems and should be evaluated separately when selecting a model.
1. MoE (Mixture of Experts)
MoE splits a model into multiple expert subnetworks, and each token activates only a few of them. The total parameter count can be large, while the parameters actually involved in computation per token are fewer, so per-token compute decreases.
There are two points to note about this structure. First, all expert parameters still need to be loaded into GPU memory or memory, so the deployment barrier does not disappear. Second, the routing strategy affects load balancing and output stability. For agent users, MoE mainly reduces unit inference cost; it does not directly guarantee that every answer will be more accurate.
2. Sparse and Linear Attention
Standard Transformer attention compute grows quadratically with sequence length. Sparse attention computes relationships only for some positions, while linear attention uses approximation to reduce complexity. Both can make long-input computation cheaper, but both are selective or approximate mechanisms. In scenarios that require precise cross-file references, accuracy may be lost.
Different models adopt quite different approaches. When selecting a model, consult its technical documentation to confirm its attention structure rather than relying only on the phrase “long context” in marketing materials.
3. Ultra-Long Context Windows
A 1M-token-level window is clearly helpful for large monorepos, cross-module review, and dependency analysis. The model can see directory structure, interface definitions, and related implementations at once. However, not all code tasks need it. Completing a function or explaining an error usually requires only a few thousand tokens of context.
Long context has two costs. First, longer input increases per-call cost and latency. Second, with very long input, the model’s attention to information in the middle may decrease, and key code can be easily overlooked. Therefore, long context should be used together with retrieval; do not package the entire repository as input.
The following table provides selection guidance by task scale:
| Task type | Typical input size | Recommended strategy |
|---|---|---|
| Single-function completion, error explanation | A few thousand tokens | Short-context model; no long window needed |
| Single-file or single-module review | Tens of thousands of tokens | Retrieval plus a small number of global files |
| Cross-module refactoring, repository-wide dependency analysis | Hundreds of thousands of tokens or more | Long-context model with controlled call frequency |
III. Designing a Stable Workflow
1. Code Indexing and Retrieval
Do not send all code to the model at once. Build an index and retrieve code on demand.
- Chunking unit: prefer functions, classes, or paragraphs instead of hard splitting by fixed character count. As a starting point, keep each chunk at 300 to 800 tokens, then adjust based on retrieval error.
- Retrieval count: the default top-k for semantic retrieval is 5 to 8. If results are insufficient, increase it gradually.
