Contents (30 slides) 1 · Title2 · Parts of an agent3 · Memory4 · Why memory 5 · Questions6 · Writing memory7 · Types8 · Short-term 9 · Trim & delete10 · Summarize11 · Trade-offs12 · Long-term 13 · Semantic14 · Why semantic15 · Representation16 · Storage 17 · Usage18 · Episodic19 · Why episodic20 · Representation 21 · Storage22 · Failure path23 · Success path24 · Retrieval 25 · Procedural26 · Why procedural27 · Representation28 · Storage 29 · Usage30 · SummaryGlossaryCheck yourself
By Shivank Agarwal · 30 slides · every slide covered

Adding Memory to Your Agents: making agents remember and evolve, explained simply

Each slide gets the same treatment: what the slide says, the idea in plain words, an everyday analogy, a real-world example, and code wherever the slide only gives theory.

Code marked Ran it was actually run, and the output under it is real. Code that needs your OpenAI key has an example output under it, so learners can follow just by reading.

▢ What the slide says💡 In simple words🍛 Analogy🌍 Real world⌨️ Try it in code⚠️ Careful

The whole talk in one picture

A language model forgets everything the moment it finishes answering. Memory is everything your agent stores and brings back so it can follow a conversation (short-term) and know its users, facts and skills across days and weeks (long-term: semantic, episodic and procedural).

1 · Why memoryslides 1–7
→
2 · Short-termslides 8–11
→
3 · Long-termslides 12–29
→
4 · Summaryslide 30
Part 1

Why agents need memory

Slide 1

Adding memory to your agents: making agents remember and evolve

by Shivank Agarwal

💡 In simple words

A model answers each message as if it has never seen you before. Memory is what your agent saves and brings back: what was said a minute ago, who the user is, what's true about your business, what happened last time, and how to do a task well. With memory, an agent can remember (continuity) and evolve (get better with experience).

🍛 Analogy

Your regular chai-wala remembers that you take less sugar, that you were travelling last week, and how to make your usual just right. A new stall forgets you every morning. Memory turns the new stall into the regular one.

Slide 2

Components of an agentic system

▢ What the slide shows

An agent in the centre, connected to four parts: model, memory, tools, and planning and reasoning.

Agent Memorywhat it remembers Toolshands and eyes Modelthe brain (e.g. gpt-6-luna) Planning & reasoningwhich step next?

💡 Each part in one line

  • Model: understands the request and writes the answer.
  • Tools: fetch real data and take real actions (previous lecture).
  • Memory: keeps what the agent has seen and learned, and brings back the right bits at the right time (this lecture).
  • Planning & reasoning: decides the next step.
Slide 3

Let us now focus on the memory

▢ What the slide shows

The same four-part picture, now with the spotlight on memory.

🍛 Analogy: a hospital

The doctor is the model, the X-ray machine is a tool, and the patient's file is memory. A brilliant doctor without the file asks every patient the same questions again and may repeat a treatment that failed last time. The file makes the whole hospital smarter.

Slide 4

Why do LLM applications need memory?

▢ What the slide says

  • LLMs are stateless.
  • Stateless bots forget past turns and need repeated clarifications.
  • Memory enables: context continuity, personalization, and richer dialog (referring to the past).
  • Real-world agents have memory modules built in.

💡 "Stateless" in plain words

Each call to a model is a fresh start: it gets the text you send, writes a reply, and keeps nothing. If a chatbot seems to remember, it's because the app sends the earlier messages along again every time. That re-sending is the simplest form of memory.

⌨️ Try it in code: forgetting vs remembering

m04_stateless.pyNeeds OpenAI key
"""An LLM API call remembers nothing. Memory = sending the history again."""
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()


def ask(messages):
    reply = client.chat.completions.create(model="gpt-6-luna", reasoning_effort="none", messages=messages)
    return reply.choices[0].message.content


print("--- Two separate calls (no memory) ---")
print("A:", ask([{"role": "user", "content": "Hi, I'm Priya. I'm vegetarian and I live in Pune."}]))
print("A:", ask([{"role": "user", "content": "Suggest a dinner place for me tonight."}]))

print("\n--- Same questions, history sent along (short-term memory) ---")
history = [{"role": "user", "content": "Hi, I'm Priya. I'm vegetarian and I live in Pune."}]
history.append({"role": "assistant", "content": ask(history)})
history.append({"role": "user", "content": "Suggest a dinner place for me tonight."})
print("A:", ask(history))
Example output (what you would see; exact text and numbers vary)
--- Two separate calls (no memory) ---
A: Hi Priya, nice to meet you! Pune has a great vegetarian food scene. How can I help you today?
A: Happy to help! Which city are you in, and what kind of food do you like? Then I can suggest
a few places for tonight.

--- Same questions, history sent along (short-term memory) ---
A: Since you're vegetarian and in Pune, how about a traditional Maharashtrian thali tonight, or a
South Indian dinner around FC Road? Both are easy to find fully vegetarian. Tell me your area and
budget and I'll narrow it down.

Same model, same question. The only difference is whether the earlier message was sent along. That's "context continuity" and "personalization" in four lines of code.

🌍 Real world

Chat assistants such as ChatGPT and Claude now offer memory that carries facts you've shared across conversations. Customer-support bots look up your past tickets before replying. Coding assistants remember your project's conventions.

Slide 5

Things to think about when adding memory

▢ What the slide says

QuestionWhat the slide asks
WhatWhat content should the agent learn: facts and knowledge, summaries of past events, or rules and style?
WhenWhen should memories be formed, and who forms them?
WhereWhere should memories be stored: in the prompt, in a semantic store? This largely decides how they're recalled.
HowRetrieval: similarity search, filtering, recency.
How muchMemory size limits and pruning strategies.

🌍 The five questions answered for a food-delivery support bot

QuestionExample answer
WhatFacts (refund rules), the user's preferences (vegetarian, no onion), past events (last order arrived cold), style rules (apologise first)
When / whoThe agent saves preferences during the chat; a nightly job summarises past tickets
WhereRefund rules in the system prompt; preferences in a database keyed by user ID; old tickets in a vector store
HowPreferences by user ID (filter); similar past tickets by meaning (similarity); only the last 90 days (recency)
How muchAt most 50 facts per user; tickets older than a year are summarised, then deleted

🍛 Analogy

Organising a kitchen: what to stock (what), when to restock (when), shelf or fridge (where), labels so you can find it (how), and throwing out what's expired (how much).

Slide 6

Writing memory: hot path vs in the background

▢ What the slide shows

Two timelines. Hot path: user message → update memory → AI response, every turn. In the background: user message → AI response, repeated; then, say 30 minutes later, a separate update of memory. Key trade-off: real-time vs computational efficiency.

🔥 Hot path
User message
Update memory
AI response
User message
Update memory
AI response

