Deploy a Persistent AI Agent on Ubuntu: A Practical Guide
This guide walks through deploying a persistent AI agent on Ubuntu from the ground up. It covers environment setup and dependency baselines, configuration management, a swappable model integration layer, a searchable memory system built on SQLite FTS5, a skill loop that turns repeated tasks into reusable scripts, scheduled tasks with proactive notifications, multi-channel messaging, execution backend isolation, and ongoing operations. The focus is on the engineering around the model—memory, skills, scheduling, channels, and isolation—rather than model size.
1. Why Deploy a Persistent Agent on a Server
Traditional conversational AI tools are stateless: once a session ends, the context is discarded, and users have to repeat their background, preferences, and project constraints every time. A persistent agent works differently. It turns a session into a long-running service that stays alive as a daemon or container, turns past interactions into searchable memory, turns repetitive work into reusable skills, and reaches out to users proactively through a message gateway.
Running this on a mainstream server distribution such as Ubuntu delivers three practical benefits:
- Data sovereignty: the memory store, logs, and credentials stay on your own disks, which makes auditing and backups straightforward.
- Cost control: you can switch between inference services of different sizes on demand and avoid being locked into a single vendor.
- Orchestration: the agent can be combined with scheduled jobs, container platforms, logging services, and monitoring and alerting to form an automated loop.
The value of this kind of system does not come from larger model parameters. It comes from the engineering around the model: memory, skills, scheduling, channels, and isolation. All five layers are required.
2. Environment Setup and Dependency Baseline
Use Ubuntu 22.04 LTS or later as the baseline and establish a reproducible runtime first.
sudo apt update && sudo apt upgrade -ysudo apt install -y git curl build-essential python3 python3-venv sqlite3
Key checkpoints:
- Python and virtual environments: pin dependencies inside a project-level virtual environment so the system interpreter stays clean.
- SQLite availability: the memory system usually relies on full-text search, so confirm that your SQLite build includes FTS5.
sqlite3
"CREATE VIRTUAL TABLE t USING fts5(x); INSERT INTO t VALUES('ok'); SELECT * FROM t WHERE t MATCH 'ok';"
- Time zone and clock sync: scheduled jobs are time-sensitive, so enable a system time sync service, store everything in UTC, and display in the local time zone.
- Resource estimation: a long-running process needs to account for resident memory and log growth, so set a log rotation policy.
3. Get the Code and Initialize Configuration
Clone the source from your code hosting platform, then initialize with configuration kept separate from code:
git clone <your-repo-url> hermes-agentcd hermes-agentpython3 -m venv .venv && source .venv/bin/activatepip install -e .
Keep configuration files in a separate directory and inject secrets through environment variables:
export AGENT_HOME="$HOME/.agent"export MODEL_API_KEY="***" # provided by a secret manager or a local secret fileexport AGENT_LOG_LEVEL="INFO"
Design notes: never commit secrets to the repository. Use a local credential file with 600 permissions or a cloud secret management capability, and apply least-privilege permissions to the directory (chmod 700 $AGENT_HOME).
4. Model Integration Layer: Make Inference a Swappable Component
A persistent agent should not be tightly coupled to a single inference service. The more robust approach is to abstract a unified model adapter layer and switch backends through configuration:
model:provider: openai_compatible # a service compatible with the unified inference protocolbase_url: https://your-gateway.example/v1model: chat-largetemperature: 0.3max_tokens: 4096
As long as the target service follows the industry-standard chat completion protocol, you can switch it by changing base_url and the model name, with zero changes to business code. In production, put a self-hosted gateway in front to provide:
- Canary rollout and failover across multiple backends;
- Unified metering and quotas (real-time monitoring of token usage);
- Ingress filtering for sensitive terms and prompt injection.
5. Memory System: From Chat History to Searchable Knowledge
The memory layer usually has two parts: a local full-text index for factual recall, and a user modeling module for preferences and long-term profiles.
A sample schema:
CREATE TABLE memory_chunks(id INTEGER PRIMARY KEY, content TEXT, created_at TEXT);CREATE VIRTUAL TABLE memory_fts USING fts5(content, content='memory_chunks', content_rowid='id');CREATE TABLE user_profile(user_id TEXT, trait TEXT, value TEXT, updated_at TEXT);
Maintain the index on write, then on retrieval do keyword recall first and hand the results to the model for reranking and summarization:
def remember(text: str):cur.execute("INSERT INTO memory_chunks(content, created_at) VALUES(?, datetime('now'))", (text,))cur.execute("INSERT INTO memory_fts(rowid, content) SELECT last_insert_rowid(), ?", (text,))def recall(query: str, k: int = 5):rows = cur.execute("SELECT c.content FROM memory_fts f JOIN memory_chunks c ON c.id=f.rowid ""WHERE memory_fts MATCH ? ORDER BY rank LIMIT ?", (query, k)).fetchall()return [r[0] for r in rows]
In practice, give memory tiers and expiration policies (session-level, project-level, long-term), and run periodic deduplication and compression so retrieval noise does not grow linearly with usage.
6. Skill Loop: Let Repetitive Work Settle into Reusable Assets
A skill is essentially a successful trajectory structured into a reusable script. A reliable loop has four steps:
- Task execution: the agent calls tools to complete the task and records the full trajectory (input, tool calls, results).
- Pattern recognition: when the same kind of task recurs with a stable success rate, abstract it into parameterized steps.
- Skill generation: write it to disk as a skill file using a template plus placeholders, with applicability conditions and a failure fallback.
- Reuse and evaluation: later tasks match existing skills first, and hit rate and success rate are recorded; low-scoring skills are automatically down-weighted.
name: daily_reportwhen: "task contains keywords such as daily report or summary"steps:- query_memory: "{{topic}}"- run_sql: "{{sql}}"- render: "markdown"fallback: "freeform_chat"
This mechanism makes the system’s capabilities grow monotonically with usage, and it is what sets a persistent agent apart from one-off question answering.
7. Scheduled Tasks and Proactive Push
The built-in scheduler lets you describe tasks in natural language and compiles them into standard five-field cron expressions:
# Generate a summary and push it at 09:00 every weekday0 9 * * 1-5 agent task run daily_report --notify
Three things need to be in place: task idempotency (repeated triggers produce no duplicate side effects), failure retries and alerts (wired into a monitoring and alerting channel), and execution traces (structured logs for retrospection).
8. Multi-Channel Access and Message Gateway
One agent instance can mount multiple message entry points at once, such as team collaboration tools, email, and home automation platforms. Abstract a unified message adapter interface:
class Channel(Protocol):async def receive(self) -> Message: ...async def reply(self, msg: Message, text: str) -> None: ...
The gateway layer handles identity mapping (external user to internal user_id), rate limiting, deduplication, and content moderation. Always enforce length and frequency limits on all inbound messages so the agent is not abused as a free inference endpoint.
9. Execution Backend Isolation and Security Baseline
Tool execution is the part that most needs isolation. Choose a backend by risk tier: local process (trusted tasks only), container platform (the default), remote host, or a serverless persistent execution environment. Security checklist:
- Run as non-root inside containers, mount the code directory read-only, and disable privileged mode;
- Route egress through a whitelist proxy, and inject credentials via environment variables or secret mounts;
- Restrict file writes to the working directory and explicitly deny sensitive paths;
- Centralize full audit logs in a logging service and configure alerts for anomalous behavior.
10. Acceptance, Operations, and Evolution
Before going live, complete four kinds of acceptance checks: functional (memory recall accuracy, skill hit rate), stability (memory and handle leaks under long-running operation), security (unauthorized read/write and prompt injection cases), and cost (average token consumption per task).
Day-to-day operations track three curves: memory store size, skill count and success rate, and task failure rate. When memory retrieval noise rises, prioritize compression and tiering; when skill success rate drops, trigger regeneration. To scale horizontally, move the memory store to a dedicated data service and containerize the agent itself so a container platform can orchestrate and scale it.
Follow this path and what you get is not another chat window, but a persistent agent infrastructure that can evolve continuously, be audited, and be isolated—which is the real value of deploying from zero to one.
