Skip to content
AgenticAIWiki
  1. Learn
  2. Part 10
  3. 57. Managing memory over time
  4. 57.5

Lesson 57.5 · 5 of 5 · 6 min read · Reviewed 24 Nov 2026

Memory layers in practice: extract, update and decay

By the end, you can

  • Describe a memory layer that extracts, updates and decays memories automatically.
  • Choose add, update, delete or no-op for a new candidate memory.

Lessons 57.1 to 57.4 each cover one job: choose, retrieve, consolidate, forget. A memory layer runs those jobs automatically on every exchange, so the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. code only calls remember(conversation) and recall(query). Mem0 is one open-source example of this pattern; Letta, Zep and several framework memory modules work along similar lines, and you can build a small one yourself.

The pipeline

new exchange
     |
     v
1 extract   model pulls out candidate facts:  "started at Globex", "still a designer"
     |
     v
2 compare   find similar stored memories (vector search, same owner)
     |
     v
3 decide    for each candidate: ADD, UPDATE, DELETE or NOOP
     |
     v
4 write     apply the operation, keep provenance
     ...
5 decay     on a schedule: lower scores of old, unused memories; expire past a floor

1. Extract

A model call with a narrow prompt: list durable facts about the user or task in this exchange, one per line; skip small talk. This is the 47.1 test, automated. Output is short candidate facts, not summaries.

2 and 3. Compare and decide

For each candidate, fetch the few most similar stored memories for the same owner and decide:

Candidate Closest stored memory Operation
“Vegetarian” none similar ADD
“Started at Globex” “Works at Acme” UPDATE to Globex, keep the old value as history
“No longer vegetarian” “Vegetarian” DELETE (or mark retired)
“Likes short answers” “Prefers short answers” NOOP, already known

The decision is often another model call that sees the candidate and its neighbours and returns one operation. Your code then checks it: same owner, allowed type, no instruction-like text (57.4).

5. Decay

Memories are scored, and the score falls with age unless the memory is used. A common shape is exponential decay with a half-life, plus a boost each time a memory is retrieved and helps:

score = importance * 0.5 ** (days_since_last_use / half_life)

With a half-life of 30 days, an unused memory of importance 0.8 falls to 0.4 after a month and 0.2 after two. Below a floor, say 0.1, it stops being retrieved and can be archived or deleted. The Generative Agents paper used a similar recency decay when ranking memories.

When to use a memory layer

  • Good fit: assistants that talk to the same people for months, where preferences and facts change.
  • Overkill: single-session tools, or agents whose facts all live in a system of record.

Common mistakes

  • Add-only memory. Without UPDATE and DELETE, contradictions pile up (57.3).
  • Decay on facts that must not fade. Allergies, consent choices and legal holds need a “never decay” flag.
  • Trusting the decider blindly. Log every operation so a wrong DELETE can be undone.
  • Extracting from untrusted text. A pasted web page is not the user telling you a fact about themselves.

Key points

  • A memory layer sits between your agent and its stores: after each exchange it extracts candidate facts, then reconciles them with what is already stored.
  • Reconciling means one of four operations per candidate: add, update, delete or do nothing.
  • Decay lowers the weight of memories that are old and unused, so retrieval favours what is fresh and useful.
  • Mem0 is one open-source example of this pattern; you can also build it yourself with a model call and a store.
Hands-on labRuns in the Playground

Build a tiny extract, update, decay layer

Build a small memory layer in the style of Mem0 and similar tools: extract facts from messages, choose ADD, UPDATE, DELETE or NOOP, and decay unused memories.

You will have: A MemoryLayer class with remember and decay methods, and a log of every operation it chose.

Steps

  1. Write extract(message) that turns sentences like 'I work at X', 'I am vegetarian' and 'I am no longer vegetarian' into (key, value) candidates.
  2. Write decide(candidate, stored) that returns ADD, UPDATE, DELETE or NOOP.
  3. Apply and log each operation, keeping old values as history.
  4. Write decay(today) using score = importance * 0.5 ** (days_unused / 30), and drop memories below 0.1 unless they are flagged never_decay.
  5. Run the sample conversation and print the log and the final memories.