✅ Memory is fresh at once · ❌ every reply is slower and costs an extra model call

🌙 In the background
User message
AI response
User message
AI response
⏱ 30 min later
Update memory (one batch)

✅ Fast replies, fewer calls · ❌ new facts aren't saved until later

⌨️ Try it in code: the same chat, both ways

m06_hot_vs_background.pyNeeds OpenAI key
"""Writing memory: in the hot path (every turn, before replying) vs in the background (later, in one batch)."""
import json
import time

from dotenv import load_dotenv
from langchain_openai import ChatOpenAI

load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
extractor = llm.bind(response_format={"type": "json_object"})

EXTRACT = ('Extract lasting facts about the user from these messages as JSON: {{"facts": ["..."]}}. '
           'Only facts worth remembering for future chats. Messages:\n{messages}')

chat = ["I'm planning a trip to Rishikesh with my parents next month.",
        "My mother can't climb stairs, by the way.",
        "Which area should we stay in?"]

print("=== HOT PATH: update memory inside every turn ===")
memory, start = [], time.perf_counter()
for msg in chat:
    t0 = time.perf_counter()
    facts = json.loads(extractor.invoke(EXTRACT.format(messages=msg)).text)["facts"]   # extra call BEFORE replying
    memory += facts
    reply = llm.invoke(f"Known about the user: {memory}\nUser: {msg}").text
    print(f"user: {msg}\n   memory now: {memory}\n   reply waited {time.perf_counter() - t0:.1f}s")
print(f"total {time.perf_counter() - start:.1f}s\n")

print("=== BACKGROUND: reply now, update memory later in one batch ===")
start = time.perf_counter()
for msg in chat:
    t0 = time.perf_counter()
    reply = llm.invoke(f"User: {msg}").text                                            # no memory work here
    print(f"user: {msg}\n   reply waited {time.perf_counter() - t0:.1f}s")
facts = json.loads(extractor.invoke(EXTRACT.format(messages="\n".join(chat))).text)["facts"]   # e.g. 30 min later
print(f"later, one batch job saved: {facts}")
print(f"total {time.perf_counter() - start:.1f}s")
Example output (what you would see; exact text and numbers vary)
=== HOT PATH: update memory inside every turn ===
user: I'm planning a trip to Rishikesh with my parents next month.
   memory now: ['Planning a trip to Rishikesh with their parents next month']
   reply waited 2.1s
user: My mother can't climb stairs, by the way.
   memory now: ['Planning a trip to Rishikesh with their parents next month', "User's mother can't climb stairs"]
   reply waited 1.9s
user: Which area should we stay in?
   memory now: ['Planning a trip to Rishikesh with their parents next month', "User's mother can't climb stairs"]
   reply waited 2.3s
total 6.3s

=== BACKGROUND: reply now, update memory later in one batch ===
user: I'm planning a trip to Rishikesh with my parents next month.
   reply waited 1.2s
user: My mother can't climb stairs, by the way.
   reply waited 1.1s
user: Which area should we stay in?
   reply waited 1.3s
later, one batch job saved: ['Planning a trip to Rishikesh with their parents next month', "User's mother can't climb stairs"]
total 4.6s

Both saved the same two facts. The hot path made every reply about a second slower; the background job made one extra call at the end. Inside this conversation the chat history still carries the facts either way; what's delayed is them reaching future conversations.

🍛 Analogy

A shopkeeper who writes each sale in the ledger before serving the next customer (hot path) versus one who serves everyone and updates the ledger at closing time (background).

Slide 7

Types of memory in agents

▢ What the slide shows

A tree: types of memory split into short-term and long-term; long-term splits into semantic, procedural and episodic.

Types of memory Short-termthis conversation Long-termacross conversations Semanticwhat is true Episodicwhat happened Proceduralhow to act
Semantic = facts · Episodic = experiences · Procedural = skills.
TypeRemembers…Human exampleAgent example
Short-termThe current conversationWhat your friend said a minute agoThe last 20 messages of this chat
SemanticFacts: what is true"Delhi is the capital of India""Refunds are allowed within 30 days"; "This user is vegetarian"
EpisodicExperiences: what happened"My last train to Pune was 2 hours late""Last time, the shipping API rejected this order ID"
ProceduralSkills: how to do thingsRiding a bike"To track an order: validate the ID, then look it up in the DB"
Part 2

Short-term memory

Slide 8

Short-term memory

▢ What the slide says

  • Short-term memory (thread-scoped) keeps the ongoing conversation history within a session.
  • In LangGraph it is managed as the agent's state.
  • State includes the conversation history, uploaded files, retrieved documents and generated artifacts.
  • Persistence: state is saved to a database by a checkpointer, so a thread can be resumed.
  • Update cycle: memory updates when the graph is invoked or a step completes.
  • Usage: state is read at the start of each step for continuity.

💡 New words

  • Thread: one conversation, identified by a thread_id. Two users chatting = two threads, each with its own memory.
  • State: everything the agent is carrying for this thread right now (messages, files, results).
  • Checkpointer: saves the state after every step, like an auto-save. Come back tomorrow with the same thread_id and the conversation continues.

⌨️ Try it in code: two threads, one checkpointer

m08_checkpointer.pyNeeds OpenAI key
"""Short-term memory in LangGraph: the state is saved per thread by a checkpointer."""
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import START, MessagesState, StateGraph

load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")


def chatbot(state: MessagesState):
    return {"messages": [llm.invoke(state["messages"])]}     # the whole thread history goes to the model


builder = StateGraph(MessagesState)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
graph = builder.compile(checkpointer=InMemorySaver())       # saves the state after every step

ravi = {"configurable": {"thread_id": "ravi-chat"}}
meera = {"configurable": {"thread_id": "meera-chat"}}

graph.invoke({"messages": [("user", "Hi, I'm Ravi. My order number is 4471.")]}, ravi)
print("Ravi, same thread :", graph.invoke({"messages": [("user", "What's my order number?")]}, ravi)["messages"][-1].text)
print("Meera, new thread :", graph.invoke({"messages": [("user", "What's my order number?")]}, meera)["messages"][-1].text)

saved = graph.get_state(ravi).values["messages"]
print(f"\nSaved in thread 'ravi-chat': {len(saved)} messages")
for m in saved:
    print(f"  {m.type:>5}: {m.text[:70]}")
Example output (what you would see; exact text and numbers vary)
Ravi, same thread : Your order number is 4471.
Meera, new thread : I don't have your order number yet. Could you share it, along with the name or
email used for the order?

Saved in thread 'ravi-chat': 4 messages
  human: Hi, I'm Ravi. My order number is 4471.
     ai: Hi Ravi! Thanks for sharing your order number, 4471. How can I help you with it today?
  human: What's my order number?
     ai: Your order number is 4471.

