Building AI Agents with Persistent Memory and Skill-Based Workflows
This article explains how to build production-ready AI agents by adding three missing capabilities: persistent memory, execution determinism, and reusable skill packaging. It covers a database-backed memory layer with task deduplication and retention policies, cost control through model routing and a code-first execution pattern, always-on agents on low-power devices with local handling of sensitive data, and a local-first knowledge dashboard that turns repeated friction into reusable skills. A staged adoption roadmap and optional cloud scaling are included.
1. The Starting Problem: Why a Chat-Only Agent Cannot Handle Real Work
Most teams run into the same wall after trying an AI agent: the context resets as soon as the session restarts, the same instruction has to be explained over and over, and model call volume grows linearly with task complexity, making the bill unpredictable. The root cause is not the model itself. It is that the agent lacks three things: persistent state, execution determinism, and reusable capability packaging.
An agent that can carry production work typically needs a closed loop like this:
- Perception: read task input and external environment data;
- Memory: persist historical actions, configuration, and results so they can be reused across sessions;
- Decision: weigh cost against reliability when choosing between “call the model directly” and “generate code, then execute it”;
- Execution: complete actions in a scripted, replayable way;
- Reflection: write new experience back as reusable skills.
The “missing memory leads to repeated instructions, frequent restarts, and excessive token spend” pattern described in the source material is essentially three typical symptoms of a broken loop. Each one is addressed below from an engineering perspective.
2. Persistent Memory: Moving Context from the Session to a Database
Reliable agent memory comes down to separating volatile session context from stable long-term state. A common industry approach is to use a lightweight embedded relational database to store task logs, key-value configuration, and action traces, instead of stuffing everything into the prompt.
A minimal viable memory table design:
CREATE TABLE agent_memory (id INTEGER PRIMARY KEY,task_key TEXT NOT NULL, -- task deduplication keypayload TEXT, -- JSON-serialized contextresult TEXT, -- execution result summarycreated_at INTEGER);CREATE INDEX idx_task_key ON agent_memory(task_key);
Corresponding read and write logic (illustrative):
def remember(task_key, payload):db.execute("INSERT OR REPLACE INTO agent_memory(task_key, payload, created_at)"" VALUES (?,?,strftime('%s','now'))",(task_key, json.dumps(payload)),)def recall(task_key):row = db.execute("SELECT payload FROM agent_memory WHERE task_key=?", (task_key,)).fetchone()return json.loads(row[0]) if row else None
Three engineering points matter. First, the task deduplication key should be derived from business semantics (for example, “date + entity + action”); on a hit, skip the duplicate execution. Second, sensitive credentials should not be stored in plaintext; inject them through environment variables or a secrets management service, and keep only a reference identifier in the database. Third, memory needs a decay and archival policy, otherwise the table grows without bound; the recommendation is to aggregate by time window into a summary before storing.
3. Cost Control: Model Routing and a Code-First Execution Pattern
The key to lowering spend is not switching to a cheaper model but reducing unnecessary model calls. Two layers of strategy are practical.
The first layer is model routing: split traffic by task complexity, sending simple extraction, formatting, and classification to a low-cost model and escalating complex reasoning to a more capable model. In the industry this is usually implemented through a unified model gateway or aggregation routing service; in a self-built agent it can be wrapped in a single route() function:
def route(task):if task["complexity"] == "low":return cheap_modelreturn strong_model
The second layer delivers the largest gain: for deterministic tasks, have the agent write code instead of continuing the conversation. When the task steps are fixed, let the model generate a script once and reuse that script for subsequent runs, which drops model calls from “once per step” to “generate once, reuse many times.”
# First run: the model generates the script; later runs: execute the cached script directlyscript = recall("report_script") or llm.generate(CODE_TEMPLATE)if not script:remember("report_script", {"code": script})exec_result = sandbox.run(script, data=current_input)
This “code-based workflow” turns uncertain natural-language reasoning into code assets that are testable, replayable, and versionable, so the bill naturally shifts from unpredictable to budgetable.
4. Always-On Agents on the Device: Running on Low-Power Hardware
An always-on agent needs a low-cost, low-power host that can stay online for long periods. A development terminal environment on a mobile device (for example, a Unix-like terminal emulation approach) can run a script runtime and access local data such as sensors, notifications, and battery level, enabling hardware-level automation. Examples include automatically reading and processing two-factor authentication SMS messages, or delaying non-critical jobs based on battery policy.
Compliance and security boundaries need emphasis: automation involving sensitive data such as SMS and notifications must parse that data locally on the device, with sensitive fields never sent to the cloud or transmitted externally; publishing or outbound actions should prefer official authorized interfaces, avoiding the account risk that comes with relying on unofficial automation.
A minimal always-on scheduling skeleton:
while True:if battery_level() < 20:sleep(600); continue # yield when battery is lowfor job in pending_jobs():run(job) # run locally, write results back to memorysleep(interval)
5. Knowledge Dashboard and Skills: Packaging Repeated Friction into Reusable Capabilities
Mobile chat interfaces have low information density and overload easily. A better approach is to write agent output into a local-first bidirectional-link note library, forming a structured, searchable personal dashboard: task logs, decision records, to-dos, and knowledge cards organized into separate stores, with the agent appending entries against fixed templates and the human only reviewing.
Skill packaging turns “notice a repeated friction point, abstract the process, package it as a skill, write it back to memory” into a routine action. The minimal structure of a skill should include a trigger condition, an input schema, execution steps, and a failure fallback:
skill: weekly_finance_digesttrigger: "Every Monday 09:00 or manual invocation"input: {accounts: list, period: string}steps: [fetch, normalize, compute, render, notify]fallback: "Output a list of gaps when data is missing instead of guessing"
Once the skill library reaches a certain size, the agent evolves from a “general-purpose conversationalist” into an “automation employee specific to the organization,” and its value depends not on how strong the model is but on how many high-quality skills have accumulated.
6. Adoption Roadmap
- Connect the memory layer first to solve repeated instructions and restart amnesia;
- Then add model routing and script caching to bring the bill into a budgetable range;
- Choose a low-power host for always-on operation and process sensitive data locally;
- Replace the chat dashboard with a local note library to build a searchable console;
- Review friction points once a week and produce at least one new skill.
If elastic scaling is needed, the memory store, script sandbox, and scheduler can be moved to a cloud container platform, combined with object storage for archival, a logging service for audit, and monitoring and alerting as an exception safety net, forming a robust device-cloud architecture.
