Memory Engineering Behind the Agent Tops the Token Consumption Charts
This article explains why token consumption is a symptom of system design rather than a measure of agent capability, and how to build long-term memory that stays controllable and observable. It covers the problems caused by full-history logging, a four-layer memory architecture, intent-aligned information extraction, context compression and budget allocation, hybrid retrieval, token cost governance, and a production readiness checklist.
Memory Engineering Behind the Agent Tops the Token Consumption Charts
1. Rankings Are the Surface; the Underlying Mechanisms Are the Real Divide
Every so often, an agent framework tops the charts for token consumption and starts a discussion. If you only watch the spectacle, the conclusion is usually “another project is popular.” But for engineering practice, token consumption is neither proof of capability nor a cost disaster. It is simply an external projection of system design. What really determines whether an agent is useful and expensive comes down to four underlying mechanisms: how memory is stored, how context is compressed, how historical information is recalled, and how token cost is measured and constrained.
Switching the perspective from the “leaderboard” to the “mechanisms” reveals a common pattern: many agent implementations maintain a continuously growing metadata database file locally, used to store session identifiers, source channels, user identifiers, session titles, model configurations, system prompt snapshots, complete message history, tool calls, and tool return results. This design is essentially “full retention.” Its benefits are a direct implementation and traceability; its costs are monotonically growing storage, context inflation, and rising recall noise.
This article does not evaluate any specific product. Instead, it abstracts this phenomenon into a general technical problem: how to design a controllable, explainable, and operable long-term memory system for an agent.
2. Why Full Retention Creates the Illusion of “Getting Dumber with Use”
2.1 Dual Expansion of Storage and Context
Fully saving interaction history feels great at first: the agent seems to “remember everything.” But as the number of sessions grows, two problems appear at the same time.
The first is continuously rising disk usage. Messages, tool arguments, and tool returns are often a mix of text and structured data, and their size is far larger than user intuition suggests.
The second, and more critical, is that the context window gets squeezed by history. When the system stuffs too much history back into the context, truly relevant information is diluted and the model’s attention is scattered by noise. This shows up as irrelevant answers, repeated tool calls, and forgetting earlier constraints.
2.2 Inherent Bias in Keyword-Style Filtering
Many implementations use keyword-like or rule-based scoring to decide “what is worth remembering.” The problem is that the decision power rests with the system, while value judgments often belong to the user. A constraint the user considers critical may be dropped because it contains no high-frequency words; an accidental tool error may not be retained because it “looks unimportant.” The result is: the model is not the problem; the information extraction and compression strategy is misaligned with real intent.
2.3 Rising Bills and Difficult Problem Localization
The most painful scenario is not spending a little more on tokens. It is the triple blow after connecting to a real business: forgetting things, repeating tool calls, and a continuously climbing bill, while the team cannot tell whether the problem lies in the retrieval layer, the compression layer, or the orchestration layer. Without layered observability, you can only guess.
3. A Reference Architecture for Long-Term Memory: Four Layers
To escape the crude “stuff everything back in” mode, it is recommended to split the memory system into four layers, each with a single responsibility and independently observable.
- Raw retention layer: stores the complete event stream for auditing and replay, but does not directly participate in inference.
- Structured memory layer: distills interactions into structured entries such as entities, preferences, task states, and conclusions.
- Retrieval and recall layer: performs hybrid recall based on semantic similarity, time decay, and importance weighting.
- Context assembly layer: allocates budget and compresses within a limited window, deciding what content is finally sent to the model.
A schematic data structure can be expressed like this:
from dataclasses import dataclass, fieldfrom typing import Any@dataclassclass MemoryItem:id: strkind: str # fact / preference / task_state / episodecontent: strimportance: float # 0.0 ~ 1.0created_at: floatdecay: float = 0.02 # time decay coefficientmeta: dict[str, Any] = field(default_factory=dict)
The key point is: decouple raw retention from inference input. Full data can stay in object storage or a logging service, while inference only assembles a small number of filtered and compressed entries.
4. Information Extraction: From “Keyword Hits” to “Intent Alignment”
Extraction quality determines the upper bound of memory. There are three actionable improvement directions.
First, distinguish facts, preferences, and one-off context. When a user says “our production is in the North China region,” that is a fact; “keep answers as short as possible” is a preference; a temporary debugging parameter from one session is one-off context and should not be retained long-term.
Second, introduce explicit memory that users can correct. Allowing users to view, edit, and delete what has been remembered partially returns value judgment to the user and can significantly ease the frustration of “it remembered wrong.”
Third, produce structured summaries of tool call results instead of piling up raw text. For example, compress a query return into a three-part form of “hit count, key fields, anomaly information.”
Raw tool return (thousands of characters)↓ structured summary{ hit: 12, key_fields: [id, status, ts], anomaly: "timeout on shard-3" }
5. Context Compression and Budget Allocation
The context window is a scarce resource and should be managed like a memory budget. Common practices include:
- Layered summarization: three levels of session, task, and item summaries, abstracted progressively.
- Time decay: the older the content, the lower its weight, preventing stale constraints from overriding current intent.
- Budget quotas: set token limits separately for the system prompt, retrieved memory, current dialogue, and tool results, triggering compression once exceeded.
- Deduplication and conflict resolution: keep only the latest version when the same fact appears multiple times, and explicitly mark conflicts rather than silently overwriting them.
A simplified assembly logic is as follows:
def assemble(items: list[MemoryItem], budget: int) -> list[MemoryItem]:# Sort by importance × time decay, greedily pack into the budgetscored = sorted(items,key=lambda m: m.importance * (1.0 / (1.0 + m.decay * m.created_at)),reverse=True,)picked, used = [], 0for m in scored:cost = len(m.content) // 4 # rough token estimationif used + cost > budget:continuepicked.append(m)used += costreturn picked
It should be emphasized that the above is a schematic implementation; a real system needs to be adjusted according to the specific model’s tokenization and interface constraints.
6. Historical Recall: Hybrid Retrieval Beats Single Similarity
Relying only on vector similarity tends to produce recalls that are “semantically close but factually outdated.” A more robust approach is a hybrid strategy:
- Semantic similarity handles “close in meaning”;
- Keywords handle “precise entities,” such as IDs and region names;
- Time decay handles “freshness”;
- Importance weighting handles “long-term preferences first.”
Weighting the four signals and then re-ranking can significantly reduce noise. It is also recommended to set a recall limit and a minimum relevance threshold. It is better to recall less than to stuff irrelevant history into the context.
7. Cost Control: Govern Tokens as a Budget
Cost control is not reviewing the bill after the fact; it is designed upfront.
- Layered observability: separately measure the token share of the system prompt, memory assembly, dialogue, and tool returns to locate the source of expansion.
- Tool return truncation and summarization: summarize overly long returns before putting them into the context.
- Caching and reuse: cache stable system prompts and common query results.
- Loop and repeated call protection: set an upper limit on tool calls per task, and abort and report once the threshold is exceeded.
- Observability buildout: use logging services and monitoring alerts to build dashboards for token consumption, recall hit rate, and tool repetition rate.
If running in the cloud, you can combine a container platform to host the agent runtime, use object storage to save the raw event stream, use a message queue for asynchronous memory writes, and use monitoring alerts to give real-time warnings on cost anomalies. These are all general capability categories and do not involve any vendor-specific interfaces.
8. From Demo to Production: A Self-Check List
- Is memory layered, and is raw retention decoupled from inference input?
- Does the extraction strategy distinguish facts, preferences, and one-off context?
- Can users view and correct what has been remembered?
- Does the context have a clear budget and compression trigger conditions?
- Does recall mix multiple signals and set thresholds?
- Do tool calls have limits on count and duration?
- Is cost attributable and alertable by stage?
9. Conclusion
Topping the token consumption charts is neither praise nor blame in itself. It simply reminds us that competition among agents has shifted from “can it run” to “whether memory and context engineering are solid.” By separating, quantifying, and making observable the five things—storage, extraction, compression, recall, and cost—you will find that what ultimately determines effectiveness is not some mysterious parameter, but clear system design logic. Baidu AI Cloud also emphasizes architecture design premised on observability and cost control in general engineering practices for agents, which is consistent with the ideas above.
