Engineering Long-Horizon Tasks for General-Purpose AI Agents
This article explores the engineering practices required to build general-purpose AI agents capable of completing long-horizon tasks, moving beyond single-turn question answering toward end-to-end task delivery. It covers four foundational capabilities—long context and long output, multimodal input with tool-based output, evolving training paradigms with recursive self-improvement, and safety with tiered release—and proposes a five-layer production architecture spanning goal, planning, execution, verification, and governance. It also discusses the practical limits of computer operation and embodied scenarios, strategies for managing cost, latency, and stability, and a phased migration path for enterprises. Readers will gain a structured framework for orchestrating reliable, permission-aware, and recoverable agent workflows.
1. From Answering Questions to Doing Work: The Capability Leap of General-Purpose Agents
Over the past two years, the focus of general-purpose large models has shifted from single-turn question answering to end-to-end task delivery. In engineering terms, “doing work” carries four meanings. First, the model can perform multi-step complex reasoning, breaking a vague goal into executable subtasks. Second, it can write and debug code, forming a closed loop in the software engineering sense. Third, it can operate a computer and software interfaces, completing flows that once required manual clicking through the graphical interface. Fourth, it can maintain goal consistency across long workflows, calling tools, browsing web pages, reading and writing files, and independently advancing a task until it converges.
The emergence of these capabilities has changed the shape of applications. We used to treat the model as a “generator”: input a prompt, output text. Now we treat it as an “executor”: input a goal and constraints, and the output is a series of action traces and a final artifact—a document, a spreadsheet, a presentation, or a successful deployment. The engineering focus therefore shifts from “how well the prompt is written” to “whether task orchestration is reliable, whether permission boundaries are clear, and whether failures are recoverable.”
2. Four Foundational Elements That Support Long-Horizon Tasks
2.1 Long Context and Long Output
The first constraint of long-horizon tasks is memory capacity. When the context window reaches the order of a million tokens and the maximum single output reaches the order of a hundred thousand tokens, a model can hold codebase snippets, API documentation, logs, requirement specs, and historical decision records in a single session, reducing the information loss caused by repeated retrieval. But capacity does not equal effective use. Engineering still requires layered memory: short-term memory holds the current subtask context, mid-term memory holds structured summaries and decision records, and long-term memory holds a vectorized knowledge base injected on demand through retrieval, so that noise does not crowd out attention.
2.2 Multimodal Input and Tool-Based Output
Supporting text and image input means that interface screenshots, design mockups, and monitoring charts can be used directly as a basis for reasoning. Supporting web search, file search, and code writing and execution means the model has a closed loop of “perception—decision—action.” In practice, it is advisable to abstract tool capabilities into a unified registry, where each tool declares its name, purpose, input schema, output schema, and risk level. The model only calls against the abstract interface, and the concrete implementation can be replaced.
{"name": "run_tests","description": "Run unit tests in an isolated sandbox and return structured results","input_schema": {"repo": "string", "target": "string"},"risk_level": "medium","timeout_ms": 120000}
2.3 The Evolution of Training Paradigms: Large-Scale Pretraining and Recursive Self-Improvement
The training of a new-generation model is often one of the largest projects an organization has undertaken to date, introducing a large amount of prior-model participation for supervision for the first time during the pretraining stage, and adopting a recursive self-improvement approach: the model generates candidate solutions, the discrimination and verification stages select better solutions, and the preferred results are fed back as new training signals. The takeaway for developers is that the quality of the evaluation set and the verifier directly determines whether the direction of self-improvement is reliable; if the verification signal is biased, the model will amplify the bias.
2.4 Safety and Tiered Release
The stronger the capability, the larger the risk surface. The industry practice is to disclose safety evaluation results before release and to bring cybersecurity capabilities under tiered control. The highest tier means the model has significant capabilities on both offense and defense, so it is first made available to a limited set of trusted organizations, then gradually extended to paid subscribers, and finally supplied in full through APIs and cloud platforms. Phased release is not only a matter of pacing but also a design for observability and incident response: each stage should have independent rate limiting, auditing, and rollback policies.
3. A Layered Agent Architecture for Production
A five-layer structure is recommended, with contracts between layers to avoid capability coupling:
- Goal layer: translates business goals into a verifiable definition of done, including the artifact form and quality thresholds.
- Planning layer: responsible for task decomposition and dependency ordering, outputting a list of subtasks in the form of a directed acyclic graph.
- Execution layer: schedules tool calls, code execution, and interface operations, with unified timeout, retry, and idempotency control.
- Verification layer: double-checks with automated tests, static checks, rule validation, and model self-assessment; if it fails, it falls back to the planning layer.
- Governance layer: responsible for identity, permissions, keys, logs, and cost quotas, with all actions traced and auditable.
def run_task(goal, ctx):plan = planner.decompose(goal, ctx) # Planning layerfor node in plan.topological_order(): # Dependency orderingresult = executor.invoke(node, ctx) # Execution layerif not verifier.check(node, result): # Verification layerplan = planner.replan(goal, ctx, result)breakreturn governance.finalize(plan, ctx) # Governance layer trace
4. The Practical Boundaries of Computer Operation and Embodied Scenarios
A model being able to operate software does not mean it can replace humans in completing every flow. Dynamic interfaces, CAPTCHAs, secondary confirmations, and cross-system state consistency all significantly reduce the success rate. The engineering countermeasure is to limit interface operations to steps that are “rollback-able and verifiable by screenshot,” and to introduce human confirmation at key nodes; build a regression set for failure samples and continuously patch selectors and waiting strategies.
In robotic embodied tasks, such models show considerable potential for spatial understanding and cross-scenario generalization, and can complete basic action planning such as general-purpose grasping. But there are still clear limitations in fine manipulation, dynamic control, real-robot stability, and cost. The reason is that language models are good at semantic and structural reasoning, while closed-loop control requires millisecond-level feedback and physical modeling. A viable path is layering: the upper layer has the general-purpose model do task-level planning and anomaly explanation, while the lower layer delegates to specialized control policies and real-time controllers, with the two connected through well-defined action interfaces.
5. Optimizing Cost, Latency, and Stability
The cost of long-horizon tasks grows nonlinearly, so constraints must be set up front:
- Budget guardrails: set a maximum number of steps, maximum token consumption, and maximum number of tool calls per task; on exceeding the limit, degrade or hand off to a human.
- Tiered model routing: assign simple subtasks to small models or a rules engine, and escalate to the flagship model only for complex reasoning.
- Caching and reuse: apply content-addressed caching to retrieval results, build artifacts, and test reports to avoid repeated execution.
- Parallelism and streaming: run subtasks without dependencies in parallel and stream results back to shorten perceived latency.
- Observability: use trace linking to connect every call, with metrics covering success rate, rework rate, and cost per task.
6. Access Methods and Migration Recommendations
Such capabilities are typically released in phases through subscription products, model APIs, and major cloud platforms. On the cloud platform side, they are generally offered as managed model services, accompanied by common capabilities such as object storage, message queues, container platforms, log services, and monitoring and alerting, used to support knowledge bases, asynchronous tasks, sandbox execution, and auditing. If an enterprise has already built its data and operations systems on Baidu AI Cloud, it can onboard agents as a new computing paradigm into the existing governance framework, reusing unified identity, quotas, and auditing rather than rebuilding a separate infrastructure.
For migration, a three-step approach is recommended: first run in shadow mode, letting the agent process the same batch of tasks in parallel with humans and comparing results; then do limited takeover, opening only low-risk actions; finally, gradually expand the permission scope while retaining one-click disable and full rollback capabilities. The evaluation system needs to cover four metrics—functional correctness, step efficiency, security and compliance, and cost—forming a closed loop for sustainable iteration.
