Module 6: Memory Systems for Agents

1. Introduction: Agents with memory

Overview

Module 5 solved an intelligence problem: your agent stopped acting mechanically and started thinking. With planning, it breaks down complex tasks before executing them. With reflection, it evaluates its own output and corrects itself. With reasoning traces, its thinking is visible and debuggable. Research Agent v2 has intelligent planning, quality gates, and diagnosis-driven re-planning — it's a deliberative agent. But there's a problem deliberation doesn't solve: your agent forgets everything between sessions. It researches for 20 minutes, produces a plan with 6 sub-tasks, completes 4, and the user closes the laptop. When they come back the next day and say "continue with yesterday's work," the agent has no idea what they're talking about. All the progress — the plan, the partial results, the reflections, the 4 completed sub-tasks — is gone. Every interaction starts from zero, as if nothing had ever happened before.

This module adds the missing layer: memory as a system. Guide #9 on LangChain & LangGraph covered checkpointing and MemorySaver as features — tools you can turn on with a couple of lines of code. This module goes beyond turning them on. The question isn't "how do I enable MemorySaver?" but "what types of memory does my agent need, where do they persist, when do they get cleaned up, what do they cost, and how do I design a coherent memory strategy?" Three types of memory define this module: short-term (the active conversation — what was said in this session), long-term (knowledge that persists between sessions — preferences, learned facts, task history), and episodic (memories of past experiences — "the last time you researched RAG, you found that..."). Each type has a different implementation, trade-offs, and costs. Together they transform the agent from a stateless service that answers questions into a personal assistant that learns, remembers, and can pick up where it left off.

The difference between an agent without memory and one with memory is the difference between a tool and a colleague. A tool does what you ask, every time you ask, with no context from the previous times. A colleague remembers what you worked on together last week, knows your preferences, and can continue a conversation that was left hanging. In production, that difference translates into concrete metrics: research that gets resumed instead of repeated, answers that improve over time because the agent knows the user, and debugging that can navigate the agent's complete history of decisions. The tone of this module is architectural: this isn't about turning on a feature, it's about designing a memory system with deliberate decisions about what to remember, where to persist it, when to forget it, and how much you're willing to pay for it.


Where are we in the guide?

Context

This guide has 10 modules organized into 3 phases:

Phase 1: Agent Foundations (Modules 1-3)          ✓ COMPLETED
├── Module 01: Anatomy of an AI Agent             ✓ COMPLETED
├── Module 02: Tool Use Fundamentals              ✓ COMPLETED
└── Module 03: Function Calling Patterns          ✓ COMPLETED

Phase 2: Agent Architecture (Modules 4-7)         ← YOU ARE HERE
├── Module 04: State Machines for Agents          ✓ COMPLETED
├── Module 05: Multi-Step Reasoning and Planning  ✓ COMPLETED
├── Module 06: Memory Systems for Agents          ← THIS MODULE
└── Module 07: MCP and Advanced Tool Integration

Phase 3: Multi-Agent & Production (Modules 8-10)
├── Module 08: Multi-Agent Orchestration
├── Module 09: Testing and Evaluating Agents
└── Module 10: Agents in Production and Alternatives

Third module of Phase 2 — and the last one before MCP. Modules 4, 5, and 6 build the three fundamental layers of an agent's architecture: flow control (M4), decision intelligence (M5), and state persistence (M6). With M6 complete, your agent has the internal architecture it needs to work as a robust system. Module 7 (MCP) opens the door to the outside world: external tools at scale.

The progression of Phase 2 is deliberate — each module solves a limitation the previous one leaves exposed:

  1. Module 4 — How you control the flow → State machines: cycles, branching, stop conditions ✓
  2. Module 5 — How it reasons deeply → Planning, reflection, self-correction ✓
  3. Module 6 — How it remembers → Short-term, long-term, checkpointing, durable execution ← HERE
  4. Module 7 — How it connects to the world → MCP servers, clients, dynamic tools, ecosystem

Where you're coming from

