Building Persistent Autonomous Agents: Architecture and Practical Guide

    This article explains how persistent autonomous agents differ from stateless conversational AI and why they are better suited for long-running, multi-step business tasks. It covers a five-layer architecture, a three-tier memory engine, closed-loop skill generation, tool and context engineering, deployment and operations, and evaluation with a phased adoption roadmap. Readers will find practical structures, SQL and Markdown examples, and orchestration pseudocode they can adapt to their own systems.

    1. Background: Why Stateless Conversations Fall Short for Real Business

    Most mainstream conversational AI today is stateless and one-shot: a request comes in, the model reasons, and a result is returned. Context is released as soon as the session ends. This works well for Q&A, copy polishing, and single-point code completion, but it quickly shows its limits when a task has the following characteristics:

    • The task spans days or weeks and requires continuous tracking of project background.
    • It takes multiple rounds of tool calls (retrieval, file reads and writes, internal API calls, test execution) to converge.
    • It requires seamless switching across multiple entry points such as mobile, desktop, and group chat.
    • Similar tasks recur, and the expectation is that “once it is done, it becomes a standard procedure.”

    As a result, the industry is shifting toward the technical path of the persistent autonomous agent: treating the agent as a long-running online service process rather than a function call. The core is not smarter single-shot reasoning, but a complete engineering system built around state, memory, tools, and a learning loop.

    2. Core Differences from Traditional Approaches: From One-Off Tool to Execute-Learn-Optimize Loop

    The two forms can be compared across three dimensions:

    Dimension Stateless Conversational Tool Persistent Autonomous Agent
    Context Lost when the session ends Persisted in layers, fully searchable
    Capability growth Depends on the model’s own iterations Self-enhances by distilling experience into skill documents
    Access Single interface Multi-entry message gateway with synchronized context
    Task complexity Single or a few turns Multi-step tool orchestration, resumable after interruption

    The key difference is the loop: after a task completes, the system automatically abstracts the “reusable solution path” into a structured document. The next time a similar problem appears, it is loaded directly; if a better path is found during use, it is written back and updated. This makes the agent’s capability curve no longer flat, but monotonically rising with usage over time.

    3. Overall Architecture: A Five-Layer Design

    A deployable persistent autonomous agent can typically be broken into five layers:

    1. Access layer (message gateway): A single process mounts multiple channels at once, such as the command-line terminal, instant messaging groups, enterprise collaboration tools, and email and webhook entry points. It handles identity recognition, rate limiting, and context ownership mapping in a unified way.
    2. Orchestration layer (task and tool scheduling): Responsible for task decomposition, tool selection, timeouts and retries, failure rollback, and resuming long-running tasks from breakpoints.
    3. Memory layer: A three-tier memory engine, detailed in Section 4.
    4. Skill layer: Carries reusable procedures as Markdown skill documents based on an open standard, with support for versioning and canary rollout.
    5. Runtime and governance layer: Containerized deployment, logging services, monitoring and alerting, key management, and auditing.

    4. The Three-Tier Memory Engine: The Technical Core of Persistence

    Memory cannot mean “stuffing all history into the prompt,” which is costly and noisy. The industry generally adopts a combination of “summary + full-text retrieval + structured facts,” which can be implemented on top of an embedded relational database with full-text search capabilities:

    • Session memory (short-term): Stores the current task context, compressed by rolling model summaries to control token size.
    • Persistent memory (long-term): Stores preferences, project background, and agreed conventions as fact triples or entries, retained permanently and supporting full-text retrieval.
    • Skill memory (procedural): Solidifies “how to do it” into documents; this is executable knowledge rather than factual knowledge.

    A sample table structure is shown below:

    1. CREATE TABLE facts (
    2. id INTEGER PRIMARY KEY,
    3. scope TEXT, -- user/project/global
    4. subject TEXT,
    5. content TEXT,
    6. updated_at TEXT
    7. );
    8. CREATE VIRTUAL TABLE facts_fts USING fts5(content, content='facts');
    9. CREATE TABLE skills (
    10. id INTEGER PRIMARY KEY,
    11. name TEXT UNIQUE,
    12. path TEXT, -- skill document path
    13. version INTEGER,
    14. usage_count INTEGER DEFAULT 0
    15. );

    Retrieval uses a hybrid strategy: first recall candidates with keyword search, then supplement with semantically similar items via vector similarity, and finally rerank by “recency + hit count + scope priority.” Two disciplines are enforced on writes: first, deduplication and conflict resolution (new facts override old ones while keeping a change record); second, scope isolation, to avoid contaminating global memory with a temporary convention from a single project.

    5. Closed-Loop Learning: Automatic Skill Generation and Iteration

    Closed-loop learning is the most valuable part of such systems. The trigger is usually set as “the number of tool-call steps exceeds a threshold (for example, 5 steps) and the task is judged successful.” The flow can be summarized as:

    1. Trace collection: Record the tool name, a summary of the input parameters, the return status, and the elapsed time for each step.
    2. Key-step extraction: Remove failed retries and redundant queries, keeping the decisive actions.
    3. Structuring into a skill document: Include applicable scenarios, preconditions, steps, checkpoints, and fallback plans.
    4. Storage and indexing: Write into the skill library and build a retrieval index.
    5. Usage and evaluation: Track the call success rate and average number of steps; if below the threshold, trigger optimization or decommissioning.

    Skill documents should follow an open skill description specification, remaining plain-text readable and version-controllable. An example skeleton:

    1. ---
    2. name: Weekly Report Data Aggregation
    3. when: Need to aggregate multi-source metrics weekly and generate charts
    4. requires: data query tool, chart generation tool
    5. ---
    6. 1. Pull this week's metrics (filtered by dimension)
    7. 2. Validate nulls and abnormal fluctuations
    8. 3. Generate trend charts and summary conclusions
    9. 4. Output to the designated document directory
    10. fallback: when the data source is unavailable, use a cached snapshot and annotate its freshness

    Governance must add two gates: high-risk actions (deletion, transfers, external publishing) require human confirmation; skill changes go through canary rollout, validated on small traffic before full rollout.

    6. Toolset and Context Engineering

    Tool design follows the principle of “few and orthogonal”: file reads and writes, command execution (inside a sandbox), retrieval, HTTP requests, structured data queries, chart generation, scheduled tasks, notification pushing, and so on, grouped by toolset and enabled on demand. Each tool must clearly declare its name, purpose, parameter schema, and side-effect level, so the orchestration layer can perform static validation.

    Context engineering determines success or failure. Key practices include:

    • Layered loading: System prompt + long-term facts (Top-K) + skill documents + recent session summary.
    • Budget control: Set token limits for each part; when exceeded, compress history first.
    • Structure first: Information that can be expressed with tables or JSON should not be written as prose.
    • Traceability: Record which memory entries were loaded for each inference, to ease debugging.

    A minimal orchestration pseudocode:

    1. def run(task, scope):
    2. ctx = load_facts(scope, top_k=8) + load_skills(task, top_k=3)
    3. steps = []
    4. for _ in range(MAX_STEPS):
    5. action = plan(task, ctx, steps)
    6. if action.type == "tool":
    7. result = call_tool(action, confirm=action.risk == "high")
    8. steps.append(result)
    9. if done(result):
    10. break
    11. else:
    12. return action.answer
    13. if len(steps) >= 5 and success(steps):
    14. save_skill(extract(steps))

    7. Deployment and Operations Essentials

    It is recommended to host the agent process on a container platform, use object storage to keep skills and snapshots, use a message queue to make long-running tasks asynchronous, and cover core metrics such as tool failure rate, average number of steps, and memory hit rate with logging services and monitoring and alerting. Keys should be managed centrally by a key management service and must never be written into skill documents. Multi-entry scenarios need a “session-user-scope” mapping table to keep context continuous when switching between mobile and desktop.

    For capacity planning, focus on three points: growth of the memory store size and retrieval latency, false recalls caused by an expanding number of skills, and context isolation for concurrent sessions. It is advisable to set retention policies and periodic archiving for memory and skills.

    8. Evaluation, Risks, and Adoption Roadmap

    Evaluation should go beyond “whether the answer looks good” and establish quantifiable metrics: task success rate, average number of tool steps, human takeover rate, skill reuse rate, and memory hit accuracy. On the risk side, focus on guarding against prompt injection (external content carrying instructions), unauthorized tool calls, memory contamination, and skill drift, with corresponding measures of input isolation, least privilege, change auditing, and a periodic regression test set.

    The adoption recommendation is split into three phases: the first phase only does persistent memory and multi-entry access, validating that it “remembers”; the second phase adds tool orchestration and sandboxed execution, validating that it “gets things done”; the third phase enables automatic skill generation and canary iteration, validating that it “gets stronger with use.” If elastic compute and managed capabilities are needed, the above components can be hosted on general capabilities such as the container platform, object storage, logging services, and monitoring and alerting provided by Baidu AI Cloud, letting you focus your energy on the memory and skill loop itself.