Evaluating AI Agents on Long-Horizon Tasks: Metrics Breakdown and Engineering Practices
Long-horizon agent tasks involve dozens of tool calls and state changes, so single-turn answer quality alone cannot reflect real capability. This article explains how to build an evaluation framework for long-horizon agent tasks, covering metrics decomposition (task success rate, shell command reliability, controllability, composite improvement rate, cost and latency), task set design, isolated execution environments, review methods, statistical analysis with sample code, common interpretation pitfalls, and practical rollout recommendations.
Introduction
An AI agent differs from a single-turn question-answering model in that it must call tools, read and write state, and execute commands across multiple reasoning steps, adjusting its next action based on intermediate results. A single task may involve dozens or even hundreds of steps, and an error at any point can cause the entire workflow to fail. Evaluating only single-turn answer quality therefore no longer reflects real capability.
This article discusses how to design an evaluation framework for long-horizon tasks, covering metrics decomposition, task data construction, execution environment isolation, result interpretation, and common pitfalls.
1. Challenges in Evaluating Long-Horizon Tasks
Compared with short question answering, the difficulty of evaluating long-horizon tasks comes mainly from four aspects.
Strong step dependencies. Later actions depend on the results returned by earlier tool calls. An early misjudgment gets amplified along the chain, and the final outcome may diverge far from the initial deviation. Evaluation must record the inputs, outputs, and state changes of every step, rather than looking only at the final answer.
Non-unique ground truth. The same goal usually has multiple feasible paths. For example, a misconfiguration can be fixed either by editing the config file or by regenerating the configuration. Evaluation criteria should focus on whether the final state meets the requirements, not on whether the path matches a reference answer.
Side effects in the execution environment. Commands may modify files, write to databases, or make network requests. Evaluation must run in an isolated environment that can be restored to an initial snapshot before each run; otherwise, results across versions will contaminate each other.
Compounding cost and latency. Every step consumes inference resources and tool-call resources. Total time and total cost per task result from both the number of steps and per-step overhead, and must be measured separately.
2. Metrics Breakdown
Evaluation metrics should cover three layers: outcome, process, and cost. Each dimension is explained below.
2.1 Task Success Rate
Task success rate is the proportion of tasks that reach the target end state within a limit on steps and time. End-state verification should rely on objectively verifiable results, such as whether file contents match expectations, whether an API returns correctly, or whether a database record was written. The agent’s self-reported “task complete” should not be trusted, because its claim may not match the actual state.
2.2 Shell Command Execution Reliability
This metric measures the proportion of agent-generated shell commands that execute correctly in the target environment. It can be broken down into three sub-metrics:
- Syntax correctness: whether the command can be parsed and launched;
- Argument validity: whether the arguments and options conform to the tool’s conventions;
- Result conformance: whether the exit code and output meet task expectations.
In addition, the recovery rate after failure should be tracked: when a command errors out, can the agent read the error message and produce an effective fix?
The calculation is:
R_exec = number of commands with expected results / total number of commands
2.3 Controllability (Steering and Course Correction)
Controllability refers to whether, after the user issues a corrective instruction mid-task, the agent adjusts its direction correctly in subsequent steps while preserving valid progress already made. This capability is especially important in production scenarios, where real requirements often become clear only during execution.
During evaluation, a steering instruction can be injected mid-session, such as “do not change the database schema; only adjust the query logic,” and then two quantities are measured:
- Steering success rate: the proportion of tasks that ultimately reach the goal after the correction;
- Unnecessary rollback rate: the proportion of cases where the agent reverted steps that were already correct, causing extra work.
2.4 Composite Improvement Rate
When comparing two versions, individual metrics may move in different directions. A common practice is to combine the metrics into a weighted score, then compute the change relative to a baseline:
Δ = (S_new − S_old) / S_old × 100%
Here, S is the weighted composite score, and the weights are determined by business priorities. Once set, weights should remain consistent across evaluations and be disclosed in reports. The composite score is useful for quick comparisons, but it hides internal structure, so the per-dimension metrics must always be examined alongside it.
2.5 Cost and Latency
Cost and latency metrics include average token consumption per task, average tool calls per task, end-to-end latency, and P95 latency. P95 better reflects the long-tail experience than the mean and is a better reference for launch gating.
3. Building the Evaluation Framework
3.1 Task Set Design
The task set is the foundation of evaluation, and its quality directly determines whether conclusions are trustworthy. Design principles include:
- Cover real scenarios: Stratify by business category, such as document processing, code modification, data querying, and general Q&A, with sufficient samples in each category;
- Grade difficulty: Distinguish single-step, multi-step, and cross-tool tasks to locate capability boundaries;
- Holdout set: Reserve a portion of tasks that are not exposed, used for final validation, to prevent overfitting to public tasks during version iterations;
- Regular updates: Replace outdated tasks promptly as the business changes, to avoid data drift.
3.2 Execution Environment
The execution environment must satisfy three requirements: isolation, resettability, and observability.
- Restore from a snapshot before each run to ensure a consistent starting state;
- Tool interfaces may use real services or mock services. Either way, all call parameters and return values must be logged;
- Set timeouts and resource limits to prevent a single task from looping indefinitely or exhausting quotas;
- Apply whitelists or permission boundaries to command execution, so accidental deletions or unauthorized operations cannot affect the host system.
3.3 Review Methods
The review method depends on the task type.
- Automatically verifiable tasks use rule-based checks, such as comparing file hashes or querying database results;
- Open-ended tasks use blind review, where reviewers do not know which version they are evaluating, reducing subjective bias;
- Multiple reviewers score the same samples, and inter-rater agreement (such as Cohen’s kappa) is computed. If agreement is low, the scoring rubric should be revised before trusting any conclusions.
3.4 Statistical Analysis
Evaluation results need statistical testing before they can inform decisions.
- Report confidence intervals, not just point estimates;
- Use paired comparisons: comparing two versions on the same tasks removes the confounding effect of task difficulty;
- Show distributions (median, percentiles) rather than relying only on means.
Below is an illustrative implementation that aggregates single-version metrics and computes the paired win rate between two versions.
from dataclasses import dataclassfrom statistics import mean@dataclassclass TaskRecord:task_id: strcategory: strsuccess: booltool_calls: intcommands_total: intcommands_ok: intsteer_attempts: int = 0steer_recovered: int = 0tokens: int = 0latency_s: float = 0.0def summarize(records: list[TaskRecord]) -> dict:n = len(records)if n == 0:raise ValueError("records is empty")cmd_total = sum(r.commands_total for r in records)steer_total = sum(r.steer_attempts for r in records)return {"task_success_rate": sum(r.success for r in records) / n,"shell_reliability": (sum(r.commands_ok for r in records) / cmd_totalif cmd_total else None),"steer_recovery_rate": (sum(r.steer_recovered for r in records) / steer_totalif steer_total else None),"avg_tokens": mean(r.tokens for r in records),"avg_latency_s": mean(r.latency_s for r in records),}def paired_win_rate(new_results: dict[str, bool],old_results: dict[str, bool]) -> float:"""Count only tasks where the two versions disagree, and compute the new version's win rate."""shared = new_results.keys() & old_results.keys()if not shared:raise ValueError("no shared tasks")wins = sum(1 for t in shared if new_results[t] and not old_results[t])losses = sum(1 for t in shared if old_results[t] and not new_results[t])decided = wins + lossesreturn wins / decided if decided else 0.5
paired_win_rate counts only tasks where the two versions disagree, because tasks where both succeed or both fail provide no discriminative signal. When the number of disagreeing samples is small, more tasks should be added; otherwise conclusions are unstable.
4. Common Pitfalls When Interpreting Results
Looking only at a single ranking. Rankings are affected by task distribution, review criteria, and sample size. When two versions are close, a change in ranking may just be random noise and must be judged together with confidence intervals.
Treating the composite score as a business conclusion. The composite score depends on weight settings, and the same score can correspond to very different internal structures. Examine each sub-metric first, identify weaknesses, and then decide whether to adopt a version.
Ignoring cost. One approach may have a higher success rate, but its per-task token consumption could be several times the baseline. Compute unit task cost and weigh it against business value before launch.
Overfitting to public tasks. If version iterations tune only against public tasks, metrics will keep rising while real-world performance may not improve. Holdout sets and periodic task replacement are the main defenses.
Ignoring safety incidents. Command execution metrics that only track success rates can hide risks. Incidents such as accidental deletion, unauthorized access, and budget overruns should also be tracked and treated as veto items.
5. Practical Recommendations
- Start small. Begin with 50 to 200 internal tasks close to your business, ensure every task has clear verification rules, then expand gradually.
- Build a regression mechanism. After every change to the model version, prompts, or tool definitions, automatically run the regression set and set alert thresholds for key metrics.
- Unify log collection. Write every step’s calls, commands, returns, and latency into a unified log, so failures can be traced by task category. Existing logging and monitoring/alerting infrastructure can be reused.
- Compare offline and online signals. During a canary release, compare evaluation metrics against online task success rates and user complaint rates. If the two point in different directions, first check whether the evaluation set has drifted from real traffic.
- Accumulate steering samples. Conversation fragments with human course corrections are valuable data for improving controllability.