Module 5 left you with a Research Agent v2 that thinks before it acts:

  • Intelligent planning: The planning_v2 node breaks tasks into sub-questions with dependencies, produces structured plans (not free text), and re-plans based on detected gaps
  • Reflection with quality gates: A reflection node evaluates the output with specific critique prompts and produces actionable evaluations — not a generic "looks fine" but "gap: didn't cover European regulations"
  • Directed re-planning: When reflection detects gaps, re-planning generates new sub-questions to cover them — it doesn't repeat the same search
  • Reasoning traces: The agent's thought process is visible as structured data — debugging the reasoning, not just the code
  • Decision function: You know when planning and reflection justify their cost and when they don't, based on data

That's a deliberative agent. But everything it knows lives in the state of a single execution. When the execution ends — the plan, the reflections, the partial results, the reasoning traces — it all disappears. M5 solved intelligence; nobody solved persistence.

Where you're headed

The transition from M5 to M6 is direct: "Your agent plans, reflects, and reasons intelligently → now make those plans, reflections, and lines of reasoning survive between sessions." M5 made the agent intelligent within a session. M6 makes that intelligence persist over time.

After M6, Module 7 solves a problem that emerges naturally from an agent with memory: an agent that remembers and persists needs access to tools at scale. MCP (Model Context Protocol) gives it exactly that — tool servers the agent discovers and uses dynamically, instead of hardcoded tools. The transition is: "Your agent remembers between sessions → now give it access to an ecosystem of external tools."

And beyond that: with M6 and M7 complete, Phase 2 is closed. Phase 3 begins with M8 (Multi-Agent Orchestration), where multiple agents — each with its own memory — collaborate. Without M6, multi-agent would be impossible: you need each agent to remember its state and the system to have shared memory.


The amnesia problem

A concrete scenario

Monday, 2:30 PM. An analyst uses your Research Agent to investigate "impact of AI regulations on healthcare startups in Europe." The agent plans, breaks the task into 6 sub-questions, and starts executing:

Sub-task 1: AI regulations in the EU (AI Act)   ✓ completed
Sub-task 2: Healthcare startups affected        ✓ completed
Sub-task 3: Documented financial impact         ✓ completed
Sub-task 4: Comparison with US regulation       → in progress...
Sub-task 5: Founders' perspective
Sub-task 6: 2025-2027 projections

The analyst has a meeting. Closes the laptop.

Monday, 4:00 PM. They come back and type: "Continue with the regulations research."

Agent: "I have no context of any previous research.
        Can you describe what you'd like to look into?"

Three completed sub-tasks — each one with searches, analysis, and reflections that cost time, tokens, and money. All lost. The analyst has to start over. The same searches. The same tokens. The same wait.

But the problem runs deeper than "lost progress"

Amnesia doesn't just destroy progress — it destroys relationship. Look at these three scenarios:

Scenario 1: No personal context

Session 1: "Research RAG vs fine-tuning. Give me academic sources, not blogs."
           → The agent produces a report with 8 academic papers.

Session 2: "Research embeddings for RAG."
           → The agent produces a report with 3 blogs and 2 tutorials.

The user already said they prefer academic sources. But in session 2, the agent doesn't know that. It doesn't remember the preference. Every session starts with no context about the user.

Scenario 2: No task history

Session 1: "Research LLM providers for production."
           → Detailed report comparing OpenAI, Anthropic, Google, Mistral.

Session 5: "Which providers had we compared?"
           → "I have no record of previous research."

The agent did the work for the user, but can't reference it afterward. The user becomes the agent's memory system — they have to remember what was researched and where the results were saved.

Scenario 3: No cumulative learning

Session 1: "Research X." → The agent makes error A, corrects itself via reflection.
Session 2: "Research Y." → The agent makes error A again.
Session 3: "Research Z." → The agent makes error A again.

M5's reflection corrects errors within a session. But the agent doesn't learn from previous sessions. It repeats the same mistakes because every session is, literally, its first time.

What an agent with memory would do differently

Same Monday scenario:

Monday, 4:00 PM.
Analyst: "Continue with the regulations research."

