Memory Systems

Module 4: How Agents Remember and Learn

Picture this: one thread, two turns

Turn 2 only says “What is my name?” MemorySaver + the same thread_id replay turn 1 so the model still knows Kodin.

Turn 1Hi, my name is Kodin
→
MemorySaverthread_id = 1
→
Turn 2What is my name?
→
ReplyYour name is Kodin

Change thread_id to 2 and the name is forgotten. That is short-term (session) memory, not a vector database.

Types of Agent Memory

Short-Term Memory

Conversation context and immediate state.

Duration: Current session
Size: 4K-100K tokens
Use: Current conversation

The current conversation history that the agent uses to understand context and make decisions in real-time.

Long-Term Memory

Persistent knowledge and learned patterns.

Duration: Across sessions
Size: Unlimited (database)
Use: Knowledge base

Stored in databases, enables the agent to remember user preferences, past interactions, and learned strategies.

Memory Evolution in Agents

Generation 1

No memory. Each query is independent.

Generation 2

Conversation history. Remembers current chat only.

Generation 3

Summarization. Compresses history to fit limits.

Generation 4

Semantic search. Finds relevant past interactions.

Generation 5

Hybrid memory. Short-term + long-term combined.

Today

Persistent learning. Agents that truly remember.

Short-Term vs Long-Term Memory

Aspect Short-Term Long-Term
Storage In memory (RAM) Database (persistent)
Lifespan One session Years
Speed Instant access Query-based (ms)
Capacity Limited (tokens) Unlimited
Example "User just said they like coffee" "User always prefers morning meetings"

Before you click Practice — Module 4 notebook

Short-term memory in LangGraph is a checkpointer plus a thread_id. Same thread → the graph remembers prior messages. Different thread → a blank conversation.

StateGraph→MemorySaver→thread_id = 1→two invokes

You will say your name in turn 1 and ask “What is my name?” in turn 2. If memory works, the model answers Kodin.

Practice task 1

Install packages into this notebook’s Python

Run the first code cell. It uses sys.executable -m pip so packages go into Kodin’s Jupyter kernel, not a random Windows pip.

# Install into THIS notebook kernel (not Windows pip).
import sys
import subprocess

print("Installing into:", sys.executable)
subprocess.check_call([
    sys.executable, "-m", "pip", "install", "-qU",
    "langgraph", "langchain-groq", "langchain-core",
])
print("Done. Run the next cells.")

Expected: Prints the kernel path, then “Done.”

Why this cell: A plain !pip install on Windows often installs into a different Python, then the next cell fails with ModuleNotFoundError: langgraph. If import still fails: Kernel → Restart Kernel, then Run All.
Practice task 2

API key + MODEL + groq_text (same as Module 1)

Every practice notebook repeats this cell. Run it before any Groq call. Key stays in os.environ["GROQ_API_KEY"] for this kernel session.

import os
MODEL = "openai/gpt-oss-20b"

def groq_text(msg) -> str:
    # GPT-OSS may return text, a list of parts, or reasoning_content
    ...

if not os.getenv("GROQ_API_KEY"):
    os.environ["GROQ_API_KEY"] = input("Enter GROQ_API_KEY: ").strip()
print("API key ready. Model:", MODEL)

Expected: “API key ready. Model: openai/gpt-oss-20b”

Why this cell: Without this cell, ChatGroq has no key. Without groq_text, later prints can look empty even when the model answered.
Practice task 3

Stateful graph: chatbot node + MemorySaver

The state is a list of messages. add_messages appends instead of replacing. compile(checkpointer=memory) stores that list under thread_id.

from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langchain_groq import ChatGroq
from langgraph.checkpoint.memory import MemorySaver

class State(TypedDict):
    messages: Annotated[list, add_messages]

llm = ChatGroq(model=MODEL, temperature=0)

def chatbot(state: State):
    return {"messages": [llm.invoke(state["messages"])]}

graph_builder = StateGraph(State)
graph_builder.add_node("chatbot", chatbot)
graph_builder.add_edge(START, "chatbot")
graph_builder.add_edge("chatbot", END)

memory = MemorySaver()
app = graph_builder.compile(checkpointer=memory)
config = {"configurable": {"thread_id": "1"}}

resp1 = app.invoke({"messages": [("user", "Hi, my name is Kodin.")]}, config)
print("AI:", groq_text(resp1["messages"][-1]))

resp2 = app.invoke({"messages": [("user", "What is my name?")]}, config)
print("AI:", groq_text(resp2["messages"][-1]))
  • State — shared bag of data the graph updates.
  • add_node / add_edge — START → chatbot → END (one hop per invoke).
  • config thread_id — which conversation to load/save.

Expected: Second print includes the name Kodin.

Why this cell: Turn 2 only sends “What is my name?” — the name is not in that string. The checkpointer replays the saved thread so the LLM sees both messages. Change thread_id to "2" and the name is forgotten. That is short-term (session) memory, not a vector database.

✏️ Practice: Memory Type Identification

Q1: An agent remembers that a user said "I prefer tea over coffee" 6 months ago and uses this for recommendations. Which memory type?

Q2: An agent is having a conversation and references something the user said 5 minutes ago. Which memory type?