AI Agent Long-Term Memory and Context Cost Management

    Effective agent memory requires more than storing every conversation and tool result. This article explains how to separate memory layers, structure and retain useful facts, compress context without losing constraints, and retrieve history within a fixed budget. It also covers tool-call deduplication, token cost monitoring, and practical diagnostics for forgotten facts, repeated actions, and outdated decisions.

    Agents consume large numbers of tokens. That may look like heavy usage, but the underlying cause is often unchecked growth in the memory architecture. Preserving every conversation, system prompt snapshot, tool call, and tool result can make similar tasks feel more consistent. It does not, however, mean that long-term memory is working well.

    The experience depends on four things: how information is persisted, how it is compressed, how the system decides what to retain or discard, and how history is reintroduced into the next context window. Without clear rules across these layers, an agent can forget critical facts while expanding both its bill and its storage footprint.

    What an Ever-Growing Conversation Store Actually Solves

    Many agents that can continue operating across tasks maintain conversation state locally or on a server. In principle, this store can grow indefinitely because the default write policy is to retain as much as possible.

    Typical fields include session IDs, source channels, user IDs, conversation titles, model names and sampling settings, system prompt snapshots, complete message sequences, and tool names, arguments, results, and error stacks.

    This design has three direct benefits:

    1. Traceability. When something goes wrong, the team can replay the prompts, tool arguments, and model responses rather than relying on “the agent decided to do it.”
    2. Reuse. Similar tasks do not require users to explain their background, preferences, and constraints from scratch.
    3. Evolution. Historical records provide the material for summarization, preference extraction, and reusable procedures. Much of what is called “self-improvement” follows this pipeline; it does not mean the model is quietly training its weights locally.

    The cost is equally direct: storage grows linearly, or even faster. A tool result containing a web page, log, or complete file can occupy tens of kilobytes to several megabytes. Nested calls may preserve the same fact many times. With frequent use, the state store becomes less a memory system than an unmanaged collection of raw logs.

    Why Saving Everything Is Not Long-Term Memory

    Long-term memory must answer a different question: which facts remain valid for future decisions, at what level of detail, and within what budget?

    Saving everything answers only what happened at the time.

    Retrieving raw history often relies on keyword matching or basic vector similarity. A matching title, entity name, or frequent term can cause an entire conversation segment to be inserted into the prompt. The system may treat repeated or prominent text as important, while the user’s critical information is a brief constraint, a negation, or an exception mentioned only once.

    If retrieval misses that detail, it is effectively unavailable. The result can look like a weak model, even when the real problem is that extraction, compression, retention, and context assembly are working against one another.

    Staleness and conflict are subtler problems. An API address from three months ago, a preference revoked last week, and a conclusion corrected yesterday may all remain in the store with equal standing. Without timestamps, confidence scores, and supersession markers, retrieval can present outdated information as current fact. The agent then appears stubborn or inconsistent.

    Separate Memory Layers Instead of Putting Everything in One Table

    Raw execution traces and retrievable memory should be separate. At minimum, use four layers.

    Working Memory

    Working memory is the content in the current context window: the user’s immediate goal, unfinished plans, recent exchanges, and summaries of active tool results.

    It is the most expensive layer and has the greatest influence on the next action. Keep it short, current, and actionable.

    Episodic Memory

    Episodic memory contains raw records organized by conversation or task. It supports auditing and replay but should not enter prompts by default.

    Records can be partitioned by session ID. Cold data can move to object storage, while hot data remains in a local database or logging service.

    Semantic Memory

    Semantic memory contains stable facts extracted from episodes: user roles, project conventions, environment constraints, and confirmed decisions.

    Each item should include its source session, update time, expiration conditions, and confidence. When a new fact conflicts with an old one, mark the old item as superseded rather than physically deleting it, preserving traceability.

    Procedural Memory

    Procedural memory captures reusable methods: task-specific step outlines, common tool combinations, and branches to follow after failures.

    These should be compact templates, not lengthy logs copied from a successful run.

    With this separation, open-ended growth belongs only in the episodic layer—and even that layer can be archived, compressed, and cleaned up under a retention policy. Semantic and procedural memory need explicit limits and update rules, or they become sources of noise.

    Writing Memory: Structure First, Then Decide What to Keep

    Do not use the model’s free-form text as the only memory format. Apply lightweight structuring before writing, using general fields such as a fact statement, scope, evidence pointer, validity period, and sensitivity level.

    Retention policies should depend on information type, not a single model judgment about whether something is “important.”

    Always retain:

    • Explicit long-term user preferences.
    • Safety and compliance constraints.
    • Confirmed environment facts, such as repository paths, account boundaries, and prohibited actions.
    • Outstanding commitments.

    Retain selectively:

    • Key fields from tool results, rather than complete response bodies.
    • Error types and retryability conclusions, rather than repeated copies of full stack traces.

    Do not retain by default:

    • A complete system prompt snapshot on every turn; a configuration version and changes are sufficient.
    • Successful small talk that adds no information.
    • Intermediate reasoning already covered by a summary.

    Mark sensitive content separately. Secrets, tokens, and personally identifiable information should not enter retrievable memory. If they appear in execution traces, redact them before persistence. Otherwise, “understanding the user better” becomes “making their secrets easier to search.”

    A simple schema need not depend on a specific product. It only needs a stable internal convention:

    1. memory_item
    2. id, user_scope, kind # fact | preference | decision | procedure
    3. text, entities[]
    4. valid_from, valid_until, superseded_by
    5. source_session, source_message
    6. sensitivity # public | internal | secret
    7. salience # 0–1, assigned by rules, not arbitrary one-off generation

    Do not rely solely on a generative model to assign salience. Rules are more consistent: increase the weight of information the user explicitly asks the agent to remember, repeats, references in later tasks, or uses to correct the model. Reduce the weight of expired information that has not been referenced for a long time, or archive it.

    Compression: Reduce Tokens Without Losing Decision-Critical Information

    Compression occurs at two points: when memory is written and when the next context is assembled. These stages have different goals.

    Compressing at Write Time

    Write-time compression prioritizes fidelity and retrievability.

    For an exchange, extract entities and decisions first, then produce a three-to-five-sentence summary with pointers to the original messages. Summaries inevitably lose detail. Source pointers allow the system to inspect the episodic record when necessary instead of treating the summary as a complete substitute.

    Compressing During Context Assembly

    Context compression prioritizes the budget.

    Allocate the prompt budget before assembly rather than filling the window and truncating whatever exceeds the limit. A practical allocation pattern—not a performance guarantee—is:

    • Keep system constraints and safety rules fixed and as short as possible.
    • Prioritize the current task and unfinished plan.
    • Select relevant semantic memories using top-K retrieval.
    • Preserve recent exchanges verbatim.
    • Represent older exchanges as summaries.
    • Include only conclusions, key fields, and failure reasons from tool results.

    The allocation should vary by task type, but it needs hard limits, such as a maximum number of recalled items per request and a maximum character count per tool result.

    Preserve Negations and Boundaries

    One of the most dangerous compression errors is losing negation.

    “Do not commit automatically” must not become “handle commits.” “Do not use the production database” must not become “connect to the database.”

    Negations, permission boundaries, and data scope should occupy explicit, non-compressible slots. Keep them on separate lines rather than merging them into ordinary summaries.

    Avoid Repeated Summarization

    Repeatedly summarizing earlier summaries causes cumulative information loss. Proper names and numbers are often the first details to disappear.

    Once stable facts enter semantic memory, avoid repeatedly rewriting them. Summarize only new episodes, and allow numbers, identifiers, paths, and version strings to remain verbatim through an allowlist.

    Retrieval: How History Reenters Context Determines Its Value

    Retrieval should not mean “search, then paste.” Use a short pipeline.

    1. Build a query from the current goal. Include the task type, entities, and constraint terms rather than the entire conversational exchange.
    2. Search semantic memory. Combine keyword and vector retrieval. Restrict the scope by session ID when needed.
    3. Filter results. Remove expired items, items with inappropriate sensitivity levels, and items that conflict with current tool permissions.
    4. Deduplicate and resolve conflicts. For multiple facts about the same entity, retain the latest valid item. Explicitly note when it supersedes an earlier conclusion rather than leaving the model to choose between conflicting records.
    5. Pack within the budget. Insert high-priority constraints first, directly relevant facts second, and background summaries last. If space runs out, discard background—not constraints.

    Use a format the model can follow, rather than a long block of prose. Useful section headings include:

    • Current constraints
    • Existing facts relevant to this task
    • Historical summaries for reference only

    State that recalled information may be outdated and that explicit instructions in the current user turn take precedence over conflicting recalled information. Retrieved memory is evidence, not a second system prompt.

    If retrieval returns nothing, take an explicit no-memory path. Do not fill the gap with vaguely similar sessions. Forced matches are a common source of both apparent forgetfulness and fabricated context.

    Token Costs Are an Architecture Problem

    Rising token consumption is usually not just a more expensive model. It often reflects growth in both call volume and context length.

    Repeated Tool Calls

    If a previously fetched result is missing from working memory or a short-term cache, the planner may reason again from the original goal and call the same interface with the same arguments.

    Use a tool-result fingerprint—tool name plus normalized arguments—to deduplicate calls within a session. On a match, reuse the result summary. Also set a maximum retry count.

    Snowballing Context

    Sending complete history and all raw tool outputs on every turn makes input tokens grow roughly linearly with the turn number, or faster.

    Use a sliding window with summary anchors. Store raw tool outputs in logs or object storage, and keep only summaries and pointers in context.

    Bloated System Prompts

    Memory, persona instructions, tool manuals, and history are sometimes combined into a system prompt that is sent in full on every call.

    Keep the stable prefix concise and cache-friendly. Put dynamic content in later messages and inject memory only when needed.

    Retry Storms

    After a tool error, the system may resend the full error and complete context, prompting the model to attempt almost the same call again.

    Classify errors. Terminate branches with non-retryable failures, and record “do not call again” in working memory.

    Measure Where the Cost Comes From

    Track at least four metrics:

    • Input and output tokens per session.
    • Number of tool calls.
    • Number of recalled memory items and their share of input tokens.
    • Duplicate tool-call rate.

    Without these metrics, teams can observe that the system is becoming more expensive but cannot distinguish memory injection, tool results, and wasted retries.

    Set alert thresholds by session or user. Sample anomalous sessions for replay from episodic memory rather than extending prompts and hoping for improvement.

    Troubleshooting Forgetfulness, Repetition, and Poor Answers

    Different symptoms point to different layers.

    Forgotten Facts

    The fact may never have entered semantic memory, or it may have been filtered too aggressively. Query vocabulary may also differ from the stored wording.

    Check whether the fact was persisted, whether it was marked invalid, and whether permission filtering removed it.

    Repeated Tool Calls

    Working memory may lack a tool fingerprint, or the planner may not see that the action has already been completed.

    Check whether the tool traces from the most recent N steps are represented in the current prompt.

    Verbose but Irrelevant Answers

    Too many low-relevance summaries may be crowding out the current task.

    Inspect the context packing order and top-K settings.

    Persistent Use of an Outdated Approach

    Conflict resolution may be missing, leaving old decisions and new instructions in the same context.

    Check supersession markers and the precedence given to the current turn.

    Rapid Storage Growth Without Better Answers

    The episodic layer may be storing complete tool outputs while semantic memory remains nearly empty.

    That means the system is collecting logs, not forming useful memory. Treat archival and extraction as separate processes.

    Implementation Order

    Define retention periods and sensitivity levels before adding more intelligence.

    Store raw traces in episodic memory and archive them regularly. Admit only structured facts into semantic memory. Give context assembly a hard budget and dedicated, non-compressible constraint slots. Deduplicate tool results. Use the four cost metrics for regression checks.

    The model can change; these architectural boundaries remain useful.

    An agent’s ability to understand its user does not depend on whether its conversation store can grow indefinitely. It depends on controlled extraction, compression, retrieval, and budgeting.

    A working demo proves that the components connect. A memory system proves its value in daily use: it retains important facts, avoids meaningless repeated tool calls, and produces an explainable bill. Clear logic and constraints matter more than another layer of unmanaged historical text.