AI Agent Memory Architecture and Token Cost Optimization: A Practical Guide
This article explains how to build persistent, retrievable memory for AI agents and bring token spending under control. It covers a three-layer agent architecture, a local database schema for task logs and idempotent execution, hybrid retrieval with minimal context injection, model routing, shifting deterministic work from prompts to generated code, always-on agents on low-power devices, a knowledge-base control panel, reusable skill definitions, and a phased rollout with clear risk boundaries.
1. The Starting Problem: Why Stateless Agents Fail at Long-Horizon Work
Most teams that wire a large language model into an automated workflow eventually hit the same three symptoms. The context is wiped every time the process restarts. The same instruction runs twice because the system cannot tell whether something was already done. And the bill grows far faster than expected, with token consumption out of proportion to business value.
All three are surface expressions of one architectural flaw: the agent has no persistent, retrievable state layer. A context window that only lives for a single session cannot hold long-lived facts such as “I already handled this yesterday,” “the key for that API is stored here,” or “this kind of report should follow that template.” So every startup re-probes the environment, and every decision re-reads a pile of background material. Cost climbs linearly at best, and superlinearly at worst.
The fix is to split the agent into three layers: an interaction layer that receives instructions and returns results, a reasoning layer that handles planning and decisions, and a state layer that persists memory, task logs, and skill definitions. Once the three are decoupled, a restart no longer means amnesia, and cost control finally has a concrete place to act.
2. The Memory System: A Searchable Long-Term State on a Local Database
The minimum viable implementation of persistent memory needs no heavy infrastructure. A local embedded relational database is enough. The choice of engine is not what matters; the write timing and the retrieval strategy are.
Record at least four categories of information: task logs (what was done, a summary of the input, the output result, a timestamp), configuration and credential references (store only the reference identifier, never a plaintext secret), user preferences (output format, common templates, exclusions), and a skill index (capability name and invocation conditions).
-- Task log table: supports idempotency checks and history replayCREATE TABLE task_log (id INTEGER PRIMARY KEY AUTOINCREMENT,task_key TEXT NOT NULL, -- Normalized task fingerprintpayload TEXT, -- Input summary; avoid storing full textresult_ref TEXT, -- Reference to where the result is storedstatus TEXT DEFAULT 'done',created_at TEXT DEFAULT (datetime('now')));CREATE UNIQUE INDEX idx_task_key ON task_log(task_key);-- Idempotent execution: skip on a hit to avoid duplicate instructionsINSERT OR IGNORE INTO task_log(task_key, payload) VALUES (?, ?);
On the retrieval side, a hybrid strategy works best: structured filtering plus vector similarity. First narrow the candidate set with fields such as time, type, and status, then rank by semantic similarity inside that set. This avoids the cost of scanning vectors across the whole store while keeping recall quality high. Context injection should follow a minimal-sufficiency rule: put only the few memory fragments directly relevant to the current task into the prompt, rather than pasting in entire stretches of history. The latter is a common cause of runaway token cost.
It is worth stressing that the value of memory compounds rather than growing linearly. Once the system has accumulated enough task samples, the planning stage can reuse successful historical paths directly, compressing several rounds of trial and error into a single call.
3. Cost Governance: Model Routing and Letting Code Do the Work
Two orthogonal levers reduce cost, and stacking them produces the clearest effect.
The first is tiered model routing. Grade requests by complexity: deterministic work such as intent recognition, format conversion, and field extraction goes to a lightweight or low-cost model; only tasks that need long-chain reasoning or synthesis across documents get escalated to a more capable model. In practice, wrap a unified gateway around the call chain and let the gateway pick the route dynamically based on task labels, input length, and historical success rate, so business code stays unaware of the specific model.
def route(task):if task.kind in ("extract", "format", "classify"):return "light" # Low-cost modelif task.estimated_tokens > 8000 or task.needs_reasoning:return "strong" # High-capability modelreturn "standard"
The second lever has the larger payoff: deterministic tasks should generate code to run, not call the model over and over. The test is straightforward. If a stable rule exists between input and output, harden that rule into a script or a query and let the agent do nothing more than “write the code” and “step in when something breaks.” One code generation pass typically costs less than dozens of model round trips. In practice, moving work like report aggregation, log cleaning, and batch renaming from “ask the model every round” to “generate a script once, then run it on a schedule” is usually where the cost curve bends.
Two supporting practices: log token usage and task labels for every call to build a cost dashboard, and add a circuit breaker for repeatedly failing calls so that futile retries do not inflate the bill.
4. Always-On Agents on the Edge: Low-Power Devices
An always-on agent is sensitive to latency and availability, and the hardware does not need to be high spec. A low-power embedded device or an old phone can both host a lightweight agent runtime. The edge approach pays off in three ways.
First, access to local context. Sensor readings, notifications, battery level, and network state on the device can all serve as triggers or decision inputs, and a cloud-only design cannot get at them.
Second, genuine hardware-level automation. When a one-time passcode notification arrives, for example, the agent can parse it locally and fill the pending form directly, without uploading sensitive content to a remote service and waiting for it to come back.
Third, publishing actions complete locally, which removes the uncertainty and rate-limit exposure of routing everything through an external interface.
Engineering notes: an edge runtime is usually resource-constrained, so keep heavy reasoning on the remote side and only scheduling and execution locally; encrypt local credentials and restrict file permissions; and give the resident process a watchdog with automatic restart, restoring the task queue from the state layer after a restart so that “a restart never drops work.”
5. A Structured Control Panel: From Chat Window to Personal Knowledge Base
Using a chat tool as the only interface runs into information overload quickly: instructions, results, and alerts all land in one timeline that can be neither searched nor reused. A more mature approach is to make a local notes and knowledge base the control panel, with the agent collaborating by reading and writing documents.
A recommended directory convention:
vault/├── inbox/ # Inputs awaiting triage├── tasks/ # Task definitions and execution records├── skills/ # Skill descriptions (trigger + steps + verification)├── daily/ # Daily execution summaries└── reference/ # Long-term reference material
After each round of work, the agent appends a structured summary to daily/ and distills any reusable procedure into skills/. After feeding it for one to three weeks, the system models the user’s routine, priorities, and preferences in noticeably finer detail, and can surface pending items and generate recurring reports proactively instead of waiting passively for instructions.
6. Skills: Packaging Recurring Friction into Callable Capabilities
Real competitive advantage in the AI era comes from spotting the friction points that keep recurring and packaging them as skills. A sound skill definition has four elements: trigger condition, input contract, execution steps, and verification plus rollback.
name: monthly-finance-summarytrigger: "Last day of each month at 20:00, or on manual request"input: { period: "YYYY-MM", sources: ["reference/bills"] }steps:- Normalize bill fields and deduplicate- Generate an aggregation script and run it- Render conclusions against reference/templateverify: Total matches the sum of line items; otherwise flag the anomaly and keep intermediate artifactsrollback: Delete the files generated this run and restore the previous version
A short inventory is enough to find candidates: list the manual actions you repeated three or more times in the past month, rank them by “frequency × time per occurrence,” and package the top few first. Meal planning from what is in the fridge, recurring report analysis, and aggregated information summaries are all typical high-value entry points.
7. Rollout Path and Risk Boundaries
Roll out in four stages: first connect the state layer with task logs and idempotency; then add the unified model gateway for tiered routing and usage visibility; then migrate the interaction surface to the structured knowledge base; and finally build up the skill library over time.
Draw the risk boundaries up front as well: store credential references only, never plaintext; encrypt edge data and minimize what gets uploaded; require human confirmation for actions involving money, deletion, or external publishing; and keep rollback-capable intermediate artifacts and an audit log for every execution. If you need elastic compute, a managed runtime, or unified monitoring and alerting, general-purpose cloud product categories such as container platforms, logging services, and monitoring and alerting can carry that load — Baidu AI Cloud offers general-purpose infrastructure capabilities of this kind — so effort stays on the two things that actually determine results: memory design and skill abstraction.
