How to Build a Persistent AI Agent on Ubuntu: A Practical Guide
This article walks through building a persistent AI agent on Ubuntu, moving beyond a stateless chat window to a long-running service. It covers environment setup with a non-root account, dual Python and Node.js runtimes, virtual environments, containerization, and systemd process management. It then explains a layered memory system using SQLite FTS5, reusable skills defined as declarative YAML, scheduled tasks, a unified message gateway for multi-platform integration, replaceable model backends with isolated execution, and a pre-launch checklist focused on least privilege, auditability, idempotency, observability, and recoverability.
1. Why a Persistent Agent Instead of Another Chat Window
Over the past two years, interaction with large language models has largely stayed in a “one question, one answer” pattern: when the session ends, the context disappears, and the next conversation starts from scratch. This is sufficient for validating model capabilities, but the shortcomings surface quickly in real production scenarios—user preferences have to be explained repeatedly, project background cannot accumulate, recurring tasks can only be triggered manually, and messages across channels remain fragmented.
The persistent agent is an engineering paradigm designed to address these pain points. It deploys an agent as a long-running server process with four core capabilities: searchable long-term memory, reusable skill accumulation, schedulable recurring tasks, and a connectable message gateway. The model is only the reasoning core; what really determines the user experience is the surrounding engineering infrastructure.
It is worth emphasizing that the value of such a system grows over time, but so does its complexity. Observability, isolation, and recoverability should therefore be built into the design from the start, rather than patched in after something breaks.
2. Environment Preparation: Building a Solid Foundation
When deploying a long-running service on Ubuntu, preparation is recommended at the following levels.
At the system level, use a recent long-term support release, keep the kernel and base libraries updated, and create a dedicated non-root account for running the agent so the agent process does not hold excessive privileges.
At the runtime level, confirm a dual-stack environment with both Python and Node.js. The orchestration layer and the tool ecosystem of most agent frameworks are built on these two runtimes respectively, and version mismatches are the most common cause of startup failures. Use a version management tool to pin versions and avoid drift caused by system upgrades:
# Install a version manager and pin the runtime versionscurl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -sudo apt-get install -y python3 python3-venv nodejs git jq sqlite3python3 -m venv ~/agent-envsource ~/agent-env/bin/activate
At the dependency isolation level, a virtual environment plus containerization provides double protection. The virtual environment resolves Python dependency conflicts, while containers handle system-level dependencies and file system pollution.
The process supervision layer is the key to persistence. Do not carelessly launch the process with nohup; use systemd instead to gain automatic restarts, centralized logging, and startup ordering control:
# /etc/systemd/system/hermes-agent.service[Unit]Description=Persistent AI AgentAfter=network-online.target[Service]User=agentWorkingDirectory=/home/agent/appExecStart=/home/agent/agent-env/bin/python -m agent.mainRestart=alwaysRestartSec=5EnvironmentFile=/home/agent/app/.env[Install]WantedBy=multi-user.target
3. Memory System: From Remembering Context to Retrieving Context
Stuffing the entire conversation history into the prompt is the most primitive and most expensive approach. A more practical engineering approach is layered memory.
The first layer is short-term context, which keeps only the messages within the current task window and slides them out once they exceed the window. The second layer is long-term memory, which extracts facts, preferences, and conclusions into structured entries stored in a database, annotated with timestamps and source tags. The third layer is the retrieval layer, which recalls relevant entries by relevance using full-text search rather than injecting everything.
SQLite’s FTS5 module is a suitable choice for lightweight scenarios: a single file, zero operations overhead, and support for full-text indexing and boolean queries, which is enough to support memory retrieval for a single-host agent. When data volume grows to the point where multiple instances need to share it, migrate to a dedicated search service or a vector database.
CREATE VIRTUAL TABLE IF NOT EXISTS memory USING fts5(content, tags, created_at);-- Write a long-term memory entryINSERT INTO memory(content, tags, created_at)VALUES ('The user prefers concise code examples', 'preference', datetime('now'));-- Recall by relevanceSELECT content, rank FROM memoryWHERE memory MATCH 'deployment preference'ORDER BY rank LIMIT 5;
On top of retrieval, add user modeling to aggregate scattered memories into a stable understanding of the user profile, which can significantly reduce the cost of repeated clarification. Here is a practical rule: memory writes must carry a confidence score and an expiration policy. The damage caused by an incorrect memory being recalled repeatedly is far greater than having no memory at all.
4. Skill Accumulation: Turning Task Experience into Reusable Assets
The essence of the skill mechanism is to solidify “one successful resolution process” into an invokable unit. A complete loop consists of four steps: task execution, process logging, abstraction, and registration for reuse.
The abstraction step is the most easily overlooked. Storing a complete conversation record directly as a skill will cause the skill library to bloat and lower the retrieval hit rate. A more robust approach is to distill it into a four-part tuple of “trigger condition + prerequisites + execution steps + verification method”, stored as readable text, with the name and applicable scenario registered in a registry.
# skills/deploy_service.yamlname: deploy_servicetrigger: when the user asks to deploy a service to the test environmentrequires: [git_repo, registry_credential]steps:- check out the specified branch and run unit tests- build the image and push it to the image registry- update the test environment orchestration config and roll out- run health checksverify: health check returns success three times in a row
Skill reuse requires boundary constraints. It is recommended to add a manual confirmation step for high-risk skills and to log the input and output of each invocation, forming an auditable trail.
5. Scheduled Tasks and Multi-Platform Integration
Scheduled tasks are the dividing line between a persistent agent and a conversational tool. There are three design points: first, describe tasks with declarative configuration to avoid scattering scheduling logic in code; second, tasks must be idempotent, and failure retries must not produce duplicate side effects; third, execution results need a clear delivery target.
# cron configuration example- name: daily_reportschedule: "0 8 * * *"skill: generate_summarydeliver: channel_opson_failure: notify_admin
For multi-platform integration, it is recommended to abstract a unified message gateway layer that provides a standardized message structure upstream (sender, channel, content, time, attachments) and adapts to the differences of each channel downstream. The benefit is that adding a new channel only requires implementing an adapter, without changing the agent’s core logic. Channel adaptation must handle three types of problems: message deduplication, rate limiting, and fallback conversion between rich text and plain text.
6. Model Integration and Execution Backend
The model layer should remain replaceable. Managing model endpoints, keys, and parameters centrally through a configuration center, so that switching models only changes configuration rather than code, is a basic means of controlling vendor lock-in risk. Keys must be stored in environment variables or a key management service and must never be committed to a code repository.
The execution backend determines the agent’s isolation strength. Local execution is the simplest but carries the highest risk; container execution provides file system and network isolation; remote sandboxes and serverless forms suit scenarios where elasticity and persistence coexist. If you use Baidu AI Cloud’s container platform, object storage, and log service, you can host the image registry, state files, and runtime logs separately, and combine them with monitoring and alerting to form a complete operations loop.
7. Pre-Launch Checklist
- Least privilege: the runtime account is non-root, and keys are not stored in the repository
- Governable memory: confidence, expiration, and a manual correction entry point are in place
- Auditable skills: high-risk operations require confirmation, and invocations are logged
- Idempotent tasks: retries do not produce duplicate side effects
- Full-chain observability: logs, metrics, and alerts are all in place
- Recoverable state: the memory database and configuration are backed up regularly and recovery is rehearsed
8. Conclusion
Building a persistent agent from scratch is difficult not in calling the model, but in turning memory, skills, scheduling, and integration into an engineering system that can evolve sustainably. Make isolation and observability solid first, then gradually open up autonomous permissions, so that the agent truly becomes “smarter the more you use it” over long-term use, rather than harder to maintain.
