AI Agent Long-Term Memory: Architecture and Engineering Practices
This article examines how long-term memory systems in AI agents work in practice. Starting from the attention around token consumption, it explains where agent memory is stored, how context is compressed and filtered, how historical information is recalled and reinjected, and why token costs can spiral. It then outlines production symptoms such as forgetting, repeated tool calls, and budget overruns, and summarizes engineering practices for storage, compression, recall, and cost control.
1. Starting from “Token Consumption First”: The Engineering Problems Behind the Hype
Recently, news that “an open-source agent project had become the top token consumer worldwide” sparked a good deal of discussion in the developer community. At surface level, this looks like just another agent project climbing a leaderboard. But for developers who care about agent engineering, the interesting question is not “who made the list again.” It is the set of core problems the event exposes:
- How is an agent’s memory actually stored?
- How is context compressed and filtered?
- How is historical information recalled and reinjected into the conversation?
- How do token costs get out of control as a result?
This article unpacks a typical agent memory system around these four questions.
2. Where Agent Memory Lives: The Design Logic Behind state.db
If you have ever inspected the directory structure of a mainstream open-source agent project, you have probably found a local database file, commonly named something like state.db. In theory, this file can grow without limit. It stores almost every piece of interaction information between you and the agent, including but not limited to:
- Session identifiers: session ID, source platform, user ID, session title;
- Model configuration: model name, model parameters, system prompt snapshot;
- Full message history: user input, model output, message timestamps;
- Tool call records: input parameters, return results, and execution status for each tool call.
This means that all the information you enter and all your interaction history are persisted to local disk. As long as you use the agent frequently, it will keep consuming your storage space.
From an architectural perspective, this “full persistence” design is the technical basis for many agents’ claims that they can “improve themselves” or “evolve themselves.” Put simply, the system saves all interaction history. When you encounter a similar or related question next time, it retrieves relevant content from the historical conversation records in the database, reinjects it into context, and produces the effect of “understanding you better.”
The advantages of this design are straightforward:
- Simple to implement; an embedded database is enough;
- Data remains fully local, with a clear privacy boundary;
- Historical information is retained losslessly, so any interaction is theoretically traceable.
But it also creates three risks: unlimited disk growth, a lack of structured governance for historical data, and most importantly, recall quality depends entirely on retrieval and filtering strategy.
3. The Cost of “Understanding You Better”: The Hard Problem of Information Compression and Trade-offs
So is storing all interaction history the best way to achieve long-term memory? In real usage, the answer is no.
In practice, I have found that the information extraction methods used by these systems are fairly simple, similar to keyword-matching-style filtering. The system keeps what it considers important, but discards content that I consider important while the system does not. This creates a common user-experience gap: many people feel that the agent is “not that smart.”
It is worth emphasizing that this is often not a failure of model capability. Rather, users do not understand the underlying logic. An agent’s memory system essentially has to answer four questions:
- How to extract information: from a conversation, which entities, conclusions, preferences, and constraints are worth persisting as memories?
- How to compress information: a long conversation cannot all be put back into context. How can summarization and merging be done without losing key information?
- How to decide what to keep and what to discard: what are the criteria for importance? Frequency, emotional intensity, explicit user instructions, or the model’s own subjective score?
- How to put history back into context: how many items to recall, in what order, within what token budget, and how to avoid conflict between recalled content and the current task?
The following illustrative pseudocode describes a typical memory read/write flow:
# Write memories (triggered after a conversation ends)def extract_memories(session):candidates = llm_extract(session.messages) # Model extracts candidate memoriesfor mem in candidates:score = importance_score(mem) # Importance scoringif score > THRESHOLD:memory_store.upsert(mem, score) # Write to memory store# Otherwise discard directly — information loss happens here# Read memories (triggered before a new conversation starts)def recall_memories(query, budget_tokens):hits = memory_store.search(query, top_k=20) # Semantic/keyword retrievalranked = rerank(hits, by="score + recency") # Rerankingselected = truncate_to_budget(ranked, budget_tokens)return selected # Inject into system prompt or context
As the example shows, the root cause of “forgetting” is often not the storage layer. It lies in two gates: the extraction threshold and the recall budget.
4. Why Your Agent Forgets Things, Repeatedly Calls Tools, and Keeps Raising the Bill
Many teams get an agent running by following tutorials, and everything works fine during the demo. But once they connect it to a real production workflow, problems begin to erupt:
- It starts forgetting things: a constraint explicitly stated yesterday is gone today, because that piece of information was judged “unimportant” during extraction and discarded;
- It repeatedly calls tools: historical tool-call results are not correctly recalled, so the agent runs the same query again and again, wasting tokens and slowing responses;
- The bill spirals: to “compensate” for missing memory, many people simply enlarge the context window and increase the number of recalled items. As a result, each turn carries more and more historical baggage, and token consumption rises linearly or even exponentially;
- Problems are hard to locate: when something goes wrong, it is unclear which layer to inspect. Did extraction miss it? Did retrieval fail to hit it? Or was it truncated during injection?
The biggest problem is not how many extra tokens the agent consumes. It is that you cannot even find which layer the problem is hiding in. That is the real engineering difficulty of long-term memory systems.
5. What Is Worth Learning Is the Method, Not the Project Itself
So the thing truly worth studying is not “yet another agent project.” It is the four general technical concerns behind it:
1. How to store memory
Do not rely only on a “full message log.” A better approach is layered storage: raw interaction logs for audit and traceability, and structured memories (facts, preferences, conclusions) for daily recall, with the two linked by session ID. At the same time, add metadata such as timestamps, source, and confidence to memories, leaving room for later eviction strategies.
2. How to compress context
Commonly accepted industry practices include rolling summaries (generating summaries for older conversations to replace the original text), selective retention (keeping key decision points while discarding greetings and intermediate states), and structured merging (combining similar information from multiple interactions into one item). The goal of compression is not “the shorter the better.” It is to preserve the highest-information-entropy parts within the token budget.
3. How to recall historical information
Recall quality = retrieval capability × ranking strategy × budget allocation. Keyword matching covers only cases with literal overlap. Semantic retrieval covers cases where the wording differs but the intent is similar. Combining the two and then reranking is a complete approach. In addition, control the injection position and format so that recalled content does not dilute the instruction strength of the system prompt.
4. How to control token cost
Establishing observability is the first step: record the token composition of each conversation turn (how much is system prompt, injected history, and tool results), so you know where the money goes. On that basis, optimize item by item through history compression, on-demand recall, and tool-result trimming. If these capabilities need to be carried into production, general cloud platform services such as logging, monitoring and alerting, and object storage can also support persistence and cost auditing of memory data, without building infrastructure from scratch.
6. Final Thoughts
“Token consumption first” is essentially an outcome metric. It reflects the combined trade-offs a memory architecture makes across four stages: storage, compression, recall, and control. For developers, rather than chasing a specific agent project, it is more useful to study its memory system as an engineering sample: understand how information is extracted, how it is compressed, how decisions are made to keep or discard it, and how it is reinjected into context. Once you understand this chain, no matter how many new agent frameworks appear in the future, you can quickly judge whether their memory design is a solid engineering solution or merely a lazy implementation that “stores everything.”
