How to Build an Autonomous AI Agent from Scratch

    This guide walks through building an autonomous AI agent that executes tasks with minimal human involvement. It covers the shift from human-in-the-loop to human-on-the-loop, how to define responsibility boundaries, a five-layer reference architecture, and three core mechanisms: task planning and decomposition, tool calling with sandboxes, and memory, reflection, and evolution. It also outlines evaluation metrics, observability practices, common failure modes, and a phased rollout path. The focus is on engineering constraints rather than model capability alone.

    1. The Paradigm Shift: From a Conversation Loop to an Autonomous Execution Loop

    Traditional LLM applications carry an implicit assumption: a human is always in the loop. The user asks, the model answers, the user judges, and constraints are added. Every step of the decision loop requires human participation. This caps throughput at the limit of human attention and cannot support long-running tasks that take tens of minutes or even hours.

    The goal of an autonomous agent is to turn “human in the loop” into “human on the loop”: humans define only the goal, boundaries, and acceptance criteria, while the system drives execution itself. Supporting this shift requires three foundational capabilities to be in place at the same time.

    1. Task decomposition: Break a vague goal into independently verifiable subtasks, and define the input, output, and success criteria for each one.
    2. Environment awareness: An agent must do more than “think”; it must also “see” and “act.” The file system, terminal, browser, and various interfaces together form its digital sandbox.
    3. Dynamic evolution: Turn execution traces into reusable experience so that strategies for similar future tasks improve, rather than starting from scratch every time.

    Several general-purpose agent frameworks that have emerged in the industry over the past two years are essentially trade-offs along these three lines: some emphasize “less structure, more intelligence,” handing decision-making back to the model as much as possible; some emphasize process orchestration and role separation; others emphasize a reproducible engineering skeleton. Understanding the logic behind these trade-offs is more valuable than memorizing any specific implementation.

    2. Capability Boundaries: First Decide What It Should Not Do

    The higher the autonomy, the greater the cost of losing control. The first design document should not be an architecture diagram but a responsibility list.

    • Suitable for full delegation: Tasks with clear goals, enumerable steps, and automatically verifiable results, such as batch code refactoring, log inspection and root-cause analysis, and research collection and structured organization.
    • Requires spot checks: Tasks whose output is quantifiable but subject to quality variance, such as test case generation and producing multiple versions of copy.
    • Prohibited from delegation: Irreversible, high-impact actions, such as deleting production data, financial operations, and official external releases. These actions should retain a human confirmation checkpoint.

    A practical principle: score tasks on two dimensions, “reversibility” and “verifiability.” Only tasks that score high on both are allowed to run fully autonomously.

    3. Reference Architecture: A Five-Layer Structure

    1. ┌─────────────────────────────────────────┐
    2. │ Access Layer: goal input / permissions │
    3. │ and quotas / audit entry │
    4. ├─────────────────────────────────────────┤
    5. │ Cognitive Layer: planner + reflector + │
    6. │ memory read/write │
    7. ├─────────────────────────────────────────┤
    8. │ Execution Layer: tool registry / │
    9. │ sandbox runtime / retry │
    10. ├─────────────────────────────────────────┤
    11. │ State Layer: task graph / intermediate │
    12. │ artifacts / checkpoints │
    13. ├─────────────────────────────────────────┤
    14. │ Observability Layer: logs / metrics / │
    15. │ tracing / alerting │
    16. └─────────────────────────────────────────┘

    Key responsibilities of each layer:

    • The access layer converts natural-language goals into structured task objects while binding identity, quotas, and auditing. Permissions are not checked here, but they must be collected here.
    • The cognitive layer is the “brain” that decides what to do next; it does not touch the external world directly and only outputs structured action intents.
    • The execution layer is the “hands and feet,” translating action intents into real calls and uniformly handling timeouts, retries, and idempotency.
    • The state layer ensures long tasks are recoverable: if the process crashes, it can resume from a checkpoint instead of starting over.
    • The observability layer determines whether the system can be operated. Without tracing, an autonomous agent cannot be diagnosed when something goes wrong.

    4. Core Mechanism One: Task Planning and Decomposition

    Planning is essentially compiling a goal into a directed acyclic graph. In practice, a two-stage approach of “coarse planning + fine planning” is recommended: first use a single call to produce high-level steps, then refine within each step as needed, avoiding planning too deeply all at once and causing context explosion.

    1. plan_schema = {
    2. "goal": "str",
    3. "steps": [
    4. {
    5. "id": "s1",
    6. "action": "str", # natural-language description of what this step does
    7. "tool": "str | null", # expected tool; null means pure reasoning
    8. "inputs": "dict",
    9. "acceptance": "str", # success criteria; must be automatically判定able
    10. "depends_on": ["s0"],
    11. "risk": "low|medium|high"
    12. }
    13. ]
    14. }

    There are three key design points. First, every step must have automatically verifiable acceptance criteria; otherwise the reflection stage has nothing to work with. Second, dependencies must be declared explicitly; steps with no dependencies can run concurrently, significantly compressing total time. Third, risk levels propagate down with each step; high-risk steps are forced to insert a human confirmation at the execution layer.

    5. Core Mechanism Two: Tool Calling and Sandboxing

    More tools is not better. As the number of tools grows, the model’s selection accuracy is diluted, so follow three principles: “narrow interfaces, strong typing, clear semantics.”

    1. @tool(
    2. name="run_tests",
    3. description="Run a specified test suite in an isolated sandbox and return the pass rate and a failure summary",
    4. schema={"target": "str", "timeout_sec": "int"},
    5. idempotent=False,
    6. risk="low"
    7. )
    8. def run_tests(target: str, timeout_sec: int = 300):
    9. ...

    A sandbox must satisfy at least four conditions: controllable file system and network egress, resource limits per run, rollback-able execution traces, and sensitive credentials injected through controlled injection rather than written in plaintext. In production, code-execution tools should run by default in containers or microVMs, network-isolated from the main process.

    The execution layer must also uniformly handle three classes of exceptions: retryable transient errors (retry with backoff), errors that require a different path (switch tools or fall back), and errors that must terminate the run (insufficient permissions, exhausted quota). Blindly retrying all three mixed together is the most common cause of long-task failure.

    6. Core Mechanism Three: Memory, Reflection, and Evolution

    Layered memory significantly improves performance:

    • Short-term memory: Intermediate artifacts and tool returns for the current task, reclaimed when the task ends.
    • Long-term memory: Reusable experience across tasks, typically indexed by both vector retrieval and structured tags.
    • Procedural memory: Solidify successful traces into callable templates, downgrading similar tasks from “reasoning” to “reuse.”

    The reflection mechanism is best implemented as a separate “critic” role, separated from the executor to avoid self-confirmation bias. Its inputs are the goal, the execution trace, and the acceptance results; its output is structured correction suggestions:

    1. {
    2. "verdict": "fail",
    3. "failed_step": "s3",
    4. "root_cause": "tool input is missing the pagination cursor",
    5. "patch": {"action": "retry s3", "inputs": {"cursor": "next"}},
    6. "max_retry": 2
    7. }

    Evolution does not have to rely on training. The vast majority of gains come from the engineering approach of “experience library + retrieval augmentation + template solidification,” which is low-cost, explainable, and rollback-able.

    7. Evaluation and Observability: Making Autonomy Measurable

    An autonomous agent without evaluation cannot iterate. It is recommended to establish at least three layers of metrics:

    1. Task layer: End-to-end success rate, average number of steps, human intervention rate.
    2. Step layer: Per-step acceptance pass rate, tool call failure rate, proportion of invalid loops.
    3. Cost layer: Token consumption per task, sandbox duration, peak concurrency usage.

    In implementation, write each run as a complete trace with a trace id, linking planning, calls, and reflection; connect metrics to monitoring and alerting, store traces and intermediate artifacts in object storage, and decouple high-frequency events through a message queue. If running on a container platform, use elastic scaling to absorb concurrency peaks and a log service for centralized retrieval. Baidu AI Cloud offers corresponding product categories for these general capabilities and can be combined as needed, but the architecture itself is vendor-agnostic.

    8. Common Failure Modes and How to Avoid Them

    • Goal drift: Gradually deviating from the original intent over a long chain. Avoid it by re-injecting the original goal and constraints at every checkpoint.
    • Idle looping: Repeatedly calling the same tool. Set a repeated-action counter that triggers a path switch or escalation to a human once exceeded.
    • Context bloat: Stuffing all history back into the prompt. Switch to summary compression plus on-demand retrieval.
    • Toothless acceptance: Writing criteria as “the result is correct.” Criteria must be executable, for example “test pass rate is 100% and the diff is under 200 lines.”
    • Over-broad permissions: Giving the agent long-lived, high-privilege credentials. Switch to short-lived credentials, least privilege, and action-level auditing.

    The first phase is an “observable semi-automatic” system: it only does planning and suggestions, actions are confirmed by humans, and the priority is to get traces and evaluation working. The second phase opens up fully autonomous execution for low-risk, reversible actions and introduces reflection and retry strategies. The third phase adds long-term memory and template solidification to form organization-level experience assets. Each phase should set clear entry metrics; for example, only expand the scope of autonomy after end-to-end success rate and human intervention rate reach their thresholds.

    The real barrier is not model capability but the ability to express engineering constraints: whether you can write goals as verifiable criteria, contain actions within a rollback-able sandbox, and accumulate experience into searchable assets. Achieve these three points, and a stable, controllable, and continuously evolving agent system takes shape.