Agent Token Consumption, Memory, and Context Engineering
As an AI agent framework gains attention for ranking first in global token consumption, the discussion often turns into jokes rather than engineering analysis. This article looks past the ranking to explain why agent state databases keep growing, how so-called self-improvement usually comes from retaining and reusing interaction history rather than updating model weights, and how to manage memory and context in production. It covers a four-layer memory structure, compression trade-offs, hybrid history recall with token budgets, four layers of observability for cost control, and a checklist for moving from demo to production. Readers will learn practical ways to keep both cost and output quality under control.
Introduction: Beyond the Ranking
When an agent framework enters public view as the “world’s number one in token consumption,” the community’s first reaction is often emotional. Jokes reduce a complex systems engineering problem to a catchy line. But if we stop at the spectacle, we miss the part that actually matters.
Any agent with a self-evolution capability almost inevitably has a state database file in its directory that keeps growing. It typically stores session identifiers, source channels, platform and user identifiers, session titles, model names and configurations, snapshots of system prompts, full message history, tool call records, and tool return results. In other words, every message you type and every interaction you have may be written to disk. The more you use it, the more storage it consumes.
This explains a common misunderstanding. What looks like “self-improvement” is often not updated model weights. It is complete retention of interaction history, which is retrieved and re-injected into context in similar later scenarios, producing the effect of an agent that “understands you better.” Understanding this is the first threshold for context engineering.
1. Why the State Database Grows Without Bound
An agent’s “memory” is essentially data, and data accumulates by nature. In a moderately heavy usage scenario, a single day can generate tens of thousands of messages, each carrying tool call arguments and return payloads. Without boundaries, storage and retrieval costs expand together.
Growth itself is not the problem. The lack of lifecycle management is. Production-grade solutions usually set limits at three levels:
- Storage layer: hot and cold tiering, with recent sessions kept on fast storage and older sessions moved down to object storage;
- Data layer: partitioning by session and time, with a trimmable retention policy;
- Semantic layer: summarizing and compressing raw records, keeping only reusable conclusions and preferences.
A sample retention policy can be expressed as follows:
retention_policy = {"raw_messages": {"ttl_days": 7, "action": "archive"},"session_summary": {"ttl_days": 180, "action": "keep"},"user_preference": {"ttl_days": None, "action": "keep"},"tool_result": {"ttl_days": 3, "action": "drop"}}
The core idea is that raw interactions are process data, while summaries and preferences are asset data. The two must be treated differently.
2. The Four-Layer Structure of Memory: From Raw Text to Preferences
Treating “memory” as one big file is the most common beginner mistake. A more reliable engineering approach is to layer it:
- Raw layer: complete messages and tool call records, used for auditing and traceback;
- Summary layer: compressed conclusions generated per session, used for cross-session recall;
- Fact layer: structured user preferences, project conventions, and environment parameters;
- Index layer: vector indexes and keyword indexes that serve as retrieval entry points.
Once layered, the question of “what to keep” no longer depends on a single judgment. Each layer carries its own responsibility. The raw layer pursues completeness, the summary layer pursues accuracy, the fact layer pursues stability, and the index layer pursues speed.
3. Information Compression: Why It Is “Not That Smart”
The original text makes a key observation: the agent’s approach is close to keyword matching. Content the system considers important is retained, while content the user considers important may be discarded. This is the direct result of compression trade-offs.
Common compression methods include:
- Truncation: keep the most recent N turns. Simple, but prone to losing early constraints;
- Summarization: a second pass by the model. Low cost, but may distort meaning;
- Structured extraction: turn the conversation into “goal-constraint-conclusion” triples, with the best explainability;
- Importance scoring: weighting based on repetition, imperative statements, and explicit markers.
The problem often lies in who defines “importance.” When the system’s default weights conflict with the user’s real intent, you get “it forgot what I emphasized.” The direction for improvement is not a larger model, but partially returning the right to define importance to the user, for example by supporting explicit markers and manual confirmation:
[PIN] All API responses in this project use UTC for timestamps[PIN] Database connection strings must never be written to logs
Marked content enters the fact layer and does not participate in routine compression, which prevents it from being dropped at the mechanism level.
4. History Recall: Putting the Right Content Back into Context
Recall determines whether “memory” translates into results. Engineering practice usually mixes three paths:
- Keyword recall: exact matching of identifiers, function names, and error codes. High hit rate but weak semantics;
- Vector recall: semantically similar content, suitable for vague descriptions but may introduce noise;
- Structured recall: filtering by session, project, and time. Stable and controllable.
The recommended order in practice is “filter first, then semantic, then keyword as a fallback,” with budget control applied to recall results:
def build_context(query, budget=6000):facts = fetch_pinned_facts() # highest priorityhist = vector_search(query, top_k=5)exact = keyword_search(query, top_k=3)merged = dedup(facts + hist + exact)return truncate_by_token(merged, budget) # unified token budget
The key point is that recall must have a budget cap. Recall without a budget means handing the bill to luck.
5. Token Cost Control: Four Layers of Observability
What is most painful is not how many extra tokens the agent consumes. It is that after integration into real work, it starts forgetting things, repeatedly calling tools, and driving the bill up while you cannot locate which layer the problem is in. The prerequisite for cost control is observability, and at least four layers of metrics are recommended:
- Input layer: the share of system prompts and tool definitions, often the largest fixed overhead;
- Recall layer: the number of history items and tokens injected each time;
- Loop layer: the number of repeated tool calls and ineffective retries;
- Output layer: single-turn output length and summarization frequency.
A practical constraint is to set a “tool call deduplication window” and a “per-task token cap.” When the same tool is called repeatedly within a short window, force it through cache or require the model to explain why. Such mechanisms do not change model capability but can significantly suppress nonlinear growth of the bill.
6. From Demo to Production: A Checklist
- Have retention and archiving policies been defined for state data;
- Have raw records been separated from reusable assets;
- Are users allowed to explicitly mark key constraints;
- Does recall have a token budget and deduplication;
- Are layered observability metrics and alerts in place;
- Are deduplication and caps set for tool calls.
Conclusion
An agent topping the token consumption chart is essentially a reminder: competition has shifted from “can it run” to “how memory is stored, how context is compressed, how history is recalled, and how cost is controlled.” None of these four things is mysterious, and none depends on a single special technology. They test the developer’s ability to design system boundaries. Get the logic right, and the model is only one part of it. Draw the boundaries clearly, and both the bill and the results become controllable. To manage these capabilities systematically, you can build your own context engineering foundation on the combination of general capabilities offered by Baidu AI Cloud, such as container platforms, log services, monitoring and alerting, and object storage.
