Contents1What it teaches2How to run it3What changed and whyAmemory_demo_1.pyBmemory_demo_2.pyCshort_term_memory.ipynbDfastmcp_demo_v1.ipynb↔Link to the lectures!Known limits✎Exercises★Glossary{}Full source
By Shivank Agarwal · code explainer · 05-memory-and-mcp/code folder (2 Python files, 2 notebooks)

Memory and MCP in code: an agent that remembers its customers, a chat that manages its history, and tools served over MCP

Two Python files build a customer-service agent that uses semantic, episodic and procedural memory, then teach it to update and save what it learns. One notebook shows the four ways to keep a conversation's history under control. The other serves two real tools (time and weather) from an MCP server and lets the model use them.

OpenAI gpt-6-lunaLangChainLangGraphFastMCPOpen-Meteo (free, no key)
1

What the folder teaches

FileNew ideaLecture slides
memory_demo_1.pyThree kinds of long-term memory (facts, customer history, a lookup procedure) feeding one answer, as a LangGraph pipelineMemory 12–30
memory_demo_2.pyMemory that updates itself: the model spots "keep it brief from now on", the preference changes at once and is saved to a JSON fileMemory 6, 12, 18–24
short_term_memory.ipynbThe conversation buffer, and three ways to keep it small: trimming, deleting, summarizingMemory 8–11
fastmcp_demo_v1.ipynbAn MCP server with two real tools, and a host that lets the model discover and call themMCP 6–14
C · short-termone conversation
→
A · long-termfacts, history, procedure
→
B · memory that learnsupdate + save
→
D · MCP toolsdiscover + call
A good teaching order: start with the notebook on short-term memory (C), then the two demos (A, B), then MCP (D).
2

How to run it

  1. Install the packages: pip install -r requirements.txt
  2. Copy .env.example to .env and put your key in it: OPENAI_API_KEY=sk-...
  3. Run the demos: python memory_demo_1.py and python memory_demo_2.py
  4. Open the notebooks in Jupyter or Google Colab and run the cells from top to bottom. If OPENAI_API_KEY isn't already set, the notebook asks for it once.
requirements.txt (complete file)
openai>=2.0
langchain>=1.0
langchain-openai>=1.0
langgraph>=1.0
fastmcp>=4.0
requests>=2.31
python-dotenv>=1.0

⚠️ Two notebook details

  • Lines starting with ! (like !pip install) are notebook commands, not Python. They work in Jupyter and Colab only.
  • The MCP notebook's last cell uses await run_demo() directly. Notebooks allow that; in a normal .py file you'd write asyncio.run(run_demo()).

Every model call uses OpenAI's gpt-6-luna. Running all four files makes about 40 short model calls in total.

3

What changed from the original, and why

Same files, same data, same teaching order. Here's everything that's different.

