A Practical Guide to Building Autonomous Agents with Memory and Skills
This article presents an engineering approach to building autonomous agents that move beyond basic chat to reliable, cost-effective task execution. It covers persistent memory layers, code-first deterministic execution, multi-model routing, on-device always-on deployment, integration with a local knowledge base, and packaging methods into reusable skills. Readers will find practical design principles, sample schemas, and code snippets for creating agents that accumulate experience and automate repetitive work.
1. Background: From Chatting to Getting Work Done
Autonomous agents have become a hot topic recently, often discussed as potential disruptors in the cloud space. However, from an engineering perspective, what determines whether an agent is valuable is not how fluent its conversations are, but whether it can turn high-frequency, repetitive, and relatively well-defined tasks into low-cost, deterministic automation.
Typical problems observed in early implementations are representative:
- Processes restart frequently, causing context loss;
- Without persistent memory, users have to repeat the same instructions;
- Token consumption is too high, with five days of usage reaching the hundreds of dollars range;
- The interactive interface suffers from information overload, burying important details.
The root cause is that the agent is treated as a chat box rather than a software system that can run continuously and accumulate experience. The following sections outline a more rigorous engineering approach across six dimensions.
2. Persistent Memory: The Core Competitiveness of an Agent
An agent’s capability ceiling is largely determined by its memory. Without memory, it starts from scratch every time; with memory, it can accumulate experience and reuse historical conclusions.
From an engineering standpoint, memory can be divided into three layers:
- Working memory: the context of the current task, with a short lifecycle that is released when the task ends;
- Episodic memory: historical task logs, execution results, and failure reasons, persisted to a database;
- Semantic memory: structured facts such as user preferences, common parameters, secret references, and environment constraints.
For implementation, a local embedded relational database (such as an in-process SQL store) can record task logs and execution traces, with fields including at least task ID, input summary, model used, token consumption, execution status, error stack, and duration. Example:
CREATE TABLE task_log (task_id TEXT PRIMARY KEY,created_at INTEGER NOT NULL,goal TEXT NOT NULL,model_used TEXT,tokens_in INTEGER DEFAULT 0,tokens_out INTEGER DEFAULT 0,status TEXT NOT NULL, -- success / failed / partialerror_stack TEXT,duration_ms INTEGER);
Key design principles:
- Sensitive information such as secrets should not be stored in plaintext; only reference identifiers are stored, and values are read at runtime from environment variables or a secret management service;
- Logs must be replayable, so failed tasks can be “self-corrected” based on historical traces;
- Memory compression and summarization should be performed periodically to avoid unbounded context growth.
With this layer in place, the accuracy of an agent handling complex workflows improves over time because it no longer repeats the same mistakes.
3. Determinism First: Let the Agent Write Code Instead of Continuously Calling the Model
This is the most effective methodology for reducing costs: for deterministic tasks, let the agent generate and execute code rather than requesting model inference at every step.
Compare two modes:
- Pure inference mode: the model is called at every step, token consumption grows linearly, and results are unstable;
- Code-based mode: the model is responsible only for “planning once” and producing a script, which is then executed deterministically by the runtime.
# Pseudocode: plan first, then execute deterministicallyplan = agent.plan(goal="Summarize this week's financial transactions and generate a report")script = agent.emit_code(plan) # produce an executable scriptresult = run_script(script) # runtime execution, no more token consumptionagent.remember(goal="Summarize this week's financial transactions", script_hash=hash(script), ok=True)
The benefits are twofold: token overhead drops significantly (in one case from about $130 every five days to around $10), and execution results become reproducible, testable, and rollback-able.
4. Multi-Model Routing: Switching Flexibly by Task Complexity
Different tasks have vastly different requirements for model capability. Engineering practice should introduce a “model routing layer” to distribute tasks by complexity:
- Simple extraction, format conversion, and classification/tagging: route to low-cost or free-tier models;
- Medium-complexity writing and summarization: route to cost-effective models;
- High-complexity planning and code generation: route to more capable models.
The routing layer needs three capabilities: task complexity assessment, automatic fallback and retry on failure, and cost tracking with alerts. A unified abstraction interface shields business code from differences between models. This controls costs while ensuring quality for critical tasks.
5. On-Device Always-On: A Low-Power Deployment Model
To make an agent truly “always present,” the deployment model matters. Compared with running on a small host or a cloud virtual machine, on-device deployment (such as a terminal runtime on a mobile device) offers three advantages:
- Lower cost and low idle power consumption;
- Direct access to local capabilities such as device sensors, notifications, and battery, enabling hardware-level automation (for example, automatically reading and processing two-factor authentication SMS messages);
- Publishing scripts execute locally on the device, reducing the risk of platform-side demotion caused by calls through external interfaces.
Engineering considerations: on-device environments are resource-constrained, so task queues and rate limiting are needed; sensitive operations require local confirmation; and an offline fallback strategy is needed when disconnected.
6. Structured Knowledge Base Integration: Using a Local Note Library as a Control Panel
Chat interfaces are inherently prone to information overload. A better approach is to tightly integrate the agent with a local Markdown knowledge base, letting it automatically organize daily summaries, travel plans, and to-do items into structured notes.
Agree on directory and metadata conventions:
---date: 2025-01-01type: daily-summarytags: [auto, agent]---## Completed Today- ...## To-Do- [ ] ...
By continuously “feeding” it for 7 to 20 days, the agent gradually understands the user’s rhythm of life and proactively generates a structured knowledge base instead of passively waiting for questions. Data stays local, privacy is controllable, and it is easy to search and reprocess.
7. Skill-Based Thinking: Packaging Methodology into Reusable Skills
One of the core competencies in the AI era is the ability to “skillify”: discovering repetitive friction points in daily life (financial report analysis, fridge ingredient pairing, weekly report generation) and packaging them into standardized skills.
A skill should include: trigger conditions, input schema, execution steps, validation rules, output template, and failure fallback. Example structure:
{"skill": "fridge-meal-plan","trigger": "User uploads a fridge photo or ingredient list","input_schema": {"ingredients": "string[]"},"steps": ["Identify ingredients", "Match recipe library", "Generate shopping gaps"],"output_template": "markdown","fallback": "Output only three dishes that can be made"}
The value of skillification lies in reuse and composition: multiple atomic skills can be orchestrated into complex workflows, freeing up cognitive bandwidth.
8. Implementation Recommendations and Summary
In summary, the key path to building a high-value autonomous agent is: use persistent memory as the foundation, reduce costs through code-based deterministic execution, balance cost and quality with multi-model routing, achieve always-on operation through on-device deployment, use a local knowledge base as the control panel, and encapsulate methodology through skillification. If cloud hosting is needed, general-purpose capability categories (such as object storage, message queues, container platforms, logging services, and monitoring/alerting) can serve as supplements, keeping the architecture neutral and portable. General cloud product categories offered by cloud vendors such as Baidu AI Cloud can also serve as one optional foundation for hosting this type of architecture.
