Agent Token Consumption, Memory, and Context Engineering
This article explains why general-purpose AI agents can top token consumption rankings and what that reveals about their underlying design. It examines how persistent session databases store full interaction history, why full retention with keyword filtering falls short, and how to build a practical four-layer memory architecture spanning storage, extraction, compression, and retrieval. It also covers context compression, tool-call efficiency, and observable token cost governance for production systems.
1. What the Token Consumption Rankings Actually Tell Us
When a general-purpose agent framework tops the token consumption charts, stopping at “another project got popular” misses the real technical signal. Token consumption is essentially the product of interaction volume, context length, and call frequency. A high ranking usually means three things are happening at once: a large user base, long conversation histories carried in each session, and frequent tool calls with results fed back into the context.
So the question worth studying is not “who ranks first,” but: why does token consumption in these systems keep growing? The answer usually lies in their state persistence design.
2. The State Database: The Physical Carrier of Long-Term Memory
Open the local directory of one of these agents and you will typically find a steadily growing local database file. It serves as the session state store, with typical fields including:
- Session ID, source channel, platform, and user ID;
- Session title, model name, and inference configuration;
- System prompt snapshot;
- Complete message history;
- Tool call requests and tool return results.
This means everything the user inputs and the entire interaction trail is written to disk. The more often it is used, the larger the disk footprint and the longer the context that can be fed back. The so-called “self-evolution” or “it understands you better over time” is not mysterious in engineering terms: it retains the full interaction history and retrieves and reuses it in later similar tasks.
A schematic data structure can be abstracted as:
Session├── meta: sessionId, source, platform, userId, title├── model: name, config, systemPromptSnapshot└── messages[]├── role / content├── toolCalls[] -> name, arguments└── toolResults[] -> payload, status, latency
3. Is This the Best Long-Term Memory Approach?
The answer is no. Full retention combined with keyword-style filtering has three structural flaws:
- Selection bias: The system’s criteria for what is “important” do not match the user’s actual intent, so information the user considers critical may be discarded.
- Unbounded growth: Without tiering and eviction mechanisms, storage and retrieval costs rise monotonically.
- Coarse recall: Relying on keyword similarity alone struggles with references, omissions, and multi-turn rewrites.
Many developers think an agent is “not smart enough,” but the issue is often not model capability. It is a failure to understand the four underlying pipelines: how information is extracted, how it is compressed, how retention and discarding are decided, and how it is put back into the context.
4. A Practical Four-Layer Memory Architecture
1. Storage Layer: Tiered, Not Full Retention
Divide memory into working memory (the current session window), episodic memory (summaries of past sessions), and semantic memory (user preferences and domain facts). Separate hot and cold data: keep hot data local or in cache, and move cold data to object storage.
2. Extraction Layer: From Keywords to Structured Extraction
Extract free text into four structured entry types—facts, preferences, tasks, and conclusions—each with a confidence score and timestamp. This keeps small talk and noise out of long-term memory.
3. Compression Layer: Summary + Vector + Symbolic Hybrid
Apply recursive summarization to long histories, vectorize semantic fragments, and preserve key constraints as original symbolic expressions. Compression must be traceable, retaining references that point back to the original records.
4. Retrieval Layer: Hybrid Retrieval with Budget Control
Use hybrid recall combining keywords, vectors, and structured filters, then trim by token budget:
budget = contextWindow - systemPrompt - currentTurnscore = α * relevance + β * recency + γ * importanceselect top-k until budget exhausted
5. Engineering Essentials for Context Compression and Tool Calls
Context compression must distinguish what is “droppable” from what is “not droppable”: system constraints, hard user requirements, and unfinished tool contracts cannot be dropped; repeated logs and lengthy raw returns can be. For tool calls, common waste comes from parameters that fail to converge and from feeding back full results. Switch to paginated retrieval, result summarization, and capped retry limits, and apply idempotent deduplication to repeated calls.
6. Token Cost Governance
Cost governance must be observable: instrument metrics across three dimensions—session, user, and tool—recording input/output tokens, cache hit rate, and tool latency, and configure budget thresholds and alerts. The real pain point is not how many extra tokens a single call consumed, but that after launch, forgetting, repeated calls, and rising bills appear with no way to locate which layer the problem is in.
7. Conclusion
The gap between “a demo that runs” and “a production system you can operate” is not about showing off. It comes down to four fundamentals: how memory is stored, how context is compressed, how history is recalled, and how cost is controlled. In the general-purpose capability systems of cloud platforms such as Baidu AI Cloud, categories like object storage, message queues, container platforms, logging services, and monitoring and alerting can all be used to support the tiered design above. Once you clarify these concepts, you will find that an agent’s core competitive edge is your logic design, not some advanced technique.