Agent: "Resuming research 'Impact of AI regulations on healthcare
        startups in Europe.'

        Current progress:
        ✓ Sub-task 1: AI regulations in the EU (AI Act) — completed
        ✓ Sub-task 2: Healthcare startups affected — completed
        ✓ Sub-task 3: Documented financial impact — completed
        → Sub-task 4: Comparison with US regulation — interrupted
        ○ Sub-task 5: Founders' perspective — pending
        ○ Sub-task 6: 2025-2027 projections — pending

        Continuing from sub-task 4..."

And in session 2 of the sources scenario:

Session 2: "Research embeddings for RAG."
           → The agent remembers: "This user prefers academic sources."
           → Produces a report with 6 academic papers, 0 blogs.

That's the difference. It's not just "saving state" — it's turning the agent into a system that accumulates context, learns preferences, and improves with every interaction.


Types of memory

An agent's memory isn't a monolithic concept. It's three different systems that solve different problems, with different implementations:

Short-term memory: The active conversation

Short-term memory is the most intuitive one: the history of the current conversation. The messages exchanged between the user and the agent in this session.

[user]:      "Research the impact of LLMs on education"
[assistant]: "I'm going to break this down into 4 sub-questions..."
[tool_call]: tavily_search("LLMs education applications 2024")
[tool_result]: {...results...}
[assistant]: "I found 3 main applications..."
[user]:      "Go deeper on personalized tutoring"

That sequence of messages is the short-term memory. It's what gives the agent context within a session — without it, every message would be independent.

The problem: it grows linearly. A 30-minute research run can generate 50+ messages with tool calls and results. That's context sent to the LLM on every request — more tokens, more cost, more latency. And eventually, you exceed the model's context window.

The strategies: window trimming (keep only the last N messages), token-based trimming (keep whatever fits in a token budget), and summarization (condense the history into a summary). Each one has trade-offs that capsule 02 explores in detail.

Long-term memory: Knowledge between sessions

Long-term memory is information that persists between different conversations. It's not the history of one session — it's knowledge the agent accumulates over time:

  • User preferences: "Prefers academic sources, bullet point format, concise reports"
  • Learned facts: "The user works in fintech, their company is called Acme, they use Python and FastAPI"
  • Task history: "Has researched RAG, embeddings, and fine-tuning in previous sessions"
  • Detected patterns: "When researching a new topic, they always ask for an overview first and then go deeper"

Long-term memory isn't implemented as chat history. It's a separate store — a database (or an in-memory store for development) where the agent saves and queries structured information. LangGraph offers InMemoryStore and BaseStore as abstractions for this.

The critical question: what deserves to be remembered? Not everything the agent observes in a session should go into long-term memory. Saving everything is unviable (cost, noise). Saving nothing is useless. Designing what persists and what gets discarded is an architectural decision that defines how useful the agent is.

Episodic memory: Past experiences

Episodic memory is the most sophisticated type: memories of complete experiences — not just facts, but the context of how they were obtained. In humans, it's the difference between knowing that "Paris is the capital of France" (semantic) and remembering "that time we researched European capitals and found a surprising fact about Brussels" (episodic).

For an agent, episodic memory includes:

  • "The last time you researched AI regulations, the most useful sources were the European Commission's site and a Stanford paper"
  • "When you tried to look up startup data on Crunchbase, the API returned errors — we tried Pitchbook and it worked"
  • "The RAG research took 3 reflection iterations before reaching quality_score > 0.8"

Episodic memory lets the agent learn from its own experience. It doesn't just know facts — it knows which strategies worked and which didn't, which sources are reliable for which kinds of questions, and how to avoid mistakes it has already made.

The three types together

TypeWhat it storesDurationExample
Short-termActive conversationOne session"The user asked to research LLMs in education"
Long-termFacts and preferencesPermanent"Prefers academic sources"
EpisodicComplete experiencesPermanent"The Crunchbase search failed, Pitchbook worked"