Ravi's thread remembers his order number; Meera's brand-new thread doesn't. Nobody wrote any "save" or "load" code: the checkpointer stored the state after each step and loaded it on the next call with the same thread_id. In production, swap InMemorySaver for a database-backed checkpointer (for example PostgreSQL) so threads survive restarts.

🍛 Analogy

WhatsApp chats: each contact has its own chat (thread). Open any chat and the old messages are still there (checkpointer). Your messages with Ravi don't appear in your chat with Meera.

Slide 9

Managing short-term memory: trimming and deleting

▢ What the slide shows

Trim messages
Remove the first or last N messages before calling the LLM. The code uses trim_messages(state["messages"], strategy="last", token_counter=count_tokens_approximately, max_tokens=128, start_on="human", end_on=("human", "tool")).
Delete messages
Remove messages from LangGraph state permanently. The code returns RemoveMessage(id=m.id) for the earliest two messages.

💡 Why we need this at all

Every message in the history is sent again on every call. A long chat means more tokens (more cost), slower replies, and eventually hitting the model's context limit. So we keep the history small.

Trimming changes only what the model sees this time; the saved history stays complete. Deleting changes what is saved.

⌨️ Try it in code: both techniques on one conversation

m09_trim_delete.pyRan it ✓ real output below
"""The slide's two techniques on a saved conversation: trim before calling the model, delete from state."""
from langchain_core.messages import AIMessage, HumanMessage, RemoveMessage, trim_messages
from langchain_core.messages.utils import count_tokens_approximately
from langgraph.graph.message import add_messages

conversation = [
    HumanMessage("Hi, I'm Kabir. I need a laptop for college, budget ₹60,000."),
    AIMessage("Hi Kabir! For ₹60,000, good options are thin-and-light laptops with 16 GB RAM and an SSD."),
    HumanMessage("I also edit videos sometimes. Does that change anything?"),
    AIMessage("Yes. For video editing, prefer a dedicated GPU and at least 16 GB RAM; battery life will be lower."),
    HumanMessage("Which is more important for editing, RAM or GPU?"),
    AIMessage("For 1080p editing, 16 GB RAM matters most; the GPU speeds up exports and effects."),
    HumanMessage("Okay. So what should I buy?"),
]


def show(title, messages):
    print(f"{title} ({len(messages)} messages, ~{count_tokens_approximately(messages)} tokens)")
    for m in messages:
        print(f"   {m.type:>5}: {m.content[:60]}")


show("FULL HISTORY", conversation)

# 1. TRIM: what the model sees this turn (the saved history is NOT changed)
trimmed = trim_messages(
    conversation,
    strategy="last",                          # keep the newest messages
    token_counter=count_tokens_approximately,
    max_tokens=80,
    start_on="human",                         # kept part must start with a user message
    end_on=("human", "tool"),                 # ...and end with one (the question to answer)
)
show("\nTRIMMED for this model call", trimmed)

# 2. DELETE: remove messages from the agent's state for good
state = add_messages([], conversation)        # LangGraph gives every message an id
state = add_messages(state, [RemoveMessage(id=m.id) for m in state[:2]])   # remove the earliest two
show("\nSTATE after deleting the earliest two", state)
Output (real run)
FULL HISTORY (7 messages, ~148 tokens)
   human: Hi, I'm Kabir. I need a laptop for college, budget ₹60,000.
      ai: Hi Kabir! For ₹60,000, good options are thin-and-light lapto
   human: I also edit videos sometimes. Does that change anything?
      ai: Yes. For video editing, prefer a dedicated GPU and at least 
   human: Which is more important for editing, RAM or GPU?
      ai: For 1080p editing, 16 GB RAM matters most; the GPU speeds up
   human: Okay. So what should I buy?

TRIMMED for this model call (3 messages, ~53 tokens)
   human: Which is more important for editing, RAM or GPU?
      ai: For 1080p editing, 16 GB RAM matters most; the GPU speeds up
   human: Okay. So what should I buy?

STATE after deleting the earliest two (5 messages, ~101 tokens)
   human: I also edit videos sometimes. Does that change anything?
      ai: Yes. For video editing, prefer a dedicated GPU and at least 
   human: Which is more important for editing, RAM or GPU?
      ai: For 1080p editing, 16 GB RAM matters most; the GPU speeds up
   human: Okay. So what should I buy?
  • strategy="last" kept the newest messages; start_on="human" made sure the kept part begins with a user message (models expect that); end_on made it end with the question being answered.
  • Notice what trimming lost: Kabir's name and his ₹60,000 budget. If the model is asked "so what should I buy?", it no longer knows the budget. That's slide 11's warning.

🍛 Analogy

Trimming is reading only the last page of your notes before an exam: the notebook is untouched. Deleting is tearing out the first two pages for good.

Slide 10

Managing short-term memory: summarizing

▢ What the slide shows

A flowchart: start conversation → save new message → increment message counter → count ≥ threshold? If no, continue the conversation. If yes: trigger summarization → summarize using the LLM → clear old messages → store the summary in the buffer → reset the counter → continue with the updated memory.

New message saved
↓
More messages than the threshold?
No → carry on
Yes → LLM writes a summary → delete old messages → keep summary + last few

⌨️ Try it in code: the flowchart as a LangGraph agent

m10_summarize_graph.pyNeeds OpenAI key
"""The slide's flowchart in LangGraph: when the history gets long, summarise it and delete the old messages."""
from dotenv import load_dotenv
from langchain_core.messages import RemoveMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, MessagesState, StateGraph

load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
THRESHOLD = 6           # summarise once there are more than 6 messages


class State(MessagesState):
    summary: str        # the running summary, stored next to the messages


def chat(state: State):
    context = [SystemMessage(f"Summary of earlier conversation: {state['summary']}")] if state.get("summary") else []
    return {"messages": [llm.invoke(context + state["messages"])]}


def should_summarize(state: State):
    return "summarize" if len(state["messages"]) > THRESHOLD else END     # "count >= threshold?"


def summarize(state: State):
    prompt = (f"Current summary: {state.get('summary', 'none')}\n"
              "Extend it with the new messages above. Keep names, numbers and decisions. 3 sentences max.")
    summary = llm.invoke(state["messages"] + [("user", prompt)]).text
    old = [RemoveMessage(id=m.id) for m in state["messages"][:-2]]           # "clear old messages", keep the last 2
    return {"summary": summary, "messages": old}


g = StateGraph(State)
g.add_node("chat", chat)
g.add_node("summarize", summarize)
g.add_edge(START, "chat")
g.add_conditional_edges("chat", should_summarize)
g.add_edge("summarize", END)
graph = g.compile(checkpointer=InMemorySaver())

