# Evaluating AI Agents on Long-Horizon Tasks: Methods and Key Metrics
How do you reliably evaluate AI agents that perform long, multi-step tasks? This article covers blind head-to-head comparison design, core metrics such as task completion rate, shell command reliability, course-correction ability, net improvement rate, and cost efficiency, along with practical Python code and common pitfalls when interpreting results.
Why a Single Demo Isn’t Enough to Evaluate an Agent
Unlike a standard question-answering model, an AI agent must call tools, execute commands, read the results, and decide on its next action across multiple rounds of reasoning. A single demo typically covers only the smoothest path and reveals little about how stable the system is over a long workflow. A system that excels at a three-step task may get stuck in a loop at step forty because one command returned an unexpected error. Evaluating an agent therefore requires answering three questions: Can it complete the task? Is the process reliable? And can it cooperate when corrected mid-task?
The difficulty with long-horizon tasks is that errors compound. If each step has a 90% success rate, the probability of success across twenty consecutive steps is roughly 0.9²⁰ ≈ 12%. This simple calculation shows that evaluation must cover the full execution trajectory, not just the final output.
Basic Design of a Blind Head-to-Head Comparison
Blind head-to-head testing is a relative evaluation method. The same batch of tasks is given to two or more systems, and reviewers compare output quality without knowing which system produced each result. The comparisons are then aggregated into rankings. The value of this approach is that it reduces reviewer expectation bias, making rankings closer to real user experience.
Four design points deserve attention:
- Diversify task sources. Hand-crafted test cases tend to be well-structured, while real user sessions contain vague requirements, missing context, and unexpected interruptions—conditions that expose system weaknesses. Tasks should cover coding, document processing, data analysis, and everyday office work.
- Hide identity information. Remove model names, version numbers, and obvious formatting signatures from what reviewers see, so brand impressions don’t influence scores.
- Eliminate position bias. Randomize which result appears on the left and record the order in your statistics. Otherwise reviewers may habitually favor the first option and distort the results.
- Keep ties. If two results are close in quality, record a tie rather than forcing a winner. Forced decisions inject reviewer noise into the rankings.
For ranking algorithms, pairwise comparison models such as Elo or Bradley-Terry work well. Elo updates scores incrementally after each match, while Bradley-Terry estimates each system’s relative strength from all matches. Both require a sufficient sample size. With too few samples, ranking gaps may simply be random fluctuations, so confidence intervals should be reported alongside the rankings.
Core Metrics: Definitions and Calculations
An evaluation shouldn’t produce just a single overall score. The following metrics cover different capability dimensions and work best in combination.
3.1 Task Completion Rate
The proportion of tasks the system completes independently within a step limit and whose results pass validation. Calculations should distinguish three states: “fully completed,” “partially completed,” and “failed or abandoned.” Partially completed tasks can be weighted, but the weighting rules must be fixed before the evaluation begins—no adjustments after the fact.
3.2 Shell Command Execution Reliability
Among commands executed in a sandbox, the proportion whose exit codes match expectations, whose output passes validation rules, and which require no human intervention. This metric demands special attention to error recovery. Whether the system can analyze an error message, fix its parameters, and retry after a command fails is more meaningful than simply tracking first-attempt success rates. Evaluation logs should record the type of each failure—path errors, permission issues, timeouts, or syntax errors—to help locate problems.
3.3 Course-Correction Ability
Partway through a task, inject a corrective instruction such as “only modify the configuration file, don’t touch the source code,” then observe three behaviors: whether the system accurately adopts the new instruction, whether it preserves previously completed and valid work, and whether it drifts off course again in later steps. This capability determines whether an agent can be effectively guided by humans in real collaboration.
3.4 Net Improvement Rate
Used to compare a new version against an old one. On the same batch of tasks, count how many tasks the new version wins and how many it loses:
Net improvement rate = (wins − losses) ÷ total tasks
A positive value indicates overall improvement, but it says nothing about whether the gains are consistent. When reporting, include a confidence interval and list the losing samples to check whether regressions cluster in a particular task category.
3.5 Step Count and Cost Efficiency
The number of tool calls, model output tokens, and end-to-end time needed to complete the same task. Efficiency metrics must be read alongside completion rate. If a system finishes tasks in fewer steps but completion rate drops significantly, its efficiency gains don’t hold up.
Evaluation Workflow and Example Code
The following code demonstrates two basic functions: calculating the net improvement rate with a confidence interval, and applying randomized positioning to reviewer results. It relies only on the Python standard library and can be used directly for offline analysis.
import randomdef net_improvement(results):"""Calculate net improvement rate. Each element in results is 'better', 'worse', or 'tie'."""total = len(results)if total == 0:raise ValueError("No evaluation results")better = sum(r == "better" for r in results)worse = sum(r == "worse" for r in results)return (better - worse) / totaldef bootstrap_ci(results, n_iter=2000, alpha=0.05, seed=42):"""Estimate the confidence interval of the net improvement rate using bootstrap."""rng = random.Random(seed)scores = []for _ in range(n_iter):sample = [rng.choice(results) for _ in results]scores.append(net_improvement(sample))scores.sort()low = scores[int(alpha / 2 * n_iter)]high = scores[int((1 - alpha / 2) * n_iter) - 1]return low, highdef blind_layout(output_a, output_b, rng):"""Randomly decide the display order of two outputs; return the layout and a swap flag."""if rng.random() < 0.5:return {"left": output_a, "right": output_b, "swapped": False}return {"left": output_b, "right": output_a, "swapped": True}if __name__ == "__main__":judgements = ["better"] * 58 + ["worse"] * 21 + ["tie"] * 21score = net_improvement(judgements)low, high = bootstrap_ci(judgements)print(f"Net improvement rate: {score:.3f}, 95% CI: [{low:.3f}, {high:.3f}]")
A complete evaluation workflow typically has five stages:
- Task preparation. Sample from real sessions and hand-crafted cases, stratify by scenario, and fix random seeds for reproducibility.
- Sandbox execution. Run each system in the same isolated environment and record the full trajectory, including every tool call, return value, and timing.
- Blind review. Reviewers see only de-identified results and score them against a pre-defined rubric.
- Statistical analysis. Compute each metric, report confidence intervals, and examine per-scenario breakdowns.
- Retrospective and archiving. File typical failure trajectories into a problem library as input for the next round of improvements.
Common Pitfalls When Interpreting Results
Relying on a single ranking. An overall ranking masks capability differences. A system may lead on coding tasks but fall behind on office document processing. Break results down by scenario before deciding which system fits a particular use case.
Ignoring sample size. Gaps observed over a few dozen tasks often fall within the confidence interval. When samples are limited, state the uncertainty explicitly rather than issuing a definitive ranking.
Ignoring distribution shift. If evaluation tasks differ greatly from real workloads, high scores don’t reflect actual performance. Refresh the evaluation set periodically with real production tasks.
Treating reviewer preferences as objective standards. Reviewers may favor friendly tone or tidy formatting even when the content is inaccurate. The scoring rubric should explicitly separate correctness, completeness, and presentation quality, and score them independently.
Overlooking process quality. A correct final result achieved through repeated dangerous commands or skipped validation steps is still a problem worth recording in production environments.
Practical Recommendations for Getting Started
For engineering teams that want to run agent evaluations internally, a sensible order of progression looks like this:
First, pick three to five task categories directly relevant to your business, prepare at least one hundred samples per category, and annotate the completion criteria. Second, standardize the sandbox environment so that dependency versions, file structures, and permission settings are consistent across every run. Third, build an automated pipeline that saves the trajectory, scores, and statistics from every evaluation run for traceability.
On the infrastructure side, you can use container platforms—on Baidu AI Cloud or other cloud environments—to run evaluation tasks in parallel, use logging services to store full trajectories, and use monitoring and alerting to catch abnormal swings in success rate and average latency. These are generic engineering capabilities; choose based on your team’s existing stack and compliance requirements.
Finally, evaluation should be continuous. After every model or prompt change, re-run the core task set and compare the net improvement rate and per-metric results against the previous version. Only by making evaluation part of your daily workflow can a team tell which changes delivered real gains—and where they introduced new risks.