Not every agent needs all three types. A support chatbot can work with short-term alone. A personal assistant needs all three. Deciding which types to implement is a product and architecture decision — not a technical one. This module gives you the tools to implement each type and the judgment to decide which ones you need.


Memory as a system

Beyond "adding MemorySaver"

Turning on MemorySaver is one line of code:

from langgraph.checkpoint.memory import MemorySaver

checkpointer = MemorySaver()
graph = builder.compile(checkpointer=checkpointer)

Done. Your agent now has "memory." But this is the surface version — the equivalent of saying your application "has a database" because you added SQLite. It works for development. In production, the real questions are different:

Where does it persist?

MemorySaver saves in the process's memory. If the process restarts — deployment, crash, scaling — everything is lost. For production you need durable persistence:

OptionDurabilityLatencySetupWhen to use
MemorySaverProcess (lost on restart)~0ms1 lineDevelopment, tests
PostgresSaverDisk (always persists)1-5msDB + connectionStandard production
RedisMemory + disk (configurable)<1msRedis serverHigh-throughput, TTL

The choice isn't "which is better" — it's "what does my system need." An agent serving 10 internal users can work with PostgresSaver. One serving 100,000 concurrent users needs Redis with TTL (time-to-live) so checkpoints don't fill up memory.

When does it get cleaned up?

Memory grows. Without management, an active agent accumulates gigabytes of checkpoints, conversations, and long-term memories. You need cleanup strategies:

  • TTL (Time-to-Live): Checkpoints expire after N days. Research from 6 months ago probably isn't relevant
  • Size limits: Maximum N checkpoints per thread, N memories per user. Once the limit is exceeded, the oldest ones get deleted
  • Relevance decay: Memories that haven't been accessed in N sessions lose priority and are eventually deleted
  • Explicit cleanup: The user or an admin can say "forget my history" — GDPR, privacy, right to be forgotten

Not designing cleanup is designing a system that eventually degrades — slower, more expensive, with noisy context that confuses the agent.

How much does it cost?

Memory has a cost along three dimensions:

Storage: Every checkpoint is a snapshot of the agent's complete state. An agent with a large state (plan, tool_results, reasoning_traces, reflection_notes) generates checkpoints of several KB. With thousands of sessions, that adds up.

Tokens: Long-term memories injected into the agent's context are extra tokens on every LLM call. If the agent has 50 memories relevant to the current user, that can be 2,000-5,000 extra tokens — multiplied by every call in every step.

Latency: Querying the long-term memory store adds latency to every interaction. With MemorySaver it's negligible. With PostgreSQL in another region, it can be significant.

The architect's mindset

This module teaches you to think about memory as a system with components, trade-offs, and design decisions — not as a feature you turn on or off. The questions a memory architect answers:

  1. What types of memory does my agent need? (short-term always, long-term if there's continuity, episodic if there's learning)
  2. Where does each type persist? (in-memory for dev, PostgreSQL for prod, Redis for high-throughput)
  3. When does each type get cleaned up? (TTL, size limits, relevance decay, explicit cleanup)
  4. How much context do I inject on each call? (all relevant memory, top-K, summary)
  5. How do I manage growth? (garbage collection, archiving, compression)
  6. What about privacy? (right to be forgotten, data retention policies, multi-tenant isolation)

If you can answer these six questions for your agent, you have a memory strategy. If you can't, you have a MemorySaver and technical debt.


Prerequisites

From Module 5 (Multi-Step Reasoning and Planning)

This module takes the Research Agent v2 from M5 directly and extends it with memory. You need these to be solid:

  • Intelligent planning: Your agent breaks tasks into sub-questions with dependencies, produces structured plans, and re-plans based on detected gaps
  • Reflection with quality gates: The reflection node evaluates output with critique prompts and produces recommendations ("deliver", "re-plan", "refine") that feed conditional edges
  • Reasoning traces: You capture the agent's thought process as structured data in the state
  • Decision function: You know when planning and reflection justify their cost

From Module 4 (State Machines for Agents)