Done when

  • The log shows ADD, UPDATE, NOOP and DELETE at least once each.
  • The employer ends as Globex with Acme in history.
  • The allergy is flagged never_decay, so decay can never drop it; the unused hobby is dropped.

Open in the Playground No API key needed.

Starter code (Python)
import re

class MemoryLayer:
    def __init__(self):
        self.mem = {}   # key -> {"value", "importance", "last_used", "history", "never_decay"}
        self.log = []

    def extract(self, message):
        cands = []
        # TODO: patterns such as "i work at (\w+)" -> ("employer", X),
        # "i am no longer vegetarian" -> ("diet", None), "i am vegetarian" -> ("diet", "vegetarian")
        return cands

    def decide(self, key, value):
        # TODO: return "ADD", "UPDATE", "DELETE" or "NOOP"
        return "NOOP"

    def remember(self, message, day):
        for key, value in self.extract(message):
            op = self.decide(key, value)
            self.log.append((day, op, key, value))
            # TODO: apply the operation

    def decay(self, today, half_life=30, floor=0.1):
        # TODO: drop memories whose decayed score is below floor, unless never_decay
        pass

layer = MemoryLayer()
for day, msg in [(1, "I work at Acme. I am vegetarian."), (5, "I like rowing."), (40, "I work at Acme."),
                 (60, "I work at Globex now."), (70, "I am no longer vegetarian."), (71, "I am allergic to nuts.")]:
    layer.remember(msg, day)
layer.decay(today=100)
for entry in layer.log:
    print(entry)
print(layer.mem)
Show a solution
import re

PATTERNS = [
    (r"i work at (\w+)", "employer", 0.6, False),
    (r"i am no longer vegetarian", "diet", 0.6, False),
    (r"i am vegetarian", "diet", 0.6, False),
    (r"i like (\w+)", "hobby", 0.3, False),
    (r"i am allergic to (\w+)", "allergy", 1.0, True),
]

class MemoryLayer:
    def __init__(self):
        self.mem = {}
        self.log = []

    def extract(self, message):
        cands = []
        for sentence in message.lower().split("."):
            for pat, key, imp, keep in PATTERNS:
                m = re.search(pat, sentence)
                if m:
                    value = None if "no longer" in pat else (m.group(1) if m.groups() else "vegetarian")
                    cands.append((key, value, imp, keep))
                    break
        return cands

    def decide(self, key, value):
        old = self.mem.get(key)
        if value is None:
            return "DELETE" if old else "NOOP"
        if not old:
            return "ADD"
        return "NOOP" if old["value"] == value else "UPDATE"

    def remember(self, message, day):
        for key, value, imp, keep in self.extract(message):
            op = self.decide(key, value)
            self.log.append((day, op, key, value))
            if op == "ADD":
                self.mem[key] = {"value": value, "importance": imp, "last_used": day, "history": [], "never_decay": keep}
            elif op == "UPDATE":
                m = self.mem[key]
                m["history"].append(m["value"])
                m["value"], m["last_used"] = value, day
            elif op == "DELETE":
                del self.mem[key]
            elif op == "NOOP" and key in self.mem:
                self.mem[key]["last_used"] = day

    def decay(self, today, half_life=30, floor=0.1):
        for key in list(self.mem):
            m = self.mem[key]
            score = m["importance"] * 0.5 ** ((today - m["last_used"]) / half_life)
            if score < floor and not m["never_decay"]:
                self.log.append((today, "DECAYED", key, round(score, 3)))
                del self.mem[key]

layer = MemoryLayer()
for day, msg in [(1, "I work at Acme. I am vegetarian."), (5, "I like rowing."), (40, "I work at Acme."),
                 (60, "I work at Globex now."), (70, "I am no longer vegetarian."), (71, "I am allergic to nuts.")]:
    layer.remember(msg, day)
layer.decay(today=100)
for entry in layer.log:
    print(entry)
print(layer.mem)
Quick checkStored: 'Works at Acme as a designer'. New message: 'I've just started at Globex, still designing.' What should the memory layer do?
How sure are you?
Pick an answer and how sure you are

Finished the chapter? Take the chapter check.