Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Long-term memory for AI agents

After this lesson: I can choose which memories an agent reads back for a task.

75 min lesson4 commandsAI coding agent lab: use opencode to explain and fix code, and check its work

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Long-term memory lets an agent remember you

Long-term memory is what an AI agent keeps between conversations: facts about a person, things that happened and lessons learned. Each new task reads back only the few memories that matter.

It matters because a help desk assistant that forgets a peanut allergy is dangerous, and one that reads back every note is slow and costly.

By the end of this lesson

Note

I can choose which memories an agent reads back for a task.

Key words

WordWhat it meansExample
Memoryone saved note about a person or event
Relevancehow well a memory fits the task
Recencyhow new a memory is
Importancehow much a memory matters, from 0 to 10
Half-lifethe days for recency to halve7
Keya label so a newer fact replaces an older one

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Facts, events and lessons are kept apart

Long-term memory holds three kinds of note. Semantic memory is facts: Sam has a peanut allergy. Episodic memory is events: Sam ate at the canteen on Friday. Procedural memory is how to do things: send Sam an email, not a call.

Module 67 kept a store under a size limit. This lesson is about the read: which few notes go into the window for this task.

A score mixes relevance, recency and importance

A 2023 research paper on simulated characters scored memories by three parts, and many agents do the same. Relevance is how well a note fits the task. Recency halves every seven days here. Importance is set when the note is saved.

Here relevance is the share of the task's tags a note shares. A real agent compares vectors, as in module 108; tags stand in for them so every number is the same for everyone.

Worked example: two scores for a lunch order

MemoryRelevanceRecencyImportance / 10Score
Sam has a peanut allergy. (day 5)1 of 2 tags = 0.50.5 to the power 25/7 = 0.0840.91.48
Sam ate at the canteen on Friday. (day 29)0.50.5 to the power 1/7 = 0.9060.11.51

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Write the memory store, part 1

Command
docker exec -w /home/node/project agent sh -c "printf '%s\n' 'const TODAY = 30;' 'const HALF_LIFE = 7;' 'const MEMORIES = [' '  {\"text\":\"Sam is vegetarian.\",\"tags\":[\"food\",\"diet\"],\"day\":2,\"importance\":6,\"key\":\"diet\"},' '  {\"text\":\"Sam asked when the library opens.\",\"tags\":[\"library\"],\"day\":27,\"importance\":2,\"key\":\"\"},' '  {\"text\":\"Sam has a peanut allergy.\",\"tags\":[\"food\",\"allergy\",\"health\"],\"day\":5,\"importance\":9,\"key\":\"allergy\"},' '  {\"text\":\"Sam prefers email to phone calls.\",\"tags\":[\"contact\"],\"day\":20,\"importance\":4,\"key\":\"contact\"},' '  {\"text\":\"Sam ate at the canteen on Friday.\",\"tags\":[\"food\",\"canteen\"],\"day\":29,\"importance\":1,\"key\":\"\"},' '  {\"text\":\"Sam has a project due on 12 December.\",\"tags\":[\"project\",\"deadline\"],\"day\":25,\"importance\":7,\"key\":\"\"},' '];' 'const QUERY = [\"food\",\"lunch\"];' 'function score(m) {' '  let shared = 0;' > memory4.js"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the memory store, part 2

Command
docker exec -w /home/node/project agent sh -c "printf '%s\n' '  for (const q of QUERY) if (m.tags.includes(q)) shared = shared + 1;' '  const relevance = shared / QUERY.length;' '  const recency = Math.pow(0.5, (TODAY - m.day) / HALF_LIFE);' '  return relevance + recency + m.importance / 10;' '}' 'function show(store) {' '  console.log(\"Top 3 for\" + \" \" + QUERY.join(\", \"));' '  const ranked = store.slice().sort((a, b) => score(b) - score(a) || b.day - a.day);' '  for (const m of ranked.slice(0, 3)) console.log(\"  \" + score(m).toFixed(2) + \"  \" + m.text);' '}' 'show(MEMORIES);' 'const FRESH = {\"text\":\"Sam now eats fish.\",\"tags\":[\"food\",\"diet\"],\"day\":30,\"importance\":6,\"key\":\"diet\"};' 'const at = MEMORIES.findIndex((m) => m.key === FRESH.key && m.key.length > 0);' 'if (at >= 0) console.log(\"Replaced\" + \": \" + MEMORIES[at].text);' 'else console.log(\"Added a new memory\");' >> memory4.js"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the memory store, part 3

Command
docker exec -w /home/node/project agent sh -c "printf '%s\n' 'const store = MEMORIES.filter((m, i) => i < at || i > at).concat([FRESH]);' 'console.log(\"Memories\" + \": \" + MEMORIES.length + \" -> \" + store.length);' 'show(store);' >> memory4.js"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Score the memories and update one

Command
docker exec -w /home/node/project agent node memory4.js

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the store printed

RankingFirstSecondThird
Before1.51 Sam ate at the canteen on Friday.1.48 Sam has a peanut allergy.1.31 Sam has a project due on 12 December.
After the update2.10 Sam now eats fish.1.51 Sam ate at the canteen on Friday.1.48 Sam has a peanut allergy.

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Read the ranking with care

Before the update, the project note came third for a lunch order. It shares no tag with lunch, but it is recent and important. Weighting relevance more, or dropping notes with no shared tag, would fix it.

Then Sam now eats fish arrived with the key diet. It replaced Sam is vegetarian rather than sitting beside it, so the agent never reads two facts that disagree. The store still holds six memories.

A common mistake

Warning

Many people think an agent should remember everything forever. Old facts go stale and contradict new ones, and memories about a person are personal data. Replace facts by key, let old events fade, and let people see and delete what is kept.

Match each memory to its kind

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: recall and update memories

Build the memory store from the lab in Python. A memory is a dictionary with text, tags, day, importance and key.

relevance(tags, query) is the share of the query tags found in tags, or 0.0 for an empty query. recency(day, today, half_life) is 0.5 to the power of the age divided by the half-life. score(memory, query, today, half_life) adds relevance, recency and importance divided by 10, rounded to 3 places.

recall(memories, query, today, half_life, k) returns the texts of the k best scores, highest first; on a tie the newer day first, then the one earlier in the list. remember(memories, new) returns a new list: when new has a key that is not "", any memory with the same key is left out; then new is added at the end. Do not change the list you were given.

Code: python
def relevance(tags, query):
    return None


def recency(day, today, half_life):
    return None


def score(memory, query, today, half_life):
    return None


def recall(memories, query, today, half_life, k):
    return None


def remember(memories, new):
    return None

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.