AI Agent Memory and Token Cost Control: An Engineering Deep Dive
Learn how state persistence, structured memory, context compression, and history retrieval support reliable, long-running AI agents. This article explains how to manage memory lifecycles, reduce unnecessary tool calls, and monitor token usage to keep production systems maintainable and costs predictable.
When an AI agent application attracts attention, the discussion often centers on its rankings, popularity, or performance on a single task. From an engineering perspective, however, long-term reliability depends less on one impressive response than on how the system persists state, manages context, retrieves useful historical information, and controls token costs over time.
Many agents perform smoothly in demonstrations but reveal problems in real workloads: repeated tool calls, forgotten constraints, growing context windows, slower responses, and rising costs. These symptoms may look like limitations of the model. More often, they reflect weaknesses in memory design, context compression, and cost management.
1. State Persistence: The Foundation of Agent Memory
An agent designed for long-running use generally cannot rely solely on the temporary context of an individual request. It needs to write important state to persistent storage.
This state may include session identifiers, source channels, user identifiers, conversation titles, model configurations, system prompt snapshots, complete message histories, tool call records, and tool results.
If all of this information is stored in a local state database, the dataset will grow with usage. In the short term, persistence enables historical lookup. Without lifecycle management, however, it can eventually lead to storage bloat, slower retrieval, greater privacy risks, and context contamination.
Persistence itself is not the problem. The important questions are what to save, how long to retain it, how to index it, and when to remove it. A maintainable agent system typically separates data into several categories:
- Session metadata: Information that identifies a conversation or task, such as session ID, creation time, source, and user ID.
- Raw interactions: User inputs, model outputs, tool call arguments, and tool results.
- Structured memory: Preferences, facts, task states, and constraints extracted from interactions.
- Temporary caches: Intermediate results that are useful only within the current task.
- Audit logs: Records used to investigate issues, evaluate behavior, and diagnose anomalies.
Writing everything indiscriminately into a single long-term memory store makes it harder for the system to distinguish important information from noise. Different data types need different retention policies and access strategies.
2. “Self-Improvement” Usually Means Retrieving Historical Information
Agents are often described as becoming more familiar with a user over time. In many systems, this does not mean that the model continuously learns by updating its parameters. Instead, the system saves past interactions, retrieves relevant information for later tasks, and inserts it into the model’s context.
This is a form of retrieval augmentation. The agent does not keep every detail in its active context; it retrieves relevant fragments from a memory store when needed. Its effectiveness depends on three factors:
- Whether historical information was saved correctly.
- Whether retrieval finds genuinely relevant content.
- Whether the model can use the retrieved content effectively.
A weak implementation at any stage can make the agent appear capable in one interaction and forgetful in the next.
For example, a user may explicitly prohibit a particular output format. If the system stores only the raw conversation without extracting that instruction as a structured constraint, a later task may violate it. Similarly, a large history is not necessarily useful if keyword-only retrieval fails to surface the most important context.
Long-term memory therefore requires more than accumulating chat logs. It needs an information extraction, compression, indexing, and retrieval process.
3. Information Extraction: Not Everything Deserves Long-Term Storage
Raw interactions contain substantial noise: greetings, repeated confirmations, temporary corrections, unsuccessful experiments, and discussions unrelated to the current task. Keeping all of this as active memory wastes storage and increases the context burden.
Before writing to long-term memory, an agent typically needs to extract information that may be useful again. Common categories include:
- Persistent user preferences: Output language, formatting requirements, and preferred technology stacks.
- Project facts: System architecture, interface conventions, and deployment environments.
- Task state: Current progress, unfinished work, and questions awaiting confirmation.
- Constraints: Security requirements, compliance requirements, and performance boundaries.
- Lessons from failures: Reasons a previous approach failed, helping the agent avoid repeating the same mistake.
The following pseudocode illustrates the idea:
def extract_memory(messages):facts = []for msg in messages:if msg.role == "user" and contains_preference(msg.content):facts.append({"type": "preference","content": normalize(msg.content),"timestamp": msg.time})if msg.role == "tool" and is_error(msg.content):facts.append({"type": "failure_lesson","content": summarize_error(msg.content),"timestamp": msg.time})return deduplicate(facts)
The specific implementation is less important than the design principle: long-term memory should be structured, verifiable, and updateable, rather than a growing pile of raw text.
4. Context Compression: The First Line of Token Cost Control
Every model call must include the information needed for the next step. Longer context consumes more tokens and may increase latency. Excessive context can also dilute important information, making it harder for the model to stay focused.
Context compression is therefore a central part of cost control. Common strategies include:
- Summary compression: Condense multiple conversation turns into a task summary.
- Layered context: Keep global constraints at the system level, current objectives at the task level, and recent summaries at the conversation level.
- Sliding windows: Retain only the most recent turns in their original form and summarize older content.
- Tool-result truncation: Keep only essential fields or summaries when tool outputs are too long.
- Structured replacements for raw text: Use tables, key-value pairs, or state-machine representations instead of lengthy prose.
For example, a long-running task could maintain the following context:
global_constraints:- Output language: Chinese- Never disclose secretstask_state:- Current objective: Complete the API design- Completed: Requirements analysis- Pending confirmation: Authentication methodrecent_summary:- The user prioritizes maintainability- Tightly coupled approaches have been ruled out
This structure is easier to manage and budget than repeatedly inserting dozens of raw conversation turns into the model context.
5. Memory Retrieval: Balancing Relevance and Freshness
The value of long-term memory depends on retrieval quality. Retrieving too little makes the agent forget important information. Retrieving too much adds noise and increases token costs.
A practical retrieval strategy usually considers several dimensions:
- Semantic relevance: Whether the historical memory relates to the current task.
- Time decay: Older information receives less weight unless it has been repeatedly confirmed.
- User and tenant isolation: Memories from different users or projects must not be mixed.
- Access boundaries: Sensitive information must not enter a context that lacks authorization.
- Task stage: Planning, execution, and review require different information.
The following pseudocode illustrates a weighted retrieval approach:
def recall(query, user_id, top_k=5):candidates = memory_store.search(query=query,user_id=user_id,limit=50)scored = []for item in candidates:score = (semantic_similarity(query, item.content) * 0.6+ recency_score(item.timestamp) * 0.2+ importance_score(item) * 0.2)scored.append((score, item))scored.sort(reverse=True)return [item for _, item in scored[:top_k]]
Retrieved results should then undergo another filtering pass to remove duplicates, expired information, low-confidence entries, and content that does not match the current permissions. Only the filtered information should enter the model context.
6. Token Cost Control: From Functional to Sustainable
Token cost is not an isolated concern. It is part of a system-wide process spanning memory writes, retrieval, compression, model inference, and tool calls.
Effective cost management requires attention to several areas.
Control Input Length
Do not send the entire conversation history to the model. Prefer summaries, structured state, and only the necessary original text. For long documents or large tool results, extract the important fields before adding them to context.
Limit Redundant Tool Calls
Repeated tool calls are a common source of waste. Record tool results and reuse them when the arguments and relevant context are unchanged.
Failed calls should also be recorded with their failure reasons so that the agent does not make pointless retries.
Build a Caching Mechanism
Frequently asked questions, stable knowledge, and repeated tasks can benefit from result caching.
Cache keys should account for the user, task, version, and key parameters to prevent incorrect reuse.
Use Tiered Storage
Keep frequently accessed data in low-latency storage and archive infrequently used data in lower-cost storage. Audit and historical investigation requirements can be handled through tiered log services or object storage.
Add Observability
Without monitoring, it is difficult to identify why costs are rising. At a minimum, track:
- Input and output tokens for each request.
- The number of memories retrieved and the retrieval hit rate.
- Tool call counts, failure rates, and average execution times.
- Context length before and after compression.
- Total cost per task and cost trends per user.
These metrics help distinguish context growth from retrieval noise, repeated tool calls, or excessively long model outputs.
7. A Common Mistake: Treating “Save Everything” as Long-Term Memory
Some teams initially assume that a larger memory database will produce a better agent. In practice, memory quality matters more than memory volume.
Accumulating low-value content creates three problems:
- More retrieval noise and lower retrieval accuracy.
- Irrelevant information in the context, which can impair model judgment.
- Increasing storage and compute costs.
A better approach is to establish a memory lifecycle:
- Extract before writing: Keep only high-value information in long-term memory.
- Classify at write time: Separate facts, preferences, task state, and temporary caches.
- Evaluate during use: Gradually reduce the weight of rarely retrieved or low-confidence entries.
- Clean up expired information: Define expiration policies for information that is no longer valid.
- Update conflicting information: Replace outdated entries with new information rather than keeping contradictory versions active.
8. Practical Steps for Developers
Developers building an agent system can start with the following sequence:
- Define task boundaries. Specify what the agent needs to remember over time and what it does not.
- Design the state model. Model sessions, users, tasks, memories, and logs separately.
- Implement a minimal end-to-end loop. Establish memory writing, search, compression, and recall.
- Add cost controls. Track token consumption and tool call costs from day one.
- Create an evaluation set. Use real tasks to assess retrieval accuracy, forgetting rates, and cost changes.
- Iterate on the policies. Use monitoring data to adjust compression ratios, retrieval counts, and retention periods.
9. Conclusion
The engineering challenge of an AI agent is not simply producing a fluent response. It is maintaining useful memory, manageable context, appropriate tool usage, and predictable costs throughout long-running operation.
State persistence is only the starting point. Information extraction, context compression, historical retrieval, and cost control determine whether an agent can become a practical production system.
For developers, understanding these mechanisms is more valuable than following the popularity of a single application. A clear design for what to store, how to compress context, what to retrieve, and how to control costs is what turns an agent from a demonstration into a sustainable system.
