High Token Consumption in AI Agents: Memory, Context, and Cost Governance
As AI agents consume tokens at an increasing rate, it is crucial to distinguish between actual usage growth and engineering inefficiencies. This article explores the architecture behind agent memory and context management, detailing how to implement layered storage, optimize memory extraction, improve context compression, and control costs. It also provides troubleshooting strategies for common issues like "forgetfulness" and repeated execution, guiding developers from building one-off demos to deploying reliable production-grade agents.
1. What High Consumption Means: Distinguishing Scale, Capability, and Efficiency
When token consumption for a certain type of agent grows rapidly, the easiest conclusion to draw is that higher usage means a more advanced system. However, from an engineering perspective, consumption is merely a workload metric. It cannot independently prove task quality, reasoning capability, or the effectiveness of long-term memory.
First, we must clarify the statistical scope. A consumption ranking within a specific channel, time period, or model range does not automatically represent global usage. Without verifiable data sources, time ranges, and input/output statistical rules, treating “highest consumption” as a premise for technical conclusions is misleading.
Even if consumption data is reliable, its growth may stem from different factors:
- An increase in active users leading to higher total task volume;
- Individual tasks becoming more complex, requiring more reasoning and tool interactions;
- Historical messages continuously entering the context, making each input turn longer;
- Tools returning large amounts of raw data without filtering or compression;
- Failed retries, repeated retrieval, or invalid loops increasing the number of API calls.
The first two changes may reflect genuine demand growth, while the latter three likely expose engineering inefficiencies. When analyzing agents, we should shift the focus from “how many tokens were used” to “what tasks were completed with those tokens.”
Therefore, more meaningful evaluation metrics include task success rate, average cost per successful task, completion latency, number of user corrections, and the proportion of repeated tool calls. Only by observing quality, speed, and cost together can we determine whether the growth in consumption is justified.
2. Saving All Interactions Does Not Equal Having Long-Term Memory
Many agents record sessions in local databases or remote persistent storage. Common records include session IDs, user IDs, message content, model configurations, prompt versions, tool parameters, tool results, and execution statuses.
This data holds significant value: developers can use it to restore tasks, reproduce failures, audit operations, and provide material for subsequent retrieval. But first and foremost, these are interaction logs, not fully processed long-term memory.
We should distinguish between three different concepts:
Interaction records answer “what happened in the past.” They emphasize completeness and traceability, allowing for duplicate content, failed attempts, and temporary information.
Working context answers “what the current task needs to know.” Constrained by the model’s context window, it must prioritize current goals, constraints, execution progress, and necessary evidence.
Long-term memory answers “which future tasks will still need this information.” It emphasizes stability, scope of application, retrievability, and update mechanisms.
For example, if a user says “please keep the output short this time,” it might only be a current task requirement and should not immediately become a permanent preference. Conversely, if a user repeatedly states “project reports must include risk and rollback plans,” this is better suited to form long-term memory tied to a specific project scope.
If a system merely accumulates historical messages without information extraction, scope management, and recall mechanisms, expanding storage size will not naturally lead to a better user experience.
Similarly, saving history, updating summaries, or accumulating task experience cannot be directly equated with changes in model parameters. Without corresponding training processes and validation evidence, these mechanisms should not be described as the model having achieved autonomous evolution.
3. Building Layered Storage Instead of a Single Database for Everything
A single database can serve as an early implementation, but it is not advisable to manage raw logs, user preferences, retrieval indexes, and task states all together. As usage frequency rises, the access patterns and retention requirements for different data will diverge significantly.
A more rational design is to layer by responsibility.
1. Raw Record Layer: Preserving Facts and Evidence
Raw messages and tool results are used for auditing, replay, and traceability. They should retain metadata such as time, source, associated user, and associated task.
For large attachments or lengthy tool outputs, the main content can be placed in independent storage, while the database retains references, summaries, and necessary attributes. This prevents the main database from being overwhelmed by large-volume content and facilitates separate access control and retention policies.
2. Task State Layer: Maintaining Current Execution Progress
Task state should record goals, to-do items, completed steps, key dependencies, and termination conditions. It does not need to duplicate the entire conversation; rather, it should help the system accurately resume after an interruption.
For example, “which files have been checked,” “which checks failed,” and “which operations are awaiting user confirmation” are typically more suitable for directly entering the next round of context than dozens of rounds of historical messages.
3. Long-Term Memory Layer: Saving Filtered Information
Long-term memory can store stable preferences, project rules, confirmed facts, and reusable experiences, but each memory entry must have a defined scope.
A schematic memory record might include:
Memory content: Delivery reports need to include a rollback planScope: Specified projectSource: Explicitly confirmed by userCreation time: When the record was formedUpdate time: Most recent confirmation timeValidity status: Valid, pending confirmation, or invalidEvidence reference: Corresponding interaction record
The fields here are just a generic design example and do not represent any specific product interface. The key is to make memory explainable, updatable, and deletable, rather than just saving a piece of text without a source.
4. Retrieval Index Layer: Responsible for Finding Relevant Information
Indexes should act as rebuildable derived data, not the sole carrier of facts. Whether using keyword matching or semantic retrieval, consistency between the index and the raw records must be considered.
When a user deletes history or revokes information, the raw records, memory, summaries, indexes, and related caches should all be processed synchronously according to policy. Otherwise, information that has been deleted from the interface might reappear in subsequent retrieval.
4. Memory Extraction: Importance Should Not Be Decided by the Model Alone
Information extraction is the entry point for long-term memory and the stage most prone to error.
If information is saved purely by keyword, the system might capture surface terms while ignoring truly important constraints. If it relies entirely on model judgment, the system might mistake a temporary expression for a stable fact or write uncertain speculations into long-term memory.
Therefore, the extraction process needs to synthesize multiple signals:
- Whether the user explicitly requested to remember it;
- Whether the information repeatedly appears across multiple interactions;
- Whether the content is a stable fact or a one-off requirement;
- Whether it will affect future task decisions;
- Whether there are time limits or project scopes;
- Whether it contains sensitive information;
- Whether it conflicts with existing memories.
For high-impact information, the user should be prioritized for confirmation. For example, memories involving approval processes, financial operations, permission boundaries, and compliance requirements should not be formed based solely on model speculation.
When encountering conflicts between new and old information, the system should not default to “the latest sentence necessarily overrides the old rule.” The system needs to determine whether it is a temporary exception, a scope change, or a formal update. If it cannot be determined, it should be flagged as pending confirmation and the user should be asked before executing related tasks.
5. History Recall: Finding Relevant Content and Determining Usability
The value of long-term memory lies not in how many entries are saved, but in whether the correct content can be recalled when needed.
Keyword retrieval excels at finding exact terms, IDs, and specific expressions; semantic retrieval is better suited for handling queries with different wording but similar meanings. A practical system can combine both methods, but the retrieval results still need to be filtered by permissions, validity, and scope.
A general recall process can be:
Parse current task↓Determine user, project, and permission scope↓Retrieve candidate memories and historical evidence↓Filter out invalid, unauthorized, and obviously irrelevant content↓Check conflicts and sort↓Assemble necessary information according to context budget
Sorting cannot rely solely on semantic similarity; it must also consider source reliability, temporal validity, and task relevance. A highly similar sentence from an old document may no longer be applicable to the current project.
Additionally, “no recall results” and “the information does not exist in history” are two different things. The former might result from missing indexes, permission filtering, or poor query expression. When it comes to critical decisions, a path should be provided to expand the retrieval scope or request user confirmation, rather than directly concluding that the information does not exist.
6. Context Compression: Reducing Redundancy Without Flattening Information
Context compression is not just about shortening text; more importantly, it is about preserving content that affects decision-making.
For continuous, multi-turn tasks, prioritize retaining:
- Current goals and acceptance criteria;
- Explicit user constraints;
- Confirmed facts and their sources;
- Executed actions and results;
- Unresolved issues and pending items;
- Next step action plan.
Explanatory dialogue, repeated tool outputs, and already invalidated attempts can be moved out of the current context and retrieved from history if needed later.
The biggest risk of compression is information distortion. For example, if “this solution is usable under specific conditions” is compressed to “this solution is usable,” the boundary of application is lost. If “not yet verified” is omitted, speculation might be treated as fact.
Therefore, summaries should explicitly retain negations, conditions, numerical values, time ranges, and uncertainties. For key evidence, it is best to include raw record references so that the full text can be restored for verification if necessary.
It is also not advisable to continuously summarize the previous summary over a long period. Repeated compression easily leads to error accumulation. For critical tasks, status summaries should be periodically regenerated from raw evidence.
7. Cost Control: Separating Storage Overhead from Model Input Overhead
As historical data increases, the first impact is on storage, indexing, and maintenance overhead. Only when this content is read and sent to the model does it directly increase corresponding input token consumption.
Thus, database growth and rising model bills may be related, but the two are not a simple one-to-one correspondence.
The model call cost for a task can be calculated individually for each actual call:
Single call cost≈ Billable input quantity × Corresponding input unit price+ Billable output quantity × Corresponding output unit priceTotal task cost≈ Sum of all model call costs+ Tool and infrastructure-related costs
Specific billing rules may involve caching, different call types, or other factors, and should be subject to actual service rules. Bills cannot be estimated solely based on text length.
When controlling costs, priority should be given to handling three types of waste.
The first type is repeated context transmission. Passing the full history in every turn repeatedly processes information that has already appeared. Redundancy can be reduced through task summaries, on-demand recall, and context layering.
The second type is oversized tool results. If retrieval, file reading, or log queries return the entire content, the model may only use a very small fraction. Range limitation, pagination, field filtering, and result truncation should be applied on the tool side, while keeping a path for further querying.
The third type is invalid loops. Repeatedly calling tools with the same input, failing without changing strategies, and lacking stop conditions all drive up overhead. The system should set task budgets, maximum execution steps, retry strategies, and manual confirmation nodes, while recording termination reasons.
Cost constraints cannot sacrifice correctness as the only trade-off. A more reasonable goal is to reduce invalid consumption and allocate the limited budget to key evidence verification and necessary decision-making.
8. Troubleshooting “Forgetfulness” and Repeated Execution
When users perceive an agent as “not smart,” the issue may occur at entirely different layers. Troubleshooting should verify step-by-step along the data pipeline.
1. Check if it was written
Did the information the user explicitly asked to retain actually enter persistent storage? Did the write fail? Was it incorrectly categorized as temporary content?
2. Check if it is retrievable
The record existing does not mean the index is usable. It is necessary to check whether index updates, retrieval scope, user isolation, and permission filtering are correct.
3. Check if it entered the context
After successful recall, the content might be discarded during sorting, deduplication, or budget trimming. The candidate results, actual selected content, and exclusion reasons should be logged.
4. Check if the model used it correctly
If the correct memory has entered the context but the response still ignores constraints, you need to check for prompt conflicts, evidence expression, task complexity, and model fit.
5. Check if the execution state is synchronized
Repeatedly calling a tool might not be a reasoning error; it could be that the state was not updated after successful execution, or that idempotency control is lacking during retries. Operations with external side effects should have anti-duplicate submission mechanisms and require user confirmation when necessary.
Observability should at least cover call counts, input/output volumes, tool latency, error types, context composition, and final task status. Debug logs must also be desensitized and access-controlled to avoid expanding the exposure of sensitive information just for troubleshooting.
9. From Demo to Production: Establishing a Quality, Cost, and Security Loop
Production-grade agents require a clear data lifecycle. Raw logs, long-term memory, attachments, and indexes can adopt different retention periods, but all must have cleanup, archiving, and deletion mechanisms.
In particular, external files, web content, and tool return results are unverified data. They should not automatically become high-priority instructions, nor should they be written into long-term memory without inspection. Otherwise, malicious or erroneous content may affect subsequent tasks.
Before going live, a test set simulating real workloads should be established, covering scenarios like preference updates, cross-task recall, information conflicts, permission isolation, long task recovery, tool failures, and budget exhaustion. Acceptance testing should look beyond whether the response is fluent and also check:
- Whether currently valid rules are correctly applied;
- Whether key conditions and uncertainties are preserved;
- Whether cross-user information leakage is avoided;
- Whether it can recover or stop orderly after a failure;
- Whether the task is completed within a reasonable cost.
What is truly worth researching about agents is not a consumption ranking itself, but how they transform historical data into usable memory, maintain task continuity within a limited context, and ensure every model and tool call provides clear value.
Only by simultaneously excelling at memory governance, context orchestration, execution control, and cost observation can a system transition from a one-off demo to reliable, long-term use.
