Skip to main content
LearnMLAcademy
Advanced10 min read

Memory in AI Agents: Short-Term, Long-Term & Persistence

Design AI agent memory using short-term state and long-term vector storage, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

What an agent should remember—and when it should forget

Agent memory is information deliberately saved for later use. Short-term or session memory supports the current conversation; durable memory can preserve approved facts across sessions. Memory is not the model's weights, and it is not automatically everything in the current context—the application chooses what to write, retrieve, update, and delete.

What You Will Learn

  • Distinguish working, episodic, semantic, and procedural memory.
  • Separate memory from context, task checkpoints, and model weights.
  • Apply explicit write, recall, update, and deletion policies.
  • Handle stale or conflicting memories using provenance and recency.

Memory is a managed application capability

The model does not automatically decide that every conversation detail should be retained. The application applies a write policy: what is useful later, what is permitted to persist, how long it lives, and whether the user can inspect or delete it. A recall policy then selects only memories relevant to the current goal.

When memories conflict, prefer an authoritative source and newer verified evidence rather than silently combining both. Store provenance—who or what supplied the fact, when it was recorded, and why it was saved—so the system can resolve conflicts and explain important decisions.

A practical memory taxonomy

A practical memory taxonomy
Memory typeWhat it storesTypical lifetimeRecall styleMain risk
Working / sessionRecent messages and temporary factsOne task or sessionIncluded directly or summarizedNoise and context overflow
EpisodicPast events and outcomesAcross sessionsRetrieve similar relevant episodesOld events misapplied
Semantic / preferencesApproved facts and preferencesUntil updated or deletedKey lookup or relevance searchPrivacy and stale facts
ProceduralApproved procedures or learned routinesVersioned long termSelected by task typeOutdated or unsafe procedure

Do not confuse four different stores

Do not confuse four different stores
ConceptMeaningDoes it persist?Who changes it?
ContextWorking packet for the next model decisionOnly if the application saves itContext assembler
MemoryInformation deliberately saved for possible recallYes, by policyMemory service / user controls
Checkpoint / stateAuthoritative progress of an ongoing taskYes, for durabilityWorkflow runtime
Model weightsParameters learned during trainingYes across inference callsTraining or fine-tuning process

Write, retrieve and retire a memory

  1. Keep immediate messages and temporary task facts in short-term memory; keep durable task checkpoints mainly in the long-running-agent system.

  2. Apply a write policy: save only information that will be useful later and that the user or policy allows you to retain.

  3. Apply a recall policy: retrieve a few relevant memories instead of replaying everything, using semantic search when meaning-based lookup helps.

  4. Update, version, or delete stale and conflicting memories, and record where important facts came from.

  5. Protect stored information with authorization, privacy controls, retention limits, and user-visible correction or deletion.

Instructional figure

The memory lifecycle

How does an approved fact become useful memory without being stored forever or recalled blindly?

Candidate fact
Write policy
Stored + provenance
Relevant recall
Verify freshness
Use in context
Update
newer verified fact
Version
keep trace
Delete
expiry or user request
Memory needs deliberate write, retrieve, verify, update, and delete policies. Provenance and recency help resolve stale or conflicting facts.

Worked Example: A preference is written, recalled, superseded, and deleted

A user explicitly says, 'Save PDF as my preferred report format.' The candidate value comes from that request; the application—not the model weights—owns the memory lifecycle.

  1. Write: policy confirms that a non-sensitive format preference may persist and records {format: 'PDF', source: 'user U-17', saved_at: '2026-09-12T09:00Z', version: 1}.
  2. Recall: during a later report task, the recall service retrieves the preference because report format is relevant. It adds the selected value and provenance to the current context; unrelated memories stay out.
  3. Conflict: the user later says, 'Use HTML from now on.' The newer explicit instruction conflicts with version 1, so the service creates version 2 and marks PDF superseded rather than combining both formats.
  4. Delete: when the user asks to forget the preference, the memory record is removed according to policy. A future report task asks for a format instead of guessing from the deleted value.

What the result means: The current context changes on each call, the memory store keeps only policy-approved history, a workflow checkpoint would track unfinished report work, and model weights remain unchanged throughout.

Instructional figure

Memory is managed application state—not automatic model knowledge

How does one explicit preference move through write, recall, conflict, update, and deletion?

User: save PDF format
Write policy
Store value + source + time
Recall for report task
New preference supersedes old
Delete on request
Context: current call packetMemory: persisted preferenceCheckpoint: task progressWeights: unchanged
The application stores an approved preference with provenance, recalls it only when relevant, supersedes the old value when the user changes it, and removes it on request. The model weights never change.

A Realistic Example: A study-planning agent

During the session it remembers which quiz is active. Across sessions it may remember an approved preference like “use 20-minute lessons,” but should not silently store sensitive personal details.

Read the Mechanism in Code

Use the label and note to understand what this block represents before reading each line.

Conceptual pseudocode
memory = {
  "working": recent_messages[-8:],
  "task_state": {"lesson": 4, "quiz_score": 7},
  "retrieved": search_memories(user_id, current_goal)
}
response = agent.run(goal, memory=memory)
Learner note: Conceptual memory read/write example. search_memories() and agent.run() are application placeholders.

Hands-On Runnable Python Lab: Update, Protect and Forget a Report Preference