The state machine foundation is still fundamental:

  • StateGraph for agents: Functional nodes, explicit edges, controlled cycles
  • Extensible typed state: AgentState with fields that grow module by module without breaking the existing ones
  • Conditional routing: Deterministic decision points based on the state
  • Modular subgraphs: Encapsulated capabilities with clear interfaces

From Phase 1 (Modules 1-3)

The agent foundations are still in play:

  • Cognitive architecture (M1): Perceive-reason-act, agent taxonomy
  • Tool use (M2): @tool with schemas, tool execution loop, error handling
  • Function calling patterns (M3): Parallel calls, routing, structured extraction

From Guide #9 (LangChain & LangGraph)

From guide #9 specifically you need: familiarity with checkpointing and MemorySaver as concepts. Guide #9 introduced them as LangGraph features. Here you go deeper into the implementation, the trade-offs, and the design of the complete memory system.

Tools for this module

  • Python 3.11+
  • langchain v1.2+ and langchain-openai
  • langgraph v1.0+
  • OpenAI API key (GPT-4.1 or GPT-4.1-mini)
  • tavily-python for web search
  • python-dotenv for environment variables
  • psycopg for PostgreSQL (new in this module)
pip install langchain langchain-openai langgraph tavily-python python-dotenv psycopg[binary]

New dependency: psycopg (the PostgreSQL driver). It's the only new dependency compared to M5. For the PostgresSaver capsules, you'll need a running PostgreSQL instance — capsule 04 covers the complete setup.


Objectives of Module 6

By the end of this module you'll be able to:

  • Implement short-term memory with management strategies: Conversation history with trimming strategies (window-based, token-based) and summarization for long contexts — not just "saving messages", but actively managing how much context you keep and how much you discard
  • Configure checkpointing for durable execution: MemorySaver for development, PostgresSaver for production — with thread_id for sessions, the ability to resume interrupted conversations, and checkpoint inspection
  • Implement durable persistence with PostgresSaver: Complete PostgreSQL setup, connection strings, pool configuration, and the criteria for choosing between MemorySaver, PostgresSaver, and Redis based on your durability, latency, and throughput requirements
  • Build cross-session long-term memory: Memory that persists between conversations using InMemoryStore/BaseStore — user preferences, learned facts, task history, with strategies for what to remember and what to forget
  • Use time-travel debugging: Navigate the agent's complete state history, replay from any checkpoint, roll back to previous states — debugging the agent's decisions at the level of "what was it thinking in step 3?"
  • Design conversation management and memory patterns: Summary memory, entity memory, episodic memory — when to use each type, how to combine them, and how to manage memory as a limited resource with garbage collection and decay
  • Add persistent memory to the Research Agent: Checkpointing to resume interrupted research, long-term memory for user preferences, conversation management for long research runs — the complete Research Agent v3

Module map

#CapsuleWhat you'll learn
02Short-term MemoryConversation history as a managed resource. Window trimming, token-based trimming, summarization. When each strategy applies. The cost of keeping everything vs the risk of losing context. Implementation with trim_messages and summarization chains
03Checkpointing and MemorySaverHow checkpointing works internally — every node generates a snapshot. thread_id for sessions, resuming interrupted conversations, inspecting and listing checkpoints. MemorySaver as the development abstraction
04PostgresSaver: Durable PersistenceFrom MemorySaver to PostgresSaver: PostgreSQL setup, connection pool, configuration. Quantitative comparison: latency, durability, setup complexity. When each backend is justified. Migration path from dev to prod
05Cross-Session Long-term MemoryInMemoryStore and BaseStore for memory that survives sessions. Saving and querying preferences, facts, history. Namespaces for multi-tenant. The decision of what to remember and what to forget
06Time-travel DebuggingNavigating the state history, replaying from arbitrary checkpoints, rollback. Debugging that goes beyond logs: "what state was the agent in when it made this decision?" The most powerful debugging tool for agents
07Conversation Management and Memory PatternsSummary memory, entity memory, episodic memory as reusable patterns. Garbage collection: TTL, size limits, relevance decay. Memory as a limited resource. Designing a complete memory strategy
08Project: Research Agent with Persistent MemoryResearch Agent v3: checkpointing to resume research, long-term memory for preferences, conversation management for long sessions. The agent that remembers, learns, and persists

