AI Agent Memory and Token Cost Management

    Effective agent memory requires more than storing complete conversations. This article explains how to separate session records, execution traces, and reusable memory; compress context before it enters the model window; make retrieval and tool reuse traceable; and enforce token budgets. It also outlines practical checks for validating memory quality and controlling costs before deployment.

    Many teams assume that making an AI agent “understand you better” means saving every conversation verbatim. As interactions accumulate, storage usage, retrieval latency, and context size grow together—and token bills follow.

    What determines the outcome is not simply having another program that can chat. It is how four underlying mechanisms work: memory storage, context compression, history retrieval, and budget-based cost control.

    1. Separate Three Types of State

    A complete interaction produces at least three categories of data. Putting them into a single, indefinitely growing store makes governance difficult.

    1. Session ledger: Session ID, source channel, user ID, title, model name and configuration snapshot, and system prompt version. This records who participated and which execution strategy was used. It is relatively small, but must remain traceable.
    2. Messages and tool traces: User inputs, model outputs, tool names, parameter summaries, tool results, error codes, and execution times. This records what happened. It is the largest category and a common source of repeated reasoning and duplicate tool calls.
    3. Reusable memory: Stable facts, preferences, unfinished tasks, and verified conclusions extracted from the traces. These are the items that should receive priority when a similar question arises later.

    Session ledgers are suitable for long-term retention. Traces should be tiered by age and importance. Memory requires both extraction and eviction.

    Treating all three as material to feed back into the model creates two opposing failures: important preferences get discarded by keyword rules, while small talk and failed retries repeatedly consume the context window.

    2. Full Logging Is Not Long-Term Memory

    Keeping complete records is useful for auditing and replay. When something goes wrong, teams can check whether the system prompt changed, a tool returned an empty result, or the model kept retrying the same parameters. But logging is not a memory strategy.

    The common approach of retaining content whenever it matches a keyword has three structural weaknesses:

    • Importance is misaligned. The system may prioritize entities and nouns, while the user cares about constraints, exceptions, and negation. If “Do not use the same approach as last time” is discarded as an ordinary sentence, the agent may repeat the mistake.
    • Similarity is not relevance. Textually similar history can bring back an outdated plan, allowing old conclusions to override new constraints.
    • Freshness and evidence are missing. When a fact is rewritten several times, retrieval without timestamps, sources, or confidence scores returns noise rather than reliable knowledge.

    A more robust approach is to store memory as structured records rather than another block of conversation text. Each record should include at least:

    • A statement of the fact
    • Its scope of applicability
    • An evidence pointer to a specific session and message, rather than a full copy of the source text
    • An update timestamp
    • Expiration or invalidation conditions
    • A sensitivity level

    During retrieval, filter by scope first, rank by semantic similarity second, and resolve conflicts through explicit rules. New facts supersede old ones. Explicit user instructions take precedence over inferred preferences. Low-confidence content should not enter the system prompt by default.

    3. Compress Context Before It Enters the Window

    The context window is a scarce resource. Compression should not simply truncate history to a fixed number of messages. It should change the representation according to the stage of the task.

    Keep recent content verbatim. Preserve the current turn and any unfinished tool chain as original messages so the model can see fields that have just been returned.

    Convert intermediate history into events. Compress completed exchanges into “goal—attempts—result—remaining questions.” For long tool-result lists, retain only primary keys, matching criteria, and whether the result was empty. Store raw payloads in object storage or logs, using references instead of embedding the full content.

    Retain only decision-relevant memory from older sessions. Inject a small set of memories relevant to the current task, with an explicit note such as: “The following is a historical summary. If it conflicts with instructions in the current turn, follow the current instructions.”

    A practical budget can allocate context proportionally:

    • Reserve a fixed portion for system instructions and tool descriptions.
    • Allocate the largest share to the current user goal and recent turns.
    • Give memories and summaries a smaller allocation with a hard limit.

    When the budget is exceeded, discard distant small talk first, compress intermediate tool results next, and modify recent verbatim content only as a last resort. Without a hard limit, recalling history becomes a source of unchecked context growth.

    The following structure illustrates field responsibilities; it is not an interface for a specific platform:

    1. MemoryItem
    2. id, scope, statement
    3. evidence_ref, updated_at, expires_at
    4. confidence, sensitivity
    5. ContextBudget
    6. system_tokens, recent_tokens, memory_tokens, max_tokens

    4. Make Retrieval Explainable and Tool Calls Stoppable

    If “understanding the user better” only means pasting similar conversations back into the prompt, the model may follow the same path and call the same tool again.

    Repeated calls are often not a sudden loss of model capability. The context is simply missing the state: “These parameters have already been queried, and the result is still valid.”

    Maintain a short-term call ledger for each tool, including:

    • A hash of normalized parameters
    • A result summary
    • A validity period
    • A failure count

    For identical parameters within the validity period, reuse the summary directly. After consecutive failures, escalate to asking the user for confirmation instead of retrying indefinitely.

    Recording “already attempted” in an intermediate event summary consumes fewer tokens than inserting the full tool JSON into the prompt again, and makes loops less likely.

    Retrieval also needs a trace: which memory IDs were injected in the current turn, why they matched, and which items were removed to fit the budget. Without this trace, users can only report that the agent “forgot.” Engineers cannot determine whether the information was lost during extraction, removed during compression, or pushed out of the window by retrieval ranking.

    5. Account for Costs by Layer

    A higher token count is not, by itself, a diagnosis. Track at least four separate categories:

    1. System prompts and tool descriptions
    2. History fed back into the context
    3. Generation in the current turn
    4. Additional model calls triggered by tool execution

    Cost growth often comes from current-turn generation being amplified by tool-triggered model calls. A vague question initiates multiple tool steps, each returns lengthy text, and that text is then included in full in the next context window.

    The controls are standard engineering practices:

    • Version prompts and tool descriptions to avoid attaching an ever-growing instruction set to every session.
    • Set maximum tool-result lengths. Return summaries and storage references for content beyond the limit.
    • Cap memory injection by both item count and token count, and record the trimming rate.
    • Use sampled replays to compare task success between full-history context and summaries plus memory, rather than judging quality by conversation length.
    • Alert on high-cost sessions, including a high proportion of duplicate tool calls, context that still exceeds the window after summarization, and memories repeatedly injected without changing the output.

    In cloud deployments, session ledgers and memory indexes can reside in databases, large raw tool outputs in object storage, and execution latency and token usage in logging, monitoring, and alerting systems. General-purpose cloud services, such as those offered by Baidu AI Cloud, can support these components. Memory effectiveness, however, depends on extraction, conflict resolution, and budgeting policies—not on giving storage a different name.

    6. Ask Four Questions Before Deployment

    Validate the system with real tasks rather than demonstration scripts:

    1. Does an explicit negative constraint survive into the next session, with evidence that can be identified?
    2. Does a new fact supersede an invalidated plan, rather than allowing the old plan to rank higher because it contains more matching keywords?
    3. Does the same tool call with the same parameters incur another model round trip while the previous result is still valid?
    4. When the context window is full, does the system discard small talk or constraints required for the current task?

    These questions test extraction, updating, stopping conditions, and compression order, respectively. If the system cannot answer them, it has not progressed beyond “it runs.”

    Unstable agent behavior often does not mean more history is needed. It means the system has not turned four decisions into executable rules: what to store, how to compress it, when to retrieve it, and how many tokens it may consume. The logic belongs in those rules, not in an endlessly growing conversation file.