Agent Token Consumption and the Memory Engineering Behind It
As AI agents top the charts in token consumption, the real story is a long-underestimated engineering problem: how an agent actually remembers you. This article abstracts common memory implementations into four core challenges—how memory is stored, how context is compressed, how history is recalled, and how token costs are controlled—and offers practical design approaches for each, from full retention and structured extraction to layered summarization, hybrid retrieval, cost governance, and production-grade observability.
Agent token consumption has surged to the top, and while this looks like another technology hotspot, it actually pushes a long-underestimated engineering problem into the spotlight: how exactly does an agent “remember” you? One common approach in the industry is to maintain a continuously growing local state database file that persists session identifiers, source channels, user identifiers, session titles, model names and configurations, system prompt snapshots, complete message history, tool calls, and tool return results. The logic is not mysterious: retain all interactions in full, then retrieve relevant content from history when a similar question arises and stitch it back into the context, which makes the agent appear to “understand you better.” This article does not evaluate any specific implementation. Instead, it abstracts the problem into four general engineering questions—how memory is stored, how context is compressed, how historical information is recalled, and how token costs are controlled—and provides actionable design ideas.
Full Retention: A Source of Capability and Complexity
The biggest advantage of full retention is that no information is lost. It has a low implementation barrier and a strong ability to reconstruct past interactions. But the costs are equally clear. First, storage grows monotonically: the more sessions there are and the longer the tool returns, the less controllable disk usage becomes. Second, there is privacy and compliance pressure, because system prompts, user identifiers, and complete messages may all contain sensitive information, requiring classification, redaction, and retention-period policies. Third, “being able to store it” is not the same as “being able to use it,” because retrieval noise is amplified as data volume increases. For this reason, production-grade solutions usually add a layer of structured distillation on top of the raw stream: they split long conversations into entries such as events, conclusions, preferences, and to-dos, annotate them with time, source, and confidence, and form searchable memory units that can be retired, rather than relying only on a single infinitely growing log.
The Limits of Keyword-Style Extraction: Why It Is “Not That Smart”
Many implementations use keyword-like heuristics to decide “what is worth remembering.” The problem is that the machine holds the decision power, and its selection criteria may not match the user’s: what the user considers key may be judged unimportant and discarded, while small talk and repeated content are retained, diluting useful information. A more rigorous approach breaks extraction into three observable steps: candidate generation, significance scoring, and deduplication/merge. A sketch:
def extract_memory(messages):candidates = []for m in messages:if m.role in ("user", "tool"):candidates.append(m)scored = [(significance(c), c) for c in candidates]scored.sort(reverse=True)kept, seen = [], set()for score, c in scored:key = normalize(c.content)if score < THRESHOLD or key in seen:continueseen.add(key)kept.append(to_memory_unit(c, score))return kept
The key is that both the threshold and deduplication are configurable and traceable, and users are allowed to explicitly mark “remember this long-term,” returning final control to the user.
Context Compression: Layered Summarization and Budget Constraints
The context window is a scarce resource, so compression is not optional. The industry commonly uses a layered strategy: keep recent conversations verbatim, apply rolling summarization to mid-term content, and retain only conclusions and preferences for the long term. At the same time, set a budget cap and allocate proportions across “system prompt + stable preferences + task-relevant memory + recent verbatim content,” evicting low-relevance items first when the limit is exceeded. A simplified budget allocation sketch:
budget = {"system": 0.15, "profile": 0.10, "recall": 0.35, "recent": 0.40}def assemble(ctx):parts = []for name, ratio in budget.items():parts.append(select(ctx[name], int(MAX_TOKENS * ratio)))return merge(parts)
The acceptance criterion for compression is not “shorter,” but that task success rate does not drop and key constraints are not lost, which requires a supporting regression evaluation set.
History Recall: Balancing Relevance and Timeliness
Recall determines whether “what was remembered can be used.” Pure keyword recall has limited precision, so the common approach is to combine keyword and vector retrieval, then add time decay and source weighting for reranking. Recall results should not be stuffed in wholesale; instead, apply relevance filtering and fragment trimming first, keeping only the few items strongly relevant to the current task. Conflicts must also be handled: when new and old memories contradict each other, prioritize the newer, higher-confidence, and user-explicitly-confirmed ones, and keep traceable sources for easier debugging.
Cost Control: Making the Bill Explainable
Out-of-control token costs usually come from three places: overly long tool returns being stitched back verbatim, repeated calls to the same tool, and indiscriminate replay of history. Remedies include: applying structured truncation and summarization to tool results; short-term caching for idempotent calls; setting frequency and size limits on memory reads and writes; and instrumenting the pipeline to track the token share of each context segment, forming an explainable bill view. When costs spike, being able to quickly pinpoint whether the cause is “too much recall,” “failed compression,” or “redundant tools” is more valuable than just looking at the total.
From Demo to Production: Observable, Evaluable, and Rollback-Ready
What is truly painful is not how many extra tokens are consumed, but that after launch the agent forgets things, makes repeated calls, and the bill rises without any clue about which layer the problem hides in. It is advisable to treat the memory system as an observable object: record the items and scores of each recall, the token changes before and after each compression, and the hit and cache status of each tool call; build an evaluation set covering long-term preferences, conflict resolution, and long-task continuity; and make all policy changes support canary rollout and rollback. If scaling is needed, you can use object storage for cold data, message queues for peak shaving, and logging services with monitoring and alerting for full-link tracing—all general cloud capability categories.
Conclusion
The core of agent memory is not a specific file or a piece of code, but a logic of tradeoffs: what to remember, how to compress, how to recall, and how to constrain costs. Only by designing this logic clearly, and then discussing models and frameworks, can you avoid being stuck at “the demo runs.” For developers who want to systematically master memory, context, tool calls, and cost governance, the relevant technical courses and documentation from Baidu AI Cloud provide a path from concepts to practice and are worth referencing for both getting started and going deeper.