#OriginalNowWhy
1gpt-4o-mini (demos) and gpt-3.5-turbo (notebooks), temperature=0gpt-6-luna with reasoning_effort="none" everywheregpt-3.5-turbo was shut down in October 2026, and gpt-4o-mini retires on 14 January 2027. "none" makes the model answer straight away, like the older models did. The demos don't rely on word-for-word identical replies, so temperature is left at its default.
2os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")Removed; load_dotenv() is enoughThe line did nothing useful, and if the key was missing it crashed with a confusing TypeError instead of OpenAI's clear "no API key" message.
3response.content in the demosresponse.text.text always gives the reply as plain text, whichever OpenAI API LangChain uses underneath.
4self.episodic_memory = EPISODIC_MEMORY_DEFAULT (demo 2)copy.deepcopy(EPISODIC_MEMORY_DEFAULT)A real bug. Without a copy, updating a preference also changed the "default" dictionary itself, so a second MemoryDemo() in the same program would start with the changed values.
5Preference detector parsed free text with json.loads(result.content.strip())JSON mode: llm.bind(response_format={"type": "json_object"}), plus a check that the result is a dictionaryModels sometimes wrap JSON in ```json fences or add a sentence, which made json.loads fail and silently skip the update. JSON mode guarantees valid JSON.
6order_id: str = Noneorder_id: Optional[str] = NoneCorrect type hint (it can be a string or nothing).
7Trimming counted characters with a home-made counter (max_tokens=500)LangChain's count_tokens_approximately, max_tokens=300, start_on="human"The limit is now in real (approximate) tokens, as models count them, and the kept history always starts with a user message, which models expect.
8Deletion shown only on a plain Python listNew cell: deletion with RemoveMessage and LangGraph's add_messagesThat's how you delete inside a real LangGraph agent (Memory lecture slide 9).
9t.inputSchema, nest_asyncio, unused imports, a 6-space indented functiont.input_schema, no nest_asyncio, tidy imports and indentationCurrent fastmcp uses snake_case names (inputSchema is deprecated). Notebooks already run async code, so nest_asyncio isn't needed.
10Notebook title linked to a person's GitHub page; outputs saved in the file; a warnings-filter cell at the endCredited to Shivank Agarwal; outputs cleared; filter cell removedA clean notebook for class: learners see their own outputs.
11No setup filesrequirements.txt, .env.example, README.mdOne command to install everything.
Long-term memory

A customer-service agent that remembers

A

memory_demo_1.py: three memories, one answer

A support agent answers "Where are my orders, and can I return them?" by pulling from three memories before it writes a single word.

semantic_memorycompany facts
→
episodic_memorythis customer
→
procedural_memorylook up orders
→
generate_responsegpt-6-luna writes the reply
A straight line of four steps (LangGraph nodes). Only the last step calls the model.

1. The state: one form that every step fills in

memory_demo_1.py · lines 26–33
class AgentState(TypedDict):
    user_id: str
    user_query: str
    order_id: str
    semantic_facts: Dict[str, Any]
    user_context: Dict[str, Any]
    order_details: Dict[str, Any]
    final_response: str

Think of AgentState as a form passed from desk to desk. The first three steps each fill in one box (semantic_facts, user_context, order_details); the last step reads all the boxes and fills in final_response.

2. The memories (plain Python dictionaries)

memory_demo_1.py · lines 36–107
    def __init__(self):
        # Semantic Memory (general world knowledge/facts)
        self.semantic_memory = {
            "company_policies": {
                "return_period": "30 days",
                "shipping_time": "3-5 business days",
                "customer_service_hours": "9 AM - 6 PM EST"
            },
            "product_categories": {
                "electronics": "Includes phones, laptops, accessories",
                "clothing": "Includes shirts, pants, dresses",
                "books": "Includes fiction, non-fiction, educational"
            }
        }
        
        # Episodic Memory (user-specific experiences/details)
        self.episodic_memory = {
    "user_123": {
        "name": "Alice Johnson",
        "preferred_contact": "email",
        "recent_interactions": [
            "Asked about return policy yesterday",
            "Purchased electronics last week"
        ],
        "preferences": {
            "language": "English",
            "detail_level": "detailed"
        }
    },
    "user_456": {
        "name": "Bob Smith",
        "preferred_contact": "sms",
        "recent_interactions": [
            "Complained about delayed shipping last month",
            "Frequently buys clothing items",
            "Requested premium shipping upgrade"
        ],
        "preferences": {
            "language": "English", 
            "detail_level": "brief",
            "shipping_speed": "express"
        }
    },
    "user_789": {
        "name": "Carlos Rodriguez",
        "preferred_contact": "phone",
        "recent_interactions": [
            "First-time customer",
            "Purchased books and electronics",
            "Asked about international shipping"
        ],
        "preferences": {
            "language": "Spanish",
            "detail_level": "normal",
            "currency": "EUR"
        }
    }
}
        
        # Simulated data stores (would be external in real scenario)
        self.order_store = {
            "ORD-001": {"status": "shipped", "value": 299.99},
            "ORD-002": {"status": "processing", "value": 149.50},
            "ORD-003": {"status": "delivered", "value": 89.99},
            "ORD-004": {"status": "cancelled", "value": 49.99}
        }
        
        self.user_orders = {
            "user_123": ["ORD-001", "ORD-002"],
            "user_456": ["ORD-003"],
            "user_789": ["ORD-004", "ORD-006"]
        }

💡 What's in each

  • semantic_memory: facts true for every customer: return period, shipping time, opening hours, product categories.
  • episodic_memory: one entry per customer: name, preferred contact, preferences, and recent interactions.
  • order_store and user_orders: stand for the company's order database. The "procedure" below knows how to look things up in them.

Dictionaries keep the flow easy to see. In production, facts would sit in a vector database, customer history in a database, and orders behind an API.

3. Step 1, semantic memory: pick the relevant facts

memory_demo_1.py · lines 109–125
    def get_semantic_facts(self, state: AgentState) -> AgentState:
        """Retrieve general world knowledge from semantic memory"""
        print("🔍 Accessing SEMANTIC MEMORY...")
        
        # Extract relevant semantic facts based on query
        relevant_facts = {}
        user_query = state.get("user_query", "").lower()
        
        if "return" in user_query:
            relevant_facts["return_policy"] = self.semantic_memory["company_policies"]["return_period"]
        if "shipping" in user_query:
            relevant_facts["shipping_info"] = self.semantic_memory["company_policies"]["shipping_time"]
        if "electronics" in user_query:
            relevant_facts["category_info"] = self.semantic_memory["product_categories"]["electronics"]
            
        state["semantic_facts"] = relevant_facts
        return state

Simple keyword matching: if the question contains "return", add the return policy. Only relevant facts go to the model, which keeps the prompt short (see Known limits for why "refund" would be missed).

4. Step 2, episodic memory: who is this customer?

memory_demo_1.py · lines 127–135
    def get_user_context(self, state: AgentState) -> AgentState:
        """Retrieve user-specific details from episodic memory"""
        print("👤 Accessing EPISODIC MEMORY...")
        
        user_id = state.get("user_id", "user_123")  # Default for demo
        user_context = self.episodic_memory.get(user_id, {})
        
        state["user_context"] = user_context
        return state

5. Step 3, procedural memory: follow the lookup steps

memory_demo_1.py · lines 137–159
    def procedural_lookup(self, state: AgentState) -> AgentState:
        """Execute procedural memory - follow steps to query data stores"""
        print("🔄 Executing PROCEDURAL MEMORY...")
        
        user_id = state.get("user_id", "user_123")
        order_id = state.get("order_id")
        
        # Procedural steps:
        # 1. Look up user's orders
        user_order_ids = self.user_orders.get(user_id, [])
        
        # 2. If specific order requested, get its details
        if order_id and order_id in user_order_ids:
            order_details = self.order_store.get(order_id, {})
            state["order_details"] = {order_id: order_details}
        # 3. Otherwise get all user orders
        else:
            all_orders = {}
            for oid in user_order_ids:
                all_orders[oid] = self.order_store.get(oid, {})
            state["order_details"] = all_orders
            
        return state

A fixed recipe: find the customer's order IDs; if they asked about one order they own, fetch just that one; otherwise fetch them all. The know-how lives in this code, which is what "procedural" means: how to do the task.

6. Step 4: the model writes the reply

memory_demo_1.py · lines 161–187
    def generate_response(self, state: AgentState) -> AgentState:
        """Generate final response using all memory types"""
        print("💭 Generating response using all memory types...")
        
        prompt = f"""
        Based on the following information, provide a helpful response to the user:
        
        USER QUERY: {state['user_query']}
        
        SEMANTIC KNOWLEDGE (General Facts):
        {json.dumps(state.get('semantic_facts', {}), indent=2)}
        
        EPISODIC MEMORY (User Context):
        Name: {state['user_context'].get('name', 'Customer')}
        Preferences: {state['user_context'].get('preferences', {})}
        Recent Interactions: {state['user_context'].get('recent_interactions', [])}
        
        PROCEDURAL RESULTS (Order Data):
        {json.dumps(state.get('order_details', {}), indent=2)}
        
        Provide a natural, helpful response that incorporates this information.
        Sign off with Best regards, Agent Nancy.
        """
        
        response = llm.invoke(prompt)
        state["final_response"] = response.text
        return state

Everything gathered so far is pasted into one prompt, clearly labelled by memory type. The model's only job is to turn it into a friendly reply.

7. Wiring the steps into a graph, and running two customers

memory_demo_1.py · lines 189–206
    def build_workflow(self):
        """Build the LangGraph workflow"""
        workflow = StateGraph(AgentState)
        
        # Define nodes
        workflow.add_node("semantic_memory", self.get_semantic_facts)
        workflow.add_node("episodic_memory", self.get_user_context)
        workflow.add_node("procedural_memory", self.procedural_lookup)
        workflow.add_node("generate_response", self.generate_response)
        
        # Define workflow
        workflow.set_entry_point("semantic_memory")
        workflow.add_edge("semantic_memory", "episodic_memory")
        workflow.add_edge("episodic_memory", "procedural_memory")
        workflow.add_edge("procedural_memory", "generate_response")
        workflow.add_edge("generate_response", END)
        
        return workflow.compile()
memory_demo_1.py · lines 209–247
def run_demo():
    demo = MemoryDemo()
    workflow = demo.build_workflow()
    
    # Test scenarios
    test_cases = [
        {
            "user_id": "user_123",
            "user_query": "What's the status of my orders and what's your return policy?",
            "order_id": None,
            "semantic_facts": {},
            "user_context": {},
            "order_details": {},
            "final_response": ""
        },
        {
            "user_id": "user_456", 
            "user_query": "Can you check the status of order ORD-003? I might need to return it.",
            "order_id": "ORD-003",
            "semantic_facts": {},
            "user_context": {},
            "order_details": {},
            "final_response": ""
        }
    ]
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"\n{'='*50}")
        print(f"TEST CASE {i}")
        print(f"{'='*50}")
        
        print(f"Query: {test_case['user_query']}")
        print(f"User: {test_case['user_id']}")
        
        result = workflow.invoke(test_case)
        
        print(f"\n📝 FINAL RESPONSE:")
        print(f"{result['final_response']}")
        print(f"{'='*50}\n")
Example output (what you would see; exact text and numbers vary)
==================================================
TEST CASE 1
==================================================
Query: What's the status of my orders and what's your return policy?
User: user_123
🔍 Accessing SEMANTIC MEMORY...
👤 Accessing EPISODIC MEMORY...
🔄 Executing PROCEDURAL MEMORY...
💭 Generating response using all memory types...

📝 FINAL RESPONSE:
Hi Alice,

Thanks for getting in touch! Here's where your two orders stand:

- ORD-001 ($299.99): shipped, so it's on its way to you.
- ORD-002 ($149.50): still being processed. You'll get an email as soon as it ships.

About returns: you can return items within 30 days. Since you bought electronics last week, you're well inside that window if anything isn't right. Just keep the original packaging and accessories, and we'll take it from there.

Best regards,
Agent Nancy
==================================================


==================================================
TEST CASE 2
==================================================
Query: Can you check the status of order ORD-003? I might need to return it.
User: user_456
🔍 Accessing SEMANTIC MEMORY...
👤 Accessing EPISODIC MEMORY...
🔄 Executing PROCEDURAL MEMORY...
💭 Generating response using all memory types...

📝 FINAL RESPONSE:
Hi Bob,

ORD-003 ($89.99) has been delivered. If you'd like to return it, you have 30 days from delivery. Just reply here and I'll start the return for you.

Best regards,
Agent Nancy
==================================================

💡 What to point out in the output

  • Alice asked about "my orders", so the procedure fetched both; her preference is "detailed", so the reply is long.
  • Bob named ORD-003, so only that order was fetched; he prefers "brief", so the reply is short.
  • Both questions contain "return", so both got the 30-day policy from semantic memory.

⚠️ Which memory is which, really?

The code puts everything about a customer under episodic_memory. By the lecture's definitions it's a mix:

  • recent_interactions ("Complained about delayed shipping last month") are episodic: specific past events.
  • name, preferred_contact and preferences are lasting facts about the customer, so they're really semantic memory (a user profile).

A good class question: "Which lines here are events, and which are facts?"

B

memory_demo_2.py: memory that updates itself and is saved

The same agent, plus one new step. When Alice says "keep your answers brief from now on", the agent changes her preference in the same turn and saves it to a file.

semantic_memory
→
episodic_memory
→
update_memoryNEW: detect + save
→
procedural_memory
→
generate_response

1. Two models: one for writing, one that must answer in JSON

memory_demo_2.py · lines 24–26
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# Same model, but forced to reply with a valid JSON object (used by the preference detector)
json_llm = llm.bind(response_format={"type": "json_object"})

json_llm is the same model with one setting added: its reply must be a valid JSON object. That makes the detector's answer safe to read with json.loads.

2. Where the memory lives on disk

memory_demo_2.py · lines 39–39
EPISODIC_MEMORY_FILE = os.path.join(os.path.dirname(__file__), "episodic_memory.json")
memory_demo_2.py · lines 70–77
class MemoryDemo:
    def __init__(self):
        # Reset to default and write to JSON file so we start fresh each demo
        self.episodic_memory: Dict[str, Any] = copy.deepcopy(EPISODIC_MEMORY_DEFAULT)   # a fresh copy, not the original
        with open(EPISODIC_MEMORY_FILE, "w") as f:
            json.dump(self.episodic_memory, f, indent=2)
        print(f"✅ Episodic memory written to {EPISODIC_MEMORY_FILE}")
        self.turn = 0

The file sits next to the script. deepcopy makes a separate copy of the default data, so changing Alice's preference never changes the defaults themselves.

3. The new step: detect a preference change and save it

memory_demo_2.py · lines 118–170
    def detect_and_update_preference(self, state: AgentState) -> AgentState:
        """
        Use the LLM to detect preference change requests in the user query.
        If a preference change is found, update episodic memory immediately
        so the SAME turn already reflects the new preference.
        """
        print("🔄 Checking for PREFERENCE UPDATES...")
        self.turn += 1

        prompt = f"""
You are a preference-change detector. Analyse the user message below.
If the user is requesting a change to any of their preferences (e.g. detail level,
language, contact method, shipping speed, etc.), respond with ONLY a valid JSON object
mapping preference key → new value, like:
{{"detail_level": "brief"}}

If there is NO preference change, respond with ONLY an empty JSON object: {{}}

User message: "{state['user_query']}"
"""
        result = json_llm.invoke(prompt)
        try:
            updates: Dict[str, Any] = json.loads(result.text)
        except json.JSONDecodeError:
            updates = {}
        if not isinstance(updates, dict):
            updates = {}

        state["preference_update"] = updates

        if updates:
            user_id = state["user_id"]
            if user_id in self.episodic_memory:
                old_prefs = {k: self.episodic_memory[user_id]["preferences"][k]
                             for k in updates if k in self.episodic_memory[user_id]["preferences"]}
                self.episodic_memory[user_id]["preferences"].update(updates)
                # Append to audit trail
                audit = self.episodic_memory[user_id].setdefault("preference_history", {})
                if not audit:
                    audit[f"turn_{self.turn - 1}"] = old_prefs  # seed state before first change
                audit[f"turn_{self.turn}"] = dict(updates)
                # Refresh the user_context so generate_response uses new prefs
                state["user_context"] = self.episodic_memory[user_id]
                print(f"   ✏️  Preference updated for {user_id}: {old_prefs} → {updates}")
                print(f"   📋 New preferences: {self.episodic_memory[user_id]['preferences']}")
                # Persist updated memory to JSON file
                with open(EPISODIC_MEMORY_FILE, "w") as f:
                    json.dump(self.episodic_memory, f, indent=2)
                print(f"   💾 Episodic memory saved to {EPISODIC_MEMORY_FILE}")
        else:
            print("   — No preference change detected.")

        return state

💡 Read it in four parts

  1. Ask the model (the prompt and json_llm.invoke): "Is the user changing a preference? Reply with JSON like {"detail_level": "brief"}, or {} if not."
  2. Read the answer safely (the try / isinstance checks): if it isn't a JSON dictionary, treat it as "no change".
  3. Update memory (inside if updates:): change the preference, record old and new values in preference_history (an audit trail), and refresh user_context so this same reply already uses the new preference.
  4. Save (the with open(...) block): write the whole memory to episodic_memory.json.

4. The reply follows the stored preference

memory_demo_2.py · lines 184–192
    def generate_response(self, state: AgentState) -> AgentState:
        print("💭 Generating response using all memory types...")
        prefs       = state["user_context"].get("preferences", {})
        detail_level = prefs.get("detail_level", "normal")

        prompt = f"""
You are a helpful customer service agent.
Respond to the user query below.  Detail level: {detail_level}.
{"Keep your answer SHORT and to the point." if detail_level == "brief" else "Provide a thorough, detailed answer." if detail_level == "detailed" else ""}

The detail_level lines turn the stored detail_level into a clear instruction: "Keep your answer SHORT" for brief, "Provide a thorough, detailed answer" for detailed.

5. Three turns

memory_demo_2.py · lines 249–280
def run_demo():
    demo     = MemoryDemo()
    workflow = demo.build_workflow()

    print("\n" + "="*60)
    print("TURN 1  — Normal query (detail_level = 'detailed')")
    print("="*60)
    result1 = workflow.invoke(make_state(
        user_id="user_123",
        query="What is the status of my orders and what's the return policy?"
    ))
    print(f"\n📝 RESPONSE:\n{result1['final_response']}\n")

    print("="*60)
    print("TURN 2  — User requests preference change to 'brief'")
    print("="*60)
    result2 = workflow.invoke(make_state(
        user_id="user_123",
        query="Please keep your answers brief from now on. Also, what's the shipping time?"
    ))
    print(f"\n📝 RESPONSE:\n{result2['final_response']}\n")
    print(f"🗂️  Stored preference after Turn 2: {demo.episodic_memory['user_123']['preferences']}")
    print(f"📂 Open '{EPISODIC_MEMORY_FILE}' to see the updated JSON on disk.\n")

    print("="*60)
    print("TURN 3  — Follow-up query, should now respect 'brief' preference")
    print("="*60)
    result3 = workflow.invoke(make_state(
        user_id="user_123",
        query="Can you give me an update on all my orders?"
    ))
    print(f"\n📝 RESPONSE:\n{result3['final_response']}\n")
Example output (what you would see; exact text and numbers vary)
✅ Episodic memory written to /home/learner/05-memory-and-mcp/code/episodic_memory.json

============================================================
TURN 1  — Normal query (detail_level = 'detailed')
============================================================
🔍 Accessing SEMANTIC MEMORY...
👤 Accessing EPISODIC MEMORY...
🔄 Checking for PREFERENCE UPDATES...
   — No preference change detected.
📦 Executing PROCEDURAL MEMORY...
💭 Generating response using all memory types...

📝 RESPONSE:
Hi Alice,

Here's a full update on your orders:

1. ORD-001 ($299.99): shipped. It has left our warehouse and is on its way to you.
2. ORD-002 ($149.50): processing. We're preparing it now, and you'll receive an email with tracking details as soon as it ships.

Our return policy: you can return any item within 30 days. As you asked about returns yesterday and bought electronics last week, here's what helps a return go smoothly: keep the original box and all accessories, include your order number, and reply here if you'd like help arranging a pickup.

Best regards, Agent Nancy.

============================================================
TURN 2  — User requests preference change to 'brief'
============================================================
🔍 Accessing SEMANTIC MEMORY...
👤 Accessing EPISODIC MEMORY...
🔄 Checking for PREFERENCE UPDATES...
   ✏️  Preference updated for user_123: {'detail_level': 'detailed'} → {'detail_level': 'brief'}
   📋 New preferences: {'language': 'English', 'detail_level': 'brief'}
   💾 Episodic memory saved to /home/learner/05-memory-and-mcp/code/episodic_memory.json
📦 Executing PROCEDURAL MEMORY...
💭 Generating response using all memory types...

📝 RESPONSE:
Got it, Alice: brief answers from now on. Shipping takes 3-5 business days.

Best regards, Agent Nancy.

🗂️  Stored preference after Turn 2: {'language': 'English', 'detail_level': 'brief'}
📂 Open '/home/learner/05-memory-and-mcp/code/episodic_memory.json' to see the updated JSON on disk.

============================================================
TURN 3  — Follow-up query, should now respect 'brief' preference
============================================================
🔍 Accessing SEMANTIC MEMORY...
👤 Accessing EPISODIC MEMORY...
🔄 Checking for PREFERENCE UPDATES...
   — No preference change detected.
📦 Executing PROCEDURAL MEMORY...
💭 Generating response using all memory types...

📝 RESPONSE:
ORD-001: shipped. ORD-002: processing.

Best regards, Agent Nancy.
episodic_memory.json after the three turns (example)
{
  "user_123": {
    "name": "Alice Johnson",
    "preferred_contact": "email",
    "recent_interactions": [
      "Asked about return policy yesterday",
      "Purchased electronics last week"
    ],
    "preferences": {
      "language": "English",
      "detail_level": "brief"
    },
    "preference_history": {
      "turn_1": {
        "detail_level": "detailed"
      },
      "turn_2": {
        "detail_level": "brief"
      }
    }
  },
  "user_456": {
    "name": "Bob Smith",
    "preferred_contact": "sms",
    "recent_interactions": [
      "Complained about delayed shipping last month",
      "Frequently buys clothing items"
    ],
    "preferences": {
      "language": "English",
      "detail_level": "brief",
      "shipping_speed": "express"
    }
  }
}

💡 What to point out

  • Turn 1 is long because Alice's stored preference is "detailed".
  • Turn 2 already answers briefly: the update happened before the reply was written. That's the hot path from Memory lecture slide 6.
  • Turn 3 has no instruction about length, yet stays brief: the agent remembered.
  • The JSON file's preference_history shows what changed and when: turn_1 holds the old value, turn_2 the new one.

⚠️ Saved, but not yet loaded

The first lines of __init__ overwrite the JSON file with the defaults every time the program starts. So the memory survives within one run and is written to disk, but the next run doesn't read it back. That's on purpose for a repeatable demo; Exercise 1 makes it true long-term memory.

⚠️ The cost of the hot path

Every turn now makes two model calls (detect, then reply) instead of one, even when nothing changed, as in turns 1 and 3. For a busy app you'd move detection to the background, after the reply (Memory lecture slide 6).

Short-term memory

Keeping one conversation under control

C

short_term_memory.ipynb: buffer, trim, delete, summarize

One five-turn chat (Alice learning about machine learning), handled four ways. Each part ends with the same test: does the model still know her name?

Setup

short_term_memory.ipynb · cells 3–5
!pip install -q langchain langchain-openai langgraph

import os
from getpass import getpass

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI API key: ")

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage

# reasoning_effort="none": answer straight away, no hidden "thinking" tokens
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")

1. The buffer: keep every message

short_term_memory.ipynb · cell 7
# Simple message buffer (list of messages)
message_buffer = []

def chat(user_input):
    """Chat function that maintains conversation history."""
    message_buffer.append(HumanMessage(content=user_input))
    response = llm.invoke(message_buffer)
    message_buffer.append(response)
    return response.content

def dump_memory():
    """Display all messages in the buffer."""
    print("=" * 50)
    print("MEMORY DUMP")
    print("=" * 50)
    for i, msg in enumerate(message_buffer):
        role = "Human" if isinstance(msg, HumanMessage) else "AI"
        print(f"[{i}] {role}: {msg.content[:100]}{'...' if len(msg.content) > 100 else ''}")
    print(f"\nTotal messages: {len(message_buffer)}")
    print("=" * 50)

chat() adds the user's message to a list, sends the whole list to the model, and adds the reply to the list. That list is short-term memory: the model itself remembers nothing (Memory lecture slide 4). dump_memory() prints the first 100 characters of each message.

short_term_memory.ipynb · cells 8–9
# 5-turn conversation
conversations = [
    "Hi! My name is Alice and I'm learning about AI.",
    "What are the main types of machine learning?",
    "Can you explain supervised learning with an example?",
    "What's the difference between classification and regression?",
    "Thanks! Can you remind me what my name is?"
]

for user_msg in conversations:
    print(f"Human: {user_msg}")
    response = chat(user_msg)
    print(f"AI: {response}\n")

# Full memory dump - all 10 messages (5 human + 5 AI)
dump_memory()
Example output (what you would see; exact text and numbers vary)
==================================================
MEMORY DUMP
==================================================
[0] Human: Hi! My name is Alice and I'm learning about AI.
[1] AI: Hi Alice, nice to meet you! AI is a great thing to learn. What would you like to start with: the bas...
[2] Human: What are the main types of machine learning?
[3] AI: There are three main types of machine learning:

1. **Supervised learning**: the model learns from l...
[4] Human: Can you explain supervised learning with an example?
[5] AI: Sure! In supervised learning you train a model on examples where you already know the answer.

Examp...
[6] Human: What's the difference between classification and regression?
[7] AI: Both are supervised learning; the difference is the kind of answer you predict.

**Classification** ...
[8] Human: Thanks! Can you remind me what my name is?
[9] AI: Of course! Your name is Alice. Happy learning, and ask me anything whenever you get stuck.

Total messages: 10
==================================================

10 messages, and turn 5 can answer "Your name is Alice" because turn 1 is still in the list. The catch: the list grows every turn, and every turn resends all of it.

2. Trimming: keep only the latest messages that fit

short_term_memory.ipynb · cell 13
from langchain_core.messages.utils import count_tokens_approximately

# Keep only the most recent messages that fit in ~300 tokens
trimmed_messages = trim_messages(
    message_buffer,
    max_tokens=300,
    strategy="last",                          # keep the LAST messages, drop the oldest
    token_counter=count_tokens_approximately, # fast token estimate (about 4 characters per token)
    start_on="human",                         # the kept history must start with a user message
    allow_partial=False,                      # never cut a message in half
)

print("AFTER TRIMMING (last ~300 tokens worth of messages):")
print("=" * 50)
for i, msg in enumerate(trimmed_messages):
    role = "Human" if isinstance(msg, HumanMessage) else "AI"
    print(f"[{i}] {role}: {msg.content[:80]}...")
print(f"\nMessages retained: {len(trimmed_messages)} (was {len(message_buffer)})")
print("=" * 50)

💡 Each setting in plain words

  • max_tokens=300: the kept messages must fit in about 300 tokens.
  • strategy="last": keep from the end, drop the oldest first.
  • count_tokens_approximately: a quick estimate, roughly 4 characters per token.
  • start_on="human": the kept part must begin with a user message.
  • allow_partial=False: never cut a message in half.
Example output (what you would see; exact text and numbers vary)
AFTER TRIMMING (last ~300 tokens worth of messages):
==================================================
[0] Human: What's the difference between classification and regression?...
[1] AI: Both are supervised learning; the difference is the kind of answer you predict.
...
[2] Human: Thanks! Can you remind me what my name is?...
[3] AI: Of course! Your name is Alice. Happy learning, and ask me anything whenever you ...

Messages retained: 4 (was 10)
==================================================

Only the last 4 messages fit. Alice's introduction is gone. Look closely, though: "Alice" still appears in message 3, only because the AI happened to repeat her name in its last reply. That's luck, not memory. Ask about anything else from turn 1 and the model can't know it.

The trimmed list is what you'd send; message_buffer itself is unchanged. That's the key difference from deleting.

3. Deletion: remove chosen messages

short_term_memory.ipynb · cells 17–18
# DELETION: Remove specific messages (e.g., the long explanations in middle)
# We'll delete messages 4-7 (the detailed ML explanations) but keep first and last

indices_to_delete = [4, 5, 6, 7]  # Middle messages with long explanations

deleted_buffer = [msg for i, msg in enumerate(message_buffer) if i not in indices_to_delete]

print("AFTER DELETION (removed indices 4-7):")
print("=" * 50)
for i, msg in enumerate(deleted_buffer):
    role = "Human" if isinstance(msg, HumanMessage) else "AI"
    print(f"[{i}] {role}: {msg.content[:80]}{'...' if len(msg.content) > 80 else ''}")
print(f"\nMessages retained: {len(deleted_buffer)} (was {len(message_buffer)})")
print("=" * 50)

# Compare: Can we still recall the user's name?
# With TRIMMING - name was lost (oldest messages removed)
# With DELETION - name preserved (we kept first messages)

deleted_buffer.append(HumanMessage(content="What's my name again?"))
response = llm.invoke(deleted_buffer)
print(f"AI Response: {response.content}")
print("\n** The name 'Alice' is preserved because we deleted MIDDLE messages, not the beginning! **")
Example output (what you would see; exact text and numbers vary)
AFTER DELETION (removed indices 4-7):
==================================================
[0] Human: Hi! My name is Alice and I'm learning about AI.
[1] AI: Hi Alice, nice to meet you! AI is a great thing to learn. What would you like to...
[2] Human: What are the main types of machine learning?
[3] AI: There are three main types of machine learning:

1. **Supervised learning**: the...
[4] Human: Thanks! Can you remind me what my name is?
[5] AI: Of course! Your name is Alice. Happy learning, and ask me anything whenever you ...

Messages retained: 6 (was 10)
==================================================

AI Response: Your name is Alice.

** The name 'Alice' is preserved because we deleted MIDDLE messages, not the beginning! **

Messages 4–7 (the two long explanations) are removed; the introduction stays, so the name is safe. The trade-off: you must decide what's safe to delete. Here the numbers 4–7 are typed by hand, which only works because we know this exact conversation.

4. Deletion inside a LangGraph agent: RemoveMessage

short_term_memory.ipynb · cell 20
from langchain_core.messages import RemoveMessage
from langgraph.graph.message import add_messages

state_messages = add_messages([], message_buffer)          # gives every message an id, as LangGraph state does
print(f"Before: {len(state_messages)} messages")

remove_first_two = [RemoveMessage(id=m.id) for m in state_messages[:2]]
state_messages = add_messages(state_messages, remove_first_two)
print(f"After removing the earliest two: {len(state_messages)} messages")
print("First message now:", state_messages[0].content[:80])
Output
Before: 10 messages
After removing the earliest two: 8 messages
First message now: What are the main types of machine learning?

In LangGraph you don't edit the list yourself. A step returns RemoveMessage(id=...), and the add_messages reducer deletes those messages from the saved state for good. Every message gets an id for exactly this reason.

5. Summarization: squeeze the old part into a few sentences

short_term_memory.ipynb · cell 23
def summarize_messages(messages, llm):
    """Summarize a list of messages into a single summary."""
    conversation_text = "\n".join([
        f"{'Human' if isinstance(m, HumanMessage) else 'AI'}: {m.content}"
        for m in messages
    ])
    
    summary_prompt = f"""Summarize this conversation in 2-3 sentences, preserving key facts:

{conversation_text}

Summary:"""
    
    summary = llm.invoke([HumanMessage(content=summary_prompt)])
    return summary.content
short_term_memory.ipynb · cells 25–27
# Summarize older messages (first 6), keep recent (last 4)
old_messages = message_buffer[:6]
recent_messages = message_buffer[6:]

summary = summarize_messages(old_messages, llm)
print("SUMMARY OF OLD MESSAGES:")
print(summary)

# Create new buffer with summary + recent messages
summarized_buffer = [
    SystemMessage(content=f"Previous conversation summary: {summary}")
] + recent_messages

print("SUMMARIZED BUFFER:")
print("=" * 50)
for i, msg in enumerate(summarized_buffer):
    if isinstance(msg, SystemMessage):
        role = "System"
    elif isinstance(msg, HumanMessage):
        role = "Human"
    else:
        role = "AI"
    print(f"[{i}] {role}: {msg.content[:100]}{'...' if len(msg.content) > 100 else ''}")
print(f"\nMessages: {len(summarized_buffer)} (was {len(message_buffer)})")
print("=" * 50)

# Test: Can we still recall the user's name?
summarized_buffer.append(HumanMessage(content="What's my name?"))
response = llm.invoke(summarized_buffer)
print(f"AI Response: {response.content}")
print("\n** The name is preserved in the SUMMARY even though original messages were compressed! **")
Example output (what you would see; exact text and numbers vary)
SUMMARY OF OLD MESSAGES:
Alice introduced herself and said she is learning about AI. She asked about the main types of machine learning (supervised, unsupervised and reinforcement learning) and then for an example of supervised learning, which was explained with predicting house prices from labelled sales data.

SUMMARIZED BUFFER:
==================================================
[0] System: Previous conversation summary: Alice introduced herself and said she is learning about AI. She asked...
[1] Human: What's the difference between classification and regression?
[2] AI: Both are supervised learning; the difference is the kind of answer you predict.

**Classification** ...
[3] Human: Thanks! Can you remind me what my name is?
[4] AI: Of course! Your name is Alice. Happy learning, and ask me anything whenever you get stuck.

Messages: 5 (was 10)
==================================================

AI Response: Your name is Alice. You mentioned it at the start of our conversation, when you told me you're learning about AI.

** The name is preserved in the SUMMARY even though original messages were compressed! **

The first 6 messages become one short SystemMessage; the last 4 stay word for word. 10 messages become 5, and the name survives because the summary kept it. The price: one extra model call, and details the summary leaves out are gone.

🌍 Which one to use

StrategyGood atWatch out forUse for
Full bufferNothing lostGrows until it hits the limitShort chats
TrimmingSimple, free, automaticEarly facts (name, budget) disappearOnly recent turns matter
DeletionPrecise controlYou must decide what's safe to removeDropping big tool outputs or sensitive data
SummarizationKeeps the gist of everythingExtra model call; details may be lostLong conversations
MCP

Tools served over MCP, used by OpenAI

D

fastmcp_demo_v1.ipynb: an MCP server with two real tools

"What's the time and weather in Tokyo?" The model discovers two tools on an MCP server, asks for both, and answers from real data.

Hostchat_with_tools + gpt-6-luna
⇄
ClientClient(mcp)
⇄
ServerFastMCP("MCP Demo Server")
⇄
Open-Meteofree weather API
The three MCP roles (MCP lecture slide 5), all inside one notebook.

1. The server and its two tools

fastmcp_demo_v1.ipynb · cell 4
import json
import requests
from openai import OpenAI
from fastmcp import FastMCP

openai_client = OpenAI()
MODEL = "gpt-6-luna"

# ---------------------------------------------------------------------------
# FastMCP server — tools are plain functions decorated with @mcp.tool()
# ---------------------------------------------------------------------------
mcp = FastMCP("MCP Demo Server")

WMO_CODES = {
    0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
    45: "Fog", 48: "Icy fog",
    51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",
    61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
    71: "Slight snow", 73: "Moderate snow", 75: "Heavy snow", 77: "Snow grains",
    80: "Slight showers", 81: "Moderate showers", 82: "Violent showers",
    85: "Slight snow showers", 86: "Heavy snow showers",
    95: "Thunderstorm", 96: "Thunderstorm with hail", 99: "Thunderstorm with heavy hail",
}


@mcp.tool()
def get_current_time(timezone: str = "UTC") -> str:
    """Get the current time in a given IANA timezone (e.g. 'Asia/Tokyo', 'Asia/Kolkata')."""
    from zoneinfo import ZoneInfo
    from datetime import datetime
    try:
        tz = ZoneInfo(timezone)
        now = datetime.now(tz)
        return f"Current time in {timezone}: {now.strftime('%Y-%m-%d %H:%M:%S %Z')}"
    except Exception as e:
        return f"Unknown timezone '{timezone}': {e}"


@mcp.tool()
def get_weather(city: str) -> str:
    """Get current weather for a city using Open-Meteo (no API key required)."""
    try:
        geo_resp = requests.get(
            "https://geocoding-api.open-meteo.com/v1/search",
            params={"name": city, "count": 1, "language": "en", "format": "json"},
            timeout=10,
        )
        geo_resp.raise_for_status()
        geo_data = geo_resp.json()
        if not geo_data.get("results"):
            return f"City '{city}' not found."
        loc = geo_data["results"][0]
        lat, lon = loc["latitude"], loc["longitude"]
        resolved_name = loc.get("name", city)

        wx_resp = requests.get(
            "https://api.open-meteo.com/v1/forecast",
            params={
                "latitude": lat,
                "longitude": lon,
                "current": "temperature_2m,relative_humidity_2m,apparent_temperature,wind_speed_10m,weather_code",
                "wind_speed_unit": "kmh",
                "timezone": "auto",
            },
            timeout=10,
        )
        wx_resp.raise_for_status()
        cur = wx_resp.json()["current"]
        desc = WMO_CODES.get(cur["weather_code"], f"Weather code {cur['weather_code']}")
        return (
            f"Weather in {resolved_name}: {desc}, "
            f"{cur['temperature_2m']}\u00b0C (feels like {cur['apparent_temperature']}\u00b0C), "
            f"Humidity: {cur['relative_humidity_2m']}%, Wind: {cur['wind_speed_10m']} km/h"
        )
    except Exception as e:
        return f"Could not get weather for {city}: {e}"


print("FastMCP server defined with tools: get_current_time, get_weather")

💡 What to point out

  • @mcp.tool() turns a normal function into an MCP tool. Its docstring becomes the description the model reads; its type hints become the input schema (MCP lecture slides 10 and 13).
  • get_current_time uses Python's own time-zone data, no internet needed.
  • get_weather makes two real web calls: city name → latitude/longitude, then the current weather there. WMO_CODES turns the weather code (e.g. 2) into words ("Partly cloudy").
  • Both tools return an error message instead of crashing, so the model can tell the user what went wrong.

2. The host: discover, ask the model, run the tools, ask again

fastmcp_demo_v1.ipynb · cell 5
from fastmcp import Client


async def chat_with_tools(user_message: str) -> str:
    """Send a message to OpenAI, dispatching tool calls through the FastMCP server."""
    async with Client(mcp) as client:
        tools = await client.list_tools()
        functions = [
            {
                "type": "function",
                "function": {
                    "name": t.name,
                    "description": t.description or "",
                    "parameters": t.input_schema,
                },
            }
            for t in tools
        ]

        messages = [{"role": "user", "content": user_message}]

        response = openai_client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=functions,
            tool_choice="auto",
            reasoning_effort="none",   # answer straight away, no hidden "thinking" tokens
        )
        message = response.choices[0].message

        if message.tool_calls:
            messages.append({
                "role": "assistant",
                "content": message.content,
                "tool_calls": [tc.model_dump() for tc in message.tool_calls],
            })

            for tool_call in message.tool_calls:
                tool_name = tool_call.function.name
                tool_args = json.loads(tool_call.function.arguments)

                result = await client.call_tool(tool_name, tool_args)
                text = result.content[0].text if result.content else ""

                print(f"  [Tool: {tool_name}({tool_args})] => {text}")
                messages.append({
                    "role": "tool",
                    "content": text,
                    "tool_call_id": tool_call.id,
                })

            final_response = openai_client.chat.completions.create(
                model=MODEL,
                messages=messages,
                reasoning_effort="none",
            )
            return final_response.choices[0].message.content

        return message.content


print("chat_with_tools defined.")

💡 Read it in this order

  1. Connect: Client(mcp) opens a client to the server. Passing the server object connects in memory; no separate program is needed.
  2. Discover: list_tools() sends tools/list; each tool's name, description and input_schema are copied into OpenAI's function format.
  3. First call: the question plus the tool list go to gpt-6-luna. It either answers or asks for tools.
  4. Run the tools: for each request, client.call_tool() sends tools/call to the server, and the result goes back into the conversation as a "role": "tool" message with the matching tool_call_id.
  5. Second call: the model sees the results and writes the final answer.

3. Three questions

fastmcp_demo_v1.ipynb · cell 7
async def run_demo():
    print("FastMCP Demo Starting...")

    demos = [
        "What time is it right now in Bangalore?",
        "What's the weather like in Bangalore?",
        "Can you tell me the time and weather in Tokyo?",
    ]

    for i, query in enumerate(demos, 1):
        print(f"\n--- Demo {i} ---")
        print(f"User: {query}")
        try:
            response = await chat_with_tools(query)
            print(f"Assistant: {response}")
        except Exception as e:
            print(f"Error: {e}")

    print("\nFastMCP Demo completed!")


await run_demo()
Example output (what you would see; exact text and numbers vary)
FastMCP Demo Starting...

--- Demo 1 ---
User: What time is it right now in Bangalore?
  [Tool: get_current_time({'timezone': 'Asia/Kolkata'})] => Current time in Asia/Kolkata: 2026-11-10 10:30:12 IST
Assistant: It's 10:30 AM in Bangalore right now (Tuesday, 10 November 2026, IST).

--- Demo 2 ---
User: What's the weather like in Bangalore?
  [Tool: get_weather({'city': 'Bangalore'})] => Weather in Bengaluru: Partly cloudy, 24.6°C (feels like 25.3°C), Humidity: 71%, Wind: 9.7 km/h
Assistant: It's partly cloudy in Bangalore at the moment, 24.6°C (feels like about 25°C), with 71% humidity and a light breeze of around 10 km/h. A pleasant day overall.

--- Demo 3 ---
User: Can you tell me the time and weather in Tokyo?
  [Tool: get_current_time({'timezone': 'Asia/Tokyo'})] => Current time in Asia/Tokyo: 2026-11-10 14:00:15 JST
  [Tool: get_weather({'city': 'Tokyo'})] => Weather in Tokyo: Clear sky, 17.8°C (feels like 16.4°C), Humidity: 52%, Wind: 11.2 km/h
Assistant: In Tokyo it's 2:00 PM (JST) right now. The sky is clear, it's 17.8°C (feels like about 16°C), humidity is 52% and there's a light wind of about 11 km/h. A light jacket would be comfortable.

FastMCP Demo completed!

In this example, notice that the model turned "Bangalore" into the time-zone name Asia/Kolkata by itself, and asked for two tools at once for Tokyo. The weather service answered with "Bengaluru", the city's official name.

⚠️ Only one round of tools

The second model call has no tools, so the model gets exactly one chance to ask for tools. A question like "Is it warmer in Tokyo or in whichever city is 3 hours behind it?" needs a second round and won't work. The host on MCP lecture slide 6 uses a loop instead (Exercise 6).

Teach and extend

Connecting the code to the lectures

↔

Link to the lectures

In the codeLecture ideaSlide
message_buffer resent every turnLLMs are stateless; the app supplies memoryMemory 4, 8
trim_messages, deletion, RemoveMessageTrimming and deleting messagesMemory 9
summarize_messagesSummarizing historyMemory 10–11
semantic_memory + keyword lookupSemantic memory: facts and how they're usedMemory 13–17
recent_interactionsEpisodic memory: specific past eventsMemory 18–24
procedural_lookupProcedural memory: how to do a taskMemory 25–29
update_memory node, saved JSONWriting memory in the hot path; long-term storageMemory 6, 12
FastMCP, @mcp.tool()Building a server; docstring = descriptionMCP 9–11
list_tools() → OpenAI functionsTool discoveryMCP 13
call_tool(), tool messagesTool invocation and the agentic loopMCP 6, 7, 14
!

Known limits (good discussion points)

  1. Keyword lookup misses synonyms. "Can I get a refund?" contains no "return", so no policy is fetched. Real systems search by meaning with embeddings (Memory slides 16–17).
  2. A missing order in demo 1. user_789 owns ORD-006, which isn't in order_store, so the model would be shown an empty {} for it. Demo 2 skips unknown IDs (if oid in self.order_store).
  3. Unknown customers get an empty context and are called "Customer". The agent doesn't say it couldn't find them.
  4. Demo 2 resets its memory on every start (the file is saved, never loaded). See Exercise 1.
  5. The detector can invent keys. Ask "please use a formal tone" and the model may return {"tone": "formal"}, which is added to the preferences as a brand-new key. See Exercise 3.
  6. Contact method is stored in two places. preferred_contact sits outside preferences, but the detector only updates preferences. "Contact me by SMS" would most likely add a new key inside preferences and leave preferred_contact as "email".
  7. Hard-coded deletion indices (4–7) in the notebook only fit this exact conversation.
  8. Summaries pile up. Summarizing a second time must fold the old summary into the new one, or earlier facts are lost (Memory slide 10).
  9. One round of tools in the MCP notebook, and tool output goes to the model as plain text without an "untrusted data" label (MCP slide 16).
✎

Exercises for learners

1. Make memory_demo_2 remember across runs.

In __init__, load the file when it exists instead of overwriting it:

if os.path.exists(EPISODIC_MEMORY_FILE):
    with open(EPISODIC_MEMORY_FILE) as f:
        self.episodic_memory = json.load(f)        # what earlier runs learned
else:
    self.episodic_memory = copy.deepcopy(EPISODIC_MEMORY_DEFAULT)

Run the demo twice. The second run's turn 1 is already brief. Delete the file to start over.

2. Ask demo 1 "Can I get a refund for my laptop?" What happens, and how would you fix it?

No policy is fetched, because "refund" isn't "return" (Limit 1). Quick fix: check a list of words (["return", "refund", "send back"]). Better fix: store the facts with embeddings and fetch the closest ones by meaning.

3. Only accept preferences the agent knows about.

Right after reading the detector's JSON:

ALLOWED = {"language", "detail_level", "shipping_speed", "currency"}
updates = {k: v for k, v in updates.items() if k in ALLOWED}

Now try "please use a formal tone": nothing is stored, and the console says no change was detected.

4. Add a fourth turn to demo 2: "Please contact me by SMS from now on." Then open the JSON file. What's wrong?

The change most likely lands inside preferences (for example "contact_method": "sms") while preferred_contact still says "email" (Limit 6). Fix: move preferred_contact into preferences, or have the detector update top-level keys too.

5. In the notebook, change trimming to max_tokens=1000. How many messages are kept now? Is Alice's introduction among them?

More messages fit, but with long AI explanations the first message usually still doesn't. Raise the limit until it does, and notice how many tokens you'd be sending every turn just to keep one name. That's the case for summarizing or for saving the name to long-term memory.

6. Give the MCP notebook's host a real loop.

Keep tools=functions on every call and repeat "call the model → run any tool calls" until the model replies without tool calls, with a limit of about 5 rounds. MCP explainer slide 6 has a complete version.

7. Run the MCP server as its own program.

Move the server cell into weather_server.py and end it with mcp.run(transport="stdio") under if __name__ == "__main__":. In the notebook, connect with Client("weather_server.py"). Nothing else changes: that's the transport independence from MCP lecture slide 10.

★

Glossary

Short-term memory
The messages of the current conversation, resent to the model every turn.
Long-term memory
What the agent keeps across conversations: facts, past events, procedures.
Semantic / episodic / procedural
Facts (what's true) / events (what happened) / know-how (how to do it).
State (LangGraph)
The shared "form" every step reads from and writes to.
Node / edge
One step of the graph / the arrow that says which step comes next.
Hot path
Updating memory during the reply, before the answer is written.
JSON mode
response_format={"type": "json_object"}: the model must reply with valid JSON.
deepcopy
A full independent copy of a dictionary, so changes don't leak back.
Token
A piece of text the model counts, about 4 characters of English.
trim_messages
LangChain helper that keeps only the messages that fit a token budget.
RemoveMessage / add_messages
LangGraph's way to delete messages from the saved state by id.
MCP server / client / host
Offers tools / talks to one server / owns the model and runs the loop.
input_schema
The JSON description of a tool's inputs, built from type hints.
tool_call_id
The ID that links a tool's result to the model's request.
IANA time zone
Standard names like Asia/Kolkata or Asia/Tokyo.
{ }

Full source

memory_demo_1.py (complete file)
memory_demo_1.py (complete file)
"""
memory_demo_1.py  -  three kinds of memory feeding one answer   (by Shivank Agarwal)
=====================================================================================
WHAT YOU LEARN
    A customer-service agent built as a LangGraph pipeline of four steps:
      1. semantic memory   -> general facts (return policy, shipping time)
      2. episodic memory   -> what we know about THIS customer (name, preferences, past chats)
      3. procedural memory -> a fixed procedure to look up the customer's orders
      4. generate_response -> the model writes the reply using all three
    The memories here are Python dictionaries so the flow is easy to see.

RUN:  python memory_demo_1.py      (needs OPENAI_API_KEY in .env)
"""
import json
from typing import Any, Dict, TypedDict

from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph

load_dotenv()

# The model that writes the final reply
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")

class AgentState(TypedDict):
    user_id: str
    user_query: str
    order_id: str
    semantic_facts: Dict[str, Any]
    user_context: Dict[str, Any]
    order_details: Dict[str, Any]
    final_response: str

class MemoryDemo:
    def __init__(self):
        # Semantic Memory (general world knowledge/facts)
        self.semantic_memory = {
            "company_policies": {
                "return_period": "30 days",
                "shipping_time": "3-5 business days",
                "customer_service_hours": "9 AM - 6 PM EST"
            },
            "product_categories": {
                "electronics": "Includes phones, laptops, accessories",
                "clothing": "Includes shirts, pants, dresses",
                "books": "Includes fiction, non-fiction, educational"
            }
        }
        
        # Episodic Memory (user-specific experiences/details)
        self.episodic_memory = {
    "user_123": {
        "name": "Alice Johnson",
        "preferred_contact": "email",
        "recent_interactions": [
            "Asked about return policy yesterday",
            "Purchased electronics last week"
        ],
        "preferences": {
            "language": "English",
            "detail_level": "detailed"
        }
    },
    "user_456": {
        "name": "Bob Smith",
        "preferred_contact": "sms",
        "recent_interactions": [
            "Complained about delayed shipping last month",
            "Frequently buys clothing items",
            "Requested premium shipping upgrade"
        ],
        "preferences": {
            "language": "English", 
            "detail_level": "brief",
            "shipping_speed": "express"
        }
    },
    "user_789": {
        "name": "Carlos Rodriguez",
        "preferred_contact": "phone",
        "recent_interactions": [
            "First-time customer",
            "Purchased books and electronics",
            "Asked about international shipping"
        ],
        "preferences": {
            "language": "Spanish",
            "detail_level": "normal",
            "currency": "EUR"
        }
    }
}
        
        # Simulated data stores (would be external in real scenario)
        self.order_store = {
            "ORD-001": {"status": "shipped", "value": 299.99},
            "ORD-002": {"status": "processing", "value": 149.50},
            "ORD-003": {"status": "delivered", "value": 89.99},
            "ORD-004": {"status": "cancelled", "value": 49.99}
        }
        
        self.user_orders = {
            "user_123": ["ORD-001", "ORD-002"],
            "user_456": ["ORD-003"],
            "user_789": ["ORD-004", "ORD-006"]
        }

    def get_semantic_facts(self, state: AgentState) -> AgentState:
        """Retrieve general world knowledge from semantic memory"""
        print("🔍 Accessing SEMANTIC MEMORY...")
        
        # Extract relevant semantic facts based on query
        relevant_facts = {}
        user_query = state.get("user_query", "").lower()
        
        if "return" in user_query:
            relevant_facts["return_policy"] = self.semantic_memory["company_policies"]["return_period"]
        if "shipping" in user_query:
            relevant_facts["shipping_info"] = self.semantic_memory["company_policies"]["shipping_time"]
        if "electronics" in user_query:
            relevant_facts["category_info"] = self.semantic_memory["product_categories"]["electronics"]
            
        state["semantic_facts"] = relevant_facts
        return state

    def get_user_context(self, state: AgentState) -> AgentState:
        """Retrieve user-specific details from episodic memory"""
        print("👤 Accessing EPISODIC MEMORY...")
        
        user_id = state.get("user_id", "user_123")  # Default for demo
        user_context = self.episodic_memory.get(user_id, {})
        
        state["user_context"] = user_context
        return state

    def procedural_lookup(self, state: AgentState) -> AgentState:
        """Execute procedural memory - follow steps to query data stores"""
        print("🔄 Executing PROCEDURAL MEMORY...")
        
        user_id = state.get("user_id", "user_123")
        order_id = state.get("order_id")
        
        # Procedural steps:
        # 1. Look up user's orders
        user_order_ids = self.user_orders.get(user_id, [])
        
        # 2. If specific order requested, get its details
        if order_id and order_id in user_order_ids:
            order_details = self.order_store.get(order_id, {})
            state["order_details"] = {order_id: order_details}
        # 3. Otherwise get all user orders
        else:
            all_orders = {}
            for oid in user_order_ids:
                all_orders[oid] = self.order_store.get(oid, {})
            state["order_details"] = all_orders
            
        return state

    def generate_response(self, state: AgentState) -> AgentState:
        """Generate final response using all memory types"""
        print("💭 Generating response using all memory types...")
        
        prompt = f"""
        Based on the following information, provide a helpful response to the user:
        
        USER QUERY: {state['user_query']}
        
        SEMANTIC KNOWLEDGE (General Facts):
        {json.dumps(state.get('semantic_facts', {}), indent=2)}
        
        EPISODIC MEMORY (User Context):
        Name: {state['user_context'].get('name', 'Customer')}
        Preferences: {state['user_context'].get('preferences', {})}
        Recent Interactions: {state['user_context'].get('recent_interactions', [])}
        
        PROCEDURAL RESULTS (Order Data):
        {json.dumps(state.get('order_details', {}), indent=2)}
        
        Provide a natural, helpful response that incorporates this information.
        Sign off with Best regards, Agent Nancy.
        """
        
        response = llm.invoke(prompt)
        state["final_response"] = response.text
        return state

    def build_workflow(self):
        """Build the LangGraph workflow"""
        workflow = StateGraph(AgentState)
        
        # Define nodes
        workflow.add_node("semantic_memory", self.get_semantic_facts)
        workflow.add_node("episodic_memory", self.get_user_context)
        workflow.add_node("procedural_memory", self.procedural_lookup)
        workflow.add_node("generate_response", self.generate_response)
        
        # Define workflow
        workflow.set_entry_point("semantic_memory")
        workflow.add_edge("semantic_memory", "episodic_memory")
        workflow.add_edge("episodic_memory", "procedural_memory")
        workflow.add_edge("procedural_memory", "generate_response")
        workflow.add_edge("generate_response", END)
        
        return workflow.compile()

# Demo execution
def run_demo():
    demo = MemoryDemo()
    workflow = demo.build_workflow()
    
    # Test scenarios
    test_cases = [
        {
            "user_id": "user_123",
            "user_query": "What's the status of my orders and what's your return policy?",
            "order_id": None,
            "semantic_facts": {},
            "user_context": {},
            "order_details": {},
            "final_response": ""
        },
        {
            "user_id": "user_456", 
            "user_query": "Can you check the status of order ORD-003? I might need to return it.",
            "order_id": "ORD-003",
            "semantic_facts": {},
            "user_context": {},
            "order_details": {},
            "final_response": ""
        }
    ]
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"\n{'='*50}")
        print(f"TEST CASE {i}")
        print(f"{'='*50}")
        
        print(f"Query: {test_case['user_query']}")
        print(f"User: {test_case['user_id']}")
        
        result = workflow.invoke(test_case)
        
        print(f"\n📝 FINAL RESPONSE:")
        print(f"{result['final_response']}")
        print(f"{'='*50}\n")

if __name__ == "__main__":
    run_demo()
memory_demo_2.py (complete file)
memory_demo_2.py (complete file)
"""
memory_demo_2.py  -  memory that updates itself and is saved to disk   (by Shivank Agarwal)
===========================================================================================
WHAT YOU LEARN
    Same four-step agent as memory_demo_1.py, plus a new step: update_memory.
    In every turn the model checks whether the user changed a preference
    ("keep it brief from now on"). If so, the preference is updated straight away
    (the "hot path"), an audit trail is kept, and everything is saved to
    episodic_memory.json so it survives after the program ends.

RUN:  python memory_demo_2.py      (needs OPENAI_API_KEY in .env)
"""
import copy
import json
import os
from typing import Any, Dict, Optional, TypedDict

from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph

load_dotenv()

llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# Same model, but forced to reply with a valid JSON object (used by the preference detector)
json_llm = llm.bind(response_format={"type": "json_object"})

class AgentState(TypedDict):
    user_id: str
    user_query: str
    order_id: Optional[str]
    semantic_facts: Dict[str, Any]
    user_context: Dict[str, Any]
    order_details: Dict[str, Any]
    preference_update: Dict[str, Any]   # newly detected preference changes
    final_response: str


EPISODIC_MEMORY_FILE = os.path.join(os.path.dirname(__file__), "episodic_memory.json")

EPISODIC_MEMORY_DEFAULT = {
    "user_123": {
        "name": "Alice Johnson",
        "preferred_contact": "email",
        "recent_interactions": [
            "Asked about return policy yesterday",
            "Purchased electronics last week"
        ],
        "preferences": {
            "language": "English",
            "detail_level": "detailed"
        }
    },
    "user_456": {
        "name": "Bob Smith",
        "preferred_contact": "sms",
        "recent_interactions": [
            "Complained about delayed shipping last month",
            "Frequently buys clothing items"
        ],
        "preferences": {
            "language": "English",
            "detail_level": "brief",
            "shipping_speed": "express"
        }
    }
}


class MemoryDemo:
    def __init__(self):
        # Reset to default and write to JSON file so we start fresh each demo
        self.episodic_memory: Dict[str, Any] = copy.deepcopy(EPISODIC_MEMORY_DEFAULT)   # a fresh copy, not the original
        with open(EPISODIC_MEMORY_FILE, "w") as f:
            json.dump(self.episodic_memory, f, indent=2)
        print(f"✅ Episodic memory written to {EPISODIC_MEMORY_FILE}")
        self.turn = 0

        self.semantic_memory = {
            "company_policies": {
                "return_period": "30 days",
                "shipping_time": "3-5 business days",
                "customer_service_hours": "9 AM - 6 PM EST"
            },
            "product_categories": {
                "electronics": "Includes phones, laptops, accessories",
                "clothing": "Includes shirts, pants, dresses"
            }
        }

        self.order_store = {
            "ORD-001": {"status": "shipped",    "value": 299.99},
            "ORD-002": {"status": "processing", "value": 149.50},
            "ORD-003": {"status": "delivered",  "value": 89.99},
        }
        self.user_orders = {
            "user_123": ["ORD-001", "ORD-002"],
            "user_456": ["ORD-003"],
        }

    # ── Nodes ────────────────────────────────────────────────────────────────

    def get_semantic_facts(self, state: AgentState) -> AgentState:
        print("🔍 Accessing SEMANTIC MEMORY...")
        relevant_facts = {}
        query = state.get("user_query", "").lower()
        if "return"     in query: relevant_facts["return_policy"]  = self.semantic_memory["company_policies"]["return_period"]
        if "shipping"   in query: relevant_facts["shipping_info"]  = self.semantic_memory["company_policies"]["shipping_time"]
        if "electronics" in query: relevant_facts["category_info"] = self.semantic_memory["product_categories"]["electronics"]
        state["semantic_facts"] = relevant_facts
        return state

    def get_user_context(self, state: AgentState) -> AgentState:
        print("👤 Accessing EPISODIC MEMORY...")
        state["user_context"] = self.episodic_memory.get(state["user_id"], {})
        return state

    def detect_and_update_preference(self, state: AgentState) -> AgentState:
        """
        Use the LLM to detect preference change requests in the user query.
        If a preference change is found, update episodic memory immediately
        so the SAME turn already reflects the new preference.
        """
        print("🔄 Checking for PREFERENCE UPDATES...")
        self.turn += 1

        prompt = f"""
You are a preference-change detector. Analyse the user message below.
If the user is requesting a change to any of their preferences (e.g. detail level,
language, contact method, shipping speed, etc.), respond with ONLY a valid JSON object
mapping preference key → new value, like:
{{"detail_level": "brief"}}

If there is NO preference change, respond with ONLY an empty JSON object: {{}}

User message: "{state['user_query']}"
"""
        result = json_llm.invoke(prompt)
        try:
            updates: Dict[str, Any] = json.loads(result.text)
        except json.JSONDecodeError:
            updates = {}
        if not isinstance(updates, dict):
            updates = {}

        state["preference_update"] = updates

        if updates:
            user_id = state["user_id"]
            if user_id in self.episodic_memory:
                old_prefs = {k: self.episodic_memory[user_id]["preferences"][k]
                             for k in updates if k in self.episodic_memory[user_id]["preferences"]}
                self.episodic_memory[user_id]["preferences"].update(updates)
                # Append to audit trail
                audit = self.episodic_memory[user_id].setdefault("preference_history", {})
                if not audit:
                    audit[f"turn_{self.turn - 1}"] = old_prefs  # seed state before first change
                audit[f"turn_{self.turn}"] = dict(updates)
                # Refresh the user_context so generate_response uses new prefs
                state["user_context"] = self.episodic_memory[user_id]
                print(f"   ✏️  Preference updated for {user_id}: {old_prefs} → {updates}")
                print(f"   📋 New preferences: {self.episodic_memory[user_id]['preferences']}")
                # Persist updated memory to JSON file
                with open(EPISODIC_MEMORY_FILE, "w") as f:
                    json.dump(self.episodic_memory, f, indent=2)
                print(f"   💾 Episodic memory saved to {EPISODIC_MEMORY_FILE}")
        else:
            print("   — No preference change detected.")

        return state

    def procedural_lookup(self, state: AgentState) -> AgentState:
        print("📦 Executing PROCEDURAL MEMORY...")
        user_id  = state["user_id"]
        order_id = state.get("order_id")
        user_order_ids = self.user_orders.get(user_id, [])

        if order_id and order_id in user_order_ids:
            state["order_details"] = {order_id: self.order_store[order_id]}
        else:
            state["order_details"] = {oid: self.order_store[oid] for oid in user_order_ids if oid in self.order_store}
        return state

    def generate_response(self, state: AgentState) -> AgentState:
        print("💭 Generating response using all memory types...")
        prefs       = state["user_context"].get("preferences", {})
        detail_level = prefs.get("detail_level", "normal")

        prompt = f"""
You are a helpful customer service agent.
Respond to the user query below.  Detail level: {detail_level}.
{"Keep your answer SHORT and to the point." if detail_level == "brief" else "Provide a thorough, detailed answer." if detail_level == "detailed" else ""}

USER QUERY: {state['user_query']}

SEMANTIC KNOWLEDGE:
{json.dumps(state.get('semantic_facts', {}), indent=2)}

EPISODIC MEMORY (User Context):
Name: {state['user_context'].get('name', 'Customer')}
Preferences: {json.dumps(prefs)}
Recent Interactions: {state['user_context'].get('recent_interactions', [])}

PROCEDURAL RESULTS (Order Data):
{json.dumps(state.get('order_details', {}), indent=2)}

Sign off with: Best regards, Agent Nancy.
"""
        response = llm.invoke(prompt)
        state["final_response"] = response.text
        return state

    # ── Graph ────────────────────────────────────────────────────────────────

    def build_workflow(self):
        wf = StateGraph(AgentState)

        wf.add_node("semantic_memory",  self.get_semantic_facts)
        wf.add_node("episodic_memory",  self.get_user_context)
        wf.add_node("update_memory",    self.detect_and_update_preference)   
        wf.add_node("procedural_memory", self.procedural_lookup)
        wf.add_node("generate_response", self.generate_response)

        wf.set_entry_point("semantic_memory")
        wf.add_edge("semantic_memory",   "episodic_memory")
        wf.add_edge("episodic_memory",   "update_memory")        # ← new edge
        wf.add_edge("update_memory",     "procedural_memory")
        wf.add_edge("procedural_memory", "generate_response")
        wf.add_edge("generate_response", END)

        return wf.compile()


# ── Demo ─────────────────────────────────────────────────────────────────────

def make_state(user_id: str, query: str, order_id: Optional[str] = None) -> AgentState:
    return {
        "user_id":          user_id,
        "user_query":       query,
        "order_id":         order_id,
        "semantic_facts":   {},
        "user_context":     {},
        "order_details":    {},
        "preference_update": {},
        "final_response":   ""
    }


def run_demo():
    demo     = MemoryDemo()
    workflow = demo.build_workflow()

    print("\n" + "="*60)
    print("TURN 1  — Normal query (detail_level = 'detailed')")
    print("="*60)
    result1 = workflow.invoke(make_state(
        user_id="user_123",
        query="What is the status of my orders and what's the return policy?"
    ))
    print(f"\n📝 RESPONSE:\n{result1['final_response']}\n")

    print("="*60)
    print("TURN 2  — User requests preference change to 'brief'")
    print("="*60)
    result2 = workflow.invoke(make_state(
        user_id="user_123",
        query="Please keep your answers brief from now on. Also, what's the shipping time?"
    ))
    print(f"\n📝 RESPONSE:\n{result2['final_response']}\n")
    print(f"🗂️  Stored preference after Turn 2: {demo.episodic_memory['user_123']['preferences']}")
    print(f"📂 Open '{EPISODIC_MEMORY_FILE}' to see the updated JSON on disk.\n")

    print("="*60)
    print("TURN 3  — Follow-up query, should now respect 'brief' preference")
    print("="*60)
    result3 = workflow.invoke(make_state(
        user_id="user_123",
        query="Can you give me an update on all my orders?"
    ))
    print(f"\n📝 RESPONSE:\n{result3['final_response']}\n")


if __name__ == "__main__":
    run_demo()
short_term_memory.ipynb (all code cells)
short_term_memory.ipynb · cells 1–28
!pip install -q langchain langchain-openai langgraph

import os
from getpass import getpass

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI API key: ")

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage

# reasoning_effort="none": answer straight away, no hidden "thinking" tokens
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")

# Simple message buffer (list of messages)
message_buffer = []

def chat(user_input):
    """Chat function that maintains conversation history."""
    message_buffer.append(HumanMessage(content=user_input))
    response = llm.invoke(message_buffer)
    message_buffer.append(response)
    return response.content

def dump_memory():
    """Display all messages in the buffer."""
    print("=" * 50)
    print("MEMORY DUMP")
    print("=" * 50)
    for i, msg in enumerate(message_buffer):
        role = "Human" if isinstance(msg, HumanMessage) else "AI"
        print(f"[{i}] {role}: {msg.content[:100]}{'...' if len(msg.content) > 100 else ''}")
    print(f"\nTotal messages: {len(message_buffer)}")
    print("=" * 50)

# 5-turn conversation
conversations = [
    "Hi! My name is Alice and I'm learning about AI.",
    "What are the main types of machine learning?",
    "Can you explain supervised learning with an example?",
    "What's the difference between classification and regression?",
    "Thanks! Can you remind me what my name is?"
]

for user_msg in conversations:
    print(f"Human: {user_msg}")
    response = chat(user_msg)
    print(f"AI: {response}\n")

# Full memory dump - all 10 messages (5 human + 5 AI)
dump_memory()

from langchain_core.messages import trim_messages

# Reset buffer
message_buffer = []

# Rebuild conversation
for user_msg in conversations:
    message_buffer.append(HumanMessage(content=user_msg))
    response = llm.invoke(message_buffer)
    message_buffer.append(response)

print("BEFORE TRIMMING:")
dump_memory()

from langchain_core.messages.utils import count_tokens_approximately

# Keep only the most recent messages that fit in ~300 tokens
trimmed_messages = trim_messages(
    message_buffer,
    max_tokens=300,
    strategy="last",                          # keep the LAST messages, drop the oldest
    token_counter=count_tokens_approximately, # fast token estimate (about 4 characters per token)
    start_on="human",                         # the kept history must start with a user message
    allow_partial=False,                      # never cut a message in half
)

print("AFTER TRIMMING (last ~300 tokens worth of messages):")
print("=" * 50)
for i, msg in enumerate(trimmed_messages):
    role = "Human" if isinstance(msg, HumanMessage) else "AI"
    print(f"[{i}] {role}: {msg.content[:80]}...")
print(f"\nMessages retained: {len(trimmed_messages)} (was {len(message_buffer)})")
print("=" * 50)

# Reset and rebuild
message_buffer = []
for user_msg in conversations:
    message_buffer.append(HumanMessage(content=user_msg))
    response = llm.invoke(message_buffer)
    message_buffer.append(response)

print("ORIGINAL BUFFER:")
dump_memory()

# DELETION: Remove specific messages (e.g., the long explanations in middle)
# We'll delete messages 4-7 (the detailed ML explanations) but keep first and last

indices_to_delete = [4, 5, 6, 7]  # Middle messages with long explanations

deleted_buffer = [msg for i, msg in enumerate(message_buffer) if i not in indices_to_delete]

print("AFTER DELETION (removed indices 4-7):")
print("=" * 50)
for i, msg in enumerate(deleted_buffer):
    role = "Human" if isinstance(msg, HumanMessage) else "AI"
    print(f"[{i}] {role}: {msg.content[:80]}{'...' if len(msg.content) > 80 else ''}")
print(f"\nMessages retained: {len(deleted_buffer)} (was {len(message_buffer)})")
print("=" * 50)

# Compare: Can we still recall the user's name?
# With TRIMMING - name was lost (oldest messages removed)
# With DELETION - name preserved (we kept first messages)

deleted_buffer.append(HumanMessage(content="What's my name again?"))
response = llm.invoke(deleted_buffer)
print(f"AI Response: {response.content}")
print("\n** The name 'Alice' is preserved because we deleted MIDDLE messages, not the beginning! **")

from langchain_core.messages import RemoveMessage
from langgraph.graph.message import add_messages

state_messages = add_messages([], message_buffer)          # gives every message an id, as LangGraph state does
print(f"Before: {len(state_messages)} messages")

remove_first_two = [RemoveMessage(id=m.id) for m in state_messages[:2]]
state_messages = add_messages(state_messages, remove_first_two)
print(f"After removing the earliest two: {len(state_messages)} messages")
print("First message now:", state_messages[0].content[:80])

def summarize_messages(messages, llm):
    """Summarize a list of messages into a single summary."""
    conversation_text = "\n".join([
        f"{'Human' if isinstance(m, HumanMessage) else 'AI'}: {m.content}"
        for m in messages
    ])
    
    summary_prompt = f"""Summarize this conversation in 2-3 sentences, preserving key facts:

{conversation_text}

Summary:"""
    
    summary = llm.invoke([HumanMessage(content=summary_prompt)])
    return summary.content

# Reset and rebuild
message_buffer = []
for user_msg in conversations:
    message_buffer.append(HumanMessage(content=user_msg))
    response = llm.invoke(message_buffer)
    message_buffer.append(response)

print("ORIGINAL BUFFER:")
dump_memory()

# Summarize older messages (first 6), keep recent (last 4)
old_messages = message_buffer[:6]
recent_messages = message_buffer[6:]

summary = summarize_messages(old_messages, llm)
print("SUMMARY OF OLD MESSAGES:")
print(summary)

# Create new buffer with summary + recent messages
summarized_buffer = [
    SystemMessage(content=f"Previous conversation summary: {summary}")
] + recent_messages

print("SUMMARIZED BUFFER:")
print("=" * 50)
for i, msg in enumerate(summarized_buffer):
    if isinstance(msg, SystemMessage):
        role = "System"
    elif isinstance(msg, HumanMessage):
        role = "Human"
    else:
        role = "AI"
    print(f"[{i}] {role}: {msg.content[:100]}{'...' if len(msg.content) > 100 else ''}")
print(f"\nMessages: {len(summarized_buffer)} (was {len(message_buffer)})")
print("=" * 50)

# Test: Can we still recall the user's name?
summarized_buffer.append(HumanMessage(content="What's my name?"))
response = llm.invoke(summarized_buffer)
print(f"AI Response: {response.content}")
print("\n** The name is preserved in the SUMMARY even though original messages were compressed! **")
fastmcp_demo_v1.ipynb (all code cells)
fastmcp_demo_v1.ipynb · cells 1–7
!pip install -q openai requests fastmcp

import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")

import json
import requests
from openai import OpenAI
from fastmcp import FastMCP

openai_client = OpenAI()
MODEL = "gpt-6-luna"

# ---------------------------------------------------------------------------
# FastMCP server — tools are plain functions decorated with @mcp.tool()
# ---------------------------------------------------------------------------
mcp = FastMCP("MCP Demo Server")

WMO_CODES = {
    0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
    45: "Fog", 48: "Icy fog",
    51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",
    61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
    71: "Slight snow", 73: "Moderate snow", 75: "Heavy snow", 77: "Snow grains",
    80: "Slight showers", 81: "Moderate showers", 82: "Violent showers",
    85: "Slight snow showers", 86: "Heavy snow showers",
    95: "Thunderstorm", 96: "Thunderstorm with hail", 99: "Thunderstorm with heavy hail",
}


@mcp.tool()
def get_current_time(timezone: str = "UTC") -> str:
    """Get the current time in a given IANA timezone (e.g. 'Asia/Tokyo', 'Asia/Kolkata')."""
    from zoneinfo import ZoneInfo
    from datetime import datetime
    try:
        tz = ZoneInfo(timezone)
        now = datetime.now(tz)
        return f"Current time in {timezone}: {now.strftime('%Y-%m-%d %H:%M:%S %Z')}"
    except Exception as e:
        return f"Unknown timezone '{timezone}': {e}"


@mcp.tool()
def get_weather(city: str) -> str:
    """Get current weather for a city using Open-Meteo (no API key required)."""
    try:
        geo_resp = requests.get(
            "https://geocoding-api.open-meteo.com/v1/search",
            params={"name": city, "count": 1, "language": "en", "format": "json"},
            timeout=10,
        )
        geo_resp.raise_for_status()
        geo_data = geo_resp.json()
        if not geo_data.get("results"):
            return f"City '{city}' not found."
        loc = geo_data["results"][0]
        lat, lon = loc["latitude"], loc["longitude"]
        resolved_name = loc.get("name", city)

        wx_resp = requests.get(
            "https://api.open-meteo.com/v1/forecast",
            params={
                "latitude": lat,
                "longitude": lon,
                "current": "temperature_2m,relative_humidity_2m,apparent_temperature,wind_speed_10m,weather_code",
                "wind_speed_unit": "kmh",
                "timezone": "auto",
            },
            timeout=10,
        )
        wx_resp.raise_for_status()
        cur = wx_resp.json()["current"]
        desc = WMO_CODES.get(cur["weather_code"], f"Weather code {cur['weather_code']}")
        return (
            f"Weather in {resolved_name}: {desc}, "
            f"{cur['temperature_2m']}\u00b0C (feels like {cur['apparent_temperature']}\u00b0C), "
            f"Humidity: {cur['relative_humidity_2m']}%, Wind: {cur['wind_speed_10m']} km/h"
        )
    except Exception as e:
        return f"Could not get weather for {city}: {e}"


print("FastMCP server defined with tools: get_current_time, get_weather")

from fastmcp import Client


async def chat_with_tools(user_message: str) -> str:
    """Send a message to OpenAI, dispatching tool calls through the FastMCP server."""
    async with Client(mcp) as client:
        tools = await client.list_tools()
        functions = [
            {
                "type": "function",
                "function": {
                    "name": t.name,
                    "description": t.description or "",
                    "parameters": t.input_schema,
                },
            }
            for t in tools
        ]

        messages = [{"role": "user", "content": user_message}]

        response = openai_client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=functions,
            tool_choice="auto",
            reasoning_effort="none",   # answer straight away, no hidden "thinking" tokens
        )
        message = response.choices[0].message

        if message.tool_calls:
            messages.append({
                "role": "assistant",
                "content": message.content,
                "tool_calls": [tc.model_dump() for tc in message.tool_calls],
            })

            for tool_call in message.tool_calls:
                tool_name = tool_call.function.name
                tool_args = json.loads(tool_call.function.arguments)

                result = await client.call_tool(tool_name, tool_args)
                text = result.content[0].text if result.content else ""

                print(f"  [Tool: {tool_name}({tool_args})] => {text}")
                messages.append({
                    "role": "tool",
                    "content": text,
                    "tool_call_id": tool_call.id,
                })

            final_response = openai_client.chat.completions.create(
                model=MODEL,
                messages=messages,
                reasoning_effort="none",
            )
            return final_response.choices[0].message.content

        return message.content


print("chat_with_tools defined.")

async def run_demo():
    print("FastMCP Demo Starting...")

    demos = [
        "What time is it right now in Bangalore?",
        "What's the weather like in Bangalore?",
        "Can you tell me the time and weather in Tokyo?",
    ]

    for i, query in enumerate(demos, 1):
        print(f"\n--- Demo {i} ---")
        print(f"User: {query}")
        try:
            response = await chat_with_tools(query)
            print(f"Assistant: {response}")
        except Exception as e:
            print(f"Error: {e}")

    print("\nFastMCP Demo completed!")


await run_demo()
README.md
README.md (complete file)
# Memory and MCP: code for the two lectures

By Shivank Agarwal. Every file uses OpenAI `gpt-6-luna`.

## Setup

```bash
pip install -r requirements.txt
cp .env.example .env        # then paste your OpenAI key into .env
```

The notebooks install what they need in their first cell and ask for the key if it isn't already set,
so they also run as-is in Google Colab.

## Files

| File | Lecture | What it shows |
|---|---|---|
| `short_term_memory.ipynb` | Memory | Conversation buffer, then three ways to keep it small: trimming, deleting, summarising |
| `memory_demo_1.py` | Memory | Semantic, episodic and procedural memory feeding one answer (a LangGraph pipeline) |
| `memory_demo_2.py` | Memory | The agent updates a customer's preferences mid-conversation and saves them to `episodic_memory.json` |
| `fastmcp_demo_v1.ipynb` | MCP | An MCP server built with FastMCP (time + weather tools) used by `gpt-6-luna` through function calling |

Run the scripts with `python memory_demo_1.py` and `python memory_demo_2.py`.
`memory_demo_2.py` creates `episodic_memory.json` next to itself: open it after the run to see the saved memory.