Agent Memory
Learn how AI agents remember useful information across steps and conversations, and how to design memory that is useful, controlled, and safe.
By the end of this lesson, you will be able to:
- Explain what memory means in an AI agent.
- Distinguish working memory, conversation history, and long-term memory.
- Understand how memory can influence an agent's next action.
- Design a simple Python memory model.
- Choose what information should and should not be stored.
- Apply retention, privacy, validation, and deletion principles to agent memory.
What Is Agent Memory?
Agent memory is information an agent can keep available so that later steps can use relevant context instead of starting from zero every time.
Why Do Agents Need Memory?
Without memory, an agent may repeatedly ask for the same information or lose progress between steps.
Remember relevant facts from earlier turns instead of repeating questions.
Keep tool results, decisions, and intermediate state available during a task.
Use durable preferences when the product intentionally supports them.
Reuse validated information when it is still accurate and relevant.
Working Memory
Working memory is information needed during the current agent run. It can include the goal, recent messages, tool results, and intermediate decisions.
The agent remembers the order ID and the result returned by the order-status tool during the current task.
Once the task is complete, this information may no longer need to be retained.
Conversation Memory
Conversation memory is the message history or a useful summary of previous turns that helps the agent understand what the user has already said.
A practical system may keep recent messages and summarize older context when appropriate.
Long-Term Memory
Long-term memory stores selected information that may remain useful across future sessions.
Approved user preference
For example, a user explicitly chooses a preferred output format.
Stable application data
Information intentionally stored as part of a product profile.
Reusable task context
Facts that the application deliberately retains for future tasks.
Controlled retention
Every memory should have a reason, scope, and retention policy.
Memory Is Not the Same as RAG
RAG retrieves relevant external knowledge. Memory retains selected information about the agent's interaction or state. A system can use both.
Find relevant documents, chunks, or records from a knowledge source.
Keep selected information from previous interactions or agent execution.
For example, an agent can retrieve a company's return policy with RAG while remembering an approved conversation preference separately.
A Simple Memory Model in Python
This example shows a small in-process memory store. It is a teaching model, not a production persistence layer.
memory = {
"user_preferences": {},
"current_task": {},
"recent_results": []
}
memory["user_preferences"]["format"] = "concise"
memory["current_task"]["order_id"] = "1042"
memory["recent_results"].append({
"tool": "get_order_status",
"result": "shipped"
})
print(memory)A production system would normally persist selected memory in an appropriate datastore and enforce access, retention, validation, and deletion rules.
Memory Retrieval
When an agent has a large memory store, it should not blindly send every stored item to the model. It should retrieve relevant memory.
Memory + Agent Decisions
Memory matters because it can influence the agent's next decision.
The agent may ask the user for a preference that was already provided.
The agent can use an approved preference and move to the next step.
That does not mean memory should override the current request. Current, explicit instructions should be handled carefully when they conflict with stored memory.
What Should an Agent Remember?
Information the user intentionally wants the product to reuse.
Information required to continue an active workflow.
Application-approved information that has a clear purpose.
Results that remain useful and have an appropriate freshness policy.
What Should an Agent Not Remember?
More memory is not automatically better. Avoid retaining information without a clear purpose or appropriate authorization.
- Secrets such as passwords, API keys, or private credentials.
- Information that is unnecessary for the product's function.
- Unverified assumptions presented as facts.
- Temporary information that has no future value.
- Sensitive data when the application has no valid reason and controls to retain it.
Memory Freshness and Expiration
A stored fact can become wrong. Good memory systems consider how long information should remain valid.
Minutes or hours
Temporary task state and tool results.
Current conversation
Context useful during a user session.
Approved preference
A preference intentionally retained for future sessions.
Revalidate
Refresh information when accuracy matters.
Memory vs Conversation Summary
A conversation summary compresses dialogue. Long-term memory is a deliberate store of selected information. They can complement each other.
Reduce a long conversation into useful context for the current interaction.
Retain information that the product intentionally wants to reuse later.
Memory + Tools
Tools can read or update memory, but memory tools should be treated like any other tool: validate inputs, enforce permissions, and control side effects.
Retrieve approved memory relevant to the current task.
Store a new memory only when the policy allows it.
Correct or replace an existing memory with validation.
Remove information according to the application's retention and deletion rules.
A Safe Memory Update Pattern in Python
Keep the write operation narrow and explicit.
ALLOWED_KEYS = {"format", "language"}
def save_preference(memory, key, value):
if key not in ALLOWED_KEYS:
raise ValueError("Preference is not allowed")
if not isinstance(value, str) or not value.strip():
raise ValueError("Preference must be a non-empty string")
memory["user_preferences"][key] = value.strip()
save_preference(memory, "format", "concise")
print(memory["user_preferences"])In production, authorization, auditing, encryption, retention, and deletion requirements should be handled by the application architecture rather than trusted to the model.
Privacy and User Control
Memory changes how an AI system handles information over time, so users should have understandable controls and the application should have clear policies.
Make it clear what the system stores and why.
Provide appropriate ways to review, update, or delete retained information.
Keep only information that has a legitimate product purpose.
Apply access controls and appropriate security measures.
Memory in the Agent Loop
Memory is therefore not a separate βbrain.β It is one part of the larger agent architecture alongside the model, tools, instructions, retrieval, and safety controls.
Common Memory Mistakes
- Storing everything without a clear purpose.
- Letting stale information override current facts.
- Mixing users or sessions because memory scope is incorrect.
- Allowing the model to bypass application authorization.
- Sending an unnecessarily large memory set to the model.
- Failing to provide appropriate deletion and retention behavior.
Mini Project: Add Memory to a Support Agent
Design a support agent that remembers a user's approved response-format preference and the current order ID during a support task.
Store only the information needed for the support experience.
Use the current user and task scope to retrieve memory.
Do not blindly trust old information when the current system is authoritative.
Apply access, retention, update, and deletion rules.
Challenge: Decide which information should be session-only and which information, if any, should be retained across sessions.
Quick Quiz
A) Any model parameter B) Controlled information retained for later use C) Only a vector database
A) Current task state and relevant intermediate context B) Permanent storage of every message C) Model training
A) Stored facts can become outdated B) Models cannot read text C) Tools never change
A) The model alone B) The application and its security controls C) The user prompt
30-Second Recap
Key Takeaways
When designing agent memory, start with the product requirement, define what should be retained, decide how long it remains valid, and enforce security and user-control requirements in the application.