How to Choose and Evaluate LLM Code Generation Capabilities
Choosing the best LLM for coding has no fixed answer because coding is a composite capability and evaluation criteria often conflict. This article presents a reusable selection and evaluation method: define a task profile first, build a layered private evaluation set with automated verification, measure correctness, engineering quality, and cost across repeated samples, embed the model in a full pipeline with retrieval, constraint orchestration, isolated execution, and observability, and keep results fresh through continuous regression testing.
1. The Core Problem: Why There Is No Fixed Answer to “Which Model Writes the Best Code”
As AI coding tools evolve quickly, many teams ask the same question: which LLM currently has the strongest code-writing ability? In a real engineering context, however, this question rarely has a constant answer. The issue is not that model capability is unimportant, but that “code writing” is a highly composite set of capabilities, and different tasks place very different demands on a model.
First, coding tasks can be roughly divided into layers:
- Snippet-level completion: completion inside a function body, boilerplate generation; emphasizes low latency and a high hit rate;
- Function-level generation: generating a complete function from a comment or signature; emphasizes semantic correctness and edge-case handling;
- File-level modification: cross-function refactoring, defect fixing; emphasizes context understanding and minimal changes;
- Repository-level tasks: cross-file dependency analysis, interface alignment, batch migration; emphasizes long context and adherence to engineering constraints.
Second, evaluation dimensions are not unified either. First-pass rate, compile pass rate, unit test pass rate, human-review acceptance rate, average number of interaction turns, and cost per task often conflict with one another. A model that excels at algorithm problems is not necessarily as reliable when making local changes in an existing codebase; a model with an advantage in long-context understanding may not be cost-effective in low-latency scenarios.
A more rigorous framing, therefore, is not “who is the best” but “which type of model is more suitable under a given task distribution and a given set of constraints.” The rest of this article builds on that judgment and provides a reusable evaluation and selection method.
2. Build a Task Profile: Define the Requirements Before Discussing Model Capability
Selection failures are often not caused by a weak model but by unstructured requirements. Before evaluation, produce a task profile containing at least the following fields:
| Dimension | Question to clarify | Example value |
|---|---|---|
| Language and framework | What is the main tech stack | Backend services, frontend components, data scripts |
| Task type | Completion, generation, fixing, refactoring, testing | Mainly defect fixing |
| Context size | How many files must be read | Single file, across three to five files |
| Correctness standard | How to determine a pass | Compilation plus unit tests |
| Interaction constraints | Latency and turn limits | Low first-token latency, no more than two turns |
| Compliance requirements | Whether code may leave the environment | Must be on-premises or via a dedicated channel |
The value of this table is turning “which one feels stronger” into “which one is stronger under which constraints.” Once the task profile is clear, the evaluation set and metrics have a basis, instead of directly applying rankings from public benchmarks.
3. Build the Evaluation Set: Use Your Own Data Instead of General Impressions
General leaderboards can only serve as an initial filter; what really drives selection is a private evaluation set close to your business. Three principles are recommended when building it.
First, stratified sampling. Sample enough cases from each layer described earlier, and avoid concentrating everything on simple completion. A workable ratio is 30% snippet-level completion, 30% function-level generation, 20% file-level modification, and 20% repository-level tasks, then fine-tune by business line.
Second, make cases automatically verifiable. Each case should include an executable verification method where possible, such as a build command, unit tests, or static check rules. A sample data structure looks like this:
{"id": "fix_0031","layer": "file_level","language": "backend_service","prompt": "Fix the out-of-bounds issue of this function under specific input, keeping the interface unchanged","context_files": ["src/util/parse.x", "src/util/buf.x"],"verify": {"build": "build_tool compile","tests": ["tests/parse_case_a", "tests/parse_case_b"],"static_check": "lint_rule_set_default"},"constraints": {"max_turns": 2,"latency_budget_ms": 8000}}
Third, include negative and trap cases. For example, vague requirement descriptions, missing key definitions in the context, or situations with multiple reasonable solutions. Such cases test whether the model proactively asks for clarification and whether it fabricates nonexistent interfaces, which reflects engineering usability better than simply generating correct code.
4. Metrics: Break “Good” Into Measurable Items
A combination of three metric groups—correctness, engineering quality, and economics—is recommended to avoid single-point conclusions.
For correctness, track compile pass rate, unit test pass rate, number of new static check warnings, and human acceptance rate. For engineering quality, look at whether the change scope is minimal, whether existing naming and directory conventions are followed, whether unnecessary dependencies are introduced, and the average number of interaction turns. For economics, look at average consumption per task, first-token latency, concurrency capacity, and the cost of failed retries.
To keep conclusions stable, sample each case multiple times and record the mean pass rate and its variance range. Evaluating only once easily misreads randomness as a capability difference. The following pseudocode shows a minimal evaluation loop:
def evaluate(model_client, dataset, repeats=3):report = {}for case in dataset:results = []for _ in range(repeats):out = model_client.run(case.prompt, case.context_files)results.append(verify(out, case.verify))report[case.id] = {"pass_rate": mean(results),"variance": variance(results),"avg_turns": avg_turns_of(results)}return aggregate_by_layer(report)
It is worth emphasizing that metric weights should be determined by the task profile. Teams focused on defect fixing should put unit test pass rate and change minimality first; teams focused on rapid prototyping can relax static check requirements moderately in exchange for lower latency.
5. Engineering Integration: Model Capability Is Only One Link in the Chain
The actual development experience is determined by the whole pipeline, not a single model. A mature AI coding solution usually includes these general capability stages:
- Context retrieval: locate relevant files and symbols in the repository, and control the injected length;
- Prompt and constraint orchestration: write coding standards, directory conventions, and interface contracts into constraint templates;
- Execution and verification: compile and run tests in an isolated environment, and feed failure information back to the model;
- Logging and monitoring: record the call chain, latency, and failure reasons to form an observable loop;
- Permissions and compliance: centrally manage the scope in which code may leave the environment, key usage, and audit trails.
When deploying on the cloud, you can combine general product categories: object storage to hold evaluation sets and artifacts, message queues to smooth traffic peaks, container platforms to host isolated execution environments, and logging services plus monitoring alerts to support observability. Baidu AI Cloud offers corresponding capabilities in these general categories, and teams can choose a combination that fits their existing architecture rather than being locked into a single implementation.
An example of a practical constraint template:
You must follow these constraints:1. Only modify code directly related to the defect; do not reorder unrelated lines;2. Do not introduce new third-party dependencies;3. Keep existing function signatures and error code semantics;4. If the context lacks a key definition, ask a clarifying question first; do not assume it exists;5. After the output, provide self-test steps.
Such templates can significantly reduce the proportion of output that “looks correct but cannot be merged,” and the benefit often outweighs switching the model itself.
6. Continuous Regression: Make Selection an Ongoing Mechanism
Both models and toolchains keep updating, so one-off evaluation conclusions expire quickly. Connect the evaluation set to the continuous integration process and run periodic regression: whenever a candidate model or prompt strategy changes, automatically run the layered evaluation, output pass rate, variance range, and cost comparison curves, and set alerts for significant regressions.
Also keep a human spot-check step. Automated metrics are good at spotting obvious degradation, but questions such as “is the design reasonable” and “does the naming match team conventions” still require human judgment. Combining both keeps the process fast and stable.
7. Common Pitfalls and How to Avoid Them
- Only looking at public leaderboards: their task distribution differs greatly from your business, so they are only for initial screening;
- Drawing conclusions from a single sample: randomness gets misjudged as a capability difference, so sample multiple times and look at the range;
- Ignoring context engineering: most failures come from failing to retrieve key definitions, not from insufficient generation ability;
- Over-pursuing long context: injecting irrelevant content dilutes attention and can lower the hit rate;
- Ignoring compliance boundaries: the scope in which code may leave the environment and key management must be decided at the architecture stage and cannot be fixed after the fact.
8. Conclusion
“Which model writes the best code” is a question that needs to be decomposed. A more reliable approach is to first complete the task profile, then build a layered, automatically verifiable private evaluation set, evaluate with multiple samples using correctness, engineering quality, and economics metrics, place the model in a complete pipeline that includes retrieval, constraint orchestration, isolated execution, and observability, and finally keep conclusions fresh with a continuous regression mechanism. With this method, teams get not a ranking but a selection basis that matches their own scenarios and can be updated as the technology evolves.
