AI Agent Long-Term Memory Design and Token Cost Control
This article explains how agent long-term memory is typically implemented through local state stores, why full-history retention drives both disk and token costs, and how extraction, compression, recall, and context injection affect reliability. It presents a layered memory architecture with schema examples and a practical checklist for keeping token consumption under control.
AI Agent Long-Term Memory Design and Token Cost Control
Many developers encounter a similar problem after they first connect an agent to their daily workflow: it works well at first, but after a few weeks it starts to “forget” things, repeatedly calls the same tools, and steadily increases the bill—without an obvious indication of which layer is responsible. Recent industry discussions about an open-source agent framework ranking high on token-consumption leaderboards because of massive interaction volume have pushed these usually overlooked underlying mechanisms into the spotlight. This article does not discuss a specific project. Instead, it breaks down the common technical issues behind this phenomenon: how agent long-term memory is actually implemented, why it creates pressure on both disk storage and token usage, and how to design a more reasonable memory system.
1. Session State Stores: The Material Basis for Agent “Self-Evolution”
Many popular open-source agent frameworks maintain a local state database file in their working directory, commonly a SQLite file such as state.db. This file usually stores several categories of information:
- Session metadata: Session ID, source channel, user identifier, session title
- Model configuration: model name, parameter settings, system prompt snapshot
- Full message history: user input, model responses, tool calls, and tool return results
From a design-intent perspective, this is a “full-trace retention” strategy: all interactions are persisted as searchable data. When the user asks a similar question next time, the framework can recall relevant fragments from historical records, inject them into the context, and create the effect of “understanding you better over time.” This is also the underlying principle behind many frameworks’ claims of “self-improvement” and “self-evolution”—what is called evolution is essentially turning interaction history into reusable context assets.
But the cost of this design is obvious: the state database can theoretically grow without bound. As long as the agent is used frequently, messages, tool call results, and system prompt snapshots will continue to be appended, and disk usage will rise accordingly. The more hidden cost is on the token side—every recalled historical item is inserted back into the context window, consuming real inference budget.
2. Why Many Agents Are “Not That Smart”: Four Gaps in Memory Mechanisms
Poor user experience is often caused not by insufficient model capability, but by a rough memory pipeline in the following four areas:
1. Information extraction: what counts as “key content”?
Many frameworks use approximate keyword or heuristic rules to decide which content is worth persisting. The problem is that the criteria for “key” are not aligned between the system and the user: things the system considers key, such as explicit task descriptions, are saved, while content the user considers important but expresses implicitly—such as an occasional correction or an implied preference—may be discarded. This misalignment accumulates over time, causing the agent to repeatedly make mistakes the user has already corrected.
2. Information compression: how should history be reduced?
Storing everything does not mean using everything. A mature memory system needs to compress at write time or recall time—folding lengthy conversations into summaries, distilling raw JSON returned by tools into conclusions, and merging repeated preference expressions into a single user profile. If the compression strategy is too aggressive, details are lost; if it is too conservative, the context expands rapidly. This is fundamentally a trade-off between information fidelity and context budget, and there is no free lunch.
3. History recall: how do relevant items get retrieved?
Common recall methods include exact keyword matching, semantic similarity retrieval based on vector embeddings, and hybrid retrieval combining both. Keyword approaches are simple to implement but have low recall—if the wording changes, the item may not be found. Vector approaches generalize better semantically, but they are less effective than keywords for proper nouns, code snippets, and other exact-match scenarios. Choosing a single approach without considering the specific usage scenario is a direct cause of poor memory in many agents.
4. Context reinjection: when and in what form should recalled content be inserted?
How recalled content is organized into the prompt also has a major impact. Should three years of history be inserted all at once, or sorted by relevance and truncated according to a budget? Should the original historical text be preserved, or rewritten into a structured “fact list”? The former causes severe context pollution and high cost; the latter is closer to a usable long-term memory format.
3. A More Reasonable Layered Memory Architecture
Based on widely recognized industry best practices, an engineering-sustainable agent memory system is usually divided into four layers:
┌─────────────────────────────────────┐│ Working memory: full context of the current session, archived when the session ends │├─────────────────────────────────────┤│ Episodic memory: session-level summaries + key event indexes │├─────────────────────────────────────┤│ Semantic memory: user preferences, facts, and decision records extracted from history │├─────────────────────────────────────┤│ Procedural memory: retained workflow templates and tool usage experience │└─────────────────────────────────────┘
The corresponding persistence table structure can be abstracted as follows:
CREATE TABLE session (session_id TEXT PRIMARY KEY,user_id TEXT,summary TEXT, -- Summary generated after the session endscreated_at TIMESTAMP);CREATE TABLE memory_item (memory_id TEXT PRIMARY KEY,user_id TEXT,content TEXT, -- Compressed fact/preferenceembedding BLOB, -- Vector indeximportance REAL, -- Importance score, used for evictionlast_hit_at TIMESTAMP -- Last recall time, used for decay);
Several key design points:
- Compress at write time, not read time: Generate a summary and extract memory items immediately when a session ends, avoiding the need to spend tokens on temporary compression during every recall.
- Introduce importance and decay mechanisms: Assign an importance score to each memory item, and downweight or archive items that have not been recalled for a long time to prevent the state database from growing without bound.
- Use hybrid retrieval: Keywords handle exact matches such as usernames, project names, and code symbols; vectors handle semantic generalization. Merge and deduplicate the two result sets, then truncate by score.
4. A Practical Checklist for Token Cost Control
The memory system directly determines the token consumption curve. The following are actionable control measures:
- Set a hard budget for reinjected content: Set an upper limit for the proportion of context occupied by recalled history, such as no more than 25%, and truncate the excess by relevance ranking.
- Compress tool return results before storing them: For raw JSON and long logs, keep only conclusions and key fields to avoid a “garbage in, garbage out” cycle that amplifies costs.
- Deduplicate system prompt snapshots: When configuration changes, store only the differences instead of copying the full system prompt for every session.
- Use summaries instead of long histories: For sessions exceeding N turns, replace turn-by-turn history injection with a rolling summary.
- Establish cost observability: Track token consumption by session and by memory module, and use general logging, monitoring, and alerting capabilities to locate “cost black holes”—most billing anomalies are hidden in some low-value memory block that is repeatedly recalled.
5. Conclusion
Returning to the phenomenon at the beginning: an agent framework topping token-consumption rankings may look like excitement on a leaderboard, but it actually exposes a common problem in long-term memory design—full storage is simple and crude, compression and recall strategies are rough, and costs keep accumulating at a layer users cannot see. For developers, what is truly worth studying is never “which new agent project has appeared,” but the four general questions behind it: how should memory be stored, how should context be compressed, how should historical information be recalled, and how should token costs be controlled. Once you understand these four things, you can judge whether a framework’s memory mechanism is reliable no matter which framework you switch to—and you can fill in that missing layer yourself when it is not.
