Evaluating LLMs for Code and Long-Horizon Agent Tasks: A Practical Guide
This article explains how to move beyond public leaderboards and build a reproducible evaluation pipeline for large language models, covering code tasks with pass@k, long-horizon agent behavior, tool interaction, factual accuracy, safety governance, and per-task cost analysis, with sample code for evaluation harnesses and cost calculation.
1. Why Evaluation Should Focus on Tasks, Not Leaderboards
Aggregate scores on public leaderboards reflect a model’s general capability, but they rarely answer a team’s practical questions: Can this model handle our code reviews? Can it reliably call tools across multi-step workflows? Is the per-task cost acceptable? Leaderboard scores are produced under specific datasets, prompts, and grading rules, so they need to be re-validated against your own workloads before they transfer.
The core of evaluation is breaking “is the model good” into measurable questions: on which tasks, with which inputs, against which success criteria, and at what cost.
2. Evaluation Dimensions
1. Code and engineering tasks
Code evaluation should be based on unit test results, not text similarity. The standard metric is pass@k: the probability that at least one of k independent samples passes. pass@1 reflects single-attempt reliability, while pass@k reflects the model’s ceiling across multiple attempts. The two should be reported separately.
2. Long-horizon agent tasks
Long-horizon tasks typically require multi-turn planning, tool calls, and state maintenance. Key metrics include task completion rate, step efficiency, and the ability to recover from mid-task failures. Inspecting only the final answer often hides errors in intermediate steps, so full execution traces must be recorded.
3. Tool and environment interaction
Execute commands in a restricted terminal or sandbox, then verify whether the resulting system state matches expectations. The judgment should rely on the actual state, not on the model’s description of what it did.
4. Factual accuracy
Break model answers into atomic factual claims and verify each one. Two metrics should be distinguished: the per-claim error rate, which measures the reliability of individual statements; and the proportion of answers containing at least one error, which measures the probability that an entire output can be used as-is. They emphasize different things and should both be reported.
5. Safety
Examine the model’s refusal and compliance behavior in risky scenarios, and review whether the training data governance process is complete—for example, data source records, sensitive content filtering, and version traceability.
6. Cost and latency
Cost-effectiveness should be measured as cost per successful task, not unit price alone. A model with a higher unit price may cost less overall if it completes tasks in half as many calls.
3. Building a Reproducible Evaluation Pipeline
Reproducible evaluation rests on three principles: fix sampling parameters and record random seeds; keep the task set and grading scripts under version control; and save raw outputs from every run, then aggregate statistics across multiple runs.
Below is a simplified evaluation skeleton. The model call function and grading function need to be implemented according to your actual integration:
from dataclasses import dataclassfrom typing import Callable@dataclassclass TaskResult:task_id: strpassed: boolinput_tokens: intoutput_tokens: intlatency_s: floatdef run_suite(tasks, model_call: Callable, grader: Callable, n: int = 5):"""Sample each task independently n times and record grading results and usage."""results = []for task in tasks:for _ in range(n):resp = model_call(task["prompt"])results.append(TaskResult(task_id=task["id"],passed=grader(task, resp["text"]),input_tokens=resp["usage"]["input"],output_tokens=resp["usage"]["output"],latency_s=resp["latency"],))return resultsdef pass_at_k_empirical(results, k: int) -> float:"""Empirical estimate: a task counts as a hit if at least one of its first k samples passes."""by_task: dict[str, list[bool]] = {}for r in results:by_task.setdefault(r.task_id, []).append(r.passed)hits = [any(runs[:k]) for runs in by_task.values()]return sum(hits) / len(hits)
This implementation uses an empirical estimate. When the number of samples n exceeds k, a more rigorous approach is to use the unbiased pass@k estimator to reduce small-sample variance. The grading function also needs independent validation—for example, sampling outputs for manual review to confirm the grading logic has no systematic bias.
4. Measuring and Interpreting Factual Accuracy
Adversarial test sets deliberately constructed from error-prone cases are effective at exposing model weaknesses, but their error rates are typically higher than those in everyday usage distributions. These results should not be interpreted directly as everyday error rates.
A more robust approach:
- Build a sample set consistent with your business distribution and stratify statistics by question type;
- Report adversarial and everyday sets separately, noting how each was constructed;
- Retain human review for high-risk domains, regardless of how high the scores are.
5. Calculating Cost per Task
Cost typically consists of input, output, and caching components. Cache hits, cache writes, and writes with different retention periods are billed differently and must be accounted for separately.
def task_cost(input_tokens: int, output_tokens: int,in_price: float, out_price: float,cached_tokens: int = 0, cache_price: float = 0.0,cache_write_tokens: int = 0, cache_write_price: float = 0.0) -> float:"""Prices are per million tokens."""fresh_input = input_tokens - cached_tokens - cache_write_tokenscost = (fresh_input * in_price+ cached_tokens * cache_price+ cache_write_tokens * cache_write_price+ output_tokens * out_price)return cost / 1_000_000
On top of this, compute the cost per successfully completed task: total cost divided by the number of successful tasks. For products offering different service tiers, weigh the price difference against the latency benefit to decide whether the extra spend is justified.
6. Engineering Essentials for Safety Governance
Safety governance is not a single filtering step but a process spanning data, training, and evaluation:
- Data source auditing: Record the sources, cleaning rules, and versions of training data for traceability.
- Sensitive content filtering: Identify and remove content related to high-risk operations during data processing, and retain filtering reports.
- Red-team evaluation: Build test sets covering risk scenarios, run them regularly, and observe the balance between refusal rate and over-refusal rate.
- Version comparison: Run the same test set against unfiltered and released versions to quantify the actual effect of governance measures.
7. Common Pitfalls
- Relying only on aggregate leaderboards while ignoring fit with your own tasks.
- Drawing conclusions from a single run while ignoring randomness.
- Assuming grading scripts are correct without spot-checking.
- Treating adversarial-set error rates as everyday error rates.
- Comparing only unit prices without computing cost per successful task.
8. Recommendations for Adoption
Proceed in the following order:
- Identify the core tasks in your business and define success criteria for each type;
- Build a seed evaluation set covering typical and edge cases, and put it under version control;
- Implement automated grading and calibrate its quality with manual sampling;
- Record accuracy, latency, and cost together, and compute cost per successful task;
- Validate with limited traffic first, then gradually expand usage;
- Continuously monitor key metrics after launch, and re-run evaluations whenever the model or prompts change.
The value of an evaluation pipeline is that it makes model selection and iteration evidence-based. Once the relationship between tasks, criteria, and cost is fixed, a team can make reproducible decisions with the same methodology even as models evolve rapidly.
