Engineering Long-Running Tasks for AI Agents: Architecture and Best Practices

    This article outlines a practical engineering approach to building AI agents capable of completing long-running tasks. It introduces a five-layer reference architecture, addresses core challenges such as context growth, error accumulation, state consistency, and cost control, and explains when and how to use multi-agent collaboration. It also covers observability, quality gates, evaluation metrics, and a phased adoption roadmap.

    1. From Answering Questions to Taking Action: A Shift in the Technical Paradigm

    Over the past two years, the dominant form of LLM applications has been “prompt in, text out.” With the new generation of models emphasizing “frontier intelligence plus the ability to act,” the application pattern is shifting. Models are no longer expected only to generate content; they are required to autonomously break down goals, call external tools, verify intermediate results, and roll back and retry on failure within a longer time window. The capabilities mentioned in the original report—automatic planning, multi-step execution, tool calling, and deploying multiple collaborating sub-agents—essentially describe a Task Runtime, not merely an inference API.

    This means the engineering focus has fundamentally changed: from “single-response quality” to “completion rate, recoverability, and unit cost of long-running tasks.” The sections below break this down by architectural layer.

    2. Reference Architecture: A Five-Layer Structure

    1. Interaction Layer: Collects goals, constraints, and authorization boundaries. The key is converting vague requirements into a structured task description (goal, inputs, deliverables, acceptance criteria, forbidden actions).
    2. Orchestration Layer: The core of task planning and scheduling, responsible for task decomposition, dependency management, and timeout and retry policies.
    3. Execution Layer: A collection of tool adapters that encapsulate capabilities such as file systems, retrieval, databases, build pipelines, and message notifications.
    4. Collaboration Layer: Handles division of labor and result aggregation across multiple sub-agents, managing parallelism and conflicts.
    5. Governance Layer: Manages permissions, auditing, observability, cost accounting, and quality gates.

    A minimal example of a task description structure:

    1. {
    2. "goal": "Upgrade dependencies in a specified repository and deliver a change summary",
    3. "constraints": {
    4. "allowed_paths": ["src/", "tests/"],
    5. "forbidden_actions": ["force_push", "delete_branch"],
    6. "max_duration_minutes": 45
    7. },
    8. "acceptance": [
    9. "All unit tests pass",
    10. "No new static analysis warnings",
    11. "A change summary document is produced"
    12. ],
    13. "budget": { "max_steps": 60, "max_tool_calls": 120 }
    14. }

    3. Core Challenges of Long-Running Tasks and How to Address Them

    Challenge 1: Context Growth. Long tasks accumulate large volumes of tool output. Stuffing all of it into the context is both expensive and degrades the signal-to-noise ratio. In practice, a layered memory approach should be used: short-term memory retains raw output relevant to the current sub-goal; mid-term memory stores structured summaries (conclusions, evidence locations, to-dos); long-term memory keeps only pointers (such as object keys in object storage or query conditions in a logging service), retrieved on demand.

    Challenge 2: Error Accumulation. In a multi-step chain, a 95% success rate per step leaves only about 36% after 20 steps. Therefore, a “verifiable signal” must be defined for every step—for example, compiler exit codes, number of passing tests, API response codes, or the number of inconsistent rows from data validation. Tasks without verifiable signals should not be handed to an agent for autonomous execution.

    1. def run_step(step, ctx):
    2. for attempt in range(3):
    3. result = step.invoke(ctx)
    4. if verify(step, result): # Explicit acceptance check
    5. return result
    6. ctx = ctx.rollback(step.snapshot()) # Return to a known good state
    7. ctx.note_failure(result.error)
    8. return escalate_to_human(ctx) # Fallback: hand off to a human

    Challenge 3: State Consistency. For write operations, use a “snapshot first, mutate second, roll back on failure” pattern. Use idempotency keys for external systems to avoid duplicate submissions caused by retries. For irreversible actions (deletion, release, transfer-like operations), set up explicit human confirmation gates.

    Challenge 4: Cost Overruns. Agents can get stuck in unproductive loops. Engineering-wise, three types of budgets should be set: step budget, tool-call budget, and time budget. If any limit is exceeded, the task should be halted and the current progress reported rather than continuing to consume resources.

    4. Multi-Agent Collaboration: When and How to Use It

    Multi-agent systems are not better by default. They are suitable for “parallelizable fan-out scenarios,” such as reviewing multiple modules simultaneously, running multiple sets of data validations in parallel, or independently evaluating different candidate solutions. They are not suitable for tasks with strong sequential dependencies or those requiring globally consistent decision-making.

    There are typically three collaboration patterns:

    • Supervisor–Worker: The supervisor decomposes and merges; workers independently complete sub-tasks.
    • Pipeline: Each agent handles a single stage, and its output becomes the input for the next stage.
    • Debate/Review: Multiple agents produce independent conclusions, which are then resolved by arbitration logic or a human.

    The key implementation point is contract-based interaction: sub-agents exchange only structured artifacts (data validated against a JSON Schema), not free text, and each artifact is annotated with its source and confidence level to help locate disagreements during conflicts.

    5. Observability and Quality Gates

    Long-running tasks must be observed like production services. At minimum, collect: task success rate, average steps, cost per task, tool failure rate distribution, human takeover rate, and rollback count. Distributed tracing should record a summary of inputs and elapsed time for each tool call, with sensitive fields masked before storage.

    Quality gates should be placed before delivery, not after: static analysis, unit tests, integration tests, and security scans are chained by level. If any gate fails, automatic delivery is blocked and a human-readable failure report is generated.

    6. Evaluation: Do Not Rely on a Single Leaderboard

    While the original report emphasizes relative performance on several agent and coding benchmarks, engineering implementation should establish a proprietary evaluation set. Four categories of metrics are recommended:

    1. Task completion rate (the proportion that passes acceptance criteria end to end);
    2. Average number of interventions (frequency of human involvement);
    3. Unit task cost and latency (such as waiting time differences caused by output speed);
    4. Security and compliance violation rate (unauthorized access, out-of-bounds writes, sensitive data leakage).

    The evaluation set should include tasks that can be “automatically judged,” and 10%–20% adversarial samples (vague requirements, missing dependencies, dirty data) should be retained to test robustness.

    Phase 1: Choose low-risk, verifiable scenarios (repository inspection, report reconciliation, log attribution) to get the orchestration and acceptance loop working end to end. Phase 2: Introduce parallel sub-agents and layered memory to optimize latency and cost. Phase 3: Open controlled write permissions, supported by approval gates and full auditing. Phase 4: Establish an internal evaluation and regression system to continuously track performance drift caused by model and prompt strategy changes.

    On the infrastructure side, the common practice is to store state and artifacts in object storage, write events and audit logs to a logging service, use a message queue for task decoupling and peak shaving, run tool execution sandboxes on a container platform, and cover task timeouts and failure rate spikes with monitoring and alerting. If running on Baidu AI Cloud, these general capability categories can be directly mapped and combined without relying on any proprietary interfaces to build the entire architecture.

    8. Conclusion

    The real threshold for “having the ability to act” lies not in the model itself, but in the runtime built around it: clear task contracts, verifiable intermediate signals, rollback-capable state management, strict budget and permission boundaries, and a proprietary evaluation loop. Get these five things solid, and long-running agents can move from demonstrations to stable delivery.