Engineering Long-Horizon Tasks for General-Purpose AI Agents
This article explores the engineering practices required to build reliable long-horizon workflows with general-purpose AI agents. It covers how the shift from prompt engineering to task engineering, combined with million-token context windows and long outputs, changes system design. Key topics include context budgeting, least-privilege tool use, explicit state machines for resumable execution, sandbox isolation and security tiering, staged rollouts, layered control for embodied AI, and cost and evaluation governance. Readers will find practical constraints, pseudocode, and architectural patterns for turning high-capability but uncertain models into auditable, operable production systems.
1. From Answering Questions to Doing Work: The Capability Leap of General-Purpose Agents
The defining change in the new generation of general-purpose large models is not higher single-turn answer quality. It is that these models are explicitly positioned as agents that can execute tasks directly. They can perform multi-step reasoning, write and debug code, operate graphical interfaces, search the web and local files, and complete end-to-end workflows with minimal human intervention.
For enterprise developers, this shifts the center of system design from prompt engineering to task engineering: how to decompose a vague business goal into a sequence of steps that the model can execute, verify, and roll back.
It is important to stress that stronger capabilities do not automatically improve reliability. The longer the task chain, the higher the probability of accumulated errors, state drift, and tool misuse. Engineering must therefore treat the model as a “highly capable but uncertain” executor and compensate for its instability with external constraints.
2. System Design Constraints from Ultra-Long Context and Ultra-Long Output
Context windows of a million tokens and single-response output limits of over a hundred thousand tokens change the architectural choices for two categories of systems.
The first is knowledge-intensive applications. The previous approach of relying on retrieved chunks stitched together can be replaced by a hybrid strategy of “load everything plus structured indexing” under long context: include complete specifications, key repository directories, and historical tickets in the context at once, while retaining retrieval to control noise. The second is generation-intensive applications, such as producing documents, tables, and presentations from templates. Ultra-long output makes “one-pass drafting” possible, but it also amplifies the risk of format drift.
The following is illustrative budget-control logic (pseudocode, expressing engineering constraints only):
def build_context(system_spec, repo_index, history, user_task, budget=900_000):# 1) Mandatory zone: specifications and safety policies must be preserved in fullmandatory = system_spec + SAFETY_POLICY# 2) Elastic zone: fill by relevance, leaving headroom for reasoning and outputremaining = budget - count_tokens(mandatory) - OUTPUT_RESERVEelastic = select_by_relevance(repo_index, history, user_task, remaining)return mandatory + elastic
Three key practices matter here: reserve a fixed budget for output to avoid “input consuming everything and output being truncated”; perform segmented validation of long context, inserting self-check prompts at critical points; and run structured validation on generated results (schema validation, field completeness, unit and definition consistency) rather than relying only on manual visual inspection.
3. Tool Calls and Computer Use: Turning “Able to Operate” into “Controlled Operation”
The engineering value of agent capabilities comes from tool calls and interface operations. Implementation should follow the principle of least privilege: grant a subset of tools per task, separate write operations from read operations, and enforce secondary confirmation or human approval for high-risk actions (deletion, transfers, external publishing).
At the same time, establish observable records for every step, including a summary of call parameters, return status, latency, and failure reasons, forming a replayable trace. The trace is not only a troubleshooting basis but also a data source for evaluation and regression. For interface-operation tasks, prefer stable APIs first, and fall back to UI automation only when no API is available. Set failure retries and termination conditions for UI changes to prevent infinite loops from consuming resources.
4. State Management and Long-Horizon Orchestration
Long-horizon task failures usually are not “a single step cannot be done” but “forgetting what has already been done.” Engineering should introduce an explicit state machine or task graph, decomposing the goal into nodes, each with defined preconditions, artifacts, and acceptance criteria. Artifacts are persisted to disk or external storage, and completion of a node is fixed immediately, supporting resume after interruption.
Goal -> Plan generation -> Node execution (parallelizable) -> Artifact validation -> Failure re-planning -> Aggregate delivery| ^+-> State persistence (recoverable) --+
Supporting mechanisms include: idempotent design to avoid duplicate side effects from retries; timeout and budget caps to control per-task resource consumption; and explicit re-planning triggers, for example, falling back to the last stable state after two consecutive validation failures.
5. Security Tiering and Sandbox Isolation
Rating the model’s safety capabilities at the highest level actually means: its offensive and defensive knowledge is sufficient to pose real-world risk, so protection must be delivered in sync with capability. Practical enterprise measures include: running code and network access in an isolated sandbox, blocking outbound connections by default with a whitelist; desensitizing sensitive data and minimizing injection; treating prompt injection and tool-returned content as untrusted input subject to the same filtering; and fully retaining audit logs connected to monitoring and alerting, blocking abnormal frequency, abnormal destination addresses, and abnormal permission requests in real time.
It is worth noting that security policies should be moved forward to the task planning stage rather than judged temporarily before action execution; otherwise, a hidden risk of “the plan has already leaked sensitive intent” easily arises.
6. Productization Lessons from Staged Rollout and Gradual Release
New models are first opened to a small scope of trusted organizations, then gradually extended to paid subscribers and API integrators. This rhythm also applies to self-developed agent platforms: roll out by capability dimension rather than user dimension, first opening read-only capabilities, then write capabilities, and finally high-risk automation; each stage should set clear admission conditions, rollback switches, and metric thresholds. Capacity and permission configuration issues during release often cause experience incidents more easily than the model itself, so configuration changes should be treated as part of the release content and included in change review.
7. Embodied AI: The Potential of Spatial Understanding and the Boundary of Fine Control
In robotics tasks, general-purpose models show good potential in spatial relation understanding and cross-scenario generalization, mapping natural-language goals into executable subtasks. However, they are not designed for real-time control and still have clear limitations in fine manipulation, dynamic balance, real-machine stability, and inference cost. A reasonable architecture is layered: the upper layer uses the general-purpose model for task decomposition and exception handling, while the lower layer uses traditional control and motion planning modules for high-frequency closed loops, with the two communicating through clear interface contracts, avoiding handing millisecond-level control to the large model.
8. Cost, Evaluation, and Governance
The cost of long-horizon agents comes mainly from three parts: repeated billing of long context, failure retries, and manual rework. Governance measures include context compression and summary caching, result caching and deduplication, tiered model configuration by task value, and offloading small tasks to lightweight models. The evaluation system should cover task success rate, cost per task, average number of steps, human takeover rate, and security interception rate, and establish a fixed regression set; any prompt or tool change should run the regression to prevent capability regression.
In summary, the engineering key to general-purpose agents is not pursuing “full automation” but using long context, explicit state, strict sandboxes, layered control, and quantitative evaluation to constrain high-capability models into deliverable, auditable, and operable productivity. Relying on general capabilities from Baidu AI Cloud such as container platforms, object storage, message queues, logging services, and monitoring and alerting, enterprises can build this controllable agent foundation at relatively low cost.