cfg = {"configurable": {"thread_id": "trip"}}
for msg in ["Hi, I'm Neha. Planning 4 days in Kerala in December with my parents.",
            "My father can't walk long distances.",
            "Budget is about ₹80,000 for all three of us.",
            "Should we do a houseboat in Alleppey?",
            "What did I say my budget was, and who is travelling?"]:
    out = graph.invoke({"messages": [("user", msg)]}, cfg)
    print(f"You: {msg}\nBot: {out['messages'][-1].text}\n   [messages kept: {len(out['messages'])}]")
print("\nSaved summary:", graph.get_state(cfg).values.get("summary"))
Example output (what you would see; exact text and numbers vary)
You: Hi, I'm Neha. Planning 4 days in Kerala in December with my parents.
Bot: Hi Neha! Kerala in December is lovely: cool and mostly dry. For 4 relaxed days with your parents,
a Kochi → Munnar → Alleppey loop works well. Want a day-by-day plan?
   [messages kept: 2]
You: My father can't walk long distances.
Bot: Thanks for telling me. I'll keep walking to a minimum: hotels with lifts, viewpoints you can drive
up to, and boat rides instead of walking tours.
   [messages kept: 4]
You: Budget is about ₹80,000 for all three of us.
Bot: That works well for 4 days: roughly ₹35,000 for hotels, ₹20,000 for a car with driver, ₹15,000 for
a houseboat night, and the rest for food and tickets.
   [messages kept: 6]
You: Should we do a houseboat in Alleppey?
Bot: Yes, one night on a houseboat is a great fit: your father can relax on board without walking, and
boarding is usually just a few steps from the jetty. Ask for a ground-level bedroom.
   [messages kept: 2]
You: What did I say my budget was, and who is travelling?
Bot: Your budget is about ₹80,000 for three people: you and your parents. And since your father can't
walk long distances, I've kept the plan light on walking.
   [messages kept: 4]

Saved summary: Neha is planning a 4-day Kerala trip in December with her parents, on a budget of about
₹80,000 for three. Her father can't walk long distances, so walking should be kept to a minimum. She
is considering a one-night houseboat in Alleppey.

After turn 4 there were 8 messages, more than the threshold of 6, so the agent summarised and deleted all but the last two. Yet in turn 5 it still knew the budget and who's travelling: those facts survived inside the summary.

🍛 Analogy

Minutes of a long meeting: nobody keeps the full recording, but the minutes keep the decisions and numbers.

Slide 11

Short-term memory: limitations and trade-offs

▢ What the slide says

  • Trim too aggressively and you lose context: the model "forgets" earlier information.
  • Summarization can omit subtle details.
  • Deciding when to summarize versus prune is heuristic-based.
  • You must balance recency against importance.
🧪 Trim a conversation yourself

Keep only the last 4 messages. Which important facts survive?

TechniqueGood atRiskUse when
Keep everythingNothing is lostCost and context limitShort chats
TrimmingSimple, free, automaticLoses early facts (name, budget)Only recent turns matter
DeletingPrecise controlYou must decide what's safe to deleteRemoving big tool outputs, sensitive data
SummarizingKeeps the key factsExtra LLM calls; may drop small detailsLong chats where early facts matter

💡 A common, practical combination

Pin the important facts (name, budget, constraints) in long-term memory or a "summary" field, summarise the middle, and keep the last few messages word-for-word. You get recency and importance.

Part 3

Long-term memory

Slide 12

Long-term memory

▢ What the slide says

  • Persistent memory across sessions.
  • Lets the agent "remember" users over time.
  • Needs a backing store plus a retrieval strategy.
  • Remembering birthdays, preferences, history.
  • Examples in AI agents: persisting user profiles, past purchases.

💡 Short-term vs long-term

Short-termLong-term
Lives forOne conversation (thread)Weeks, months, forever
Shared between chats?NoYes: every new chat with this user can use it
LangGraph toolCheckpointer + thread_idStore + namespace (e.g. the user ID)
Example"You just said your budget is ₹60,000""Happy birthday, Ananya! Still vegetarian, right?"

⌨️ Try it in code: a store that outlives the conversation

m12_long_term_store.pyRan it ✓ real output below
"""Long-term memory in LangGraph: a Store shared by ALL threads, organised by namespace (e.g. per user)."""
from langgraph.store.memory import InMemoryStore

store = InMemoryStore()          # in production: a database-backed store such as PostgresStore

# --- Session 1 (Monday): the agent learns things about user u_42 ---
ns = ("u_42", "profile")         # namespace = a folder per user
store.put(ns, "name", {"value": "Ananya"})
store.put(ns, "birthday", {"value": "14 March"})
store.put(ns, "diet", {"value": "vegetarian, no onion or garlic"})
store.put(("u_42", "orders"), "ORD-9001", {"item": "Running shoes", "status": "delivered"})

# --- Session 2 (Friday): a NEW conversation thread, same user ---
print("Profile of u_42:")
for item in store.search(("u_42", "profile")):
    print(f"   {item.key:<9} -> {item.value['value']}   (saved {item.created_at:%d %b %Y})")

print("\nPast orders:", [(i.key, i.value["item"]) for i in store.search(("u_42", "orders"))])
print("Another user's profile:", store.search(("u_77", "profile")), "(nothing leaks between users)")

# Updating a memory overwrites it; deleting forgets it
store.put(ns, "diet", {"value": "vegan"})
store.delete(ns, "birthday")
print("\nAfter update + delete:", {i.key: i.value["value"] for i in store.search(ns)})
Output (real run)
Profile of u_42:
   name      -> Ananya   (saved 10 Nov 2026)
   birthday  -> 14 March   (saved 10 Nov 2026)
   diet      -> vegetarian, no onion or garlic   (saved 10 Nov 2026)

Past orders: [('ORD-9001', 'Running shoes')]
Another user's profile: [] (nothing leaks between users)

After update + delete: {'name': 'Ananya', 'diet': 'vegan'}

A namespace is like a folder: ("u_42", "profile") holds only user u_42's profile, so one user's memories never leak into another's. The same store can be read from any thread, which is what makes it long-term.

🍛 Analogy

Short-term memory is today's conversation at the bank counter. Long-term memory is your customer file: next month, a different clerk opens it and already knows your account type and address.

Slide 13

Semantic memory: definition

▢ What the slide says

In cognitive science: memory for general knowledge, facts and concepts, not tied to a specific event.

In AI agents: stores domain knowledge (e.g. "Every order must have an order ID, a list of product IDs and a list of shipping IDs") and gives factual grounding for reasoning and dialogue.

Examples: "Refund policy: 30-day window" · "Business hours: 9 AM–6 PM EST" · "Supported currencies: USD, EUR, GBP".

💡 In plain words

Semantic memory is what is true, whether or not you remember when you learned it. You know Delhi is India's capital, but not the day you learned it. For an agent: business rules, product facts, and also facts about a user ("Ananya is vegetarian").