Learning flow

The module follows a progression from the most immediatethe most persistentthe most sophisticatedintegration into the project.

You start with short-term memory (capsule 02) because it's the most intuitive type of memory and the one you're already using implicitly. Every agent you've built in this guide has short-term memory — it's the messages list in the state. What you haven't done is manage it. What happens when the conversation has 100 messages? How many tokens are you paying to send that whole history on every LLM call? This capsule turns something that "just works" into something you deliberately manage with trimming and summarization.

Then checkpointing and MemorySaver (capsule 03) introduces the first form of persistence: the agent's state gets saved automatically at every step. It's not that "you save whenever you want" — the system generates a snapshot at every node in the graph. That enables two capabilities: resuming interrupted conversations (picking up where you left off) and inspecting the execution history (what happened at each step). It's the feature that triggers the module's "wow" moment — you interrupt a research run and pick it back up.

Capsule 04 (PostgresSaver) solves MemorySaver's obvious limitation: persisting in the process's memory doesn't survive a restart. PostgresSaver writes the checkpoints to a real database. It's the step from development to production. The capsule doesn't just show the technical setup — it compares latency, durability, and complexity across the options, so you can choose with data.

With long-term memory (capsule 05), the agent jumps from "remembers this session" to "remembers between sessions." This is where you implement the agent knowing that you prefer academic sources, that you already researched RAG, that your company uses FastAPI. It's a store separate from the chat history — structured information the agent queries at the start of every interaction. This capsule has the biggest impact on the user experience: it goes from "tool" to "personal assistant."

Capsule 06 (time-travel debugging) introduces the most powerful debugging capability for agents: navigating the complete state history and replaying from any point. If your agent made a bad decision at step 5 of a 12-step research run, you can go to the state at step 5, inspect what information it had, and understand why it decided what it decided. Combined with the reasoning traces from M5, you have complete observability of the agent's reasoning process.

Capsule 07 (conversation management and memory patterns) pulls everything into reusable patterns and adds the management layer: when do you clean up? how much do you retain? how do you prioritize which memories are relevant? These are the architectural decisions that make the difference between a memory system that works in week one and one that works at scale for months.

Finally, the project (capsule 08) applies everything to the Research Agent. It's not a new exercise — it's the direct evolution of the Research Agent v2 from M5. The result is Research Agent v3: an agent that plans, reflects, and remembers.


Connection with the ongoing project

Research Agent v2 (M5) → Research Agent v3 (M6)

The M5 Research Agent has this structure:

START → planning_v2 → research → analysis → reflection → [quality ok?]
             ▲                                                  │
             │                                    ┌─────────────┼──────────┐
             │                                    │             │          │
             │                               "re-plan"     "refine"   "deliver"
             │                                    │             │          │
             └────────────────────────────────────┘             │          ▼
                                                                ▼      synthesis → END
                                                         refinement
                                                                │
                                                                ▼
                                                           reflection

M6 doesn't change the graph — it changes the infrastructure underneath:

                         ┌─────────────────────────────┐
                         │     CHECKPOINTER            │
                         │  (MemorySaver / PostgreSQL)  │
                         │  Snapshot at every node      │
                         └──────────┬──────────────────┘
                                    │
START → planning_v2 → research → analysis → reflection → [quality ok?]
  │          ▲                                                  │
  │          │                                    ┌─────────────┼──────────┐
  │          │                               "re-plan"     "refine"   "deliver"
  │          │                                    │             │          │
  │          └────────────────────────────────────┘             │          ▼
  │                                                             ▼      synthesis → END
  │                                                      refinement         │
  │                                                             │           │
  │                                                             ▼           │
  │                                                        reflection       │
  │                                                                         │
  └──── LONG-TERM MEMORY STORE ─────────────────────────────────────────────┘
         (preferences, history, episodic)
         Queried at the start, updated at the end

