AI Agent Long-Term Memory and Token Cost Control: An Engineering Breakdown
This article examines how AI agents implement long-term memory while controlling Token costs. It breaks the problem into memory storage, context compression, history recall, and cost governance; compares full retention, summarization, and structured layered memory; explains common distortion in extraction and compression; presents hybrid retrieval with reranking and Token budgets; and outlines observability metrics and an implementation checklist.
1. Beyond the Leaderboard: Four Layers of Engineering Capability to Break Down
Every so often, discussions arise about an agent topping a Token-consumption leaderboard. If you look only at the conclusion, it seems like just another open-source project gaining attention. But if you inspect its runtime directory, you often find a continuously growing local state database file. It stores fields such as session ID, source channel, user ID, session title, model name and configuration, system prompt snapshot, full message history, tool calls, and tool return results.
The essence of this design is not mysterious: persist all interactions to disk, then retrieve relevant fragments from history the next time a similar question appears and backfill them into the context, creating the effect of “understanding you better.” This is also why it can be described as self-evolving: the carrier of evolution is data, not model parameters.
Therefore, what is worth learning is not a specific project, but the four questions it must answer: how to store memory, how to compress context, how to recall history, and how to control Token costs. These four questions form the backbone of agent engineering.
2. Three Practical Forms of Long-Term Memory and Their Trade-offs
Form 1: Full retention. This is the simplest to implement and preserves information losslessly, but storage and retrieval costs grow linearly or even superlinearly over time, and backfilling can easily consume the context budget.
Form 2: Summary compression. Generate summaries by session or time window, using a small number of Tokens to carry long history. The cost is irreversible loss of detail.
Form 3: Structured layering. Split memory into working memory (current context), episodic memory (historical interactions), semantic memory (distilled facts and preferences), and procedural memory (tool and workflow experience), with layered storage and layered recall.
In engineering practice, a more robust approach is layered combination rather than choosing only one. A simplified state structure looks like this:
class MemoryRecord:session_id: struser_id: strcreated_at: floatkind: str # message / summary / fact / tool_tracecontent: strembedding: list[float] | Noneimportance: float # 0–1, used for eviction and priorityttl_days: int | None # hot/cold tiering and expiration policy
The key fields are kind and importance: the former determines the recall strategy, and the latter determines the eviction order. Without them, the system can only degrade to a crude “reverse chronological” strategy.
3. Information Extraction and Compression: Where Distortion Comes From
The original discussion points to a real pain point: the system believes key content has been retained, while the user believes key content has been discarded. This is not a model capability problem, but a design problem in the filtering and compression mechanism. There are four common sources of distortion:
- A single filtering signal. Relying only on keywords or frequency statistics misses semantic information such as references, negation, and conditional constraints. For example, in “Do not use this plan unless the budget doubles,” the real constraint is after the turn.
- Misaligned compression goals. Optimizing for “shorter length” rather than “preserving decision-relevant information” compresses away constraints, failure reasons, and explicit user corrections. These are exactly the basis for consistency in later behavior.
- No importance modeling. Without explicit scoring and user feedback loops, the system cannot distinguish one-off small talk from long-term preferences.
- Coarse backfilling strategy. Stuffing entire historical segments back into the context dilutes useful information and scatters model attention, which shows up as “forgetting” and “repeated tool calls.”
The improvement direction is “structure first, compress second, backfill last”:
Raw messages → fact/preference/constraint extraction → structured entries stored→ conflict detection and merging (new values overwrite old values; keep change history)→ rank by relevance + importance + freshness at retrieval→ backfill only Top-K within total Token budget
“Conflict detection and merging” is the easiest part to overlook. If a user said to use Plan A last week and says to switch to Plan B this week, and both entries coexist and are both recalled, the model’s behavior will become self-contradictory.
4. Recall: From Single Similarity to Hybrid Retrieval with Reranking
Pure vector similarity is good at semantic approximation, but insensitive to exact identifiers such as order numbers, error codes, and configuration items. Pure keyword retrieval is the opposite. A more stable combination in practice is: run keyword retrieval and vector retrieval in parallel, merge and deduplicate the candidates, pass them to a reranking model or rule-based scoring, and then truncate to the budget.
def recall(query, user_id, budget=1500):cand = bm25(query) + vector_search(query, top_k=20)cand = dedup(cand)cand = [c for c in cand if c.user_id == user_id] # isolate memories to avoid cross-user leakagecand.sort(key=lambda c: 0.6*c.score + 0.25*c.importance+ 0.15*recency(c), reverse=True)out, used = [], 0for c in cand:cost = estimate_tokens(c.content)if used + cost > budget:breakout.append(c); used += costreturn out
The user_id filter is not optional. If multiple users share one memory store without isolation, it is both a quality problem and a data safety problem.
5. Token Cost Structure and Governance Measures
Bill increases usually come from four places, and they need to be located separately: persistent overhead from system prompts and tool definitions, historical backfill overhead, overly long tool return results, and failed retries and looped calls. The corresponding measures are:
- Load tool definitions on demand instead of keeping them all resident;
- Use summaries plus layered recall for history, with a hard Token budget;
- Truncate and structurally trim tool returns, keeping only fields required for decisions;
- Set retry limits and backoff, and add idempotency checks for repeated calls.
Cold data can be moved down to object storage, while runtime logs and call chains can be handed to logging services and monitoring/alerting systems to form an observable loop.
6. Observability: Locate First, Optimize Later
The most frustrating scenario is this: the demo runs, but after connecting to real business traffic, the agent starts forgetting things, repeatedly calling tools, and costs climb day by day, yet it is unclear which layer is responsible. The way to break through is to split the chain into measurable metrics: memory write volume and compression ratio, recall hit rate and empty recall rate, per-request context Token composition, tool call count and success rate, and cost per task.
With these metrics, you can determine whether the problem lies in extraction (what should have been remembered was not), compression (it was remembered but lost), recall (it was stored but not found), or backfilling (it was found but not used effectively).
7. Implementation Checklist
- Design memory layering and define the lifecycle and eviction rules for each layer;
- In the extraction stage, distinguish four types of entries: facts, preferences, constraints, and failure experience;
- Introduce conflict merging and retain change history;
- Use hybrid retrieval plus reranking, and set a hard Token budget cap;
- Trim tool returns and deduplicate calls to suppress loops;
- Establish per-stage metrics and alerts, and locate problems by layer;
- Isolate memory by user and define clear data retention and deletion policies.
Ultimately, the upper bound of agent performance is not determined by a technical term, but by how you define the logic of “what should be remembered, what should be discarded, and what should be reused in the context.” Design this logic clearly, and cost becomes controllable. Otherwise, even the strongest model can only produce unstable answers from a chaotic context.
