Advanced about 5 h
The picture
01
Working memory
the context window
02
Summarise
compress old turns
03
Write
extract durable facts
04
Store
vector + metadata
05
Recall
retrieve when relevant
Three kinds of memory
- Working memory: the current context window. Fast, limited, and gone after the run.
- Episodic memory: a record of what happened (past tasks, outcomes, mistakes), used to avoid repeating errors.
- Semantic memory: durable facts about the user, the domain or the world, such as "prefers metric units" or "the staging database is read-only".
Keeping working memory healthy
Replace old turns with a running summary while pinning the instructions and recent turns verbatim.
def compress(messages, keep_last=6, summary=""):
if len(messages) <= keep_last + 1:
return messages, summary
old, recent = messages[1:-keep_last], messages[-keep_last:]
text = "\n".join(f"{m['role']}: {m['content'] if isinstance(m['content'], str) else '[tool exchange]'}" for m in old)
summary = llm(f"Update this running summary with the new turns. Keep decisions, facts, open questions.\n\nSummary so far:\n{summary}\n\nNew turns:\n{text}", 400)
return [messages[0], {"role": "user", "content": f"[Summary of earlier conversation]\n{summary}"}, *recent], summary
A long-term memory store
Expose memory as tools so the model chooses what to save and when to look something up.
import time, numpy as np
from sentence_transformers import SentenceTransformer
emb = SentenceTransformer("BAAI/bge-small-en-v1.5")
class Memory:
def __init__(self):
self.items = [] # {text, vec, t, user, ttl}
def remember(self, text: str, user: str, ttl_days: float | None = 365) -> str:
v = emb.encode(text, normalize_embeddings=True)
for it in self.items: # dedupe near-identical facts
if it["user"] == user and float(it["vec"] @ v) > 0.95:
it.update(text=text, t=time.time())
return "updated existing memory"
self.items.append({"text": text, "vec": v, "t": time.time(), "user": user, "ttl": ttl_days})
return "saved"
def recall(self, query: str, user: str, k: int = 3) -> list[str]:
q, now = emb.encode(query, normalize_embeddings=True), time.time()
live = [i for i in self.items if i["user"] == user and (i["ttl"] is None or now - i["t"] < i["ttl"] * 86400)]
scored = sorted(live, key=lambda i: float(i["vec"] @ q), reverse=True)[:k]
return [i["text"] for i in scored if float(i["vec"] @ q) > 0.35]
Generative-agent style systems rank recalled memories by a mix of recency, importance and relevance. Start with relevance plus a time decay and add the rest if your evaluation shows it helps.
Reflection
Periodically ask the model to turn a batch of raw episodes into higher-level lessons ("deploys on Fridays have failed twice; check the freeze calendar") and store those as semantic memories. Reflexion applies the same idea to task failures: write a short verbal post-mortem and include it in the next attempt.
The risks
- Memory poisoning: an attacker plants an instruction in a web page the agent reads; the agent "remembers" it; it fires later. Store the source of every memory, treat low-trust sources as data, and never let a memory override system-level rules.
- Privacy and retention: facts about people are personal data. Scope memory per user, support deletion and expiry, and disclose what is stored.
- Stale facts: memories age. Prefer recency for volatile facts, and let new information overwrite.
- Bloat: unbounded memory slows recall and adds noise. Cap and consolidate.
Common mistakes
- Saving everything. Save only what is likely to matter later.
- Retrieving memory with a similarity threshold you never tuned.
- Sharing one memory store across users.
Exercises
- Run a 60-turn simulated conversation and compare running summary against retrieval memory on 10 recall questions.
- Write a test where a retrieved web page tries to plant a malicious memory, and show your defence blocks it.
You are done when you can…
- Implement a memory store with write, recall, dedupe and expiry
- Compare running-summary and retrieval-based memory on a long conversation
- Describe how memory can be poisoned and what you do about it