Build and Evaluate a Memory Layer

A hands-on project: reference design, working code, a test set that finds real weaknesses and a plan for improving them.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

A memory layer is a small service with four operations: observe, recall, correct and forget. Build it on an ordinary database first, with scope, source and status on every row. Then evaluate it with scripted cases that check what must be found, what must never appear and whether memory actually improves task results. Add embeddings only when the tests show that wording mismatches cause misses.

What you will learn: a reference design, a persistent implementation, how to connect it to an agent loop, metrics for recall, precision and utility, long-term recall tests and a project to extend.
Prerequisites: Python, basic SQL and Agent Memory Types and Persistence. The policies come from Memory Write, Recall and Forgetting Policies.

Beginner Design first

What we are building

Our example agent is a personal work assistant. It should remember stated facts and preferences across sessions, use the current version when something changes, keep users apart and delete on request. It does not need to remember everything, and it must not guess.

Agent runtimebuilds context, calls the model and tools
Memory interfaceobserve, recall, correct, forget
Policywrite gate, recall limits, lifetimes
Storerows with scope, source, status
Searchkeywords now, embeddings later
Evaluation and logstest cases, recall traces, deletion checks
The agent talks to an interface, not to tables.
OperationInputGuarantee
observeuser, subject, text, source, timeOne active value per subject
recalluser, query, limitOnly that user's active items
correctuser, subject, new textOld value no longer recalled
forgetuser, optional subjectAll versions removed

In the code below, correction is simply a new observation on the same subject, which supersedes the old one.

Intermediate Implementation and integration

The persistent layer

SQLite is part of Python's standard library, writes to a single file and supports transactions, so it is enough to learn the design. Pass a file name instead of :memory: and the data survives restarts.

"""A persistent memory layer: observe, recall, correct and forget."""
import re
import sqlite3

SCHEMA = """CREATE TABLE IF NOT EXISTS memory (
  id INTEGER PRIMARY KEY, user TEXT NOT NULL, subject TEXT NOT NULL,
  text TEXT NOT NULL, source TEXT NOT NULL, day INTEGER NOT NULL,
  active INTEGER NOT NULL DEFAULT 1)"""

def words(text):
    return set(re.findall(r"[a-z0-9]+", text.lower())) - {
        "the", "a", "is", "my", "i", "to", "in", "what", "do", "does", "me"}

class MemoryLayer:
    def __init__(self, path=":memory:"):
        self.db = sqlite3.connect(path)
        self.db.execute(SCHEMA)

    def observe(self, user, subject, text, source, day):
        """A newer statement on the same subject supersedes the old one."""
        with self.db:
            self.db.execute("UPDATE memory SET active=0 WHERE user=? AND subject=?",
                            (user, subject))
            cur = self.db.execute(
                "INSERT INTO memory(user,subject,text,source,day) VALUES (?,?,?,?,?)",
                (user, subject, text, source, day))
        return cur.lastrowid

    def recall(self, user, query, k=3):
        rows = self.db.execute(
            "SELECT id, subject, text, source, day FROM memory "
            "WHERE user=? AND active=1", (user,)).fetchall()
        q = words(query)
        scored = [(len(q & words(r[1] + " " + r[2])), r[4], r) for r in rows]
        scored.sort(key=lambda s: (-s[0], -s[1]))
        return [dict(zip(("id", "subject", "text", "source", "day"), r))
                for hits, _, r in scored[:k] if hits]

    def forget(self, user, subject=None):
        """Real deletion, including superseded versions."""
        sql, args = "DELETE FROM memory WHERE user=?", [user]
        if subject:
            sql, args = sql + " AND subject=?", args + [subject]
        with self.db:
            return self.db.execute(sql, args).rowcount

def as_context(items):
    lines = [f"- {m['text']} (source: {m['source']}, day {m['day']})" for m in items]
    return "Known about this user:\n" + ("\n".join(lines) or "- nothing relevant")

Points worth noticing:

  • Every query includes the user, so there is no path that reads across users.
  • Superseding and inserting happen in one transaction.
  • Values are passed as parameters, never pasted into SQL text.
  • Forget deletes old versions too, not only the active row.
  • Recall returns nothing when nothing matches, instead of padding the list.
  • The rendered context shows source and day, so the model can weigh each item.

Connecting it to an agent