What changes concretely

1. A checkpointer is added when compiling the graph

from langgraph.checkpoint.memory import MemorySaver

checkpointer = MemorySaver()  # Dev: in-memory
# checkpointer = PostgresSaver(conn)  # Prod: PostgreSQL

graph = builder.compile(checkpointer=checkpointer)

Every node in the graph now generates a snapshot automatically. If the execution is interrupted at analysis, invoking again with the same thread_id makes the agent pick up from the last checkpoint.

2. Invocations use thread_id

Before (M5):

result = graph.invoke({"messages": [("user", "Research AI regulations")]})

After (M6):

config = {"configurable": {"thread_id": "research-session-001"}}
result = graph.invoke(
    {"messages": [("user", "Research AI regulations")]},
    config=config
)

# Resume after an interruption:
result = graph.invoke(
    {"messages": [("user", "Continue with the research")]},
    config=config  # Same thread_id → picks up from the last checkpoint
)

3. A long-term memory store is added

from langgraph.store.memory import InMemoryStore

store = InMemoryStore()
graph = builder.compile(checkpointer=checkpointer, store=store)

# At the start of planning_v2: query the preferences
def planning_v2(state: AgentState, config: RunnableConfig, *, store: BaseStore):
    user_id = config["configurable"]["user_id"]
    memories = store.search(("user_preferences", user_id))
    preferences = [m.value for m in memories]
    # Use the preferences in the planning prompt...

4. Memory fields are added to the state

class AgentState(TypedDict):
    # M4 fields (unchanged)
    messages: Annotated[list[BaseMessage], add_messages]
    current_plan: dict
    iteration_count: int
    tool_results: list[dict]
    quality_score: float
    budget_remaining: float
    metadata: dict
    # M5 fields (unchanged)
    reflection_notes: Optional[dict]
    planning_iterations: int
    completed_subtasks: list[str]
    reasoning_trace: list[dict]
    synthesis_draft: Optional[str]
    # New M6 fields
    session_summary: Optional[str]
    resumed_from_checkpoint: bool
    memory_context: Optional[dict]

The M4 and M5 fields aren't touched. Only new ones are added. The extensible state you designed in M4 keeps paying dividends.

5. Research Agent v3 has three new capabilities

CapabilityWhat it doesImpact on UX
CheckpointingPersists the state at every node in the graph"Pick up where you left off" — the research survives interruptions
Long-term memoryRemembers preferences and context between sessions"It knows you prefer papers" — the agent personalizes without you repeating yourself
Conversation managementManages the history when it grows too large"It doesn't get slow" — trimming and summarization keep performance stable

What this module does NOT cover

  • LangGraph fundamentals — StateGraph, nodes, edges, and compilation are not re-taught. That's M4. Here you configure the existing graph with checkpointers and stores
  • Planning or reflection — How to plan or reflect is not re-taught. That's M5. Here you make plans and reflections persist
  • RAG (Retrieval Augmented Generation) — RAG uses embeddings and vector stores to retrieve information. Agent long-term memory is different: it stores preferences, facts, and experiences — not document chunks. If you need RAG, guide #9 covers it
  • Vector databases in detail — Pinecone, Weaviate, Chroma. This module uses LangGraph's native stores (InMemoryStore, BaseStore) and PostgreSQL. If you need vector search for your memories, it's an extension you can add — but it isn't the focus here
  • Multi-agent memory — Shared memory across multiple agents, memory isolation, and conflict resolution. That's part of Module 8 (Multi-Agent Orchestration). Here a single agent manages its own memory
  • Fine-tuning with memory — Using accumulated memories to fine-tune the model and improve its performance. That's training, not inference. This module operates with off-the-shelf models
  • Compliance and data governance — GDPR, HIPAA, data retention policies in detail. They're mentioned as considerations (right to be forgotten, cleanup), but a compliance-ready implementation is a production topic that M10 partially covers

The boundary is clear: M6 = how the agent remembers (short-term, long-term, persistence, management). M5 = how it thinks. M7 = how it connects to the world.


