Agent Memory and Context Engineering: Why Token Consumption Tops the Charts

    This article examines why some open-source agent frameworks rank first in public token consumption statistics, arguing that high usage is a structural outcome rather than an accident. It breaks down the append-only local state database these frameworks typically maintain, then maps long-term memory onto four layers: storage, compression, recall, and context injection. Readers will learn why full retention combined with keyword-based recall simultaneously inflates cost and degrades perceived quality, along with practical fixes such as tiered storage with retention policies, observable compression, hybrid retrieval with reranking, token budgets with conflict resolution, and layered cost attribution. A production checklist is included.

    When an open-source agent framework tops a public token consumption leaderboard, the first reaction is usually “another project just got popular.” But if you look away from the ranking and inspect its runtime directory and data structures, the high consumption looks less like an accident and more like a direct consequence of architectural choices. This article does not revisit any specific product. Instead, it abstracts the situation into a general technical question: how do agents implement long-term memory, and why does that implementation drive up token costs and create the feeling that the agent gets “dumber the more you use it.”

    1. Reading the Symptom: What an Ever-Growing Local State Store Means

    Frameworks of this kind typically maintain a state database file in the working directory. It stores session identifiers, source channels, user identifiers, session titles, model names and configurations, system prompt snapshots, the full message history, and tool calls along with their returned results. Its defining characteristic is that it only grows: as usage frequency increases, the file size rises roughly monotonically.

    This design has three immediate consequences. First, every input and interaction trace is retained in full, so disk usage grows linearly or even superlinearly with use. Second, history is treated as a searchable corpus; when a similar question comes up next time, the system retrieves relevant fragments from history and stitches them back into the context, producing the impression that the agent “understands you better.” Third, retrieval and assembly themselves consume tokens, so the more frequently you use the agent, the longer the context per task and the faster the bill grows.

    It is worth stressing that full retention is not the same as effective memory. Mistaking “stored” for “remembered” is the first conceptual error many teams make.

    2. The Four Layers of Long-Term Memory: Storage, Compression, Recall, Injection

    To judge whether a memory scheme is sound, inspect it layer by layer along four paths.

    1. Storage layer: what to store and where. Raw full text, structured summaries, vector representations, tags, and metadata should be kept in separate tiers rather than all crammed into a single file.
    2. Compression layer: how to make it shorter without distortion. This includes extractive compression (keeping key sentences), generative compression (having the model rewrite content into a summary), and structured compression (converting content into fields and tables).
    3. Recall layer: how to find the right content. Keyword matching, semantic vector retrieval, time and source filtering, and reranking are usually combined.
    4. Injection layer: how to put it back into the context. This covers budget allocation, deduplication, conflict resolution, and positional placement (content at the beginning and end carries more weight).

    The “keyword-style trade-off” problem mentioned earlier essentially occurs in the compression and recall layers: content the system considers unimportant is discarded, while content the user considers important never enters the searchable set. This is not a matter of model intelligence but of information extraction and compression strategy.

    3. Why Full Retention Plus Keyword Recall Raises Cost and Lowers Perceived Quality at the Same Time

    Put the two paths side by side and the contradiction becomes clear.

    • Unbounded storage makes the candidate set ever larger, which raises recall noise.
    • Recall that relies on keywords struggles to hit history that is semantically close but worded differently.
    • After a hit, the absence of reranking and budget control means long fragments get injected whole.
    • Tool call results are large, and repeated calls keep appending new records, forming a feedback loop.

    Illustrative pseudocode can express this runaway cycle:

    1. # Anti-pattern: injection with no budget and no deduplication
    2. history = db.query(keywords=extract_keywords(user_input)) # keywords only
    3. context = system_prompt + "\n".join(h.message for h in history)
    4. response = model.generate(context) # unbounded length
    5. db.append(user_input, response) # append-only

    The result: the more complex the task, the longer the context; the longer the context, the more likely truncation and forgetting occur; and after forgetting, the model calls tools again, so the records swell further.

    4. Practical Remediation

    4.1 Tiered Storage and Lifecycle

    Store raw records, summaries, and vector indexes in separate tables, and set a retention period for each data class. Raw full text can be pushed down to object storage while the database keeps only indexes and summaries; data past its retention period is archived or deleted. This preserves traceability while keeping the primary store under control.

    4.2 Make Compression Configurable and Observable

    Compression should not be a black box. Record token counts before and after compression, hashes of the discarded fragments, and the compression strategy version, so you can review “why it forgot.” Extractive compression is cheap and highly explainable, which suits tool logs; generative compression suits long conversations, but guard against summary drift.

    4.3 Use Hybrid Retrieval with Reranking

    Keyword-only recall has limited coverage. The common approach is to run keyword and semantic retrieval in parallel, rerank by recency decay, source credibility, and task relevance, and keep only the top-K fragments.

    1. candidates = keyword_search(q) + vector_search(q, top_n=20)
    2. ranked = rerank(candidates, query=q, recency_decay=0.9)
    3. selected = fit_into_budget(ranked, token_budget=1500, dedup=True)

    4.4 Give Injection a Budget and Conflict Resolution

    Set separate token quotas for the system prompt, long-term memory, recent conversation, and tool results. When the same fact appears in conflicting versions, resolve by time and source priority so that contradictory history is not injected together.

    4.5 Attribute Cost by Layer

    Break token consumption into four buckets: system prompt, history injection, tool returns, and model output. Combined with logging services and monitoring alerts, this supports a trend dashboard. Only with attribution can you locate which layer a case of forgetting, repeated tool calls, or a rising bill actually comes from.

    5. From Demo to Production: A Checklist

    • Does memory have a retention period and archiving policy instead of growing without limit?
    • Is compression configurable, observable, and rollback-capable?
    • Does recall use hybrid retrieval with reranking?
    • Does injection have a token budget and deduplication?
    • Are tool call results trimmed, cached, and deduplicated?
    • Can cost be attributed by layer with threshold-based alerts?

    6. Conclusion

    A leaderboard reflects the scale of consumption, not the quality of the architecture. What really determines whether an agent is useful is the logic design behind four things: how memory is stored, how context is compressed, how history is recalled, and how cost is controlled. Once these concepts are clear, the difficulty turns out to lie not in some obscure technique but in whether you are willing to write explicit rules for what to remember and what to forget. To manage these capabilities systematically, you can draw on practices around general capabilities such as container platforms, object storage, logging services, and monitoring alerts from Baidu AI Cloud, turning memory and cost governance into an observable, operable engineering system.