Building a Persistent AI Agent on Ubuntu: A Practical Guide

    This guide walks through building a persistent AI agent from scratch on Ubuntu, covering system architecture, environment setup, memory storage, reusable skills, model switching, multi-channel messaging, execution isolation, scheduled tasks, and tuning. It is intended for developers who want an agent with cross-session continuity that runs securely and continuously on a server.

    1. Why Choose a Persistent Agent Instead of a Regular Chat Tool

    Conventional conversational AI tools are essentially stateless question answering: once a session ends, the context is discarded, and users have to repeat the background every time. A persistent agent stores state, memory, and skills on the server side, giving it continuity across sessions. Deployed in an always-on server environment like Ubuntu, the agent can run 24/7 and continuously absorb experience from tasks.

    From an engineering perspective, this type of system usually consists of five layers:

    • Interaction layer: terminal, message gateways, and web interface;
    • Orchestration layer: task planning, tool invocation, and scheduled dispatch;
    • Capability layer: model inference and external interface extension protocols;
    • Memory layer: structured storage and full-text retrieval;
    • Execution layer: local processes, containers, or remote sandboxes.

    Understanding this layering is the prerequisite for all subsequent deployment work, and it prevents mistaking “can chat” for “has agent capabilities.”

    2. Environment Preparation: Build a Solid Foundation

    Using a long-term support (LTS) release of Ubuntu is recommended. Create a dedicated non-root account to run the agent, following the principle of least privilege.

    1. sudo apt update && sudo apt upgrade -y
    2. sudo apt install -y python3 python3-venv python3-pip git sqlite3
    3. sudo adduser agent
    4. sudo usermod -aG sudo agent
    5. su - agent

    Key points:

    1. Use a virtual environment to isolate dependencies and avoid polluting the system Python;
    2. A separate account makes directory-level permission control and auditing easier;
    3. If containerized execution is needed later, you can install a mainstream container runtime, but do not grant privileged mode by default.

    3. Obtaining and Initializing the Project

    In environments that cannot reach overseas code hosting services, it is recommended to obtain the source code through an internal mirror or an offline package first, then verify its integrity:

    1. git clone <internal mirror URL> hermes-agent
    2. cd hermes-agent
    3. python3 -m venv .venv
    4. source .venv/bin/activate
    5. pip install -r requirements.txt

    During initialization, keep all mutable configuration in a single environment variable file instead of scattering it across the code:

    1. cat > .env <<'EOF'
    2. AGENT_HOME=/home/agent/.agent
    3. MODEL_PROVIDER=compatible_openai
    4. MEMORY_BACKEND=sqlite
    5. EXEC_BACKEND=local
    6. LOG_LEVEL=INFO
    7. EOF

    This “externalized configuration” approach is the foundation for switching models or migrating the execution backend later without changing code.

    4. Memory System: Make the Agent Actually Remember

    A reliable memory design usually includes two types of storage: structured data (user preferences, project metadata) and unstructured text (conversation history, document fragments). The latter commonly uses an embedded full-text retrieval approach, for example full-text indexing based on SQLite, combined with an inverted index to achieve millisecond-level recall.

    Organize it along these lines:

    • Short-term context: keep only the current task window to control token costs;
    • Long-term facts: store stable preferences as key-value pairs;
    • Event log: append-only writes for traceability and auditing;
    • Vector or full-text index: build retrieval capability over the event log.

    Illustrative table structure:

    1. CREATE TABLE memory_fact(
    2. user_id TEXT, key TEXT, value TEXT,
    3. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    4. PRIMARY KEY(user_id, key)
    5. );
    6. CREATE VIRTUAL TABLE memory_doc USING fts5(content);

    Engineering note: memory must have eviction and redaction policies, otherwise it will grow indefinitely and introduce privacy risks.

    5. Skill Loop: The Key Mechanism That Gets Smarter with Use

    A skill is essentially a “reusable task template plus a sequence of tool invocations.” The loop has four steps: task execution, process logging, abstraction into a skill, and automatic matching and reuse for similar tasks. In practice, add a version number and success rate statistics to each skill to prevent low-quality skills from being triggered repeatedly.

    1. skill:
    2. name: weekly_report
    3. version: 1.2
    4. trigger: ["weekly report", "summary"]
    5. steps: [collect_data, summarize, render, deliver]
    6. success_rate: 0.93

    6. Model Integration and Flexible Switching

    The mainstream approach is to abstract a model adapter interface that converges the differences between providers into a unified protocol, switching through configuration rather than code changes. Before switching, be sure to fix the temperature, context length, and timeout parameters, and apply structured validation to the output to prevent a model change from breaking downstream parsing.

    7. Multi-Platform Messaging Integration and Security Boundaries

    A single instance can connect to multiple message gateways at the same time (team collaboration tools, email, home automation platforms, and so on). For security, it is recommended to:

    1. Use separate credentials for each channel with minimal authorization;
    2. Perform identity mapping at the entry point, binding external accounts to internal user IDs;
    3. Add audit logs and sensitive-word filtering to outbound messages;
    4. Require secondary confirmation for high-privilege tools (executing commands, writing files).

    8. Execution Backends and Isolation

    Choose the execution backend according to risk level: local processes suit trusted tasks; containers suit general isolation; remote sandboxes suit untrusted code. The principle is “no network by default, grant permissions on demand, and reclaim resources on timeout.”

    9. Scheduled Tasks and Observability

    Describe scheduling intent in natural language, then compile it into a standard cron expression:

    1. # Summarize and push daily at 9 AM
    2. 0 9 * * * agent run skill=weekly_report

    Also integrate logging services and monitoring alerts, and build dashboards for task success rate, token consumption, and average latency. If running in the cloud, you can use object storage for memory backups and a container platform to host the execution backend, achieving both elasticity and persistence.

    10. Common Issues and Tuning Checklist

    • Inaccurate memory recall: check chunking granularity and retrieval weights;
    • False skill triggers: tighten trigger words and introduce a confidence threshold;
    • Out-of-control costs: set context trimming and a per-task token limit;
    • Startup failures: check environment variables and directory permissions first.

    Following the process above, you can build a persistent agent on Ubuntu with memory, skill evolution, multi-channel integration, and scheduling capabilities, and keep evolving it under secure and controllable conditions.