How to Build a Persistent AI Agent from Scratch on Ubuntu

    This guide walks through deploying a persistent AI agent on Ubuntu, covering a five-layer architecture, environment setup, model abstraction, searchable memory with SQLite FTS5, reusable skills, scheduled tasks, multi-channel access, security hardening, and go-live checks. It shows how to turn a stateless chatbot into a long-running, observable, and restartable background service that retains context across sessions and executes tasks unattended.

    1. Why Deploy a Persistent Agent on a Server

    Conventional conversational AI tools are essentially stateless: once a session ends, the context is discarded, and users have to restate their background every time. A persistent agent is designed for the opposite behavior. It runs continuously, turns preferences, project context, and past conclusions into searchable assets, and proactively executes tasks when nobody is watching. The differences come down to three dimensions:

    • State: moves from session-level to instance-level, with memory reused across sessions and devices.
    • Execution: moves from giving advice to calling tools, modifying files, and running commands.
    • Reach: moves from “open a web page to use it” to proactive delivery over messaging channels.

    Ubuntu is a common choice for hosting this kind of always-on service: mature package management, solid systemd service management, and a complete container runtime ecosystem make it easy to package an agent as an observable, restartable, and upgradeable background unit.

    2. Overall Architecture: Split Capabilities into Replaceable Layers

    Deciding on the architecture before writing code prevents all the logic from ending up in a single process later. A five-layer split is recommended:

    1. Access layer: messaging gateway adapters that handle sending and receiving messages across platforms and map identities.
    2. Orchestration layer: task planning, tool selection, multi-step execution, and retry on failure.
    3. Capability layer: the toolset for file operations, terminal commands, code search, and external API calls.
    4. Cognition layer: memory storage, user modeling, and the skill library.
    5. Execution backend layer: isolated environments such as local processes, containers, remote hosts, or stateless functions.

    The key benefit of this layering is replaceability: swapping the model does not touch business code, changing the execution backend does not touch orchestration logic, and adding a messaging platform only requires implementing one adapter.

    3. Environment Setup and Baseline Constraints

    1. # Confirm basic system information
    2. sudo apt update && sudo apt install -y python3 python3-venv git sqlite3
    3. python3 --version && sqlite3 --version

    The preparation stage should settle four constraints, because they determine every design decision that follows:

    • Runtime account: do not run as root permanently. Create a dedicated low-privilege user and grant write access only to the directories that need it.
    • Dependency isolation: use a virtual environment or containers to pin dependency versions and avoid polluting the system Python.
    • Secret management: put model keys and channel credentials in environment variables or a separate secret file with permissions set to 600, and never commit them to the code repository.
    • Resource boundaries: set memory and CPU limits on the process so runaway tool calls cannot take down the host.

    4. Model Access: Abstract a Unified Invocation Layer

    An agent should not be tied to a single model provider. The more robust practice is to place an adapter interface between the orchestration layer and the model, standardizing the system prompt, context, and tool definitions on the input side and the response parsing on the output side, so switching models is a configuration change only. A sketch:

    1. # Pseudocode: unified model adapter layer
    2. def chat(messages, tools, model_cfg):
    3. provider = model_cfg["provider"] # any compatible inference service
    4. payload = {
    5. "model": model_cfg["name"],
    6. "messages": messages,
    7. "tools": tools,
    8. "temperature": model_cfg.get("temperature", 0.2),
    9. }
    10. return provider_call(provider, payload) # unified response structure

    In practice, configure a primary model and a fallback model so the service switches automatically when the primary is rate-limited or times out, keeping the always-on service from breaking.

    5. Memory System: Being Searchable Matters More Than Remembering

    A reliable memory mechanism usually has two parts: a full-text search index and a structured user profile. The former stores conversations and task artifacts; the latter stores stable preferences such as output language, code style, and common directory conventions.

    1. -- Example memory retrieval based on a full-text index
    2. CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts
    3. USING fts5(content, tag, created_at);
    4. INSERT INTO memory_fts(content, tag) VALUES (?, ?);
    5. SELECT content, tag FROM memory_fts
    6. WHERE memory_fts MATCH ? ORDER BY rank LIMIT 8;

    Three design points matter. First, tag entries on write (project, device, task type); retrieval accuracy is far higher than with plain keywords. Second, apply a tiered retention policy: archive raw records long term and keep summaries in a hot tier. Third, memory must be deletable and exportable, which is the baseline for compliance and user trust.

    6. Skill Capture: Close the Execute, Abstract, Reuse Loop

    The value of a skill library is turning one-off operations into callable units. A working loop has four steps:

    1. Record: save the full task input, the tool call sequence, and the final result.
    2. Abstract: replace concrete parameters with placeholders and extract preconditions and validation points.
    3. Store: save it with a structure of name, description, parameter schema, and steps.
    4. Reuse: when a new task arrives, run semantic matching first; call the skill directly on a hit, and fall back to generic planning on a miss.
    1. # Example skill definition
    2. name: check_service_health
    3. description: Check the port and process status of a given service and summarize
    4. params:
    5. host: string
    6. ports: array
    7. steps:
    8. - run: "ss -lntp | grep -E '{{ports}}'"
    9. - summarize: true

    One point deserves emphasis: skill reuse must include permission checks and parameter whitelists, otherwise a single misoperation gets amplified into a batch incident.

    7. Scheduled Tasks and Proactive Delivery

    What sets an always-on agent apart is being proactive. Describe the intent in natural language and let the orchestration layer turn it into a scheduled rule:

    1. Every weekday at 9:00, check the database connection count; if it exceeds the threshold, push an alert summary through the messaging channel

    Three practices are recommended in implementation: store task definitions separately from business code; give every task a timeout and a retry limit; and log all execution results uniformly so it is easy to trace back why a given message was pushed.

    8. Multi-Channel Access and Isolated Execution

    When one instance connects to several messaging channels at once, the most common problems are identity confusion and privilege escalation. Always build a mapping of channel account to internal principal to permission set, and restrict the tool scope available to each principal. Capabilities involving terminal commands and file writes should preferably run in containers or on remote hosts, with the host machine keeping only orchestration and scheduling, so abnormal tool output cannot directly threaten the main system.

    9. Security Hardening Checklist

    • Least privilege: dedicated accounts, directory whitelists, and tool-level authorization.
    • Input validation: treat content arriving from messaging channels as untrusted input and enforce length and character constraints.
    • Audit trail: log tool calls, parameter summaries, and execution results, with sensitive fields masked.
    • Rate limiting: set quotas on model calls and external requests to prevent cost overruns.
    • Backup and drills: back up the memory and skill stores regularly and verify they can be restored.

    10. Go-Live Checks and Evolution Path

    Before going live, confirm item by item: whether the process is managed by a service manager with automatic restart configured; whether logs are centrally searchable; whether monitoring covers call volume, failure rate, and resource usage; and whether secrets have been rotated. Once the service is stable, evolve in the order of expanding channels first, then tools, and finally automation tasks, keeping a rollback path at every step.

    If it is hosted in the cloud, state files can be persisted and backed up in object storage, isolated execution can run on a container platform, and logging and monitoring services with alerting can close the observability loop, yielding a runtime foundation for an agent that stays online long term and keeps learning and evolving.