Memory enters the agent loop at two points: recall before the model call, observation after. A minimal turn looks like this in words:

  1. Authenticate the user and open the task.
  2. Recall a few items relevant to the new message.
  3. Build the request: rules, recalled memory labeled as possibly outdated, recent turns, message.
  4. Let the model answer or call tools. Offer a remember tool that proposes a subject and sentence.
  5. Run the write gate on each proposal, with the source set by your code.
  6. Tell the user what was saved and allow undo.
  7. Log recalled identifiers and writes.
The user argument is not for the model

The model may suggest a subject and text. The runtime supplies the user identifier from the session. If the model could choose it, a crafted message could read or overwrite someone else's memory.

Expert Evaluation and improvement

Evaluating recall, precision and utility

MetricQuestionTarget direction
RecallOf the needed memories, how many were returned?Higher
PrecisionOf those returned, how many were useful?Higher
Staleness violationsDid a superseded value appear?Zero
Leakage violationsDid another user's data appear?Zero
Write accuracyWere the right things stored, and only those?Higher
UtilityDoes the agent do better with memory than without?Positive difference
Cost and latencyWhat does memory add per turn?Within budget

Quality metrics can be traded against each other. Safety counts cannot: any leakage is a failure, whatever the average says.

"""Score a memory layer on recall, precision, staleness and leakage."""
from layer import MemoryLayer, as_context

def build():
    m = MemoryLayer()
    m.observe("ana", "diet", "Ana eats vegetarian food", "user", 1)
    m.observe("ana", "office", "Ana works in the Pune office", "user", 2)
    m.observe("ana", "report", "Ana wants the sales report on Monday", "user", 3)
    m.observe("ana", "office", "Ana works in the Hyderabad office", "user", 40)
    m.observe("ben", "diet", "Ben eats seafood", "user", 5)
    return m

CASES = [   # user, query, must include, must never include
    ("ana", "book a food order", ["vegetarian"], ["seafood"]),
    ("ana", "which office does Ana work in", ["Hyderabad"], ["Pune"]),
    ("ana", "when is the sales report wanted", ["Monday"], []),
    ("ana", "what meal should lunch be", ["vegetarian"], ["seafood"]),
    ("ben", "which office does Ben work in", [], ["Hyderabad", "Pune"]),
]

def evaluate(layer, k):
    found = needed = useful = returned = bad = 0
    misses = []
    for user, query, must, never in CASES:
        items = layer.recall(user, query, k)
        texts = [i["text"] for i in items]
        hits = [w for w in must if any(w in t for t in texts)]
        found, needed = found + len(hits), needed + len(must)
        useful += sum(any(w in t for w in must) for t in texts)
        returned += len(texts)
        bad += sum(any(w in t for t in texts) for w in never)
        if len(hits) < len(must):
            misses.append(query)
    return found / needed, useful / max(1, returned), bad, misses

layer = build()
for k in (1, 3):
    recall, precision, bad, misses = evaluate(layer, k)
    print(f"k={k} recall={recall:.2f} precision={precision:.2f} violations={bad}")
    print("   missed:", misses)
print(as_context(layer.recall("ana", "which office does Ana work in", 1)))
print("rows deleted:", layer.forget("ana"), "| after:", layer.recall("ana", "office"))

Output:

k=1 recall=0.75 precision=0.75 violations=0
   missed: ['what meal should lunch be']
k=3 recall=0.75 precision=0.50 violations=0
   missed: ['what meal should lunch be']
Known about this user:
- Ana works in the Hyderabad office (source: user, day 40)
rows deleted: 4 | after: []

The results teach three things. There are no staleness or leakage violations, because supersession and scoping are structural. One case is missed at both settings: "what meal should lunch be" shares no words with "eats vegetarian food". And raising the limit from one to three lowers precision without finding that item. More results cannot fix a matching problem.

Improving, one change at a time

Observed failureCandidate fixCheck for side effects
Different words, same meaningEmbedding search combined with keywordsIrrelevant but similar hits
Important items outrankedAdd importance and recency to the scoreOld but vital facts sink
Core preference never recalledAlways load a tiny profileContext growth
Too many weak resultsScore floorRecall drops
Subjects differ for one factFixed subject list or merging stepWrong merges

The subject field is the quiet weak point of this design. If one write calls it "office" and the next "work location", both stay active. Constrain subjects to a known set where you can, and test that paraphrased updates supersede correctly. Memory Integrity, Isolation and Sharing adds source authority, so that a weaker source cannot replace a stronger one, a rule this small example leaves out.

Measuring usefulness, not only retrieval