User U-17 consents to storing a report-format preference. Revision 1 is PDF, revision 2 is HTML. The clock is a fixed integer so expiry and output are reproducible.

accept update ⇔ expected_version = stored_version; next_version = stored_version + 1
This optimistic-concurrency check detects stale writers. It does not replace authentication: the user namespace must still come from a trusted session.
  1. Create PDF as version 1 with expiry time 200.
  2. Update to HTML using expected_version=1; store version 2.
  3. Reject another update still based on version 1. Also demonstrate that U-99 cannot retrieve U-17’s preference.
  4. Delete the current record and verify it is no longer returned.

Memory has versions, an owner and an end of life

PDF version 1 is replaced by HTML version 2. An update based on stale version 1 is rejected. Expiry and deletion both prevent recall.Namespace U-17 · report_formatv1: PDFsupersededv2: HTMLcurrentOld writerexpects v1× version conflictRecall → Noneexpiry or forgetU-99 recall:None (isolated)
Only version 2 is current. Stale writes are rejected, another namespace cannot recall this record, and expiry or deletion prevents subsequent recall.

Only version 2 is current. Stale writes are rejected, another namespace cannot recall this record, and expiry or deletion prevents subsequent recall.

Complete Python ExercisepythonRunnable
memory = {}

def save(user, value, expected_version, consent, now=100):
    if not consent:
        raise PermissionError("memory consent required")
    key = (user, "report_format")
    old = memory.get(key)
    version = old["version"] if old else 0
    if version != expected_version:
        raise ValueError("stale version")
    memory[key] = {"value": value, "version": version + 1,
                   "source": "explicit user preference", "expires": now + 100}
    return memory[key]["version"]

def recall(user, now=100):
    record = memory.get((user, "report_format"))
    if record is None or now >= record["expires"]:
        return None
    return record["value"]

print("version", save("U-17", "PDF", 0, True), recall("U-17"))
print("version", save("U-17", "HTML", 1, True), recall("U-17"))
try:
    save("U-17", "PDF", 1, True)
except ValueError as error:
    print("rejected:", error)
print("other user:", recall("U-99"))
print("after expiry:", recall("U-17", now=200))
del memory[("U-17", "report_format")]
print("after forget:", recall("U-17"))
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
version 1 PDF
version 2 HTML
rejected: stale version
other user: None
after expiry: None
after forget: None
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. HTML supersedes PDF rather than becoming a competing active preference.
  2. The stale writer fails visibly; automatically retrying with the new version without reconsidering the intent would defeat the protection.
  3. Expiry hides a record from recall; explicit deletion removes it from this demonstration store.

Memory should improve continuity without turning old information into permanent authority. Users need ways to inspect, correct and remove appropriate stored facts.

From the Exercise to an Application

From the Exercise to an Application
SituationPractical choiceImportant qualification
Active task progressUse structured task state/checkpointsDo not treat every intermediate thought as a reusable fact.
Stable user preferenceStore a consented, scoped, versioned recordCheck freshness and allow correction.
Sensitive or temporary informationMinimize retention and retrievalA vector database is not an access-control policy.
Experiment: Call save with consent=False.

The write is denied even if the version is correct. Permission to remember and correctness of an update are separate requirements.

Summary / Key Takeaways

  • Agent memory is information deliberately persisted for later use; context is the working information supplied for the current decision.
  • Short-term/session memory supports the current interaction, while durable memories can preserve approved facts, preferences, or experiences across sessions.
  • Useful memory types include episodic experiences, semantic facts/preferences, and procedural guidance, but each needs different retention and retrieval rules.
  • A write policy decides what is worth storing; a recall policy decides what should be retrieved for the current goal.
  • Memories can become stale or conflicting, so important records need provenance, update/version rules, and deletion paths.
  • More memory is not automatically better because irrelevant or outdated memories can distract the model.
  • Memory systems must respect privacy, authorization, retention, and user-visible correction or deletion requirements.

Verified Further Reading

These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Memory in AI Agents: Short-Term, Long-Term & Persistence"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5application/scenario
Which item is best treated as durable semantic/preference memory?
Question 2 of 5conceptual
What does a memory write policy decide?
Question 3 of 5interpretation
Why can more memory reduce agent quality?
Question 4 of 5debugging/diagnostic
Two durable memories disagree about a customer’s preferred language. What should the system do?
Question 5 of 5conceptual
Which statement correctly separates memory from a durable task checkpoint?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which item is best treated as durable semantic/preference memory?▼

Correct Answer: A user-approved preference to receive concise explanations across sessions

A stable approved preference can be useful across sessions and fits durable semantic/preference memory.

2What does a memory write policy decide?▼

Correct Answer: What information is worth storing and permitted to persist

The write policy determines what should become durable memory rather than silently storing everything.

3Why can more memory reduce agent quality?▼

Correct Answer: Irrelevant or stale memories can distract the model or conflict with newer evidence

Poorly selected or outdated memories add noise and can contradict current evidence.

4Two durable memories disagree about a customer’s preferred language. What should the system do?▼

Correct Answer: Use provenance/versioning or recency rules and allow correction

Conflicts require explicit update/version logic and provenance rather than arbitrary selection.

5Which statement correctly separates memory from a durable task checkpoint?▼

Correct Answer: Memory stores useful information for later recall; a checkpoint stores execution progress needed to resume a task

Task checkpoints preserve workflow progress, while memories preserve information intended for future recall.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next