Capability Evolution and Engineering Practices of Long-Horizon AI Agents

    This article explores the evolution from single-turn Q&A models to long-horizon AI agents capable of executing extended tasks. It covers key aspects including evaluation methodologies in real-world environments, training infrastructure with reinforcement learning, engineering architectures for agent execution loops, cost and latency optimization through caching and tiered inference, and practical recommendations for safety and observability.

    1. Background: From Q&A Models to Long-Horizon Agents

    For a period, the primary use of large language models (LLMs) was single-turn Q&A. The model receives input, provides output, and the user decides the next step. As model capabilities improved, the industry shifted focus toward agents capable of autonomously decomposing goals, invoking tools, trial-and-error in environments, and continuously advancing. The value of such systems lies in their ability to maintain direction over dozens or even hundreds of steps, where the quality of a single response is only one part of the equation.

    A long-horizon agent refers to a system capable of continuously executing tasks over extended periods. Typical tasks include fixing bugs in large code repositories, completing multi-step data analysis, batch processing files in cloud environments, or regularly inspecting system status on a schedule. The common challenge in these tasks is error accumulation. A minor deviation in the first step can lead to entirely different outcomes by the twentieth step.

    2. Shift in Capability Evaluation: From Single-Turn Tests to Real-World Environments

    Evaluation methods dictate the direction of model research and development. Early benchmarks mostly used multiple-choice or single-turn generation questions to measure knowledge and reasoning. When models are integrated into real-world workflows, evaluation must shift toward executable environments.

    Evaluation for coding agents typically features the following characteristics:

    • Tasks are completed in terminals or containers, where models need to read files, run commands, view errors, and modify code.
    • Resource constraints, including limits on time, steps, and memory, closely resemble real production constraints.
    • Each task is paired with specific test cases, using test passage as the pass criteria to reduce reliance on manual grading.
    • Results are reproducible; repeating the same task in the same environment should yield comparable conclusions.

    Evaluation should simultaneously focus on multiple dimensions rather than just a single completion rate:

    1. Task completion rate: Whether it ultimately passes verification.
    2. Average steps and latency: The number of operations and time required to complete the same task.
    3. Cost: Input/output token count and tool invocation overhead.
    4. Stability: Fluctuations in results over multiple runs, especially performance in later stages of long tasks.
    5. Capability distribution: Whether performance is balanced across different types of tasks (e.g., frontend, backend, data processing).

    The issue of unbalanced capability distribution deserves special attention. A model scoring high in one type of test might struggle noticeably in another. Engineering teams should map their own business task distribution to the evaluation set rather than directly adopting the total scores from public leaderboards.

    3. Training-Side Changes: Post-Training Compute and RL Scaling

    The capability enhancement of long-horizon agents relies primarily on the post-training phase. Pre-training provides models with a broad foundation of language and knowledge, while post-training uses supervised fine-tuning and reinforcement learning (RL) to teach models how to act in specific environments.

    When applying RL to agent scenarios, three key challenges arise:

    • Reward design: Rewards should align with final task outcomes. Rewarding only intermediate steps can lead to reward hacking, where the model learns to cater to the reward function rather than completing the task.
    • Environment diversity: The more domains covered, the richer the states the model encounters. However, each domain requires an executable, verifiable environment.
    • Environment quality: If the environment has bugs or inconsistencies, the model might learn shortcuts. Therefore, a dedicated environment inspection process is needed to detect whether tests can be bypassed, whether dependencies are stable, and whether results can be clearly determined.

    The infrastructure supporting large-scale joint training typically includes the following components:

    • An RL training framework, responsible for the loop of sampling, scoring, and parameter updates.
    • A long-context inference service; agent execution trajectories are often very long, and inference throughput and memory management directly affect training speed.
    • A sandbox system, providing isolated execution environments for each sampling and reclaiming resources afterward.
    • A scheduling system, allocating compute resources among a large number of concurrent tasks and handling failure retries.
    • Training efficiency optimizations, including general techniques like mixed-precision computation, gradient checkpointing, and communication optimization.

    None of these components can be omitted. When the environment or sandbox is unstable, even the best algorithms struggle to obtain reliable training signals.

    4. Engineering Architecture of Long-Horizon Agents

    For application developers, model capability is only one part. Long-running agents also require an execution framework to manage state, tool invocations, and failure recovery.

    A typical execution loop includes planning, action, observation, recording, and checking. The following is a schematic code snippet:

    1. def run_agent(task, model, sandbox, max_steps=200):
    2. state = load_checkpoint(task.id) or init_state(task)
    3. while state.steps < max_steps and not state.done:
    4. plan = model.plan(state.summary, state.recent_observations)
    5. action = plan.next_action()
    6. if action.is_risky():
    7. if not request_human_approval(action):
    8. state.log("rejected", action)
    9. continue
    10. result = sandbox.execute(action, timeout=60)
    11. state.record(action, result)
    12. state.compress_memory_if_needed()
    13. save_checkpoint(task.id, state)
    14. state.done = task.verify(sandbox)
    15. return state

    This code illustrates several key points. Checkpoint saving allows tasks to resume after interruption. Risky actions require human confirmation. Each step is recorded for audit and review. Memory compression prevents unbounded context growth.

    Multi-agent collaboration is another common direction. A frequent approach is to split tasks into roles such as planner, executor, and verifier. The planner decomposes goals, executors complete sub-tasks in isolated environments, and verifiers independently check results. Roles should exchange information via structured messages to avoid indiscriminately passing the entire historical context to every role, which would significantly increase context costs and interference.

    5. Cost and Latency: Caching and Tiered Inference

    A characteristic of long-horizon tasks is that each step repeatedly sends a large amount of context. Without optimization, costs rise rapidly with the number of steps.

    Prompt caching is one of the most common methods. When the prefixes of multiple requests are exactly the same, the server can reuse previously computed intermediate results, thereby reducing input costs and time-to-first-token. Engineering practices can follow these guidelines:

    • Place stable content like system instructions and tool definitions at the beginning of the prompt.
    • Place step-specific observation results at the end.
    • Avoid inserting fields that change every time, such as timestamps, in the prefix.

    Tiered inference is another approach. The same model often offers different speed and price tiers. Interactive development scenarios are latency-sensitive and suitable for faster tiers. Batch offline tasks are less latency-sensitive and suitable for lower-cost tiers. Teams can dynamically select tiers based on task priority rather than uniformly using one configuration.

    Cost estimation can start with the following approximate formula:

    Total Cost ≈ Steps × Avg Input Tokens per Step × Input Unit Price + Steps × Avg Output Tokens per Step × Output Unit Price + Tool Invocation Cost

    The price difference between cache hits and misses is usually significant, so the proportion of both should be estimated separately during calculation.

    6. Practical Implementation Recommendations

    Safety and Permissions

    • The execution environment must be isolated; agents should only access directories, networks, and credentials required for the task.
    • Credentials should be injected via environment variables or key management services, and not written into prompts or logs.
    • High-risk operations like deletion, publishing, and permission changes require human confirmation or dual-person approval.
    • Maintain vigilance against instructions appearing in external web pages and file contents; they should not be allowed to directly alter the agent’s goals.

    Observability

    • Record the input summary, execution action, result, and latency for each step to facilitate failure localization.