AI Agent Token Consumption: A Practical Guide to Long-Term Memory and Context Engineering
This article examines why AI agents consume large amounts of tokens during long-running, multi-turn interactions and what that reveals about agent infrastructure. It breaks down the three main drivers of token growth, the problems caused by a single ever-growing local state database, and the difference between retrieval-augmented "self-improvement" and actual model updates. It then presents a four-layer memory architecture, four composable context compression techniques, hybrid retrieval with reranking, and a cost control approach built on observability, budgets, and graceful degradation. A minimal production checklist is included for teams moving from demo to deployment.
Recently, an open-source AI agent project topped a token consumption ranking and triggered a lot of discussion. On the surface, this is just another open-source project going viral. But if you look into its runtime directory and how it organizes data, the real signal is not the ranking itself. It is the engineering cost the system pays to stay “continuously present,” and the common infrastructure problems this exposes.
This article does not evaluate any specific product. Instead, it abstracts the phenomenon into a general technical question: when an agent needs to run long-term, interact continuously, and claim “self-evolution” capabilities, how should it store memory, compress context, recall history, and constrain token cost? Explaining these four things clearly is more valuable than remembering any leaderboard.
1. What Topping the Token Ranking Means: From Hype to Bill
High token consumption is usually not caused by a single factor, but by three behaviors stacking up.
The first is repeated injection of long history. Many agent implementations concatenate the entire conversation history into the context. As turns increase, the input tokens per request grow, roughly linearly or even superlinearly.
The second is amplification from tool call loops. When information is insufficient, the model repeatedly calls tools such as retrieval, calculation, and read/write. Each call and its return occupy context, and a single task can trigger multiple “think-call-observe” loops.
The third is memory writing and replay. To “understand the user better,” the system writes interactions into a local database and retrieves them for later tasks. Writing itself does not consume model tokens, but replay does.
So the top ranking is more of a signal: the system’s memory and context strategy leans toward “store more, replay more,” trading tokens for continuity. This is not a mistake, but it is a clear tradeoff.
2. A Typical Local State Store: The Chain Reaction of Unbounded Growth
Many agent implementations maintain a local state database file in the working directory to store nearly all interaction metadata. Common fields include:
SessionIDsource / platformuser_idsession_titlemodel_name / model_configsystem_prompt_snapshotfull_message_historytool_calls / tool_results
The advantage of this design is that it is simple, auditable, and replayable. The drawbacks are equally obvious.
- Monotonic size growth. Full message history means disk usage keeps rising with usage time, eventually requiring archiving and cleanup policies.
- Privacy and compliance pressure. System prompt snapshots, user identifiers, and complete conversations are all sensitive data, requiring encryption, masking, retention limits, and deletion mechanisms.
- High recovery cost. The larger the file, the slower retrieval, backup, and migration become, which lengthens failure recovery time.
- Uncontrollable context replay. Without compression and filtering, history returns to the context as-is, and cost rises accordingly.
A more robust engineering approach is to separate “raw facts” from “replayable context”: keep the raw layer in object storage or cold storage for low-cost retention, and keep only structured summaries and retrieval indexes in the hot layer, generating injectable context fragments by policy.
3. What “Self-Evolution” Really Means: Retrieval Augmentation, Not Parameter Updates
In most engineering implementations, so-called “self-improvement” does not mean model weights are updated. It means historical interactions are used as an external knowledge source, retrieved and injected into context when similar problems arise. Its essence is retrieval augmentation, and its effectiveness depends on retrieval quality, not on “how much is stored.”
This explains a common perception: the agent “is not that smart.” The reason is often not the model, but the policies in three areas:
- Information extraction: what counts as a “key fragment,” and who decides;
- Information compression: summary granularity, which entities and constraints to keep;
- Eviction and recall: what should be forgotten, and what should be re-injected.
If extraction rules are too coarse (for example, matching only by keyword), content the user considers important may be discarded, and the model naturally “forgets.”
4. Memory Tiering: Decoupling Storing from Using
The recommended general architecture is four-layer memory:
| Layer | Content | Lifecycle | Directly in context |
|---|---|---|---|
| Raw layer | Full messages, tool results | Long-term, low-cost storage | No |
| Summary layer | Session summaries, task conclusions | Mid-term | Selective |
| Fact layer | User preferences, constraints | Long-term, updatable | Yes (small amount) |
| Index layer | Vector/keyword indexes | Same as raw layer | No, retrieval only |
The key principle is: the context window holds only what the current task requires, and everything else is retrieved on demand. This preserves continuity while avoiding full replay every turn.
Illustrative retrieval and assembly logic:
def build_context(task, facts, retriever, budget=2000):# 1) Inject a small set of stable facts firstctx = render_facts(facts)[:budget]# 2) Retrieve historical fragments by taskhits = retriever.search(task, top_k=5)for h in hits:snippet = summarize(h) # compress before injectionif len(ctx) + len(snippet) > budget:breakctx += snippetreturn ctx
5. Context Compression: Four Composable Techniques
- Sliding window: keep only the most recent N turns. Simple to implement, but prone to losing early constraints.
- Recursive summarization: summarize old conversations in segments, then summarize the summaries. Controls length but may lose details.
- Structured extraction: extract conversations into four-tuples of “goal-constraint-conclusion-todo,” with the highest information density.
- Tool result trimming: truncate, paginate, and filter fields for long text returns to avoid a single observation blowing up the window.
In practice, combine them: recent raw text + mid-term structured summaries + long-term fact entries.
6. Recall Strategy: Hybrid Retrieval and Reranking
Each single retrieval method has weaknesses. A common industry practice is hybrid retrieval plus lightweight reranking:
score = α * keyword_score + β * vector_score + γ * recency_score
- Keyword retrieval is good at proper nouns, IDs, and error codes;
- Vector retrieval is good at semantically similar but differently phrased content;
- The recency factor ensures recent constraints take priority.
Reranking can use a cross-encoder or rules (such as weighting fragments that contain explicit user constraints), improving hit rate within a limited candidate set and avoiding stuffing irrelevant history back into the context.
7. Cost Control: Observable, Budgetable, Degradable
Cost governance should land on three levels.
Observable: record input/output tokens, tool call counts, retrieval hits, and cache hits for each request, forming cost views by session and by task.
Budgetable: set token limits and tool call limits per task, triggering degradation when exceeded.
Degradable: prefer summaries over raw text, reduce top_k, disable non-essential tools, and enable result caching for repeated requests.
budget:max_input_tokens: 8000max_tool_calls: 6on_exceed: summarize_onlycache:exact_match: truesemantic_threshold: 0.92
It is important to note that caching and summarization both introduce consistency risks and must be paired with invalidation policies and version markers.
8. From Demo to Production: A Minimal Viable Checklist
- Is memory tiering implemented, and does the raw layer use low-cost storage with a retention period;
- Are sensitive fields encrypted and masked, and is per-user deletion supported;
- Does the context have a hard budget, and can it degrade when exceeded;
- Is retrieval hybrid with reranking, and is there a “no hit” fallback;
- Do tool calls have count and timeout limits, and can they be retried idempotently;
- Is there a per-session cost dashboard and alerting;
- Is there a regression evaluation set measuring accuracy on “remembering key constraints.”
Conclusion
The real lesson from topping the token consumption ranking is not “who is stronger.” It is a reminder to developers that an agent’s core competitiveness lies in engineering details: how memory is stored, how context is compressed, how history is recalled, and how cost is controlled. Once you understand these concepts, return to the business logic itself, and you will find that the upper limit of effectiveness is often determined not by model parameters, but by how you organize the information flow. To further systematize these capabilities, you can refer to the practice documentation of Baidu AI Cloud in general product categories such as container platforms, object storage, log services, and monitoring and alerting, to build an observable, budgetable, and evolvable agent infrastructure.
