Low-Cost Code Agents with Long-Context Models

    Building code agents with long-context models often faces challenges with high costs and instability. This article explores strategies for selecting the right models, optimizing API costs through caching, constructing code context, implementing agent loops, and ensuring security and reliability in cloud environments.

    1. Why Code Agents Are Expensive and Unstable

    Code agents typically need to read multiple files and repeatedly submit the same context across multiple calls. The longer the context, the higher the input cost per call. If the context is too short, the model loses visibility into inter-module dependencies, leading to code that conflicts with other parts. These two issues are interdependent and must be addressed simultaneously.

    2. How to Choose a Model

    When selecting a model, do not rely solely on the advertised context window. Verify the following four points:

    1. Actual usable context length, based on the limits in the provider’s documentation.
    2. Pricing for input, output, and cached read operations, as well as the cache validity period and hit rules.
    3. Pass rate on your own code tasks, which can be evaluated using a test set of 20 to 50 real tasks.
    4. Output length limits and rate limits. These determine whether the model can generate complete modifications in a single pass.

    MoE architecture characteristics: MoE models can have a large total parameter count, but each token only passes through a small subset of routed experts, so the computational cost per inference is usually lower than that of a dense model with equivalent total parameters. This does not automatically translate to lower API prices; the final price depends on the provider’s pricing strategy.

    Long context also has limitations. Being able to fit content into the window does not mean the model will pay equal attention to every section. Critical files and task instructions should be placed near the end of the request, and test results should be used to verify the correctness of the modifications.

    3. How to Calculate Cost

    Billing models typically include three components: input (cache miss), cache read, and output. The unit prices below are hypothetical values for calculation purposes and are not official prices of any platform.

    Item Symbol Hypothetical Value (per million tokens)
    Input (Cache Miss) P_in $2
    Cache Hit P_cache $0.2
    Output P_out $8

    Context per task: 500,000 tokens. Output: 20,000 tokens.

    • Cache miss: 0.5 2 + 0.02 8 = $1.16
    • Cache hit: 0.5 0.2 + 0.02 8 = $0.26

    Assume 300 tasks per month, with 10 cache misses due to expiration and 290 cache hits:

    • Using cache: 10 1.16 + 290 0.26 = $87.00
    • Without cache: 300 * 1.16 = $348.00

    Under these assumptions, caching reduces the monthly cost by approximately 75%. In actual calculations, replace these with current platform prices, and include cache write fees, storage fees, and the expiration time of any limited-time discounts.

    Note two important points:

    1. The agent resends the context at each step. If a task averages 4 steps, the input cost must be multiplied by 4.
    2. New observations and instructions are incremental inputs billed at the cache miss rate.

    4. How to Enable Caching

    Most platforms’ context caching relies on an exact prefix match. Therefore, request organization should follow two rules:

    1. Place immutable content (system prompts, repository context) at the beginning, and variable content (task descriptions, observations) at the end.
    2. Do not include timestamps, random IDs, or other frequently changing fields in the prefix.

    If any file in the prefix is modified, the cache from that point onward is invalidated, requiring a cache rebuild after code changes. Refer to your specific platform’s documentation for how to enable this (request parameters or automatic caching) rather than blindly copying parameter names from examples.

    5. How to Build Code Context

    The concatenation order of the context must be logical. It is recommended to perform a topological sort based on import relationships first, placing dependent files before others, and then truncate based on the token budget. The following function takes a pre-sorted file list and does not perform dependency analysis itself.

    1. from pathlib import Path
    2. ALLOWED_SUFFIXES = {".py", ".js", ".java", ".go"}
    3. EXCLUDED_DIRS = {"node_modules", ".git", "dist", "build", "__pycache__"}
    4. MAX_FILE_BYTES = 512 * 1024
    5. def estimate_tokens(text: str) -> int:
    6. # Mixed Chinese-English code is roughly 3 to 4 characters per token.
    7. # Use the official tokenizer for an exact budget.
    8. return max(1, len(text) // 3)
    9. def read_text(path: Path):
    10. if path.stat().st_size > MAX_FILE_BYTES:
    11. return None
    12. try:
    13. return path.read_text(encoding="utf-8")
    14. except UnicodeDecodeError:
    15. return None # Binary or non-UTF-8 files
    16. def build_context(ordered_files, max_tokens=500_000):
    17. parts, used, skipped = [], 0, []
    18. for path in ordered_files:
    19. text = read_text(path)
    20. if text is None:
    21. skipped.append(str(path))
    22. continue
    23. block = f"\n--- FILE: {path} ---\n{text}\n"
    24. cost = estimate_tokens(block)
    25. if used + cost > max_tokens:
    26. skipped.append(str(path))
    27. continue
    28. parts.append(block)
    29. used += cost
    30. return "".join(parts), used, skipped

    Do not silently drop files that exceed the budget or are skipped. Write them to a log and list them in the final report to determine if the result was based on complete information. For large files, generate function-level summaries before adding them to the context. Excluding directories (such as node_modules, .git, build artifacts) and files that may contain secrets (like .env) should be done during the traversal phase, not during concatenation.

    6. How to Write the Agent Loop

    A single API call only provides suggestions. To allow the agent to verify results, a true loop is needed: the model proposes an action, the program executes it and returns the result to the model, continuing until the model provides a final answer or reaches the step limit.

    1. MAX_STEPS = 8
    2. def run_agent(call_model, tools, context, task):
    3. messages = [
    4. {"role": "system", "content": SYSTEM_PROMPT},
    5. {"role": "user", "content": f"{context}\n\nTask: {task}"},
    6. ]
    7. for _ in range(MAX_STEPS):
    8. reply = call_model(messages)
    9. messages.append({"role": "assistant", "content": reply})
    10. action = parse_action(reply) # Returns {"final": ...} or {"tool": ..., "args": {...}}
    11. if "final" in action:
    12. return action["final"]
    13. result = tools[action["tool"]](**action["args"])
    14. messages.append({"role": "user", "content": f"Observation: {result}"})
    15. raise RuntimeError("Max steps exceeded without completion, please check the task description")

    Require the model to output JSON in a fixed format. If parsing fails, return the error message to the model to regenerate the output instead of crashing the program. It is recommended to restrict tools to a few categories: reading files, searching code, applying patches, and running tests. File writing operations should be confined to a working copy and merged into the main branch via human review or a CI pipeline.

    7. Retry and Validation

    • Retry: Use exponential backoff with random jitter for timeouts, rate limiting, and server-side 5xx errors, retrying up to 4 times. Do not retry authentication failures or parameter errors, as this only results in duplicate billing.
    • Idempotency: Generate a unique ID for each task and check if it has been completed before writing results, preventing the same patch from being applied multiple times.
    • Validation: Perform a syntax check on the output code first. For Python, use ast.parse; for other languages, use their respective compilers. Run unit tests only after the syntax check passes.

    8. Secrets and Code Privacy

    • Read API keys from environment variables (e.g., os.environ["LLM_API_KEY"]); do not hardcode them or commit them to the repository.
    • Logs should only record token counts, duration, and error types—never the full prompt or code.
    • Before sending code to a third-party API, confirm you have the authorization to use the code, and exclude files containing customer data or credentials.

    9. Cloud Deployment

    • Task decoupling: Use a message queue to receive commit events or periodically scan for tasks. Keep the trigger logic separate from the agent execution logic to prevent sudden spikes in requests from exhausting API rate limits.
    • Elastic scaling: Scale worker nodes based on the queue backlog length. This ensures processing times during peak periods while avoiding resource costs during idle times.
    • Observability: For each task, record input tokens, cache hit tokens, output tokens, duration, retry count, and error type. This data is used to reconcile bills and to identify which prompt changes increased costs.

    10. Pre-Launch Checklist

    • Cost: Recalculate using actual prices; any discrepancy with the bill should be explainable.
    • Cache: Send two consecutive requests with the same prefix; the cache hit token count for the second request should be greater than zero.
    • Context: The list of skipped files has been written to the report.
    • Loop: There are corresponding tests for the step limit, termination conditions, and tool error handling.
    • Security: There are no plaintext secrets in the repository, and no complete code in the logs.