{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# Lab\n",
    "\n",
    "**Agentic AI** · `L-Memory`\n",
    "\n",
    "*Three tutorials on scripted models, each closed by comprehension questions: the session as a message\n",
    "history, compaction as a history processor, and scored recall over a memory stream.*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Setup\n",
    "\n",
    "**The lab needs no language model.** Every tutorial uses a scripted model, a Python function in place of the\n",
    "LLM, so each cell gives the same output on every machine. Install the library once:\n",
    "\n",
    "```bash\n",
    "pip install \"pydantic-ai-slim==2.67.0\"\n",
    "```\n",
    "\n",
    "The setup cell defines the function `show_parts`, which prints a message history one part per line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ[\"PYDANTIC_AI_NO_BANNER\"] = \"1\"                 # no start-up banner\n",
    "from pathlib import Path\n",
    "from pydantic import TypeAdapter\n",
    "from pydantic_ai import Agent, ModelMessage\n",
    "from pydantic_ai.capabilities import ProcessHistory\n",
    "from pydantic_ai.messages import (ModelRequest, ModelResponse, TextPart, ToolCallPart,\n",
    "                                  ToolReturnPart, UserPromptPart)\n",
    "from pydantic_ai.models.function import AgentInfo, FunctionModel\n",
    "\n",
    "def show_parts(messages):\n",
    "    \"\"\"One line per part; a tool call is shown with its name and arguments.\"\"\"\n",
    "    for m in messages:\n",
    "        for p in m.parts:\n",
    "            detail = f\"{p.tool_name}({p.args})\" if isinstance(p, ToolCallPart) else getattr(p, \"content\", \"\")\n",
    "            print(f\"{type(m).__name__:<14} {type(p).__name__:<16} {str(detail)[:90]}\")\n",
    "\n",
    "print(\"setup ok\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Tutorial: Message History across Runs\n",
    "\n",
    "**Lecture concept:** the session log, one record per line, written by appending (*Session Log*).\n",
    "**Library features:** `message_history=`, `result.all_messages()`, `result.new_messages()`, a `TypeAdapter`\n",
    "for the message type.\n",
    "\n",
    "**An agent of Pydantic AI keeps no state between two runs: the session is the list of messages that the\n",
    "caller passes back in** ([Pydantic, 2026](https://pydantic.dev/docs/ai/core-concepts/message-history/)). `result.all_messages()` returns the history of a run\n",
    "including the history it was given; `result.new_messages()` returns only the messages the run added.\n",
    "Passed as `message_history=` to the next run, the list continues the conversation. Storing the session is\n",
    "therefore the caller's task. A `TypeAdapter`, the Pydantic object that validates and serialises a type that\n",
    "is not a model class, converts each message into one JSON line and back, so the session is written as the\n",
    "JSONL log of the lecture: one line per message, appended after each run.\n",
    "\n",
    "**The history is a path, not a tree.** The log of the lecture records a predecessor for each record and\n",
    "can hold several branches; `message_history` is the one path that the caller chooses to continue.\n",
    "\n",
    "The tutorial uses a **scripted model** in place of the LLM: `FunctionModel` calls a Python function once\n",
    "per model request with the history, and the function returns the reply. The replies state how many\n",
    "messages they received, so the effect of each step on the history can be read from the output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The scripted model: a tool call when the user asks for the weather, otherwise a reply that states\n",
    "# how many messages it received.\n",
    "def scripted(messages, info: AgentInfo) -> ModelResponse:\n",
    "    asks_weather = any(isinstance(p, UserPromptPart) and \"weather\" in str(p.content) for p in messages[-1].parts)\n",
    "    if asks_weather:\n",
    "        return ModelResponse(parts=[ToolCallPart(\"weather\", {\"city\": \"berlin\"})])\n",
    "    return ModelResponse(parts=[TextPart(f\"(reply to a history of {len(messages)} messages)\")])\n",
    "\n",
    "bot = Agent(FunctionModel(scripted), instructions=\"You are a helpful assistant.\")\n",
    "\n",
    "@bot.tool_plain\n",
    "def weather(city: str) -> str:\n",
    "    \"\"\"Return today's weather in a city.\"\"\"\n",
    "    return \"sunny, 21 °C\"\n",
    "\n",
    "# Without message_history, each run starts from an empty history.\n",
    "for prompt in [\"My name is Ada.\", \"What is my name?\"]:\n",
    "    print((await bot.run(prompt)).output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The session as a JSONL log: after each run, the new messages are appended, one JSON line each.\n",
    "RECORD = Path(\"session.jsonl\")\n",
    "MESSAGE = TypeAdapter(ModelMessage)               # validates and serialises one message\n",
    "\n",
    "def append_messages(path, messages):\n",
    "    with open(path, \"a\") as f:\n",
    "        for m in messages:\n",
    "            f.write(MESSAGE.dump_json(m).decode() + \"\\n\")\n",
    "\n",
    "def load_session(path):\n",
    "    with open(path) as f:\n",
    "        return [MESSAGE.validate_json(line) for line in f]\n",
    "\n",
    "RECORD.unlink(missing_ok=True)\n",
    "history = []\n",
    "for prompt in [\"My name is Ada.\", \"What is the weather in Berlin?\", \"Thanks.\", \"Which city did I ask about?\"]:\n",
    "    r = await bot.run(prompt, message_history=history)\n",
    "    append_messages(RECORD, r.new_messages())      # append only what this run added\n",
    "    history = r.all_messages()                     # the path the next run continues\n",
    "\n",
    "print(len(history), \"messages in memory,\", len(RECORD.read_text().splitlines()), \"lines in the log\")\n",
    "print(\"log reloads to the same history:\", load_session(RECORD) == history)\n",
    "show_parts(history)\n",
    "print(RECORD.read_text().splitlines()[3][:200])    # one line of the log: the tool call"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. Why does the scripted model answer the second prompt of the first loop from a history of one message?\n",
    "2. How many messages does the session hold after four runs, and why is the number not eight?\n",
    "3. Why does the loop append `r.new_messages()` to the log and not `r.all_messages()`?\n",
    "4. A new agent that receives `load_session(RECORD)` as `message_history` never saw the earlier runs. Where\n",
    "   does it take the name and the weather from?\n",
    "5. Which property of the lecture's session log does the log of this tutorial lack, and what in the code\n",
    "   would have to change to record it?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Tutorial: History Processors as Compaction\n",
    "\n",
    "**Lecture concept:** compaction as the manage operation $P$, which replaces the records before a cut point\n",
    "and keeps the records after it (*Compaction*, *Forms of Compaction*). **Library features:** the\n",
    "`ProcessHistory` capability.\n",
    "\n",
    "**`ProcessHistory(fn)` applies a function to the message history before every model request of a run, and\n",
    "the list it returns replaces the history** ([Pydantic, 2026](https://pydantic.dev/docs/ai/core-concepts/message-history/)). The function maps a list of messages\n",
    "to a list of messages; it runs before the first request and again after every tool call, and later requests\n",
    "of the run start from its output. In the terms of the lecture, the function is $P$, its input the working\n",
    "memory $M_{t-1}$ with the new record, and its output $M_t$. A **capability** is the unit in which Pydantic AI\n",
    "adds behaviour to an agent, passed as `Agent(..., capabilities=[…])`.\n",
    "\n",
    "**A cut between a tool call and its result is repaired before the request, and the repair changes what the\n",
    "model sees.** Model APIs reject a tool result without its call and a call without its result. Before each\n",
    "request the library therefore drops a result whose call was cut away, and answers a call whose result was cut\n",
    "away with the text *\"The tool call was interrupted before a result was produced.\"* (Pydantic, 2026; observed\n",
    "with 2.67.0). A sliding window that cuts at the start of a **turn**, a user prompt that answers no tool call,\n",
    "never separates a pair.\n",
    "\n",
    "The tutorial compares two sliding windows on the session of the previous tutorial, then a summarising\n",
    "processor whose summariser is scripted: it returns a fixed summary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# A model that records the history it receives, to show the output of each processor.\n",
    "received = []\n",
    "def recorder(messages, info: AgentInfo) -> ModelResponse:\n",
    "    received.append(list(messages))\n",
    "    return ModelResponse(parts=[TextPart(\"ok\")])\n",
    "\n",
    "def starts_a_turn(m):\n",
    "    \"\"\"A request with a user prompt and no tool result: the first message of a turn.\"\"\"\n",
    "    return (isinstance(m, ModelRequest) and any(isinstance(p, UserPromptPart) for p in m.parts)\n",
    "            and not any(isinstance(p, ToolReturnPart) for p in m.parts))\n",
    "\n",
    "def last_messages(messages, n=7):                  # sliding window over messages\n",
    "    return messages[-n:]\n",
    "\n",
    "def last_turns(messages, n=4):                     # sliding window over turns; the new prompt is one\n",
    "    starts = [i for i, m in enumerate(messages) if starts_a_turn(m)]\n",
    "    return messages[starts[-n]:] if len(starts) > n else messages\n",
    "\n",
    "for proc in (last_messages, last_turns):\n",
    "    probe = Agent(FunctionModel(recorder), capabilities=[ProcessHistory(proc)])\n",
    "    await probe.run(\"And the temperature?\", message_history=load_session(RECORD))\n",
    "    print(f\"--- {proc.__name__}: the model receives {len(received[-1])} messages\")\n",
    "    show_parts(received[-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10",
   "metadata": {
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The summarise form: a second agent writes one text that replaces every turn before the last one.\n",
    "# The summariser is scripted as well: it returns a fixed summary that keeps the weather and drops the name.\n",
    "summarizer = Agent(FunctionModel(lambda messages, info: ModelResponse(\n",
    "    parts=[TextPart(\"The user asked for the weather in Berlin; it was sunny, 21 °C.\")])))\n",
    "\n",
    "async def summarise_old(messages, keep=1):\n",
    "    starts = [i for i, m in enumerate(messages) if starts_a_turn(m)]\n",
    "    if len(starts) <= keep:\n",
    "        return messages\n",
    "    cut = starts[-keep]                            # the cut point: the start of the kept turn\n",
    "    s = await summarizer.run(\"Summarise the conversation so far.\", message_history=messages[:cut])\n",
    "    summary = ModelRequest(parts=[UserPromptPart(f\"Summary of the earlier conversation: {s.output}\")])\n",
    "    return [summary, *messages[cut:]]\n",
    "\n",
    "probe = Agent(FunctionModel(recorder), capabilities=[ProcessHistory(summarise_old)])\n",
    "await probe.run(\"What is my name, and what was the weather?\", message_history=load_session(RECORD))\n",
    "show_parts(received[-1])                           # what the model would receive"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. `last_messages` keeps seven messages, yet the model receives six. Which message is missing, why, and\n",
    "   what does the model no longer know?\n",
    "2. `last_turns` keeps four turns, the new prompt counted as one. Which messages does the model receive, and\n",
    "   why can this window never separate a tool call from its result?\n",
    "3. In the run with `summarise_old`, which records are verbatim from the log and which one is new text? Which\n",
    "   row of the table in *Forms of Compaction* describes this processor? Which fact of the session can the model\n",
    "   no longer find?\n",
    "4. The processor runs before every request of a run. How often would `summarise_old` call the summarizer in\n",
    "   a run with two tool calls, and what does that cost?\n",
    "5. After a run with `ProcessHistory`, `r.all_messages()` returns the processed history. Why must the session\n",
    "   log of the previous tutorial not be rewritten from it?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Tutorial: Scored Recall\n",
    "\n",
    "**Lecture concept:** the read $R_L$ of episodic memory, scored by recency, importance and relevance\n",
    "(*Episodic Memory › Scored Recall*). **Library features:** none — the tutorial is plain Python.\n",
    "\n",
    "**Scored recall ranks the records of a memory stream by a weighted sum of three terms, so that a record\n",
    "can outrank a more similar one by being more recent or more important**\n",
    "([Park et al., 2023](https://arxiv.org/html/2304.03442), §4.1). **Recency** is $0.995^{h}$, with $h$\n",
    "the hours of simulated time since the record was last retrieved; **importance** is a rating from 1 to 10\n",
    "that a model assigns once, at the write; **relevance** is the cosine similarity of the embeddings of\n",
    "record and query. Each term is min–max normalised over the candidates (smallest value $\\mapsto 0$,\n",
    "largest $\\mapsto 1$), and Generative Agents sets every weight $\\alpha$ to 1.\n",
    "\n",
    "The tutorial uses six records with given importance ratings and three-dimensional vectors in place of an\n",
    "embedding model, so that no model is called and every number can be checked by hand. The three dimensions\n",
    "stand roughly for *about Anna*, *about where someone lives* and *about something else*. `recall` prints\n",
    "the three normalised terms and the score of every record, best first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "# A memory stream: text, hours since the record was last retrieved, importance (1–10, rated once at the\n",
    "# write) and a toy embedding. The three dimensions stand in for an embedding model: roughly\n",
    "# \"about Anna\", \"about where someone lives\", \"about something else\".\n",
    "STREAM = [\n",
    "    {\"text\": \"Anna lives in Berlin.\",                      \"h\": 2000, \"importance\": 6, \"vec\": [0.9, 0.8, 0.1]},\n",
    "    {\"text\": \"Anna moved to Hamburg last month.\",          \"h\": 20,   \"importance\": 8, \"vec\": [0.8, 0.6, 0.3]},\n",
    "    {\"text\": \"Anna had coffee at the station.\",            \"h\": 5,    \"importance\": 2, \"vec\": [0.8, 0.1, 0.6]},\n",
    "    {\"text\": \"Anna's flat in Hamburg has a balcony.\",      \"h\": 30,   \"importance\": 4, \"vec\": [0.7, 0.6, 0.4]},\n",
    "    {\"text\": \"Ben lives in Munich.\",                       \"h\": 500,  \"importance\": 5, \"vec\": [0.1, 0.9, 0.2]},\n",
    "    {\"text\": \"The weekly team meeting moved to Tuesday.\",  \"h\": 3,    \"importance\": 5, \"vec\": [0.0, 0.1, 1.0]},\n",
    "]\n",
    "WHERE_DOES_ANNA_LIVE = [1.0, 1.0, 0.0]\n",
    "\n",
    "def cosine(u, v):\n",
    "    return sum(a * b for a, b in zip(u, v)) / (math.hypot(*u) * math.hypot(*v))\n",
    "\n",
    "def minmax(xs):\n",
    "    lo, hi = min(xs), max(xs)\n",
    "    return [(x - lo) / (hi - lo) for x in xs]\n",
    "\n",
    "def recall(query, alpha=(1, 1, 1), k=3, show=True):\n",
    "    \"\"\"Rank the stream by alpha_rec·recency + alpha_imp·importance + alpha_rel·relevance (each min–max\n",
    "    normalised over the stream) and return the indices of the k best records.\"\"\"\n",
    "    rec = minmax([0.995 ** m[\"h\"] for m in STREAM])\n",
    "    imp = minmax([m[\"importance\"] for m in STREAM])\n",
    "    rel = minmax([cosine(query, m[\"vec\"]) for m in STREAM])\n",
    "    score = [alpha[0] * a + alpha[1] * b + alpha[2] * c for a, b, c in zip(rec, imp, rel)]\n",
    "    order = sorted(range(len(STREAM)), key=lambda i: -score[i])\n",
    "    if show:\n",
    "        print(f\"alpha = {alpha}\")\n",
    "        print(f\"{'rec':>6} {'imp':>6} {'rel':>6} {'score':>6}  record\")\n",
    "        for i in order:\n",
    "            print(f\"{rec[i]:6.3f} {imp[i]:6.3f} {rel[i]:6.3f} {score[i]:6.3f}  {STREAM[i]['text']}\")\n",
    "        print()\n",
    "    return order[:k]\n",
    "\n",
    "recall(WHERE_DOES_ANNA_LIVE, alpha=(0, 0, 1))      # relevance alone: plain similarity search\n",
    "recall(WHERE_DOES_ANNA_LIVE, alpha=(1, 1, 1))      # the weights of Generative Agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "# Recency counts the hours since the last *retrieval*: a record that is read is reset to h = 0.\n",
    "def retrieve(query, alpha=(1, 1, 1), k=1):\n",
    "    top = recall(query, alpha, k, show=False)\n",
    "    for i in top:\n",
    "        STREAM[i][\"h\"] = 0\n",
    "    return [STREAM[i][\"text\"] for i in top]\n",
    "\n",
    "def wait(hours):\n",
    "    for m in STREAM:\n",
    "        m[\"h\"] += hours\n",
    "\n",
    "WHERE_DOES_BEN_LIVE = [0.1, 0.8, 0.1]\n",
    "print(\"retrieved:\", retrieve(WHERE_DOES_BEN_LIVE, alpha=(0, 0, 1)), \"\\n\")\n",
    "wait(24)                                            # one simulated day later\n",
    "recall(WHERE_DOES_ANNA_LIVE, alpha=(1, 1, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. With relevance alone, which record is ranked first, and why is it the wrong answer to the question?\n",
    "2. With all weights 1, *\"Anna moved to Hamburg last month.\"* is ranked first. By how much does each of the\n",
    "   three normalised terms differ between this record and *\"Anna lives in Berlin.\"*?\n",
    "3. *\"Anna had coffee at the station.\"* has one of the highest recencies and still a low score. Which term\n",
    "   keeps it down, and when was that term computed?\n",
    "4. In the second cell, *\"Ben lives in Munich.\"* rises from last to second place for a question about Anna.\n",
    "   What changed in its record, and what does the change show about recency measured since the last\n",
    "   retrieval?\n",
    "5. Which weights reduce `recall` to plain similarity search, and which answer of question 1 would a personal\n",
    "   assistant then give?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## References\n",
    "\n",
    "**Peer-reviewed papers**\n",
    "\n",
    "- Park, Joon Sung, et al. \"Generative Agents: Interactive Simulacra of Human Behavior.\" Annual ACM Symposium on User Interface Software and Technology. Vol. 36. 2023. [arXiv:2304.03442](https://arxiv.org/html/2304.03442). — the memory stream and retrieval by recency, importance and relevance.\n",
    "\n",
    "**Blogs, documentation & other web sources**\n",
    "\n",
    "- Pydantic. \"Messages and Chat History.\" *Pydantic AI documentation*, 2026, retrieved 2026-11-10. <https://pydantic.dev/docs/ai/core-concepts/message-history/> — `message_history`,\n",
    "  `all_messages()` and `new_messages()`; storing messages with a `TypeAdapter`; the `ProcessHistory` capability; the repair of\n",
    "  split tool-call/tool-result pairs before each request."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  },
  "rise": {
   "scroll": true,
   "theme": "simple",
   "transition": "none"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}