🍛 Analogy

The company handbook on a new employee's desk: rules and facts, no stories.

Slide 14

Semantic memory: why it matters

▢ What the slide says

It gives agents world knowledge beyond what they have experienced, enabling them to answer factual questions, stay consistent in their responses, and reason abstractly over categories.

🌍 Each benefit, for an online store's support agent

BenefitWithout semantic memoryWith it
Factual answersGuesses "probably 7 days" for refunds"30 days from delivery", every time
ConsistencyMonday's answer differs from Tuesday'sSame policy for every customer
Reasoning over categoriesDoesn't know a laptop counts as electronics"Laptop is electronics, electronics have a 10-day return window"
Slide 15

Semantic memory: representation approaches

▢ What the slide says

  • Symbolic / structured: knowledge graphs (RDF triples, ontologies) and key-value stores.
  • Vector-based: embeddings of factual statements, supporting semantic-similarity queries.
  • Hybrid: a knowledge graph for structure plus embeddings for flexible recall.

💡 New words

  • Triple: a fact as (subject, relation, object), e.g. (Laptop, is_a, Electronics). A knowledge graph is many triples joined up.
  • Ontology: the agreed list of types and relations (e.g. "Product", "Category", "is_a").
  • Embedding: a list of numbers that captures a sentence's meaning, so "How long is shipping?" matches "Delivery takes 2–5 days" even with no shared words.

⌨️ Try it in code: one set of facts, three representations

m15_semantic_representations.pyRan it ✓ real output below
"""The same company facts stored three ways: key-value, knowledge-graph triples, and a SQL table."""
import sqlite3

# 1. Key-value: fastest, exact keys only
kv = {"refund_window_days": 30, "business_hours": "9 AM - 6 PM IST", "delivery_days": "2-5 business days"}
print("KV   refund window      ->", kv["refund_window_days"], "days")

# 2. Knowledge graph: (subject, relation, object) triples, good for connected facts
triples = [
    ("Order", "must_have", "order_id"), ("Order", "must_have", "product_ids"), ("Order", "must_have", "shipping_ids"),
    ("Electronics", "return_window_days", "10"), ("Clothing", "return_window_days", "30"),
    ("Laptop", "is_a", "Electronics"), ("Kurta", "is_a", "Clothing"),
]
def ask(s, r):
    return [o for (a, b, o) in triples if a == s and b == r]
print("KG   an Order must have ->", ask("Order", "must_have"))
category = ask("Laptop", "is_a")[0]                                    # hop 1: Laptop -> Electronics
print(f"KG   Laptop return window -> {ask(category, 'return_window_days')[0]} days (via {category})")   # hop 2

# 3. Relational table: facts in rows, queried with SQL
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE policies (topic TEXT, fact TEXT)")
db.executemany("INSERT INTO policies VALUES (?, ?)", [("currency", "INR"), ("currency", "USD"), ("currency", "EUR"),
                                                       ("delivery", "2-5 business days")])
print("SQL  supported currencies ->", [r[0] for r in db.execute("SELECT fact FROM policies WHERE topic = 'currency'")])
Output (real run)
KV   refund window      -> 30 days
KG   an Order must have -> ['order_id', 'product_ids', 'shipping_ids']
KG   Laptop return window -> 10 days (via Electronics)
SQL  supported currencies -> ['INR', 'USD', 'EUR']

The knowledge graph answered "what's a laptop's return window?" in two hops (Laptop → Electronics → 10 days), even though no single fact says it. That's "reasoning over categories". The vector approach is in slide 17's demo.

Slide 16

Semantic memory: storage

▢ What the slide says

  • Relational DB (SQL): facts stored in tables.
  • Document DB (MongoDB): JSON documents for flexible schemas.
  • Vector DB (FAISS/Pinecone): embeddings for fuzzy fact retrieval.
StoreBest forExample factHow you find it
SQL (PostgreSQL, SQLite)Fixed, structured factsA row: (currency, INR)Exact query: WHERE topic = 'currency'
Document DB (MongoDB)Facts whose shape varies{"user": "u_42", "diet": "vegan", "allergies": ["peanut"]}Filter on fields
Vector DB (FAISS, Pinecone, Chroma)Fuzzy questions in plain language"Standard delivery takes 2–5 business days."Similarity search by meaning

🍛 Analogy

A filing cabinet with labelled folders (SQL), a box of differently shaped notes (document DB), and a librarian who understands what you mean (vector DB).

Slide 17

Semantic memory: usage

▢ What the slide says

  • Retrieve facts relevant to the query. Q: "How long does delivery take?" Semantic memory: "2–5 business days."
  • Guide reasoning. Episodic: "Last order took 7 days." Semantic: "Deliveries usually take 2–5 days."
  • Combine with episodic memory. Agent: "Normally it's 2–5 days, but last time yours took longer."

⌨️ Try it in code: the slide's exact example

m17_semantic_plus_episodic.pyNeeds OpenAI key
"""Semantic memory (what is generally true) + episodic memory (what happened to THIS user) in one answer."""
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langgraph.store.memory import InMemoryStore

load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# A store that can search by MEANING: every value's "text" field is embedded
store = InMemoryStore(index={"embed": OpenAIEmbeddings(model="text-embedding-3-small"), "dims": 1536, "fields": ["text"]})

# Semantic memory: company-wide facts
for key, text in [("delivery", "Standard delivery takes 2-5 business days."),
                  ("refunds", "Refunds are allowed within 30 days of delivery."),
                  ("hours", "Customer support is open 9 AM to 6 PM IST, Monday to Saturday.")]:
    store.put(("company", "facts"), key, {"text": text})

# Episodic memory: this user's past experiences
store.put(("u_52", "episodes"), "2026-10-02", {"text": "Order ORD-7712 (a mixer grinder) took 7 days to arrive; user was upset."})
store.put(("u_52", "episodes"), "2026-10-20", {"text": "User asked to change their phone number."})

question = "How long does delivery take?"
fact = store.search(("company", "facts"), query=question, limit=1)[0]
episode = store.search(("u_52", "episodes"), query=question, limit=1)[0]
print(f"Semantic hit (score {fact.score:.2f}): {fact.value['text']}")
print(f"Episodic hit (score {episode.score:.2f}): {episode.value['text']}")

answer = llm.invoke(f"Company fact: {fact.value['text']}\nThis customer's history: {episode.value['text']}\n"
                    f"Customer asks: {question}\nAnswer in 2 sentences, warmly.").text
print("\nAgent:", answer)
Example output (what you would see; exact text and numbers vary)
Semantic hit (score 0.62): Standard delivery takes 2-5 business days.
Episodic hit (score 0.41): Order ORD-7712 (a mixer grinder) took 7 days to arrive; user was upset.

