How to Build a Persistent AI Agent from Scratch on Ubuntu
This guide walks through building a persistent AI agent on Ubuntu, covering environment setup, layered architecture, memory design, skill reuse, isolated execution backends, scheduled tasks, and a pre-launch checklist. It explains how to give an agent long-term memory, reusable skills, and proactive scheduling so it runs as a managed service rather than a stateless chatbot.
1. Why Build a Persistent Agent on a Server
Conventional conversational AI tools are stateless by nature: once a session ends, the context is discarded, and the user has to explain the background again from scratch on the next request. A persistent agent returns state, skills, and scheduling control to the agent itself, turning it into a long-running service process. It typically provides four core capabilities: autonomous memory, skill accumulation, scheduled execution, and multi-channel communication. Combined, these shift the agent’s behavior from passive response to proactive operation, which is why such agents stand out in developer assistance, operations inspection, and research data processing.
It is worth stressing that persistence does not mean putting a script in the background. It requires the system to separate three layers of state by design: session-level temporary context, cross-session long-term memory, and reusable skill definitions. These three differ in storage medium, lifecycle, and retrieval method, and mixing them leads to context pollution and retrieval noise.
2. Preparing the Ubuntu Environment and Baseline Constraints
Ubuntu is a common choice for this kind of service because of its mature package management, stable systemd service management, and solid container runtime support. Prefer a long-term support release and follow the principle of least privilege:
# Create a dedicated runtime account instead of running the agent as root long-termsudo adduser --system --group --home /opt/agent agentsudo mkdir -p /opt/agent/{bin,config,data,logs}sudo chown -R agent:agent /opt/agent
There are three key constraints. First, grant the runtime account read/write access only to the necessary directories, and inject model keys through environment variables or a separate configuration file with permissions set to 600. Second, if the agent needs to run terminal commands, you must establish a whitelist and a sandbox boundary, and forbid executing arbitrary commands directly on the host with high privileges. Third, route all outbound communication through a unified egress for easier auditing and rate limiting.
3. Layered Architecture
A maintainable implementation is best split into five layers:
- Access layer: a unified message gateway that normalizes messages from different channels into an internal event structure;
- Orchestration layer: intent recognition, task planning, and tool selection, deciding “what to do” and “what to use”;
- Execution layer: tools such as command execution, file operations, and code retrieval, running on an isolated backend;
- State layer: short-term context cache plus long-term memory store plus skill library;
- Observability layer: logs, metrics, token usage, and task success rate.
The core benefit of layering is controlled replacement cost. For example, when switching model providers, you only adjust the model adapter module in the orchestration layer, with no changes needed to the execution or state layers.
4. Memory System: From Full-Text Retrieval to User Modeling
A reliable memory system usually has two parts. The first is structured storage plus full-text retrieval. In practice, an embedded relational database with full-text indexing is often used to achieve fast recall by keyword and semantic cues:
CREATE VIRTUAL TABLE memory_fts USING fts5(user_id, content, tags, created_at);-- Combine tag filtering during retrieval to reduce cross-project contaminationSELECT content FROM memory_ftsWHERE memory_fts MATCH 'deploy failure troubleshoot' AND user_id = 'u_1001'ORDER BY rank LIMIT 5;
The second part is user modeling, which maintains a preference profile for each user, recording their common tech stack, output style preferences, and project background. Three engineering points matter here: writes need deduplication and conflict merging; memory needs time decay to prevent outdated conclusions from influencing decisions over the long term; and sensitive information must be redacted before storage. Without these three, the memory system quickly degrades into a noise source.
5. Skill Loop: Making the Agent Cheaper in Tokens Over Time
A skill is essentially the abstraction of a successful task’s execution trace into a reusable template, including trigger conditions, step sequences, dependent tools, and validation methods. The loop has four steps: extract the trace after a task completes; have the model generalize the common steps and generate a skill draft; try it out on similar tasks and compare results; and, after validation passes, store it with a version number.
task trace -> template generalization -> trial validation -> skill stored (v1) -> reuse and iteration (v2)
What to watch out for is that automated generalization may produce “pseudo-skills,” meaning accidental paths that only hold within a single context. So you must set admission criteria: for example, the same pattern must appear more than twice, the trial success rate must meet the threshold, and no high-risk commands may be involved before a skill is formally stored.
6. Isolated Execution Backends and Pluggable Models
Running terminal commands is the highest-risk part of an agent, so it should support multiple backend forms: local process, container, remote host, and serverless persistent execution environments. Container isolation is the recommended default, with limits on CPU, memory, execution duration, and network egress, plus a read-only filesystem mount separated from a writable workspace.
For the model layer, an adapter abstraction is recommended so you can switch between model services with different capabilities through configuration, with zero changes to business code:
# Illustrative: unified model adapter interfaceclass ModelAdapter:def chat(self, messages, tools=None): ...def stream(self, messages, tools=None): ...def switch_model(name: str) -> ModelAdapter:return registry[name]() # change config only, not the caller
If you need stronger elasticity and managed capabilities, you can migrate the execution backend and memory store to general-purpose cloud capabilities, for example using a container platform to host the execution sandbox, object storage to hold skill packages and artifacts, a message queue to smooth out traffic spikes, and logging and monitoring services for observability. Baidu AI Cloud offers the general-purpose capabilities in these categories, which can be combined as needed to avoid the operational burden of self-hosting.
7. Scheduled Tasks and Proactive Push
The differentiating value of a persistent agent lies in its proactivity. A built-in scheduler lets you describe tasks in natural language, for example “summarize service error logs every weekday morning and push a digest,” and the system parses this into a scheduling expression and an execution plan. Implementation points include: idempotent task design to avoid duplicate pushes; retry and backoff strategies on failure; unified formatting of execution results before distribution through the message gateway; and a timeout and resource cap for each task to prevent long-tail tasks from dragging down the process.
8. Terminal Experience and Protocol Extensions
Experience details for end users determine retention: multi-line editing, command autocompletion, real-time token usage hints, and streaming presentation of tool output. For capability extension, it is recommended to support an industry-standard tool integration protocol, mounting external tool services in a standardized way so the agent’s capability boundary can be extended without modifying core code.
9. Pre-Launch Checklist
- Runtime account runs with least privilege, and keys are never stored in plaintext;
- Execution backend is isolated, with command whitelist and high-risk blocking in effect;
- Memory writes include deduplication, decay, and redaction;
- Skill storage has admission criteria and version management;
- Model switching is done through configuration, with no coupling to the caller;
- Logs, metrics, token usage, and task success rate are observable;
- Scheduled tasks are idempotent, retryable, and have timeout limits.
Following this path, an ordinary server on Ubuntu can host an agent that keeps evolving: it remembers context, reuses experience, works proactively on schedule, and appears through a unified gateway in the various communication channels you use every day.