Evidence of success

By the end of this module, you'll know you succeeded if:

  • ✅ You can implement three short-term memory strategies (window trimming, token-based trimming, summarization) and argue when each one applies — with data on tokens used and context preserved
  • ✅ Your agent persists its state with checkpointing, and you can interrupt an execution halfway through, close everything, and resume exactly where it left off using the same thread_id
  • ✅ You can migrate from MemorySaver to PostgresSaver without changing the graph — only the checkpointer configuration — and explain the differences in durability, latency, and setup
  • ✅ Your agent has long-term memory that persists between sessions: it remembers user preferences without being told again, and that behavior is demonstrable across different sessions
  • ✅ You can navigate your agent's state history with time-travel debugging, go to any checkpoint, inspect the state at that point, and replay — debugging the reasoning at the level of "what did the agent know when it made this decision?"
  • ✅ Your memory strategy has garbage collection: you define when checkpoints expire, how many memories are retained per user, and what happens when the limits are exceeded
  • ✅ Your Research Agent v3 can resume interrupted research, personalizes its answers based on remembered preferences, and keeps stable performance in long conversations via conversation management

Quick self-assessment

Ask yourself these questions after finishing the module:

  1. "If my agent crashes halfway through an 8-step research run, can the user resume exactly at the step where it was interrupted?" → If yes, your checkpointing works
  2. "If a user runs my agent across 5 different sessions, does the fifth session feel different from the first because of the accumulated context?" → If yes, your long-term memory is adding value
  3. "Can I go to the agent's state at step 3 of a past research run and see exactly what plan it had and what results it had accumulated?" → If yes, your time-travel debugging works
  4. "Do I have a defined strategy for when to clean up old memories, or do I just accumulate everything?" → If you have a strategy, you thought like an architect

If you answered yes to all four → you're ready for Module 7 (MCP and Advanced Tool Integration). If you answered no to any of them → reinforce the corresponding capsule before moving on.


Summary

  • From stateless to stateful: M4 controlled the flow, M5 added intelligence to the decisions, M6 makes it all persist. Without memory, every session starts from zero — with memory, the agent accumulates context, learns preferences, and resumes interrupted tasks
  • Three types of memory: Short-term (the active conversation — managed with trimming and summarization), long-term (knowledge between sessions — preferences, facts, history), episodic (past experiences — what worked, what failed, which strategies were effective)
  • Memory as a system, not a feature: The question isn't "how do I enable MemorySaver?" but "where does it persist, when does it get cleaned up, how much does it cost, and what memory strategy does my agent need?"
  • Checkpointing enables durable execution: Every node in the graph generates a snapshot. Interruptions, crashes, deployments — the agent resumes from the last checkpoint. It's the foundation of "continue where you left off"
  • Long-term memory transforms the experience: An agent that remembers preferences between sessions goes from being a tool to being a colleague. The difference shows from the second interaction onward
  • Management is mandatory: Memory without cleanup grows indefinitely — slower, more expensive, noisier. TTL, size limits, relevance decay, and garbage collection are part of the design, not extras
  • The Research Agent evolves again: v1 (M4) had a state machine, v2 (M5) added planning and reflection, v3 (M6) adds checkpointing, long-term memory, and conversation management. The extensible state absorbs the new fields without breaking the existing ones

Resources

  1. LangGraph: Persistence & Checkpointing — Official documentation on checkpointing in LangGraph. Covers MemorySaver, PostgresSaver, and the conceptual model of persistence
  2. LangGraph: Memory — Official documentation on memory in LangGraph. Stores, long-term memory, and memory management patterns
  3. LangGraph: Time Travel — Official documentation on time-travel debugging. Replay, fork, and navigating state history
  4. How to manage conversation history — Official how-to guide for trimming and summarizing conversation history
  5. How to add long-term memory (cross-thread) — Official how-to guide for InMemoryStore and cross-session persistence
  6. Building Effective Agents — Anthropic — Anthropic's perspective on memory patterns in agents. Complements the LangGraph approach