Agent: Standard delivery takes 2–5 business days. I know your mixer grinder took longer than that last
time, and I'm sorry about that; if your next order runs late, just message us and we'll chase the courier.

The store searched by meaning: "How long does delivery take?" found "Standard delivery takes 2–5 business days" and the user's late mixer-grinder order, without any shared keywords like "how long". The answer blends the general fact with this customer's history, exactly as on the slide.

Slide 18

Episodic memory: definition

▢ What the slide says

Episodic memory, in both humans and AI agents, means recalling past events or actions. For AI agents it is often used to help the agent remember how it accomplished a task before.

💡 In plain words

Episodic memory is a diary: what happened, when, and how it turned out. "On 3 November I tried the shipping API with order #78910 and it failed." Each entry is an episode.

🍛 Analogy

You remember the time you took the expressway and got stuck in a 2-hour jam, so you take the old highway now. That memory of one specific trip is episodic.

Slide 19

Episodic memory: why it matters

▢ What the slide says

It lets agents reflect on past failures (avoid repeating mistakes), reuse successful strategies (case-based reasoning), and personalise responses based on history.

Key difference: semantic = what is generally true; episodic = what happened in a specific case.

🌍 Real world

  • Avoid failures: a coding agent remembers "running the full test suite timed out last time; run only the changed module's tests".
  • Reuse what worked: a support agent remembers the exact steps that fixed a similar complaint last week.
  • Personalise: "Sorry your last order was late; I've added priority shipping this time."

💡 "Case-based reasoning"

Solving a new problem by finding a similar old case and adapting its solution, like a doctor thinking "this looks like the patient I saw last month".

Slide 20

Episodic memory: representation approaches

▢ What the slide says

ApproachWhat it isGood for
LogsFull transcripts or step sequences, e.g. a JSON/SQL record of each step (action, result, outcome)Replaying exactly what happened
Vector embeddingsEpisodes as text embeddings"Find past failed order lookups" by meaning
Key–value storesEpisodes indexed by user ID, timestamp or goalFast "all episodes for this user"
Graph structuresNodes = events, edges = time or cause linksTracing chains of events

💡 One episode, written as a log entry

{"episode_id": 1, "user": "u_17", "goal": "track_order", "date": "2026-11-03",
 "steps": [{"action": "ask_order_id",          "result": "got #78910"},
           {"action": "shipping_api(#78910)",   "result": "error: Invalid ID format"}],
 "outcome": "failure"}

The same episode can also be embedded ("tracking order #78910 failed: shipping API rejected the ID") for similarity search, or linked in a graph to the episode that came after it.

Slide 21

Episodic memory: storage

▢ What the slide says

  • Relational DB (SQL): an episodes table for metadata (id, user, goal, outcome) and a steps table for detailed actions and results.
  • Document DB (MongoDB, Firestore): each episode as one JSON document, easy to retrieve with filters.
  • Vector DB (FAISS, Pinecone): episode descriptions as embeddings for "similar past situations".

Storing episodes in structured, retrievable formats lets agents search, compare and learn from past experience.

⌨️ Try it in code: the slide's two tables, filled with slides 22 and 23

