Evaluating LLMs and Building Low-Cost Coding Agents: A Practical Guide

    This article explores how to effectively evaluate large language models (LLMs) for programming tasks, moving beyond superficial metrics like parameter size or context window length. It details a practical approach to building a low-cost, highly stable coding agent, covering cost calculation, context caching, architectural design, security considerations, and sustainable evaluation methods to ensure true engineering value.

    1. Evaluating User Experience Beyond Model Names

    Recently, LLM products have been updating frequently. When selecting a model, developers are often attracted by single metrics such as “larger parameter size,” “longer context window,” or “lower unit price.” However, for tasks like code assistance, repository analysis, and automated modifications, what truly impacts the experience is not a single marketing metric, but the comprehensive performance of model capability, invocation cost, response stability, and engineering controllability.

    If the goal is to build a coding agent, it is recommended to evaluate from at least the following aspects:

    1.1 Accurate Code Understanding
    A model being able to read a single function is just the baseline. More importantly, can it understand the calling relationships between modules, the role of configuration files, exception handling flows, and dependencies across different directories?

    For example, if a user requests “add a limit on the number of login failures,” the model should not just modify the login interface. It also needs to determine:

    • Where the failure count should be stored;
    • Whether an expiration time is needed;
    • How to ensure count consistency in multi-instance deployments;
    • Whether an account unlock mechanism should be provided after an account is locked;
    • Whether sensitive information will be logged;
    • Whether the frontend prompt will leak the existence of the account.

    Therefore, code capabilities should be tested through complete tasks, rather than just checking if a generated code snippet looks clean.

    1.2 Truly Usable Long Context
    A long context window is important for a coding agent, but “being able to receive a large amount of text” does not equal “being able to effectively utilize all of it.” When the input contains a lot of repetitive code, build artifacts, dependency directories, or irrelevant logs, the model’s judgment quality may decrease due to lower information density, even if it doesn’t exceed the context limit.

    A more reasonable approach is to establish code indexing and a hierarchical retrieval mechanism:

    • First, read the project structure;
    • Then, locate files relevant to the task;
    • Next, extract interfaces, types, configurations, and test information;
    • Finally, assemble the necessary context for the model to analyze.

    Long context should be a fallback capability, not something where the entire repository is sent as-is with every call.

    1.3 Output Stability
    For one-off Q&A tasks, occasional errors are not terrible. But in automated programming workflows, output instability directly leads to task failure. For example, if the same requirement is executed twice, the model might modify three files one time, and a dozen files the next. Or, the model might sometimes return standard structured results and sometimes mix in explanatory text, increasing the difficulty of downstream processing.

    When evaluating stability, you can fix the prompt, input code, and execution environment, run it multiple times continuously, and focus on observing:

    • Whether the scope of modified files is consistent;
    • Whether irrelevant changes are frequently introduced;
    • Whether the output format is adhered to;
    • Whether it can self-correct based on test results;
    • Whether it proactively explains risks when uncertain.

    2. Cost Accounting: Calculating the Full Invocation Chain

    Model invocation costs are typically determined by input, output, cache reads, and the number of calls. Looking only at the input or output unit price easily leads to one-sided conclusions.

    You can use the following general formula to estimate the cost per call:

    1. Cost per call =
    2. Input Token count × Input unit price
    3. + Output Token count × Output unit price
    4. + Cache read Token count × Cache read unit price
    5. + Other supporting service costs

    Here, the input usually includes the system prompt, user requirements, project structure, retrieved code snippets, and conversation history; the output includes the analysis process summary, modification plan, code patches, and testing suggestions.

    For example, suppose a task requires 400,000 input tokens and 15,000 output tokens. If a certain pricing scheme has an input price of 0.6 CNY per million tokens and an output price of 1.8 CNY per million tokens, the single-call model cost is approximately:

    1. 0.4 × 0.6 + 0.015 × 1.8
    2. = 0.24 + 0.027
    3. = 0.267 CNY

    If it runs 100 times a day, calculating 30 days a month, the model invocation cost alone is about:

    1. 0.267 × 100 × 30 = 801 CNY

    This does not even account for costs like code indexing, log storage, task queues, container execution, and failure retries. Therefore, an enterprise’s actual budget should not be calculated solely based on the list price, but should establish a complete cost model.

    3. Why Caching Mechanisms Affect Your Coding Agent Budget

    In coding agent calls, there is often a large amount of repetitive content, such as:

    • Fixed system prompts;
    • Project coding standards;
    • Repository directory summaries;
    • Public type definitions;
    • Long-term stable base configurations;
    • Background explanations that repeatedly appear in multi-turn tasks.

    If these contents are billed as full input every time, costs will rise rapidly. Cache reads can reduce the processing cost of repetitive content, making it especially suitable for continuous conversations and batch code review scenarios.

    However, more caching is not always better. The following issues should be noted:

    First, frequently changing code is not suitable for long-term caching, otherwise the model might make judgments based on outdated versions.

    Second, cached content should be layered. Stable project standards can be retained long-term, while business code with rapid version changes should have a shorter validity period.

    Third, cache hit rates need monitoring. If there are many cache writes but few reads, it may actually increase management complexity.

    The context can be divided into three layers:

    1. Fixed layer: Role definition, output format, coding standards
    2. Project layer: Directory structure, public types, build methods
    3. Task layer: Current requirements, related files, test results

    The fixed layer and project layer are suitable for reuse, while the task layer should be dynamically generated based on each requirement.

    4. Recommended Architecture for a Low-Cost Coding Agent

    A practical coding agent should not just “send the problem to the model and display the answer.” It should possess capabilities for task decomposition, context retrieval, code modification, and result verification.

    The complete workflow can be designed as:

    1. User Requirement
    2. ↓
    3. Task Classification & Risk Identification
    4. ↓
    5. Project Structure Retrieval
    6. ↓
    7. Related Code Filtering
    8. ↓
    9. Generate Modification Plan
    10. ↓
    11. Execute Patch or File Modification
    12. ↓
    13. Run Tests & Static Analysis
    14. ↓
    15. Feed Results Back to Model
    16. ↓
    17. Output Change Summary & Risk Explanation

    4.1 Task Classification
    First, determine which category the task belongs to:

    • Code explanation;
    • Defect localization;
    • New feature development;
    • Refactoring;
    • Test generation;
    • Documentation completion;
    • Security review;
    • Performance optimization.

    Different tasks require different context scales and verification methods. For instance, code explanation might only need to read a single module, whereas cross-module refactoring requires analyzing call chains and public interfaces.

    4.2 Generate a Modification Plan
    Do not directly ask the model to output the final code. Instead, first have it list:

    • Which files it plans to modify;
    • The modification purpose for each file;
    • Whether new interfaces or data structures are needed;
    • Which existing features might be affected;
    • Which tests need to be run.

    The planning phase can effectively reduce irrelevant file modifications and also facilitates manual confirmation before high-risk operations.

    4.3 Use Patches Instead of Full Overwrites
    For code modifications, prioritize using diff patches, structured edit instructions, or scoped file operations. This has three benefits:

    • The modification scope is easier to review;
    • It can be quickly rolled back if an error occurs;
    • It won’t overwrite the original file because the model omitted content.

    If the model must generate the full file, the original version should be saved first, and syntax checks and version comparisons should be performed before execution.

    4.4 Enforce a Verification Phase
    Just because the model thinks the code is correct doesn’t mean it can actually run. The agent should at least execute:

    • Format checks;
    • Syntax checks;
    • Unit tests;
    • Type checks;
    • Build verification;
    • Critical path tests.

    After a test failure, feed the error logs and related code back to the model for targeted fixes, rather than regenerating the entire project.

    5. Controlling the Hidden Costs of Long Contexts

    Long context does not mean you should unconditionally send all files. A “summary first, load full text on demand” strategy can be adopted.

    First, generate a project-level summary, including directory purposes, main modules, entry files, and dependencies. Then, retrieve relevant files based on the user’s task. Only load the complete code when the model needs to view the specific implementation.

    For large repositories, simple retrieval rules can also be established:

    1. Priority 1: Files directly mentioned in the task
    2. Priority 2: Modules called by the target files
    3. Priority 3: Related interfaces, types, and configurations
    4. Priority 4: Test files and documentation
    5. Priority 5: Other potentially relevant implementations

    This reduces the input volume and improves context quality.

    6. Stability Design: Don’t Delegate All Decisions to the Model

    Models are good at natural language understanding, code reasoning, and plan generation, but they are not suitable for independently bearing all engineering control responsibilities. The agent system should hand over deterministic tasks to the program.

    For example:

    • Whether a file exists is determined by the program;
    • Whether a path is valid is verified by the program;
    • Whether a patch can be applied is confirmed by the patch tool;
    • Whether tests pass is returned by the execution environment;
    • Whether modifying sensitive directories is allowed is controlled by the permission system;
    • Whether changes can be committed is decided by human approval or a rule engine.

    The model is responsible for “proposing solutions,” and the program is responsible for “verifying and executing.” This is the key boundary for improving reliability.

    7. Security and Permissions Must Be Designed Upfront

    Coding agents typically need to read source code, configurations, and test environments, and in some scenarios, execute commands. Therefore, you cannot focus solely on model effectiveness; you must also consider permission isolation.

    It is recommended to at least:

    • Use minimum file access permissions by default;
    • Prohibit direct reading of keys, tokens, and production configurations;
    • Set up a whitelist for external command execution;
    • Add manual confirmation for file deletion, dependency upgrades, and database operations;
    • Retain audit logs for all model outputs and execution results;
    • Run generated code in an isolated environment.

    In particular, beware of prompt injection issues. Documentation, comments, or test data in a repository may contain text that induces the model to perform dangerous operations. The agent needs to treat “project content” as untrusted input. It cannot bypass system security policies just because a comment requests a command execution.

    8. How to Build a Sustainable Evaluation Method

    It is recommended to prepare a set of real tasks as a regression test suite, covering simple, medium, and complex scenarios. Re-run these tasks every time you change the model, prompt, or retrieval strategy.

    Evaluation metrics can include:

    • First-time completion rate;
    • Test pass rate;
    • Average number of calls;
    • Average input and output token count;
    • Proportion of irrelevant file modifications;
    • Manual rework time;
    • Average cost per task;
    • Automatic repair success rate after failure.

    Ultimately, you should focus on “how much money and human time it takes to complete a valid task,” rather than simply comparing the price per million tokens.

    9. Conclusion: Cost-Effectiveness Comes from System Design, Not Just Low Prices

    When using LLMs for coding agents, low prices do indeed lower the barrier for trial and error, but true cost-effectiveness comes from multi-faceted synergy: reasonable context retrieval, stable output constraints, cache reuse, automated testing, permission isolation, and failure retry strategies.

    If you repeatedly send the entire codebase to the model, even if the unit price is very low, it may result in high total costs due to context redundancy and repetitive calls. Conversely, through hierarchical context, task decomposition, and result verification, invalid calls can be significantly reduced without sacrificing quality.

    Therefore, when evaluating a model upgrade or a new solution, it is recommended to answer three questions simultaneously:

    1. Can it stably complete real coding tasks?
    2. Can it maintain accurate judgment within long contexts?
    3. Is the cost per valid task reasonable after accounting for retrieval, execution, testing, and retries?

    Only when capability, stability, and engineering costs reach a balance simultaneously does a coding agent truly possess practical value.