Engineering AI Agents: Persistent Memory, Cost Control, and Reusable Skills
Many teams lose confidence in AI agents after they forget context, repeat instructions, and burn tokens. This article argues that agents create compounding value as deterministic automation, not as chat boxes. It covers externalized memory, script-first workflows with model routing, always-on edge runtimes, a local knowledge-base control plane, and packaging repeat work as versioned, testable skills.
1. Start with the real problem: value is deterministic automation, not conversation
Many teams try AI agents and quickly lose interest: a restart wipes memory, the same instructions must be repeated, and token bills spiral. The root cause is rarely that the model is too weak. It is that the agent is treated as a chat box instead of an execution system.
The form that compounds value is different: take high-frequency, repetitive, well-specified work and turn it into reusable, verifiable, low-cost automation. The model should intervene only where judgment is actually required.
2. Persistent memory: first-class infrastructure
A stateless agent cold-starts every session. Users restate background, where secrets live, and past decisions. The engineering fix is to externalize state.
- Structured storage: Use an embedded relational database (for example SQLite, a single-file database) for task logs, tool results, user preferences, and intermediate artifacts. Do not dump all context into the prompt.
- Layered memory: Short-term memory stays in the current session window; mid-term memory lives in a task log table; long-term memory lives in summarized preference and fact tables, indexed by time and topic.
- Replayability: Record each tool call’s inputs, outputs, latency, and status so failures can be replayed and cost can be accounted for.
Illustrative schema:
CREATE TABLE task_log (id INTEGER PRIMARY KEY,ts TEXT NOT NULL,task TEXT,tool TEXT,input TEXT,output TEXT,status TEXT,tokens_in INTEGER,tokens_out INTEGER);CREATE TABLE long_term_fact (key TEXT PRIMARY KEY,value TEXT,updated_at TEXT);
With memory, the agent can get more accurate over time: retrieve previously successful paths and reuse validated parameters and workflows instead of trial-and-error on every run.
3. Cost control: code the workflow, then route the model
Token spend usually explodes from an anti-pattern: the model reasons step by step and repeatedly calls itself for deterministic work. A cheaper pattern is write code first, then execute it. Loops, formatting, and batch work belong in the runtime. The model generates a script once and handles exception branches.
Pair that with a unified model gateway (a common industry pattern) and dispatch by task complexity:
| Task type | How it runs | Model tier |
|---|---|---|
| Format conversion, aggregation, scheduled fetch | Local script | No model call |
| Classification, extraction, rewrite | Single call | Lightweight, low-cost model |
| Planning, debugging, architecture decisions | Multi-turn reasoning | High-capability model |
def route(task):if task.deterministic:return run_script(task.script) # zero tokensif task.complexity == "low":return call_model(task, tier="cheap")return call_model(task, tier="strong") # critical path only
Script-first plus tiered dispatch can push the marginal cost of recurring jobs from linear growth toward near-fixed overhead. That is often the highest-leverage cost control.
4. Always-on at the edge: a low-power execution node
A always-on cloud instance is not the only option. Running the agent runtime in a terminal-like environment on a phone or a low-power single-board device gives three capabilities: read local signals such as sensors, notifications, and battery; run publish and sync scripts on-device, reducing rate limits and deprioritization from external APIs; stay online 24/7 at very low power.
Engineering constraints still apply: encrypt local storage, never persist secrets in plaintext, make the execution queue idempotent, and add failure alerts plus a human confirmation gate.
5. A local knowledge base as the control plane
Write agent output back into a local Markdown knowledge base instead of dumping it in a chat window. That cuts information overload. Agree on a fixed directory layout and metadata:
---date: 2026-08-26type: daily_summarytags: [auto, agent]---## Today's progress## Todos (auto-synced)## Tomorrow's plan
The agent generates daily summaries, travel plans, and todo lists from templates and maintains a two-way index. After 7 to 20 days of continuous feeding, it can infer routines and priorities and produce structured knowledge proactively rather than only answering on demand.
6. Skills: package methods as reusable capabilities
The end state is to abstract repeated friction into skills. Each skill has a trigger, an input/output contract, execution steps, and validation rules.
skill: expense_reviewtrigger: "1st of each month or when a report file arrives"inputs: [file_path]steps: [parse, classify, compare_baseline, render_report]guard: "require human confirmation if amount deviation > 20%"
Financial report review, inventory and meal planning, or founder decision checklists can all follow this template. Skills can be versioned, tested, and shared. Team cognitive bandwidth is freed, and the agent becomes an accumulating organizational asset rather than a one-off tool.
7. Implementation checklist
- Ship the memory layer before chasing “smarter” behavior. 2. Default to scripts; use the model as fallback. 3. Add tiered model routing and budget alerts. 4. On-device deploy must encrypt and stay idempotent. 5. Route all output back into one knowledge base. 6. Encapsulate each high-frequency scenario as a testable skill.