m21_episodic_store.pyRan it ✓ real output below
"""Episodic memory in SQL: an episodes table + a steps table, then 'learn from the past' (slides 21-24)."""
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE episodes (episode_id INTEGER PRIMARY KEY, user_id TEXT, goal TEXT, outcome TEXT, created TEXT);
CREATE TABLE steps    (episode_id INTEGER, step_no INTEGER, action TEXT, result TEXT);
""")


def log_episode(user_id, goal, outcome, created, steps):
    eid = db.execute("INSERT INTO episodes (user_id, goal, outcome, created) VALUES (?,?,?,?)",
                     (user_id, goal, outcome, created)).lastrowid
    db.executemany("INSERT INTO steps VALUES (?,?,?,?)", [(eid, i, a, r) for i, (a, r) in enumerate(steps, 1)])


# Slide 22: the failure path        Slide 23: the success path
log_episode("u_17", "track_order", "failure", "2026-11-03", [
    ("ask_order_id", "got #78910"), ("shipping_api(#78910)", "error: Invalid ID format")])
log_episode("u_52", "track_order", "success", "2026-11-05", [
    ("ask_order_id", "got #78910"), ("validate_id(#78910)", "ok: ORD-78910"),
    ("order_db_lookup(ORD-78910)", "shipped, arriving Thursday"), ("confirm_status", "user satisfied")])

# A NEW user asks "Where is my order #55321?" -> goal = track_order. Retrieve similar past episodes:
past = db.execute("SELECT episode_id, outcome, created FROM episodes WHERE goal = ? ORDER BY created DESC",
                  ("track_order",)).fetchall()
for eid, outcome, created in past:
    path = [a.split("(")[0] for (a,) in db.execute("SELECT action FROM steps WHERE episode_id = ? ORDER BY step_no", (eid,))]
    print(f"Episode {eid} ({created}): {outcome.upper():<8} path = {' -> '.join(path)}")

best = db.execute("SELECT episode_id FROM episodes WHERE goal = ? AND outcome = 'success' ORDER BY created DESC LIMIT 1",
                  ("track_order",)).fetchone()[0]
plan = [a.split("(")[0] for (a,) in db.execute("SELECT action FROM steps WHERE episode_id = ? ORDER BY step_no", (best,))]
print("\nDecision: avoid shipping_api first; follow the successful path ->", " -> ".join(plan))
Output (real run)
Episode 2 (2026-11-05): SUCCESS  path = ask_order_id -> validate_id -> order_db_lookup -> confirm_status
Episode 1 (2026-11-03): FAILURE  path = ask_order_id -> shipping_api

Decision: avoid shipping_api first; follow the successful path -> ask_order_id -> validate_id -> order_db_lookup -> confirm_status

Two tables, exactly as on the slide: episodes (one row per attempt) and steps (one row per action). A new "track my order" request looked up past episodes with the same goal and chose the path that worked.

Slide 22

Episodic memory usage: a failure path

▢ What the slide says

User: "Where is my order #78910?" Agent path: ask for the order ID ✅ → use Tool C (shipping API) ❌ → result: "Invalid ID format" → failure.

"Where is my order #78910?"
→
Ask for order ID ✅
→
Shipping API ❌"Invalid ID format"
→
Failure

💡 What went wrong

The shipping API expects its own tracking number, not the store's order number, so passing "#78910" directly fails. A human support agent learns this on day one. An agent without episodic memory would make the same mistake for every customer.

Slide 23

Episodic memory usage: a success path

▢ What the slide says

User: "Where is my order #78910?" Agent path: ask for the order ID ✅ → use Tool A (validate ID) ✅ → use Tool B (order DB lookup) ✅ → confirm status ✅.

"Where is my order #78910?"
→
Ask for order ID ✅
→
Validate ID ✅
→
Order DB lookup ✅
→
Confirm status ✅

💡 Why this path works

Validating first turns "#78910" into the format the system uses ("ORD-78910"), and the order database (not the courier's API) is the right place to look it up. Both episodes, the failure and the success, are now in memory.

Slide 24

Episodic memory usage: retrieval and decision

▢ What the slide says

  • Episodic retrieval: a new query → retrieve similar past episodes.
  • Compare outcomes: episode 1 → failure (Tool C path); episode 2 → success (Tool A → Tool B path).
  • Decision: avoid the failed path, follow the successful one.

💡 How this looks in a real agent

  1. New request arrives: "Where's my order #55321?"
  2. Search episodic memory for similar past requests (by goal, as in slide 21's demo, or by meaning with embeddings).
  3. Put the best examples into the prompt: "Past attempt: shipping API first → failed. Past attempt: validate → DB lookup → succeeded."
  4. The model follows the successful pattern. This is often called few-shot learning from experience.

🍛 Analogy

Before a cricket match, the captain watches clips of past games against the same team: which bowlers worked, which field placements failed. Then picks the plan that worked.

⚠️ Careful

One failure doesn't always mean a path is bad: the API might simply have been down that day. Good systems store why it failed, and weigh many episodes, not just the last one.

Slide 25

Procedural memory: definition

▢ What the slide says

In cognitive science: memory for skills, procedures and how to perform actions.

In AI agents: stores policies, workflows or action scripts, and lets the agent repeat learned skills without relearning them.

Analogy: human: "I know how to ride a bike." Agent: "I know how to validate an order ID and fetch its status."

💡 In plain words

Procedural memory is know-how. For an LLM agent it usually takes one of two forms: a stored workflow (step 1, step 2, what to do if step 2 fails), or the agent's own instructions (its system prompt), improved over time from feedback.

⌨️ Try it in code: instructions the agent improves and keeps

m25_learned_instructions.pyNeeds OpenAI key
"""Procedural memory for an LLM agent: its own instructions, improved from feedback and saved for next time."""
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.store.memory import InMemoryStore

load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
store = InMemoryStore()
store.put(("agent", "procedures"), "refund_reply", {"instructions": "Reply to refund requests politely."})


def reply(customer_msg):
    steps = store.get(("agent", "procedures"), "refund_reply").value["instructions"]
    return llm.invoke(f"Instructions:\n{steps}\n\nCustomer: {customer_msg}\nReply:").text


def learn(feedback):
    old = store.get(("agent", "procedures"), "refund_reply").value["instructions"]
    new = llm.invoke(f"Current instructions:\n{old}\n\nManager feedback: {feedback}\n"
                     "Rewrite the instructions as a short numbered procedure that includes the feedback. "
                     "Return only the instructions.").text
    store.put(("agent", "procedures"), "refund_reply", {"instructions": new})     # saved: used in every future chat
    return new


msg = "My headphones stopped working after 10 days. I want a refund."
print("BEFORE:\n", reply(msg))
print("\nNEW PROCEDURE:\n", learn("Always ask for the order ID first, mention the 30-day refund window, "
                                  "and offer a replacement before a refund."))
print("\nAFTER:\n", reply(msg))
Example output (what you would see; exact text and numbers vary)
BEFORE:
 I'm sorry to hear your headphones stopped working. I'd be happy to help you with a refund.
Could you share a few more details so I can process it?

NEW PROCEDURE:
 1. Thank the customer and apologise for the problem.
2. Ask for the order ID before anything else.
3. Mention that refunds are possible within 30 days of delivery.
4. Offer a replacement first; offer a refund if the customer prefers.
5. Keep the reply polite and short.

AFTER:
 I'm sorry your headphones stopped working after just 10 days! Could you share your order ID?
You're well within our 30-day refund window. I can send you a replacement pair right away, or
process a full refund if you'd rather. Just let me know.

The manager's feedback was turned into a numbered procedure and saved. Every future refund chat, in any thread, now follows it. That's procedural memory: the agent didn't learn a new fact, it learned a better way to act.

Slide 26

Procedural memory: why it matters

▢ What the slide says

  • Makes agents consistent at executing tasks.
  • Reduces "reinventing the wheel" each time.
  • Enables complex multi-step tasks and automated workflows (e.g. check order → update DB → send email).
  • Complements the others: episodic = what happened, semantic = what is true, procedural = how to act.

🍛 Analogy: learning to cook dal

Semantic: "toor dal needs about 3 whistles in a pressure cooker." Episodic: "last Sunday I added salt too early and it took longer to cook." Procedural: the routine your hands just know: rinse, soak, cook, temper, add salt at the end.

🧪 Which memory is it?

Pick the memory type for each sentence an agent might store.

Slide 27

Procedural memory: representation approaches

▢ What the slide says

  • Symbolic rules / scripts: IF–THEN rules or production rules.
  • Finite state machines (FSMs): state transitions encode the procedural flow.
  • Neural policies: reinforcement-learning agents store action policies.
  • Hybrid: store procedures as symbolic plans, refined with learned policies.
ApproachOrder-tracking example
IF–THEN rulesIF the order ID isn't numeric THEN ask the user to re-check it. IF the DB has no result THEN try the cache.
Finite state machineASK_ID → VALIDATE → LOOKUP → CONFIRM, with VALIDATE --invalid--> ASK_ID. A LangGraph graph with conditional edges is exactly this.
Neural policyA model trained by trial and error to pick the next action; its "procedure" is inside its weights, not readable as steps.
HybridA written plan (validate → DB → fallbacks) whose fallback order is adjusted from experience: whichever source answers most often goes first.

💡 Which is used most with LLM agents today?

Readable ones: written workflows, graphs (LangGraph) and instructions in prompts. They're easy to inspect, test and change, which matters when the agent touches real customers' orders.

Slide 28

Procedural memory: storage

▢ What the slide says

  • Relational DB: a procedures table with metadata, and a steps table with the ordered actions.
  • Document DB: procedures stored as JSON workflows.

💡 What a stored procedure looks like

procedures:  goal = "track_order", version = 2
steps (JSON): [
  {"do": "validate_id", "on_fail": "stop: ask the user to re-check the order number"},
  {"do": "order_db",    "fallbacks": ["cached_db", "shipping_api"]}
]

A version number matters: when the procedure improves (v1 had no fallbacks; v2 learned them), you can see what changed and roll back if needed. The next slide runs this exact procedure.

Slide 29

Procedural memory: usage

▢ What the slide says

  • Retrieve a procedure when the task goal matches.
  • Execute the stored sequence of steps.
  • Adapt if the context differs (branching, retries).
  • Example: episodic: "Last time, DB lookup failed." Procedural: "Try cached DB fallback → shipping API."
  • Enables skill chaining: compose procedures into larger tasks.

⌨️ Try it in code: retrieve the procedure, run it, adapt with fallbacks

m29_procedural.pyRan it ✓ real output below
"""Procedural memory: a stored, step-by-step procedure the agent retrieves and runs, with a fallback (slide 29)."""
import json
import sqlite3

# --- the systems the procedure uses (small in-memory examples) ---
ORDER_DB = {"ORD-78910": "shipped, arriving Thursday"}            # main database (new orders take time to sync)
ORDER_CACHE = {"ORD-55321": "packed, leaves warehouse today"}     # cached copy, updated every few minutes
SHIPPING_API = {"ORD-60012": "out for delivery"}                  # courier partner


def validate_id(raw):    return f"ORD-{raw.strip('#')}" if raw.strip("#").isdigit() else None
def order_db(oid):       return ORDER_DB.get(oid)
def cached_db(oid):      return ORDER_CACHE.get(oid)
def shipping_api(oid):   return SHIPPING_API.get(oid)


ACTIONS = {"validate_id": validate_id, "order_db": order_db, "cached_db": cached_db, "shipping_api": shipping_api}

# --- procedural memory, stored as a JSON workflow in a database ---
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE procedures (goal TEXT PRIMARY KEY, version INTEGER, steps TEXT)")
db.execute("INSERT INTO procedures VALUES (?, ?, ?)", ("track_order", 2, json.dumps([
    {"do": "validate_id", "on_fail": "stop: ask the user to re-check the order number"},
    {"do": "order_db", "fallbacks": ["cached_db", "shipping_api"]},      # learned: "if DB lookup fails, try cache, then courier"
])))


def run_procedure(goal, user_input):
    version, steps = db.execute("SELECT version, steps FROM procedures WHERE goal = ?", (goal,)).fetchone()
    print(f"Procedure '{goal}' v{version} for input {user_input!r}")
    value = user_input
    for step in json.loads(steps):
        for action in [step["do"]] + step.get("fallbacks", []):
            result = ACTIONS[action](value)
            print(f"   {action:<13} -> {result if result else 'no result'}")
            if result:
                value = result
                break
        else:
            return step.get("on_fail", "stop: not found anywhere, hand over to a human agent")
    return f"Status: {value}"


for order in ["#78910", "#55321", "#60012", "#7A91"]:
    print("  =>", run_procedure("track_order", order), "\n")
Output (real run)
Procedure 'track_order' v2 for input '#78910'
   validate_id   -> ORD-78910
   order_db      -> shipped, arriving Thursday
  => Status: shipped, arriving Thursday 

Procedure 'track_order' v2 for input '#55321'
   validate_id   -> ORD-55321
   order_db      -> no result
   cached_db     -> packed, leaves warehouse today
  => Status: packed, leaves warehouse today 

Procedure 'track_order' v2 for input '#60012'
   validate_id   -> ORD-60012
   order_db      -> no result
   cached_db     -> no result
   shipping_api  -> out for delivery
  => Status: out for delivery 

Procedure 'track_order' v2 for input '#7A91'
   validate_id   -> no result
  => stop: ask the user to re-check the order number 

Four orders, one stored procedure, four different routes: the first was found straight away, the second needed the cache, the third needed the courier, and the fourth stopped early with a helpful message. The fallback list is the slide's "Try cached DB fallback → shipping API", learned from experience (episodic) and stored as know-how (procedural).

💡 Skill chaining

"Handle a refund" can reuse track_order as its first step, then "check refund window", then "issue refund". Small proven procedures become building blocks for bigger ones, just like the tools in the previous lecture.

Part 4

Wrap-up

Slide 30

Summary and key takeaways

▢ What the slide says

  • LLMs are stateless, so agents need memory for context continuity, personalization and richer dialogue.
  • Short-term memory is thread-scoped: the conversation history within a session, the basis for context-aware replies.
  • Long-term memory persists across sessions and lets agents remember users over time. Three types: semantic (general facts: what is true), episodic (past events and actions: what happened in a specific case), procedural (skills and workflows: how to act).
  • Memory-management techniques include trimming/deleting messages and summarizing, to handle the size and continuity of the history.
MemoryQuestion it answersLangGraph pieceDemo in this page
Short-termWhat did we just say?State + checkpointer (thread_id)Slides 8–10
SemanticWhat is true?Store (facts, optionally searched by meaning)Slides 15, 17
EpisodicWhat happened last time?Store or database of episodesSlide 21
ProceduralHow do I do this?Stored workflows and instructions; the graph itselfSlides 25, 29

🌍 In this module's code

short_term_memory.ipynb covers buffer, trimming, deletion and summarising; memory_demo_1.py combines semantic, episodic and procedural memory in one agent; memory_demo_2.py adds memory that updates itself in the hot path and is saved to disk. See the code explainer.

★

Glossary

Stateless
Keeps nothing between calls; every request starts from zero.
Context window
The maximum amount of text a model can read in one call.
Short-term memory
The current conversation (one thread).
Long-term memory
Memory kept across conversations, e.g. per user.
Thread / thread_id
One conversation and its ID in LangGraph.
State
Everything an agent carries for a thread: messages, files, results.
Checkpointer
Auto-saves the state after each step so a thread can resume.
Store / namespace
LangGraph's long-term memory / a "folder" inside it, e.g. per user.
Trimming
Sending only part of the history to the model this time.
Deleting (RemoveMessage)
Removing messages from the saved state for good.
Summarizing
Replacing old messages with a short LLM-written summary.
Hot path / background
Updating memory during the reply / later, in a batch.
Semantic memory
Facts: what is true.
Episodic memory
Experiences: what happened in a specific case.
Procedural memory
Skills and workflows: how to act.
Knowledge graph / triple
Facts as (subject, relation, object) linked together.
Embedding / vector DB
Meaning as numbers / a database that searches by meaning.
Finite state machine
A set of states and the allowed moves between them.
?

Check yourself (click to reveal)

1. If the model is stateless, how does ChatGPT "remember" what you said earlier in the same chat?

The app sends the earlier messages along with every new one. That re-sent history is short-term memory.

2. What's the difference between trimming and deleting?

Trimming changes only what the model sees in this call; the saved history is untouched. Deleting removes messages from the saved state permanently.

3. Your agent keeps forgetting the user's budget in long chats. Trimming is on. What would you change?

Summarize instead of (or as well as) trimming, or save the budget to long-term memory as a fact about the user, so it doesn't depend on the old message still being in the window.

4. Classify: (a) "Delivery takes 2–5 days", (b) "Order #4471 arrived late last month", (c) "Validate the ID before calling the DB".

(a) Semantic: a general fact. (b) Episodic: a specific past event. (c) Procedural: how to act.

5. Hot path or background: a voice assistant where every second of delay is noticeable?

Background. Reply first; extract and save memories afterwards, so the user never waits for memory work.