AI Agent Memory Architecture and Low-Cost Automation Practices
This article explains why conversational AI agents often work well in demos but degrade in long-running production use, and how to fix the problem at the architecture level. It covers a four-layer memory design (working, episodic, semantic, and procedural), an embedded relational database schema for episodic memory with hybrid retrieval, model routing to flatten the cost curve, code-first execution for deterministic tasks, always-on mobile runtimes for event-driven triggers, a local Markdown knowledge base as a control panel, and packaging recurring friction into reusable skills. Readers will find practical design patterns, sample SQL and Python snippets, and a suggested implementation order for reducing token cost while improving task success rates.
1. The Starting Problem: Why Conversational Agents Are Hard to Keep in Production
Many teams discover a counterintuitive pattern after connecting a large language model to their business systems: the demo looks great, but long-term operation is poor. The cause is usually not model capability but architecture. A purely conversation-driven agent lacks three things: state that persists across sessions, reusable execution paths, and predictable cost boundaries. As a result, every restart requires re-explaining the background, the same instruction gets clarified over and over, and token consumption grows linearly or even super-linearly with the number of turns.
Three questions are enough to self-check whether an agent has engineering value: Can it remember which step it reached last time? Can it turn repetitive tasks into scripts instead of reasoning them through again each time? Is the cost of a single task estimable? Missing any one of them, the system degrades into “a more expensive search box.”
2. Memory Systems: From Session Context to Persistent State
Memory is not concatenating chat history into a prompt; it is a layered design.
The first layer is working memory, the context window of the current task, which has limited capacity and a short lifecycle. The second layer is episodic memory, which records “what was done and how it turned out” and is well suited to structured tables holding task logs, tool calls, and summaries of return values. The third layer is semantic memory, where stable facts settle, such as how to reference API credentials, directory conventions, and personal preferences. The fourth layer is procedural memory, meaning executable scripts and skill definitions.
In practice, an embedded relational database is commonly used to hold episodic memory, because it requires zero operations, lives in a single file, and offers reliable transactions, which fits single-machine or on-device scenarios. The key design decisions are when to write and how to retrieve: append one structured record after each round of tool calls, and at retrieval time apply a hybrid ranking of “time decay + task similarity + tags,” injecting only the Top-K into the prompt to avoid context bloat.
A sketch of the table structure:
CREATE TABLE task_log (id INTEGER PRIMARY KEY,ts TEXT NOT NULL,goal TEXT,action TEXT,result TEXT,tokens INTEGER,tag TEXT);CREATE INDEX idx_task_tag_ts ON task_log(tag, ts DESC);
One security boundary needs emphasis: secrets and tokens must not be written into the memory store in plaintext. They should be referenced through environment variables or a key management service, with only the reference identifier stored in memory.
3. Model Tiered Routing: Flattening the Cost Curve
The root of runaway cost is often that every task is handed to the strongest model. A workable approach is to add a routing layer that splits traffic by task complexity: intent recognition, format conversion, and summarization or classification go to lightweight models or free-tier models; only complex tasks that need multi-step reasoning and code generation are escalated to a high-capability model. If an aggregation gateway is used, it can try candidate models in list order within a single call and fall back automatically on failure, balancing availability against unit price.
More important is changing the execution paradigm: for deterministic tasks, have the agent generate code and execute it rather than continuing to converse with the model. The model intervenes only where a judgment is required, and scripts handle the rest. This “reason once, execute many times” pattern reduces marginal cost from per-turn billing to nearly zero.
A simplified routing decision can be written as:
def route(task):if task.deterministic and task.has_script:return run_script(task.script) # zero model callsif task.steps <= 2:return call_model("light", task.prompt)return call_model("strong", task.prompt)
Combined with local caching, result reuse, and batching, plus a per-task token budget cap with alerts, cost becomes genuinely governable.
4. Coded Workflows: Where Determinism Comes From
Having the agent output code and the runtime execute it is the dividing line for stability, because code can be tested, diffed, and rolled back, while natural-language instructions cannot. A recommended practice is to split the workflow into four stages: collect, transform, validate, and deliver. Each stage is an independent script that can be retried on its own; the validation stage uses schema validation and business assertions to block dirty data; the delivery stage wraps retries and idempotency keys in one place to avoid duplicate submissions.
5. Always-On On-Device: Low Power and Hardware-Level Automation
Placing the agent on a low-power device that stays online for long periods is a cost-effective option. A mobile runtime environment can read sensors, notifications, battery level, and similar signals, enabling real-world triggers: for example, detecting a one-time passcode notification and writing it into a local form, or running a sync when battery level and network conditions are satisfied. Compared with keeping a small host running, the on-device approach uses less power and makes it easier to be “event-driven rather than polling.”
Three things matter for on-device deployment: process keep-alive and auto-start policies, least-privilege permissions, and local data encryption with automatic cleanup. When operating on external platforms, prefer official interfaces; running scripts on the device may be closer to real user behavior, but platform rules and rate limits still apply.
6. A Local Knowledge Base as the Control Panel
Instant messaging interfaces are good for triggering but not for holding structured information. A more practical option is to bind the agent to a local Markdown knowledge base: daily summaries, itineraries, and to-dos are written to disk as plain text files with a metadata header for retrieval, forming a version-controllable “control panel.” After feeding it continuously for two to three weeks, the agent can infer a personal rhythm and proactively produce weekly reports and reminders, while the human only reviews and revises.
---date: 2026-08-11type: daily_summarytags: [auto, review]---- Completed: ...- Blockers: ...
7. Skill-Oriented Thinking: Packaging Repeated Friction as Capability
What really separates implementations is being “skill-oriented”: identify recurring friction points in daily work, such as reconciling accounts, planning meals from what is in the fridge, or organizing expense reports, write the judgment criteria as prompt templates and validation rules, package them as callable skills, and register them in a skill inventory for the router to choose from. A skill should meet three criteria: clear inputs and outputs, observable failures, and composability.
When implementing on Baidu AI Cloud, general-purpose capabilities can be assembled directly: object storage holds the knowledge base and artifacts, a message queue decouples tasks, a container platform hosts the runtime, logging and monitoring with alerting provide observability, and key management handles credentials. Keeping the overall architecture vendor-neutral makes later migration easier.
8. Conclusion
The value of an agent lies not in chatting better but in turning high-frequency tasks into low-cost, verifiable automation. The suggested priority is: first build persistent memory, then add model tiering and code-based execution, and finally fill in on-device triggers and skill accumulation. Following this order, both the cost curve and task success rate can improve together within a few weeks.