A memory can be retrieved correctly and still not help, or even hurt. Run each end-to-end task in three conditions: no memory, your memory, and perfect memory where you hand the agent exactly the right facts. The gap between none and perfect shows how much memory could ever matter for this task. The gap between yours and perfect shows what is left to improve. Repeat runs, because model output varies, and record success, corrections needed and tokens.

Testing long-term recall

Short tests miss the problems that appear after months. Generate a long history with filler, then ask about facts placed at various ages. Include updates, contradictions, events in time order and questions whose answer was never given, where the right response is to say so. The public LongMemEval benchmark covers abilities of this kind, including multi-session reasoning, knowledge updates and abstention, and LoCoMo uses very long conversations. Public benchmarks help compare designs, but your own scripted cases decide whether the system fits your product.

Test case typePassing behavior
Old single factFound despite many newer items
Updated factOnly the new value used
Two facts from different sessionsCombined correctly
Never mentionedAgent says it does not know
Deleted factAbsent everywhere
Hostile instruction stored in a documentNot saved or not obeyed

Project: finish your own persistent agent

  1. Save the two files and run the evaluation. Confirm you get the same scores.
  2. Switch to a file database and prove that memory survives a restart.
  3. Add expiry days per type and a test with a simulated clock.
  4. Add a write gate that refuses secrets and unverified sources.
  5. Add an embedding column using a model of your choice and combine it with word matching. Re-run the evaluation and compare.
  6. Add a show my memory command and a deletion test that searches the database file contents.
  7. Connect it to a model and measure the three conditions described above.

Done when: all safety counts are zero, the missed case is found without lowering precision below your target, and you can explain each recalled item from the logs.

About physical deletion

Deleting rows does not necessarily erase bytes from database files, write-ahead logs or backups. If your requirements demand it, study the storage engine's options, such as secure deletion and vacuuming in SQLite, and define how backups expire.

Growing the design

The same interface can carry a much larger system. As load and requirements grow, change what sits behind it in steps, keeping the evaluation as your safety net.

StageStore and searchAdded responsibility
PrototypeSQLite with word matchingScripted cases and deletion test
First usersServer database with full-text and vector columnsAuthentication, backups, monitoring
Many tenantsPartitioned storage or separate indexesIsolation tests, per-tenant retention and keys
Agent teamsPrivate and shared namespacesPublish permission, review, provenance
Heavy historyRaw events in cheap storage, extracted memories indexedConsolidation jobs and their tests

Background extraction as a second writer

Once conversations are long, a scheduled job can propose memories from transcripts. Treat it as another untrusted proposer: it sends candidates through the same write gate, records which messages each came from and is measured on write accuracy. Label a set of transcripts with the memories a careful person would save, then count what the job misses and what it invents. Invented entries are the more serious error, since users will be told things they never said.

Observability for memory

For each turn, record the query, the identifiers returned with their scores, the items actually placed in context and any writes proposed, accepted or refused with the reason. With those four records you can answer the two questions people ask most: why did it say that, and why did it not remember? Keep content out of general logs and join on identifiers when an investigation needs the text.

Illustrative example: reading a miss

A user says the assistant forgot their diet. The trace shows the item exists and is active, the recall query was about lunch, and no words matched. The write and scope logic are fine; retrieval is the weak point. The team adds the case to the test set, tries meaning search, and confirms that the miss disappears while precision and the safety counts hold.

Release rule

Agree in advance what blocks a release: any leakage or staleness violation, any failed deletion check, or recall falling below the previous version by more than a margin you chose. Write the rule into the pipeline so that it does not depend on someone remembering to look. When a change improves one case and harms another, record both and decide deliberately, since averages hide exactly the failures users notice.

Before production

  • Authentication supplies scope on every call.
  • Write gate and source authority are enforced.
  • Schema carries type, dates, status and policy version.
  • Recall has a limit, a floor and logging.
  • Deletion covers versions, indexes, summaries and backups.
  • Evaluation runs automatically on every change.
  • Users can see and control what is stored.
  • Latency, errors and store growth are monitored.

Frequently asked questions

Should I use a memory framework instead?

Frameworks can save time on extraction and search. Evaluate them with the same cases, and confirm you can scope, inspect, export and delete data.

How many test cases do I need?

Start with a few dozen that reflect real use and past failures. Add one whenever something goes wrong.

Where do embeddings fit?

As an additional search signal over the same rows. Keep the relational record as the source of truth and rebuild embeddings when the model changes.

Can the evaluation use a model judge?

Yes for answer quality, after comparing the judge with human ratings. Keep scoping and deletion checks as exact assertions.

References and further reading

Next steps