How to Select the Best LLM for Software Development Using Verifiable Data
A practical framework for evaluating large language models as coding assistants. Learn how to define capability metrics, build an internal benchmark, apply statistical methods, run a reproducible Python evaluation pipeline, and make a final decision based on quality, cost, latency, stability, and compliance.
1. Why You Need a Systematic Selection Method
After introducing an AI coding assistant, engineering teams quickly discover that different models can perform very differently on the same task. Public benchmarks are based on fixed questions, prompts, and evaluation methods. They represent average performance under a specific set of conditions, but may not reflect your language stack, codebase size, or quality standards.
Model selection should therefore be divided into two questions:
- What capabilities does the team actually need?
- How can the team verify that a model has those capabilities?
This article presents a four-step process:
- Define evaluation dimensions.
- Build an internal benchmark and apply statistical analysis.
- Run a reusable evaluation script.
- Make a decision that also accounts for cost, latency, and compliance.
2. Evaluation Dimensions and Metrics
Programming ability can be divided into several relatively independent dimensions. Evaluating each dimension separately is more useful than relying on a single overall score, because different products depend on these capabilities to different degrees.
1. Code Generation Correctness
Can the model generate code from a natural-language requirement that compiles and passes the tests?
Useful metrics include:
- Single-run pass rate.
- The percentage of tasks that pass at least once across multiple samples.
2. Defect Localization and Repair
Given an error log or failing test case, can the model identify the problem and produce the smallest necessary change?
The primary metric is the percentage of repairs that pass the tests. In existing systems, this capability is often more valuable than generating code from scratch.
3. Multi-File Understanding
Can the model maintain consistent interface assumptions across modules and directories?
Measure the integration-test pass rate after cross-file changes.
4. Compliance with Engineering Conventions
Does the model follow the project’s existing naming rules, directory structure, error-handling patterns, and logging conventions?
Static-analysis warnings can be used as a proxy. The more warnings a model introduces, the higher the subsequent code-review cost.
5. Tool Use and Multi-Step Execution
In a controlled environment, can the model read files, run commands, adjust its strategy based on command output, and recover when an intermediate step fails?
Useful metrics include:
- Final task completion rate.
- Average number of steps.
6. Long-Context Processing
When working with large files or long conversation histories, can the model accurately reference important information without omitting facts or inventing details?
One possible method is to embed known facts in a long document and measure question-answering accuracy.
7. Response Latency and Cost
Interactive workflows should measure time to first token and total response time. Batch workloads should measure throughput at a given unit cost.
Data should come from real production request logs and include:
- Time to first token.
- P50 latency.
- P95 latency.
- Cost per 1,000 tokens.
Theoretical values provided by vendors should not be used directly for comparison.
8. Stability and Reproducibility
How much does the output vary for the same input at different times, and how available is the service?
Possible metrics include:
- Variation in pass rate across repeated runs of the same task.
- Service error rate.
3. Internal Evaluation Sets and Statistical Decisions
Public benchmarks are useful for quickly narrowing the candidate list, but they have three major limitations.
First, their task distribution may not match your business. An overall ranking may hide important differences between frontend, data-processing, and embedded-software tasks.
Second, scores can change with model versions and prompt wording. The confidence interval around a single result is often relatively wide.
Third, some benchmark questions may have appeared in a model’s training data, which can inflate the score.
A two-layer process is recommended:
- Use public results for initial screening. For example, keep only models near the top of a public benchmark or models that meet a minimum pass rate on a specialized test.
- Use an internal evaluation set for final selection.
An internal evaluation set should meet four requirements.
- Realistic sources: Use merged feature requests, historical defect tickets, and code-review comments from a recent period instead of simplified, manually written questions.
- Balanced coverage: Stratify samples by programming language, module, and difficulty. Keep enough samples in each category.
- Reliable judgments: Prefer automated tests as the evaluation standard. When automation is not possible, use two independent blind reviewers and document the scoring rubric.
- Regular updates: Replace part of the dataset every quarter to reduce the risk of models being optimized against the benchmark.
Before adding samples to the dataset, complete data redaction and authorization reviews. Remove secrets, access tokens, personal information, and customer data from the code. Also verify that the intended use of each sample complies with internal data-management policies.
Sample Size and Statistical Significance
Sample size determines whether a conclusion is reliable.
If each task category contains only 15 samples, an 80% pass rate has a 95% confidence interval with a half-width of approximately 20 percentage points. A five-point difference between two models is therefore almost meaningless.
To distinguish an 80% pass rate from an 85% pass rate, assuming independent samples, a significance level of 0.05, and statistical power of 0.8, each model would require approximately 900 independent samples.
If both models are evaluated on the same questions using a paired design, the required sample size can be substantially smaller.
Running each task multiple times also helps reveal per-task variation. The Wilson interval can be used to calculate confidence intervals. It is generally more stable than a normal approximation when the sample size is small or the pass rate is close to 0 or 1.
For a paired comparison between two models, a difference should be considered reliable only when its 95% confidence interval does not include 0. Otherwise, treat the models as having no statistically significant difference.
4. A Runnable Evaluation Script
The following script uses only the Python standard library and runs on Python 3.9 or later.
By default, call_model is a stub that returns a fixed answer. This verifies that the evaluation pipeline works end to end. When connecting a real model, replace the function body. After replacing CASES with your internal evaluation set, the script can produce a team-specific baseline.
import jsonimport osimport statisticsimport subprocessimport sysimport tempfileimport timefrom collections import Counterfrom dataclasses import dataclass, asdictfrom pathlib import PathTIMEOUT_S = 10SAMPLES = 5CASES = [{"case_id": "add-001","prompt": "Implement a function add(a, b) that returns the sum of two integers.","test_code": """import unittestfrom solution import addclass TestAdd(unittest.TestCase):def test_add(self):self.assertEqual(add(2, 3), 5)""",},]@dataclassclass SampleResult:case_id: strsample_idx: intpassed: boollatency_s: floaterror: str = ""def call_model(prompt: str) -> str:"""Example stub for validating the pipeline. Replace this body to call a real model."""return "def add(a, b):\n return a + b\n"def _limit_resources():import resourceresource.setrlimit(resource.RLIMIT_CPU, (TIMEOUT_S, TIMEOUT_S))mem = 512 * 1024 * 1024resource.setrlimit(resource.RLIMIT_AS, (mem, mem))def run_candidate(solution: str, test_code: str) -> tuple[bool, str]:"""Run candidate code and tests in a temporary directory with a minimal environment."""with tempfile.TemporaryDirectory(prefix="eval_") as tmp:workdir = Path(tmp)(workdir / "solution.py").write_text(solution, encoding="utf-8")(workdir / "test_solution.py").write_text(test_code, encoding="utf-8")env = {"PATH": os.defpath} # Do not pass secrets or proxy variablestry:proc = subprocess.run([sys.executable, "-B", "-m", "unittest", "-q", "test_solution"],cwd=workdir,env=env,capture_output=True,text=True,timeout=TIMEOUT_S,preexec_fn=_limit_resources if os.name == "posix" else None,)except subprocess.TimeoutExpired:return False, "timeout"except OSError as exc:return False, f"launch_error: {exc}"if proc.returncode == 0:return True, ""return False, "test_failed: " + proc.stderr[-500:]def wilson_ci(successes: int, n: int, z: float = 1.96) -> tuple[float, float]:if n == 0:return 0.0, 0.0p = successes / ndenom = 1 + z * z / ncenter = (p + z * z / (2 * n)) / denomhalf = z * (p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5 / denomreturn max(0.0, center - half), min(1.0, center + half)def summarize(results: list[SampleResult]) -> dict:n = len(results)if n == 0:return {"n": 0}passed = sum(r.passed for r in results)latencies = sorted(r.latency_s for r in results)p95_index = min(n - 1, round(0.95 * (n - 1)))low, high = wilson_ci(passed, n)failures = Counter(r.error.split(":")[0] for r in results if not r.passed)return {"n": n,"pass_rate": round(passed / n, 4),"ci95": [round(low, 4), round(high, 4)],"latency_p50_s": round(statistics.median(latencies), 3),"latency_p95_s": latencies[p95_index],"failure_types": dict(failures),}def evaluate(cases: list[dict], samples: int, out_path: str) -> dict:results: list[SampleResult] = []for case in cases:for i in range(samples):start = time.perf_counter()try:solution = call_model(case["prompt"])except Exception as exc:latency = time.perf_counter() - startresults.append(SampleResult(case["case_id"], i, False, round(latency, 3), f"model_error: {exc}"))continuelatency = time.perf_counter() - startpassed, error = run_candidate(solution, case["test_code"])results.append(SampleResult(case["case_id"], i, passed, round(latency, 3), error))report = {"summary": summarize(results),"samples": [asdict(r) for r in results],}Path(out_path).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")return reportif __name__ == "__main__":report = evaluate(CASES, SAMPLES, "eval_report.json")print(json.dumps(report["summary"], ensure_ascii=False, indent=2))
After execution, the script creates eval_report.json in the current directory.
The file contains two sections:
summary: Aggregate metrics, including sample count, pass rate, 95% confidence interval, P50 and P95 latency, and the distribution of failure types.samples: Details for every sampling run, which can be used to investigate why individual tasks failed.
Production Isolation Requirements
The script provides only limited isolation. Resource limits on a child process can constrain some uncontrolled behavior, but they cannot prevent generated code from reading local files or accessing the network.
In production, follow these practices:
- Run the evaluation inside a container or virtual machine as a non-root user.
- Disable network access, for example with
docker run --network none. - Mount the code directory as read-only and allow writes only in a temporary directory.
- Limit CPU, memory, process count, and per-task execution time.
- Clear environment variables. Never inject API keys into the code-execution environment. Deploy the evaluation scheduler separately from the code-execution environment.
- Record timeouts and exceptions. A failure in one task should not interrupt the entire batch.
- Do not execute shell commands generated by the model. Run only a fixed test entry point.
5. Making a Decision Based on Cost, Latency, and Compliance
The decision process can be divided into four steps:
- Apply compliance requirements as hard gates. Eliminate models that fail them before applying any weighted scoring.
- Filter candidates according to the budget.
- Filter candidates according to latency requirements.
- Apply a quality-weighted score to the remaining candidates.
Common compliance checks include:
- Whether code and prompts may be sent to an external service.
- Whether the provider retains submitted data.
- How long the data is retained.
- Whether the data is used for training.
- Whether the storage region satisfies organizational requirements.
- Whether an appropriate data-processing agreement has been signed.
If any required condition is not met, eliminate the model.
The thresholds below are examples only. Each team should adjust them according to its budget and service-level agreements.
| Dimension | Measurement | Example threshold | Treatment |
|---|---|---|---|
| Compliance | Data retention, training use, storage region, and processing agreement | All requirements satisfied | Eliminate models that fail |
| Unit cost | Cost per 1,000 tokens multiplied by average token usage from production logs, calculated monthly | Within the defined share of the monthly budget | Eliminate models that exceed it |
| Overall latency | P95 total latency from production logs | Must meet the service-level target | Eliminate models that exceed it |
A reliable model-selection process should therefore combine capability-specific benchmark results with confidence intervals, real production latency and cost data, execution safety, and compliance requirements. Public rankings can help create an initial shortlist, but the final decision should be based on evidence from the team’s own workloads.
