Evaluating Long-Horizon AI Agents and Code Generation: A Practical Guide
A practical guide to evaluating large language models on long-horizon agent tasks, including code generation, terminal-based task completion, factuality, safety, the pass@k metric, reproducible evaluation frameworks, long-context strategies, and cost trade-offs.
From Single-Turn Q&A to Long-Horizon Agents
Early LLM applications focused mostly on single-turn question answering, and evaluation centered on language understanding and generation quality. As models began handling multi-step tasks—reading a codebase, running commands, fixing files based on error messages, calling external tools, and summarizing results—the evaluation focus shifted accordingly. These are known as long-horizon tasks: they involve many steps, state changes persist across steps, and an early mistake gets amplified down the chain.
To determine whether a model can handle this kind of work, development teams need to answer three questions: Can the model stay goal-consistent over many steps? Can it use tools correctly and interpret tool feedback? Can it self-correct after making a mistake? None of these can be measured with a single Q&A exchange; they require a purpose-built evaluation pipeline.
Breaking Down Evaluation Dimensions
Before evaluating, clarify what your business actually cares about. A common breakdown looks like this.
Code Generation and Repair
Code capability can be measured on two levels. The first is functional correctness: whether the generated code passes pre-written unit tests. The second is engineering usability: whether it runs out of the box, follows the project’s existing coding conventions, and avoids unnecessary dependencies.
In practice, use test pass rate as the primary metric, with scope of changes and the number of compile or runtime failures as auxiliary metrics. Pass rate alone can miss cases where tests pass but the change is unnecessarily large—which creates extra cost during code review.
Task Completion in Restricted Terminal Environments
Terminal tasks require the model to accomplish goals exclusively through the command line, such as locating exceptions in logs, fixing configuration files, or rebuilding a module. Keep the following in mind when evaluating:
- Isolate the environment; every task should start from the same snapshot to ensure reproducibility.
- Log each command, its return code, and its duration so you can analyze where failures occur.
- Set step limits and timeouts to prevent the model from getting stuck in repetitive loops.
Beyond success rate, average step count and timeout rate matter too. When two models have similar success rates, the one with fewer steps typically costs less to run and keeps users waiting less.
3D Modeling and Parameterized Scripts
Asking a model to write 3D modeling scripts is a common way to test spatial understanding and structured output. Evaluation has three stages: does the script execute without errors; do the generated geometry dimensions match the required parameters; and does the geometry change as expected when parameters are modified.
Scoring for these tasks is best done programmatically—for example, by computing bounding-box dimensions or comparing volume or face counts—rather than relying entirely on manual judgment.
Factual Accuracy
Factual accuracy involves two distinct metrics. One is the per-claim error rate: split a response into individually verifiable factual statements and count the proportion that are wrong. The other is the response-level error rate: the proportion of responses containing at least one error. These reflect different things—the former measures fine-grained reliability, while the latter is closer to the user’s actual experience.
Note that error rates measured on deliberately constructed difficult samples do not generalize directly to everyday usage. When reporting results, always describe how the test set was constructed and what it covers.
Safety and Misuse Risks
Safety evaluation covers two areas: the model’s ability to refuse harmful requests, and the effectiveness of data governance during training and alignment. For sensitive capabilities such as offensive and defensive cybersecurity, a common approach is filtering at the training-data level and adding corresponding constraints and reward signals during reinforcement learning.
You can compare filtered and unfiltered versions on the same set of specialized test questions to observe capability changes. This comparison helps quantify the cost of safety measures and shows whether risk controls are effective.
Metric Design: pass@k as an Example
In sampled generation, the same prompt can produce multiple answers, and single-attempt success rate does not fully capture model capability. The pass@k metric represents the probability of at least one success in k independent attempts. It is widely used in code and mathematical reasoning evaluation.
Given n samples per problem with c passing, the unbiased estimator is:
$\text{pass@}k = 1 - \frac{\binom{n-c}{k}}{\binom{n}{k}}$
Here is a Python implementation:
from math import combdef pass_at_k(n: int, c: int, k: int) -> float:"""n: total samples per problem; c: samples that pass; k: number of attempts."""if n - c < k:return 1.0return 1.0 - comb(n - c, k) / comb(n, k)# Example: 10 samples per problem, 3 passingprint(round(pass_at_k(10, 3, 1), 3)) # 0.3print(round(pass_at_k(10, 3, 5), 3)) # ~0.917
When reporting the metric, always include the values of n, k, and the number of problems. A bare “pass@3 of X” without sampling details cannot be compared across systems.
Building a Reproducible Long-Horizon Evaluation Framework
The following example shows a minimal evaluation loop. The core idea is to decouple the agent, the environment, and the scoring logic so the same tasks can run against different models.
from dataclasses import dataclass@dataclassclass EpisodeResult:success: boolsteps: inttimed_out: booldef run_episode(agent, env, max_steps: int = 50) -> EpisodeResult:obs = env.reset()for step in range(1, max_steps + 1):action = agent.next_action(obs)obs, done, info = env.step(action)if done:return EpisodeResult(info["success"], step, timed_out=False)return EpisodeResult(False, max_steps, timed_out=True)def summarize(results: list[EpisodeResult]) -> dict:total = len(results)return {"success_rate": sum(r.success for r in results) / total,"avg_steps": sum(r.steps for r in results) / total,"timeout_rate": sum(r.timed_out for r in results) / total,}
In real engineering, you will also need:
- Sandbox isolation: run each task in a separate container or VM, with restricted network, filesystem, and resource quotas.
- Persisted results: save full trajectories, including every observation and action, for later root-cause analysis.
- Randomness control: fix random seeds, or run the same task multiple times and report the distribution.
- Programmatic scoring: replace subjective judgment with executable assertions wherever possible.
Engineering Approaches to Long Context
The larger a model’s context window, the more of a codebase or long document it can hold. But a large window does not mean everything should be stuffed into it. Consider these strategies.
Retrieval on Demand
Use an index to locate relevant files or passages first, then place only the necessary fragments into context. This reduces noise and lowers the cost of each request.
Layered Summarization
For very long tasks, periodically compress past steps into a structured summary, such as “completed items, pending items, key constraints, unresolved errors.” Summaries should preserve the reasoning behind decisions, not just conclusions.
Context Budgets
Set caps per information type—for example, a fixed share for system instructions and truncation limits for tool outputs. Anything beyond the budget should go to external storage, with a reference kept in context.
Balancing Cost and Latency
LLM service pricing typically depends on both input and output token counts, with output tokens generally priced higher than input. In long-horizon tasks, every step may carry a large amount of history, so costs grow faster than intuition suggests.
Several general techniques can keep spending under control:
- Context caching: enable caching for repeated prefixes (such as system instructions or codebase descriptions) to avoid redundant computation. Billing rules for cache hits and writes vary by provider—check the specific service’s pricing documentation.
- Task tiering: use smaller or faster models for simple steps and reserve high-capability models for complex reasoning.
- Output constraints: require structured output formats to reduce redundant text.
- Parallelism and batching: run independent subtasks in parallel to reduce total wall-clock time.
Many providers also offer a standard mode alongside a low-latency mode, with the latter usually priced higher. Choose based on your business’s latency requirements rather than defaulting to the fastest option.
Safety and Data Governance
Once an agent can call tools, the attack surface expands significantly. Consider these constraints:
- Least privilege: the agent should only access directories, endpoints, and credentials required for the task. Inject credentials via environment variables or a secrets management service—never hardcode them or write them to logs.
- Operation auditing: log all external calls and write operations, and require human confirmation for high-risk actions such as deletion, publishing, and permission changes.
- Input and output filtering: sanitize tool outputs to prevent malicious instructions from being injected into the agent’s decision process via web pages, files, or logs.
- Training data governance: remove sensitive categories of content during data collection and training, and verify filtering effectiveness with dedicated tests.
Safety evaluation should run alongside capability evaluation. Assessing capability while ignoring risk produces overly optimistic conclusions.
A Pre-Production Checklist
Before bringing a model into your production workflow, verify the following:
- Do evaluation tasks cover real business scenarios, not just public benchmark questions?
- Do your metrics include success rate, step count, latency, and cost?
- Is the test environment isolated, and are results reproducible?
- Is there a manual or programmatic spot-check mechanism for factual outputs?
- Do high-risk operations have approval and rollback procedures?
- Is the cost model calculated from actual token distributions rather than estimated from a single example?
Evaluation results should serve concrete decisions. A well-designed internal evaluation often tells you far more about whether a model fits your business than any external leaderboard.
