AI Agent Memory and Token Cost Control: How to Store, Compress, and Recall Context
When an agent's token consumption suddenly climbs the leaderboards, engineering teams should read it as a cost-structure signal rather than proof that the product got smarter. This article breaks down how persistent state differs from long-term memory, the four pipelines that determine both quality and bill size (extraction, compression, retention and discard, context reinjection), the three most common post-launch failures (forgetting, repeated tool calls, runaway spend), a practical four-layer memory design with a sample data structure, and how to set per-inference token budgets and observability so you can tell which stage is actually expensive.
Many people read “a certain class of agent has jumped to the top of token consumption rankings” as a sign that the product suddenly got stronger. For an engineering team, the more useful thing to unpack is the cost structure: are interactions being persisted with almost no bound, is history being pasted back into the context verbatim, are tool results entering the prompt over and over. The gap between a demo that runs and something that fits into a daily workflow usually has little to do with model slogans. It comes down to how memory is stored, how context is compressed, what is worth keeping, how it is recalled, and where token limits are enforced.
Persistent state is not long-term memory
Session-based systems typically persist a local or server-side state. Common fields include a session identifier, source channel, user identifier, session title, a snapshot of the model and its parameters, a snapshot of the system prompt, the full message list, and tool calls with their returns. This kind of state buys you recoverability, auditability, and replayability. It does not mean the system “has learned the user.”
Treating it as memory has three direct consequences.
First, disk and object storage grow linearly. Under heavy use, raw messages and tool payloads (logs, web excerpts, tables) are often an order of magnitude larger than the conclusions the user actually cares about.
Second, privacy and compliance boundaries blur. Once system prompts, sample keys, internal links, and personal information land in a full history, every later retrieval, export, or multi-tenant investigation runs into the same sensitive text.
Third, when a similar question is “found again” next time, the system is most likely doing similarity or keyword matching, not a validated fact update. Content the user considers critical but the extractor considers irrelevant gets dropped; content the extractor considers salient but is actually stale gets injected repeatedly. The subjective result is that the agent “isn’t that smart”: not necessarily because the parameters are inadequate, but because nobody owns the information lifecycle.
So separate two things: the interaction log is an evidence chain; long-term memory is a small state that has been extracted, deduplicated, annotated with freshness and permissions.
Four pipelines decide both quality and cost
What you actually need to understand is the four pipelines below, not another shell that can hold a conversation.
Information extraction. From a single turn, pull out reusable facts, user preferences, unfulfilled commitments, and environment constraints (repository, environment name, time zone, output format). Extraction should carry a confidence score and the source turn, so that jokes, assumptions, and one failed command do not get written down as stable preferences.
Information compression. The context window is a scarce resource. Compression is not “truncate to a fixed character count”; it is layered. Raw turns can be archived; the recent window keeps the original wording; older content keeps only decisions, constraints, and reasons for failure. Tool payloads should be summarized first, with a decision afterward on whether to keep a full-text pointer.
Retention and discard. You need explicit policies: freshness (a configuration valid “this week”), scope (this project only), conflict (a new fact supersedes an old one), sensitivity level (forgettable by default). A system without discard rules grows noise and keys together.
Context reinjection. Recall results must be reordered for the task, not pasted in reverse chronological order as one block. A typical order is: the current task instruction, hard constraints, relevant memory entries (short), any necessary tool schema notes, and the last one or two turns verbatim. Stuffing the full history back in makes the token curve blow up at exactly the moment the agent “seems to understand you better.”
Where forgetting, repeated calls, and the bill come from
Three classes of failure show up after launch. Do not lump them together as “the model is bad.”
Forgetting. Usually extraction missed a constraint, or recall got pushed out of the window by a longer tool log. When debugging, look first at the prompt actually sent to the model in that turn, not just the chat transcript in the UI.
Repeated tool calls. If the model cannot see the structured conclusion of the previous call and only sees “it was called before” or a large block of unstructured text, it will call again. The fix is to normalize tool results into small objects: status, key fields, error code, whether it is cacheable, cache key. On a cache hit within the validity period, read from memory instead of hitting the external system again.
The bill climbs every day. The usual sources are: the system prompt replayed every turn and getting longer, a fixed and generally too large number of retrieved snippets, failed retries duplicating the same context several times, and multiple agents forwarding full text to each other. Without per-component metering, you cannot tell whether the cost is in memory reinjection or in the tool loop.
A memory layering you can actually implement
Use four layers rather than one ever-growing session table.
Session layer. Stores the messages and tool trace of the current task, with a rolling window and an archive threshold. Once archived, content does not enter the prompt by default.
Episodic layer. Records “goal, steps attempted, conclusion, blocking reason” keyed by task ID. Good for resuming the same ticket across days, and it should be far smaller than the raw logs.
Semantic layer. Stable preferences and facts, with an update time, a scope, and conflict versions. For example: output language, repository conventions, no automatic commits. Retrieval filters by scope rather than matching keywords globally.
Artifact pointer layer. Large text, long logs, and generated files live in object storage or a logging service; memory keeps only a summary, a checksum, and the storage location. Details are read on demand, so you do not pay full-text tokens on every inference.
The illustrative data structure does not need to bind to any specific product; what matters is that field responsibilities are clear:
MemoryItemid, scope, kind # fact | preference | episode | pointertext # short text, with a length limitsource_turn, confidence, updated_at, expires_atsupersedes # older entries being overriddensensitivity # whether it may enter the promptcache_key # optional, used to suppress duplicate tool calls
For the write path: persist the raw log first (optionally encrypted, with a retention period), then extract asynchronously. Extraction failures should not block the main conversation, but they should be instrumented. For the read path: build a query from the current task, cap the number of entries and the total tokens, assemble, and only then send to the model. Keywords should be only one recall signal; combine them with scope, time decay, and explicit labels, otherwise “similar words” will drag in conventions from unrelated projects.
Token budgets and observability
Setting a budget per inference is more useful than reviewing the monthly bill after the fact.
Meter it in four parts: the fixed system prompt, memory reinjection, the user’s current input, and tool payloads. When any part crosses a threshold, degrade: reduce the number of memory entries, switch to shorter summaries, defer non-critical tools, or ask the user whether to keep digging. Loops need a maximum step count and a circuit breaker on identical parameters, so failed retries do not multiply the same context several times over.
For observability, answer at least four questions: which segment produced the extra tokens this time; which memories were hit and why; which tools were blocked by the cache; which content was refused reinjection because it was stale or sensitive. A logging service with monitoring and alerting suits trend analysis, object storage suits large artifacts, and a message queue suits moving extraction and archiving off the hot path of the conversation. These are all general capabilities and do not need to be tied to one proprietary interface.
Evaluation should not stop at “does the answer sound human.” Take a small batch of real tasks and compare task completion rate, number of repeated tool calls, and tokens per call with and without memory, and across different compression ratios. If memory hits go up but task quality goes down, you are reinjecting stale or overly broad entries; tighten the scope instead of extending the context further.
The capability boundary lives in your logic
The model reasons over the context it is given; you decide what is allowed to appear in that context. If self-improvement means “store every interaction and search it again next time,” that is just a chat log with retrieval augmentation: cost grows linearly or worse with usage, while correctness has no version or freshness guarantee.
The safer approach: separate logs from memory, keep memory short and supersedable, externalize large artifacts, put a budget on reinjection, make tool results cacheable, and keep sensitive information out of the prompt. Once you write these rules into the task instructions and the evaluation set, you will find that whether an agent is useful depends first on how you define “facts worth remembering” and “processes that can be forgotten,” not on consumption rankings. Getting familiar with memory, context, tool calls, and cost gets you closer to production readiness than chasing another demo that runs.
