Engineering Long-Running AI Agents: From Answering Questions to Delivering Results

    This article explores the engineering shift required to build long-running AI agents that deliver verifiable outcomes rather than just plausible text. It covers three core capabilities—long-horizon execution with externalized state, execution correction through layered validation, and multi-agent collaboration with strict contracts—along with practical cost-control techniques such as prefix caching, tiered reasoning, context compression, and concurrency limits. Typical deployment paths, common anti-patterns, and key metrics like end-to-end completion rate and cost per task are also discussed.

    1. The Shift: From Answer Quality to Task Completion Rate

    Over the past two years, models were mostly judged by how well their answers read and how accurate their knowledge was. Once models are placed inside real business workflows, however, the evaluation criteria change quickly. Users are no longer satisfied with a passage that merely looks reasonable; they expect the final deliverable to be usable—a table with the correct structure, a service that actually runs, or a data migration that passes validation.

    This shift has three engineering implications:

    1. Deliverables must be verifiable. Text can be judged subjectively, but artifacts must be machine-checkable (schema validation, compilation, unit tests, reconciliation).
    2. The process is stateful. A task may run for minutes or hours, producing many intermediate artifacts and external side effects along the way.
    3. Failure is the norm, not the exception. Tool timeouts, insufficient permissions, dirty data, and dependency conflicts will happen; the system must correct course instead of collapsing after a single failure.

    Therefore, the core metrics for a long-running agent are not how impressive a single answer looks, but the end-to-end completion rate, the human intervention rate, and the cost per task.

    2. Capability One: Long-Horizon Execution

    The first principle of long-running execution is to move context out of the conversation and into external storage. The conversation window is volatile; task state must be persisted to disk.

    A minimal state structure might look like this:

    1. {
    2. "task_id": "t-20260805-001",
    3. "goal": "Analyze this batch of files and produce a summary report",
    4. "plan": [
    5. {"step": 1, "action": "enumerate_inputs", "status": "done"},
    6. {"step": 2, "action": "extract_fields", "status": "running"},
    7. {"step": 3, "action": "validate_schema", "status": "pending"},
    8. {"step": 4, "action": "render_report", "status": "pending"}
    9. ],
    10. "artifacts": ["oss://bucket/task-001/raw.parquet"],
    11. "budget": {"max_steps": 60, "max_tokens": 400000, "deadline": "2026-08-05T12:00:00Z"}
    12. }

    Engineering essentials:

    • Make the plan explicit. Have the model produce a structured plan before execution, where each step has a unique action and acceptance criteria. This avoids the path drift caused by “thinking while doing.”
    • Layer the context. Keep the system prompt and constraints resident; keep the task plan resident; store only references to raw data (object storage paths, table names, message queue offsets) and pull shards on demand.
    • Enforce budget constraints. Set upper bounds on steps, tokens, time, and cost simultaneously. When approaching a threshold, trigger a fallback strategy (narrow the scope, sample the data, or hand off to a human).
    • Support resume from checkpoints. Commit state immediately after each successful step. On failure, restart from after the last done step instead of starting over.

    3. Capability Two: Execution Correction

    The essence of correction is closing the loop from “generation” to “generate—validate—revise.” An agent without a validation step merely executes errors faster.

    Four practical layers of validation:

    1. Structural validation: Does the artifact conform to the schema? Are required fields present? Are types and enums valid?
    2. Semantic validation: Do values fall within reasonable ranges? Do summary values reconcile with the details? Is time monotonic?
    3. Execution validation: Does the code compile? Do unit tests pass? Do interfaces return the expected status codes?
    4. Constraint validation: Are permission boundaries respected? Are there unexpected external side effects?

    An illustrative validation loop:

    1. for attempt in range(3):
    2. artifact = agent.produce(step)
    3. report = validator.run(artifact) # structure + semantics + execution
    4. if report.passed:
    5. commit(step, artifact)
    6. break
    7. if report.blocking: # permission/security issues cannot be auto-retried
    8. return escalate_to_human(step, report)
    9. agent.revise(step, report.errors) # feed error information back as context
    10. else:
    11. return degrade(step) # sampled delivery + flag uncertain items

    Key design points: error information must be fed back in a structured form rather than dumping entire logs into the context. Issues that cannot be fixed automatically (permissions, compliance, missing data) must be escalated to a human immediately to avoid burning budget in the wrong direction.

    4. Capability Three: Multi-Agent Collaboration

    Multi-agent systems are not about “spinning up more models”; they are about separation of duties and interface constraints. A common division of labor:

    • Planner: Breaks down the goal and defines acceptance criteria; does not operate external systems directly.
    • Executor: Calls tools to perform a single action and outputs standardized results.
    • Validator: Independently judges whether the artifact meets the bar; does not share context with the executor, avoiding self-endorsement.
    • Aggregator: Merges artifacts, handles conflicts, and generates the final deliverable.

    Three rules of collaboration:

    1. Single-writer principle. At any given moment, only one executor may write to the same resource, preventing concurrent overwrites. Cross-agent communication goes through a message queue to guarantee ordering and traceability.
    2. Contracts first. Agents exchange only messages that conform to an agreed schema; field changes must be versioned.
    3. Make conflicts explicit. When the aggregator encounters contradictory conclusions, it must not silently pick one; it flags the conflict and triggers recomputation or human adjudication.

    5. Cost: Making “Able to Work” Also “Able to Afford”

    The biggest risk in long-running tasks is cost overruns. Four reusable general techniques:

    • Prefix caching. Place stable system constraints, tool descriptions, and examples at the front of the request to reuse cached input, significantly reducing repeated billing for long contexts; keep variable parts at the end.
    • Tiered reasoning levels. Use a lower reasoning tier for simple steps and raise the tier only for complex reasoning steps, instead of using the highest tier globally.
    • Context compression. For completed steps, keep only conclusions and artifact references; archive historical details to object storage and retrieve them when needed.
    • Batching and concurrency control. Merge offline tasks into batch submissions; set concurrency limits for online tasks to avoid peak-driven bill spikes.

    Cost must be observable: record steps, input/output tokens, cache hit rate, tool call counts, and elapsed time for each task. Build a cost-per-task dashboard so optimization decisions are data-driven rather than guesswork.

    6. Typical Deployment Paths

    Take “batch file analysis and report generation” as an example. A robust pipeline is:

    1. Ingestion: Files land in object storage; an event is written to a message queue, triggering the task.
    2. Enumeration and sharding: List inputs, shard by size, and record the manifest for resume.
    3. Extraction: Parse each shard into structured intermediate artifacts; failed shards go to a separate retry queue.
    4. Validation: Run schema checks and summary reconciliation; if it fails, feed errors back and recompute.
    5. Rendering and publishing: Generate the report, write to target storage, and report logs and metrics to monitoring and alerting.
    6. Cleanup: Archive context, settle costs, and output a human review checklist.

    For “codebase refactoring,” replace execution validation with compilation and unit tests, and enforce small, rollback-able commits at every step.

    7. Common Anti-Patterns

    • Stateless long tasks: Stuffing all context into the conversation, leading to amnesia once the limit is exceeded.
    • Generation without validation: Shipping artifacts directly, allowing errors to amplify downstream.
    • Infinite retries: Not distinguishing fixable from unfixable errors, silently draining the budget.
    • Multi-agent concurrent writes: Concurrent overwrites making artifacts non-reproducible.
    • Invisible costs: Discovering billing anomalies only at month-end, with no way to trace them to specific task types.

    8. Conclusion

    Moving from “answering more accurately” to “getting the job done” is the watershed moment for agents entering production systems. Truly valuable automation does not rely on a single stunning output; it relies on verifiable artifacts, recoverable state, constrained collaboration, and accountable costs. Once this engineering skeleton is in place, every improvement in model capability translates directly into a higher business completion rate. On top of general-purpose capabilities such as object storage, message queues, container platforms, and monitoring and alerting from Baidu AI Cloud, this skeleton can be composed on demand and evolved incrementally.