LESSON 62 Β· AI AGENTS

Agent Memory

Learn how AI agents remember useful information across steps and conversations, and how to design memory that is useful, controlled, and safe.

30 min readβ€’Intermediateβ€’Generative AI

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.
1

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.

Simple definition:Memory gives an agent a controlled way to retain useful information across steps, sessions, or tasks.
GoalUnderstand the task
β†’
RememberLoad useful context
β†’
ActChoose the next step
β†’
ObserveRead the result
β†’
UpdateStore useful state
2

Why Do Agents Need Memory?

Without memory, an agent may repeatedly ask for the same information or lose progress between steps.

CONTINUITYKeep the conversation useful

Remember relevant facts from earlier turns instead of repeating questions.

PROGRESSTrack the current task

Keep tool results, decisions, and intermediate state available during a task.

PERSONALIZATIONReuse approved preferences

Use durable preferences when the product intentionally supports them.

EFFICIENCYAvoid unnecessary work

Reuse validated information when it is still accurate and relevant.

3

Working Memory

Working memory is information needed during the current agent run. It can include the goal, recent messages, tool results, and intermediate decisions.

EXAMPLECurrent order lookup

The agent remembers the order ID and the result returned by the order-status tool during the current task.

NOT NECESSARILY LONG-TERMTemporary state

Once the task is complete, this information may no longer need to be retained.

4

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.

Important:Sending an entire conversation forever is not the same as having a good memory system. History can become expensive, noisy, or irrelevant.

A practical system may keep recent messages and summarize older context when appropriate.

5

Long-Term Memory

Long-term memory stores selected information that may remain useful across future sessions.

PREFERENCE

Approved user preference

For example, a user explicitly chooses a preferred output format.

PROFILE

Stable application data

Information intentionally stored as part of a product profile.

KNOWLEDGE

Reusable task context

Facts that the application deliberately retains for future tasks.

POLICY

Controlled retention

Every memory should have a reason, scope, and retention policy.

6

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.

RAGRetrieve knowledge

Find relevant documents, chunks, or records from a knowledge source.

MEMORYRetain useful state

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.

7

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.

</> Python
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.

8

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.

1. New requestβ€œUse my usual format.”
β†’
2. Search memoryFind format preference
β†’
3. FilterCheck scope and freshness
β†’
4. ContextAdd relevant memory
9

Memory + Agent Decisions

Memory matters because it can influence the agent's next decision.

WITHOUT MEMORYAsk again

The agent may ask the user for a preference that was already provided.

WITH RELEVANT MEMORYContinue

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.

10

What Should an Agent Remember?

Useful preferences

Information the user intentionally wants the product to reuse.

Task state

Information required to continue an active workflow.

Stable facts

Application-approved information that has a clear purpose.

Validated results

Results that remain useful and have an appropriate freshness policy.

11

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.
12

Memory Freshness and Expiration

A stored fact can become wrong. Good memory systems consider how long information should remain valid.

SHORT-LIVED

Minutes or hours

Temporary task state and tool results.

SESSION

Current conversation

Context useful during a user session.

LONGER

Approved preference

A preference intentionally retained for future sessions.

EXPIRE

Revalidate

Refresh information when accuracy matters.

13

Memory vs Conversation Summary

A conversation summary compresses dialogue. Long-term memory is a deliberate store of selected information. They can complement each other.

SUMMARYCompress context

Reduce a long conversation into useful context for the current interaction.

MEMORYStore selected facts

Retain information that the product intentionally wants to reuse later.

14

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.

read_memory

Retrieve approved memory relevant to the current task.

write_memory

Store a new memory only when the policy allows it.

update_memory

Correct or replace an existing memory with validation.

delete_memory

Remove information according to the application's retention and deletion rules.

15

A Safe Memory Update Pattern in Python

Keep the write operation narrow and explicit.

</> Python
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.

16

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.

TRANSPARENCYExplain memory

Make it clear what the system stores and why.

CONTROLAllow management

Provide appropriate ways to review, update, or delete retained information.

MINIMIZATIONStore less

Keep only information that has a legitimate product purpose.

SECURITYProtect stored data

Apply access controls and appropriate security measures.

17

Memory in the Agent Loop

UnderstandRead the goal
β†’
RecallRetrieve relevant memory
β†’
DecideChoose next action
β†’
ActUse a tool
β†’
UpdateStore useful state

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.

18

Common Memory Mistakes

  1. Storing everything without a clear purpose.
  2. Letting stale information override current facts.
  3. Mixing users or sessions because memory scope is incorrect.
  4. Allowing the model to bypass application authorization.
  5. Sending an unnecessarily large memory set to the model.
  6. Failing to provide appropriate deletion and retention behavior.
19

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.

MEMORYPreference + task state

Store only the information needed for the support experience.

RETRIEVELoad relevant context

Use the current user and task scope to retrieve memory.

VALIDATECheck freshness

Do not blindly trust old information when the current system is authoritative.

CONTROLRespect privacy

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.

20

Quick Quiz

1. What is agent memory?

A) Any model parameter   B) Controlled information retained for later use   C) Only a vector database

2. What is working memory mainly used for?

A) Current task state and relevant intermediate context   B) Permanent storage of every message   C) Model training

3. Why should memory have a freshness policy?

A) Stored facts can become outdated   B) Models cannot read text   C) Tools never change

4. Who should enforce authorization for memory writes?

A) The model alone   B) The application and its security controls   C) The user prompt

21

30-Second Recap

1Working memory keeps information needed during the current task.
2Conversation history helps maintain continuity between turns.
3Long-term memory stores selected information for future use.
4Memory and RAG solve different problems but can work together.
5Good memory requires scope, validation, freshness, privacy, and deletion controls.
22

Key Takeaways

Remember:Good agent memory is selective, relevant, scoped, and controlled. The goal is not to remember everythingβ€”it is to remember the right information at the right time.

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.