AI Agent Long-Term Memory and Context Cost Control: Compression, Recall, and Budgeting
This article explains why agent token consumption and rising bills usually come from how memory is stored, compressed, and recalled rather than from traffic growth alone. It breaks down what an append-only session state store actually keeps, the four stages information passes through before entering the context window (extraction, compression, retention and eviction, re-injection), and the three common failure modes once an agent moves from a demo into daily work: forgotten constraints, repeated tool calls, and hidden costs. It then proposes a layered memory design (session state, episodic, semantic, tool cache, raw log), practical rules for compression and recall, cost control checkpoints, and a regression-based acceptance method.
Many people read an agent’s heavy token consumption as “another project got popular, so call volume went up.” That explanation holds if you only look at traffic charts. Open the runtime directory and the state files, and the real drivers of both experience and cost come into view: how memory is stored, how context is compressed, how history is recalled, and whether any of those actions are observable.
1. What an endlessly growing session state actually holds
Many agent implementations persist interactions to a local or remote state store. By design, that store is usually append-only per session and can grow without a hard limit. A single complete interaction commonly includes: session ID, source channel, user ID, session title, model name and configuration snapshot, system prompt snapshot, full message history, and tool calls with their return values.
In other words, user input, system configuration, intermediate reasoning traces, and tool side effects all get kept as assets that “might be useful later.” Under frequent use, disk, object storage, or database capacity keeps climbing. More importantly, the next time a similar question arrives, the system scoops content out of that history and pushes it back into the context, which is what makes the agent feel like it “knows you better.” Self-improvement and self-evolution are often not online weight updates at all; the retrieval scope simply got wider. The same model gives more scenario-specific answers because it can see more of your older records.
Treating the full log as long-term memory is easy to implement, replayable, and convenient for debugging, but it is not the optimal form of long-term memory. Logs are faithful; memory should be restrained. Faithful recording answers “what happened.” Restrained memory answers “what should be recalled next time.” When both live in one endlessly growing table, retrieval quality, latency, and token usage all degrade together.
2. Why it feels “not smart enough”: four underlying stages
When users say the agent forgets things or answers the wrong question, the base model is usually not the problem. What is missing is a clear view of the steps information passes through before it enters the context.
First, information extraction. The system has to decide which parts of a conversation are task goals, constraints, preferences, entities, unfinished items, and tool conclusions. If extraction relies only on keywords or shallow rules, it favors words that merely repeat on the surface and drops conditions the user actually cares about but phrased plainly. A constraint like “stop calling the external API, reuse this morning’s version” can carry lower keyword weight than some high-frequency business term, so it gets discarded next time.
Second, information compression. The context window is finite, so history must be summarized. Compression should preserve the basis for decisions, not just the conclusions. Keeping only “handled” leaves later turns unable to tell why it was handled that way, so the model replans and calls the tool again.
Third, retention and eviction. Retention policies usually blend recency, relevance, importance, and deduplication. The problem is that the definition of “important” belongs to the system, not the user. An exception clause the user considers critical may appear only once, carry weak emotional signal, and not look like an entity name, so it is judged low value and evicted. The larger the memory store, the more it resembles a biased filter rather than a complete brain.
Fourth, re-injection into the context. Recall is not concatenating old records verbatim. You have to decide whether content goes into the system prompt, a memory block, or retrieved snippets; how many items to include; and how to arbitrate conflicts with the current question. Inject too much and effective instructions get diluted while tokens climb; inject too little or into the wrong layer and the model behaves as if it has amnesia.
So the thing worth learning is not “here is another agent that runs.” It is how these four things work together: what to store, what to compress it into, what to recall it by, and how to keep cost inside a budget.
3. Typical failures after moving from “demo works” to “wired into work”
In the demo stage, conversations are short, tools are few, and state is nearly empty, which hides the problems. Once the agent is wired into daily work, sessions get longer, tool chains get deeper, and the state store swells. The painful part is not knowing which layer the problem lives in.
Forgetting usually has three sources. Working memory was truncated by the window, so early constraints are no longer in this request. Long-term memory was never written, or was written under the wrong key and retrieval misses it. It was written and recalled, but a newer, contradictory summary overwrote it. These three map to truncation policy, index quality, and conflict merging respectively; none of them should be lumped together as “model hallucination.”
Repeated tool calls usually mean state is not closed-loop. Tool results were not persisted in structured form, so the next planning round cannot see “this query already succeeded, with these parameters, this result digest, valid until this time.” The planner then executes the same intent again. If the tool is not cheap, or triggers downstream writes, cost and risk amplify at the same time.
A bill that climbs day by day is not just “model unit price times number of messages.” Hidden costs include: sending an over-long history in full every turn; expanding multiple memory records verbatim for recall; a large tool-return JSON entering later turns without trimming; retries without an idempotency check, stacking the same call multiple times; and an over-long system prompt snapshot resent every turn. If token usage ranks first, that only shows call volume is high; it says nothing about architectural health. It more likely shows that state is being read back into the context repeatedly while compression and caching have not kept up.
4. A more robust memory layering
Memory can be split out of “one endlessly growing session table” into layers, each with a different lifecycle and a different way of entering the context.
Session state serves only the current task: goal, confirmed slots, todos, and the most recent few turns verbatim. It is archived when the task ends or times out, and does not enter the long-term store by default.
Episodic memory keeps key, restatable fragments: one decision, one user correction, one tool failure and its cause. Use structured fields rather than whole chat transcripts, for example time, topic, conclusion, evidence pointer, and invalidation condition.
Semantic memory keeps stable preferences and facts: output language, standard phrasing, prohibited actions, environment constraints. Updates must be auditable so that one casual remark does not overwrite a long-term preference.
Tool memory keeps call signatures, parameter digests, result digests, cache keys, and expiry. Next time, check tool memory first; on a hit that has not expired, reuse it instead of calling again.
Raw logs still need to be kept, but in object storage or a logging service for audit and replay, not as the default corpus for every retrieval round. Once retrieval lands on a summary, read the original through the pointer only on conflict or low confidence. This way disk can grow without the context growing with it.
The illustrative structure is not tied to any specific product, as long as the boundaries are clear:
session_state: goal, slots, recent_turns, pending_toolsepisode: time, topic, decision, evidence_ref, ttlsemantic: preference, constraint, scope, updated_attool_cache: name, args_hash, result_digest, expires_atraw_log: immutable, for audit only
5. Designing compression, recall, and cost together
Compression should be built around “executable information” rather than a “readable story.” A qualified summary answers at least: what the user wants, what they explicitly do not want, verified facts, unverified assumptions, and the single next action. Numbers, proper nouns, time ranges, and negations should be preserved first. Multi-turn summaries should be merged incrementally, so rewriting from the full text each time does not erase early negative constraints.
Recall should weigh relevance and freshness at the same time. Keyword or vector similarity only produces candidates; you still have to filter out expired items, items the user has retracted, and items unrelated to the current channel. What goes back to the model should be a short memory block with reference numbers, not large passages of original text. When memory conflicts with the current instruction, the current explicit instruction wins, and the conflict is recorded so nothing is silently overwritten.
Cost control can be applied at a few checkpoints. Before sending, estimate the composition of this turn’s context: how many tokens the system prompt, memory, history, and tool results each take, and trim by a fixed priority order when the budget is exceeded rather than truncating at random. Apply a field allowlist and a length cap before tool results are stored. Set a short cache for read-only calls with stable parameters. Deduplicate repeated plans: the same intent, the same parameters, and an unexpired result are reused directly. For monitoring, break cost down by session, by tool, and by number of memory recalls instead of looking only at total tokens. Then when the bill rises, you can tell whether it is history re-injection, idle tool spinning, or a prompt that is simply too heavy.
6. A recommended acceptance method
Do not accept memory changes on the basis of “it feels smarter.” Use a fixed regression set: after several turns, are early negative constraints still respected; does the same read-only query avoid a repeated external call; after one user correction, is semantic memory updated and traceable; are key numbers still present after compression; when two contradictory memories are deliberately created, does the system choose explicitly instead of answering with a blend. Pair this with capacity and token curves: the state store may grow, but per-turn input tokens should vary with task complexity rather than rise linearly with days of use.
Once an agent is wired into work, the core competitive advantage is often not one more demo. It is whether you design extraction, compression, selection, recall, and budget as a single chain. The model makes judgments within the given context; what is in that context is decided by engineering logic. Separate these layers, measure them, and attach invalidation and trimming rules first. Only then do forgetting and repeated calls turn from voodoo into fixable defects, and token consumption turn from “the longer you use it, the more it costs” into a cost you can govern.
