About this notebook
Companion to Module 6: Memory and context engineering. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
Notebook 6a kept one run’s context small. This notebook makes things outlast a run. A model remembers nothing between calls. Whatever an agent appears to remember was stored by your code and put back into a request. There are two kinds of storage, at two timescales:
- sessions: one conversation, stored as a file, so it continues after a restart;
- pause and resume: a tool call waiting for approval, stored in the session;
- long-term memory, write side: durable facts extracted from a finished conversation;
- de-duplication and persistence of those facts;
- long-term memory, read side: relevant facts put into a new conversation.
Which model answers here?
With no
MODELset, the offline policy model answers. It recalls facts from earlier in the same request (“my name is …”, “I live in …”). It extracts memories with a few fixed patterns for seats, diet, name, city and team, and it fills a flight booking from the memories it is shown. A real model extracts facts phrased in any way. It also makes mistakes these patterns cannot, such as storing a one-off request as a permanent preference. The storage, de-duplication and injection are ordinary code and behave the same with any model.
from agentlab.nbsetup import setup
nb = setup("06b_sessions_memory", packs=["memory"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. Sessions: a conversation that survives a restart
agent.run starts from an empty ExecutionContext unless you pass one in. A session
is that context’s events and state, saved under an id. run_in_session loads the
session, runs one more turn, and saves it again. JsonSessionManager writes one JSON
file per session, here under the notebook’s work folder. The folder is cleared first, so
every run of the notebook starts the same way.
import shutil
from agentlab import Agent
from agentlab.memory import JsonSessionManager, run_in_session
session_dir = nb.workdir / "sessions"
shutil.rmtree(session_dir, ignore_errors=True)
manager = JsonSessionManager(session_dir)
chat = Agent(model=llm, instructions="You are a helpful travel assistant.", max_steps=4)
result = await run_in_session(chat, manager, "ada-chat", user_id="ada",
user_input="Hi, my name is Ada and I live in Lisbon.")
print("turn 1:", result.output)
result = await run_in_session(chat, manager, "ada-chat", user_input="Where do I live?")
print("turn 2:", result.output)turn 1: Thank you, noted: your name is Ada; you live in Lisbon. turn 2: You live in Lisbon.
The second call is a separate agent.run, and the model saw the first turn only because
run_in_session loaded it from the file. A different session id is a different
conversation, with nothing in it:
result = await run_in_session(chat, manager, "ada-other", user_id="ada",
user_input="Where do I live?")
print("new session:", result.output)new session: I don't know yet: nothing earlier in this conversation tells me. (A model only sees the messages included in the request.)
Now simulate a restart. A new manager and a new agent object share nothing with the old ones except the folder:
import json
manager = JsonSessionManager(session_dir) # as if the process had restarted
chat = Agent(model=llm, instructions="You are a helpful travel assistant.", max_steps=4)
result = await run_in_session(chat, manager, "ada-chat", user_input="And what is my name?")
print("after the restart:", result.output)
print()
print("files:", sorted(p.name for p in session_dir.iterdir()))
stored = json.loads((session_dir / "ada-chat.json").read_text(encoding="utf-8"))
print("ada-chat.json keys:", list(stored), "| events:", len(stored["events"]))
print(json.dumps(stored["events"][0], indent=1)[:400])after the restart: Your name is Ada.
files: ['ada-chat.json', 'ada-other.json']
ada-chat.json keys: ['session_id', 'user_id', 'events', 'state', 'created_at', 'updated_at'] | events: 6
{
"id": "evt_0000",
"execution_id": "exec_0000",
"timestamp": 1767225600.002,
"author": "user",
"content": [
{
"type": "message",
"role": "user",
"content": "Hi, my name is Ada and I live in Lisbon."
}
]
}
A JSON file per session is easy to read and good enough for one process. A service with
many users would use a database with the same interface (create, get, save),
which is what the book’s chapter on memory moves to. Two things a session store has to
get right that a plain file does not give you: two requests for the same session at
once (lock it, or detect the conflict), and deleting a user’s sessions when they ask.
2. Pause on a risky call, resume after a restart
Notebook 5b paused a run for human approval and resumed it from the result object in
memory. In a real service the person may answer an hour later, from another device,
after the process has restarted. The pending call has to live in the session.
run_in_session saves it there.
from agentlab import tool
bookings = nb.workdir / "bookings.jsonl"
bookings.unlink(missing_ok=True)
@tool(requires_confirmation=True,
confirmation_message="Book {arguments[origin]} to {arguments[destination]} "
"on {arguments[date]}?")
def book_flight(origin: str, destination: str, date: str, seat: str = "no preference",
meal: str = "standard") -> str:
"""Book a flight for the user. This charges the company card.
Args:
origin: City the flight leaves from.
destination: City the flight goes to.
date: Day of the flight, for example "12 March".
seat: "aisle", "window" or "no preference".
meal: "standard", "vegetarian" or "vegan".
"""
number = len(bookings.read_text().splitlines()) + 1 if bookings.exists() else 1
reference = f"OV-{number:04d}"
with bookings.open("a", encoding="utf-8") as f:
f.write(json.dumps({"reference": reference, "origin": origin,
"destination": destination, "date": date, "seat": seat,
"meal": meal}) + "\n")
return (f"Booked {origin} to {destination} on {date}, seat {seat}, meal {meal} "
f"({reference}).")
travel = Agent(model=llm, tools=[book_flight], max_steps=4,
instructions="You are a travel assistant. Book flights with book_flight.")
trip = "Book me a flight from Lisbon to Oslo on 12 March."
result = await run_in_session(travel, manager, "ada-trip", user_id="ada", user_input=trip)
print("status:", result.status)
print("waiting for approval:", result.pending_tool_calls[0].confirmation_message)
print("saved in the session:",
json.loads((session_dir / "ada-trip.json").read_text())["state"]["pending"][0]
["tool_call"]["arguments"])status: pending_confirmation
waiting for approval: Book Lisbon to Oslo on 12 March?
saved in the session: {'origin': 'Lisbon', 'destination': 'Oslo', 'date': '12 March', 'seat': 'no preference', 'meal': 'standard'}
The process can now stop. Later, a new process loads the session, finds the pending call, and passes the person’s decision in. No new user message is needed:
from agentlab import ToolConfirmation
manager = JsonSessionManager(session_dir) # a new process
travel = Agent(model=llm, tools=[book_flight], max_steps=4,
instructions="You are a travel assistant. Book flights with book_flight.")
session = await manager.get("ada-trip")
waiting = session.state["pending"][0]
result = await run_in_session(travel, manager, "ada-trip", confirmations=[
ToolConfirmation(tool_call_id=waiting["tool_call"]["tool_call_id"], approved=True)])
print("status:", result.status, "|", result.output)status: complete | Done. Booked Lisbon to Oslo on 12 March, seat no preference, meal standard (OV-0001).
Note the seat: “no preference”. The agent knows nothing about Ada’s seat preference, and nothing in this conversation mentioned it. That is the next problem.
3. Long-term memory: what is worth keeping
A session holds one conversation. Some things a user says are worth knowing in every later conversation, such as a seat preference, a diet or the team they work on. Others matter only for the task at hand, such as the date of one trip. Long-term memory keeps the first kind, in three steps (following the book’s task memory, with facts about the user instead of solved tasks):
write finished conversation --> the model extracts items --> skip near-duplicates --> store
(structured output) (vector similarity) (per user)
read new user message -------> similar items for this user -------> added to the instructions
(vector search) (a before_llm callback)Here is a conversation in which Ada mentions two lasting facts and one detail that matters only for this trip:
for text in ["I prefer aisle seats, and I'm vegetarian.",
"This time I need to land before noon, I have a meeting."]:
result = await run_in_session(chat, manager, "ada-prefs", user_id="ada",
user_input=text)
print(f"user: {text}\nassistant: {result.output}\n")user: I prefer aisle seats, and I'm vegetarian. assistant: Thank you, noted: you prefer aisle seats; you are vegetarian. user: This time I need to land before noon, I have a meeting. assistant: Understood, I will keep that in mind for this trip.
Extraction asks the model for structured output: a list of MemoryItem(kind, content),
validated by Pydantic, so the result can be stored without parsing prose. The prompt asks
for facts that will still matter in an unrelated conversation, written as one
self-contained sentence each:
from agentlab.memory import LongTermMemory, MemoryItem
from agentlab.memory.long_term import EXTRACTION_PROMPT
print(EXTRACTION_PROMPT, "\n")
memory_file = nb.workdir / "memories.json"
memory_file.unlink(missing_ok=True)
memory = LongTermMemory(llm, path=memory_file)
session = await manager.get("ada-prefs")
items = await memory.extract(session.events)
for item in items:
print(f"{item.kind:10s} {item.content}")[memory-extraction] Read the conversation below and extract facts about the user that will still be useful in future, unrelated conversations: preferences, constraints (such as diet or accessibility needs) and personal facts (such as their team or home city). Ignore details that only matter for the current task. Write each item as one short sentence in the third person. If there is nothing durable, return an empty list. preference Prefers aisle seats on flights. constraint Is vegetarian: book vegetarian meals.
Two items, and the landing time is not among them. With the offline model that is because no pattern matches it. A real model leaves it out because the prompt says to ignore details that only matter for the current task. Real models do not always manage that, which is why memory should be inspectable and editable by the user.
4. Storing without duplicates
remember extracts and stores in one go. Before adding an item it searches this user’s
memories, and if one is more similar than a threshold (cosine 0.8 on the hashed vectors
from Notebook 5a), it skips the new one. A user who repeats a preference in every
conversation would otherwise end up with dozens of copies.
added = await memory.remember(session.events, user_id="ada", source="ada-prefs")
print("stored:", added)
await run_in_session(chat, manager, "ada-later", user_id="ada",
user_input="As always, I prefer an aisle seat. My name is Ada.")
later = await manager.get("ada-later")
added = await memory.remember(later.events, user_id="ada", source="ada-later")
print("stored:", added)
for new, existing, similarity in memory.skipped:
print(f"skipped {new!r}: {similarity:.2f} similar to {existing!r}")stored: ['mem_0000', 'mem_0001'] stored: ['mem_0002'] skipped 'Prefers aisle seats on flights.': 1.00 similar to 'Prefers aisle seats on flights.'
The repeated preference was skipped and the new fact (the name) was stored. But similarity measures how alike two sentences look, not whether they say the same thing. Two probes:
for probe in ["Likes sitting by the aisle.", "Prefers window seats on flights."]:
hit = memory.store.search(probe, k=1, where={"user_id": "ada"})[0]
print(f"{probe!r:36s} closest: {hit.text!r} at {hit.score:.2f}")'Likes sitting by the aisle.' closest: 'Prefers aisle seats on flights.' at 0.26 'Prefers window seats on flights.' closest: 'Prefers aisle seats on flights.' at 0.78
Both would be stored as new. The first repeats an existing item in other words. The second contradicts one, and memory would then hold both “aisle” and “window”. Lowering the threshold to 0.75 would skip the window sentence, so the change of mind would be lost instead. No threshold fixes this, because the question is about meaning, not wording. The book asks the model to decide whether each new item should be added or skipped. That costs a model call per item, and a model can also see that the new item should replace the old one.
The store is a JSON file of texts and metadata. The vectors are recomputed when it is loaded, because the embedder is deterministic:
memory = LongTermMemory(llm, path=memory_file) # reload from disk
print(json.dumps(json.loads(memory_file.read_text(encoding="utf-8")), indent=1)[:600])[
{
"id": "mem_0000",
"metadata": {
"kind": "preference",
"source": "ada-prefs",
"user_id": "ada"
},
"text": "Prefers aisle seats on flights."
},
{
"id": "mem_0001",
"metadata": {
"kind": "constraint",
"source": "ada-prefs",
"user_id": "ada"
},
"text": "Is vegetarian: book vegetarian meals."
},
{
"id": "mem_0002",
"metadata": {
"kind": "fact",
"source": "ada-later",
"user_id": "ada"
},
"text": "Is called Ada."
}
]
5. Using memories in a new conversation
memory.injector(user_id) returns a before_llm callback. On every model call it
searches this user’s memories with the latest user message and appends the best matches
to the instructions. The memories are labelled as possibly out of date, so that what
the user says now takes priority:
remembering = Agent(model=llm, tools=[book_flight], max_steps=4,
instructions=travel.instructions,
before_llm_callbacks=[memory.injector("ada", k=3)])
first_call = len(llm.calls)
result = await run_in_session(remembering, manager, "ada-trip-2", user_id="ada",
user_input="Book me a flight from Denver to Oslo on 3 April.")
system_prompt = "\n".join(llm.calls[first_call][0].instructions)
print(system_prompt[system_prompt.index("What you remember"):])
print()
print("status:", result.status)
print("the call waiting for approval:", result.pending_tool_calls[0].tool_call.arguments)What you remember about this user from earlier conversations (it may be out of date; the user's current request wins):
<memories>
- Prefers aisle seats on flights.
- Is vegetarian: book vegetarian meals.
</memories>
status: pending_confirmation
the call waiting for approval: {'origin': 'Denver', 'destination': 'Oslo', 'date': '3 April', 'seat': 'aisle', 'meal': 'vegetarian'}
The booking now asks for an aisle seat and a vegetarian meal, in a conversation where neither was mentioned. Approve it and look at both bookings:
waiting = result.pending_tool_calls[0]
result = await run_in_session(remembering, manager, "ada-trip-2", confirmations=[
ToolConfirmation(tool_call_id=waiting.tool_call.tool_call_id, approved=True)])
print(result.output)
print()
for line in bookings.read_text(encoding="utf-8").splitlines():
b = json.loads(line)
print(f"{b['reference']} {b['origin']:>6} -> {b['destination']:5s} {b['date']:9s}"
f" seat: {b['seat']:14s} meal: {b['meal']}")Done. Booked Denver to Oslo on 3 April, seat aisle, meal vegetarian (OV-0002). OV-0001 Lisbon -> Oslo 12 March seat: no preference meal: standard OV-0002 Denver -> Oslo 3 April seat: aisle meal: vegetarian
Memories belong to one user. The search filters by user_id before it ranks anything, so
another user’s request never sees Ada’s preferences:
print("for ada:", [h.text for h in memory.search("book a flight seat meal", user_id="ada")])
print("for sam:", [h.text for h in memory.search("book a flight seat meal", user_id="sam")])for ada: ['Prefers aisle seats on flights.', 'Is vegetarian: book vegetarian meals.'] for sam: []
Three cautions before you give an agent long-term memory:
- Retrieval decides what is remembered. A memory that is never retrieved might as well not exist. One that is retrieved for the wrong request can mislead: a vegetarian meal is right for Ada’s flights, but should it shape a restaurant booking for a client dinner Ada is hosting?
- Memory is personal data. Users should be able to see what is stored about them, correct it and delete it, and stored text should never include secrets they pasted in.
- Memory is an attack surface. Anything written into memory is replayed into future prompts. A document or web page that convinces the agent to “remember” an instruction gets a permanent foothold (Module 12 covers prompt injection).
Try this
- Ask the remembering agent “A window seat this time: book me a flight from Denver to Oslo on 3 April.” Which wins, the memory or the request? Find the line in
agentlab/llm/fake_packs/nb06_memory.pythat decides it, and the sentence in the injector that asks a real model for the same.- Add an
updatepath toLongTermMemory.add: if a new preference has the same kind and mentions the same subject (seats), replace the old item instead of skipping it.- Run one more conversation, “I prefer window seats now.”, through
remember. What does the store hold afterwards, and which seat does the next booking get?- With a live model, run the extraction on the “ada-prefs” session. Does it keep the landing time? Rephrase the prompt until it does not.
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 14 (fake: 14) | ≈ 2,519 | ≈ 306 | ≈ USD 0.0037 (reference price) |