Skip to content

How to build a memory layer for AI agents

Build a memory layer for your AI agent in Python, improve it three times with recall measured on LoCoMo, and see why better search still isn’t memory.

Abbas Askari, AI & Backend Engineer at Alexein AI

Abbas Askari · 7 min read

You can build a working memory for your AI app in an afternoon. Making it one your users can trust takes much longer, and most teams find that out after they ship.

Every model starts each conversation knowing nothing about the person in front of it. Your users repeat their job, their stack, their kids’ names and the decision they made last Tuesday. The fix looks obvious: save what they say, and hand the useful parts back to the model next time.

This guide builds that step by step, with code. Then it walks through what breaks once real people use it. By the end you’ll know how to build one, and you’ll be able to decide whether you should.

What a memory layer is

A memory layer is a loop with two halves: one that turns conversations into something kept, and one that brings the right pieces back before the model answers.

Keeping takes three steps:

  1. Capture. Save what the user and the model said, with who said it and when.
  2. Distil. Turn talk into facts worth keeping: “prefers TypeScript”, “moved to Berlin in March”.
  3. Store. Keep those facts where you can search them by meaning, not only by their exact words.

Bringing them back takes two:

  1. Recall. When a new message arrives, find the facts that bear on it.
  2. Hand over. Put them in the prompt, so the model answers as if it remembered.

Every memory product, from a weekend project to a funded company, does some version of these five steps. What differs is how well each one holds up. The versions below start with the simplest thing that works and improve it four times, measuring each step.

Version 0: memory in 40 lines

The simplest memory that works saves every turn and, before each reply, brings back the few that are closest in meaning to the new message. Here it is in Python, with a local database file and a small open model from the sentence-transformers library that scores how alike two pieces of text are:

memory.py
import sqlite3
import numpy as np
import anthropic
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")
client = anthropic.Anthropic()
db = sqlite3.connect("memory.db")
db.execute("""create table if not exists memories (
    id integer primary key,
    user_id text not null,
    text text not null,
    meaning blob not null,
    created_at text default current_timestamp)""")

def remember(user_id: str, text: str) -> None:
    meaning = model.encode(text, normalize_embeddings=True).astype(np.float32)
    db.execute("insert into memories (user_id, text, meaning) values (?, ?, ?)",
               (user_id, text, meaning.tobytes()))
    db.commit()

def recall(user_id: str, query: str, k: int = 5) -> list[str]:
    q = model.encode(query, normalize_embeddings=True)
    rows = db.execute("select text, meaning from memories where user_id = ?",
                      (user_id,)).fetchall()
    scored = [(float(np.frombuffer(m, dtype=np.float32) @ q), t) for t, m in rows]
    return [t for _, t in sorted(scored, reverse=True)[:k]]

def chat(user_id: str, message: str) -> str:
    known = recall(user_id, message)
    system = "What you know about this user:\n" + "\n".join(f"- {m}" for m in known)
    reply = client.messages.create(
        model="claude-sonnet-5-5", max_tokens=1024, system=system,
        messages=[{"role": "user", "content": message}],
    ).content[0].text
    remember(user_id, f"User said: {message}")
    remember(user_id, f"Assistant said: {reply}")
    return reply

Try it: tell it you’re vegetarian, start a new session, and ask for a dinner idea. It works, and the first time it does feels like magic.

Three things about this version are worth noticing.

  • Every search reads every row. Each recall scores everything the user has ever said. That is fine to a few thousand rows; past that you need an index built for search by meaning, such as pgvector.
  • user_id is the only wall between people. Forget it in one query and one user’s memories turn up in another’s prompt.
  • It keeps talk, not facts. “User said: actually I eat fish now” and “User said: I’m vegetarian” sit side by side, and nothing says which is true.

How good is it?

“It remembered I’m vegetarian” is an anecdote. To know whether a change helps, you need questions whose answers you already know. We used LoCoMo, a public benchmark of ten long conversations between two people, each running to hundreds of turns over months, with 1,540 questions about them. For every question, LoCoMo marks the turns that hold the answer.

We measured recall: of those turns, the share the search brings back. If the right turn never reaches the prompt, no model can answer from it. To keep the comparison fair, every version could return as much text as Alexein returned for the same question, about 4,300 characters at the median, and Alexein was measured on the same questions.

Version 0 finds 62.9% of the turns that hold an answer. Alexein finds 91.3%. (At the five results the code above returns, Version 0 finds 29.8%.) So what does it take to close the gap?

Version 1: exact words too

Search by meaning is fuzzy about names. Ask about “Door Dash” and it brings back turns about jobs in general. A search by exact words, the kind every search box has had for decades, catches names, places and rare words. Run both and merge the two lists. Their scores can’t be compared, so merge them by place: a turn both searches rank fairly high beats one only a single search likes.

recall_v1.py
import re
from rank_bm25 import BM25Okapi

def words(text: str) -> list[str]:
    return re.findall(r"[a-z0-9]+", text.lower())

def merge(*rankings: list[str], k: int = 60) -> list[str]:
    # Each list votes by place, not by score: first place is worth 1/61, tenth 1/70.
    score: dict[str, float] = {}
    for ranking in rankings:
        for place, text in enumerate(ranking):
            score[text] = score.get(text, 0) + 1 / (k + place + 1)
    return sorted(score, key=score.get, reverse=True)

def recall(user_id: str, query: str, k: int = 5) -> list[str]:
    rows = db.execute("select text, meaning from memories where user_id = ?",
                      (user_id,)).fetchall()
    texts = [t for t, _ in rows]
    q = model.encode(query, normalize_embeddings=True)
    closeness = [float(np.frombuffer(m, dtype=np.float32) @ q) for _, m in rows]
    by_meaning = [texts[i] for i in np.argsort(closeness)[::-1]]
    shared = BM25Okapi([words(t) for t in texts]).get_scores(words(query))
    by_words = [texts[i] for i in np.argsort(shared)[::-1]]
    return merge(by_meaning, by_words)[:k]

Recall goes from 62.9% to 67.1%. On its own, the word search does worse than the search by meaning (55.6%); each catches what the other misses.

Version 2: a second look

Both searches score each turn without reading it against the question. A small model that reads the two together does much better, but it’s too slow to run over everything. So run it over the top 50 only, and let it set the final order.

recall_v2.py
from sentence_transformers import CrossEncoder

second_look = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

def recall(user_id: str, query: str, k: int = 5) -> list[str]:
    candidates = recall_v1(user_id, query, k=50)  # Version 1's recall, renamed
    scores = second_look.predict([(query, c) for c in candidates])
    order = np.argsort(scores)[::-1]
    return [candidates[i] for i in order[:k]]

Recall: 69.1%. Better, and the gains are getting smaller.

Version 3: a better model

The model that reads meaning in Version 0 is small and fast. A larger one is a one-line change, though every saved memory has to be run through it again:

memory.py
model = SentenceTransformer("all-mpnet-base-v2")

Recall: 74.0%, the biggest single gain of the three. We tried the obvious next steps too. Writing each turn’s date into its text, and bringing back the turns either side of each hit, both made recall worse: they spend the room in the prompt on words that hold no answer. No mix of the pieces above that we tried got past 75%.

Recall on LoCoMo1,540 questions
What it addsRecall
Version 0Every turn saved, searched by meaning62.9%
Version 1A search by exact words beside it67.1%
Version 2A second look at the top 5069.1%
Version 3A larger model for meaning74.0%
Alexein91.3%

Recall: of the turns LoCoMo marks as holding each answer, the share the search brought back. Each version could return as much text as Alexein returned for the same question. Every version keeps the ones before it. Measured December 2026.

This is search, not memory

Look at what the four versions do: save every turn, and look up the ones that resemble the question. That is retrieval over a chat log, the same as search over a folder of documents, with the conversation as the documents. Each version is better search. None of them is more of a memory.

LoCoMo-Plus tests the difference. It places 401 short exchanges in the same conversations. Weeks later, someone says something that depends on one of them without repeating it. “I volunteered for that project and now I’m totally overwhelmed” should bring back “since I learned to say no, I’ve felt a lot less stressed.” The two share almost no words, which is how people really talk.

Bringing back what a later message depends onLoCoMo-Plus, 401 questions
Found
Version 034.2%
Version 118.0%
Version 226.2%
Version 331.7%
Alexein67.1%

Found: the share of questions for which the search brought back the earlier exchange the message depends on, with the same room as Alexein. Measured December 2026.

Every version finds it about a third of the time at best, and each improvement does worse than Version 0. Exact words can’t help when the words differ, and a larger model still ranks by resemblance, which this benchmark is built to defeat. Alexein finds it two times in three.

Better search doesn’t close that gap, because the gap isn’t in the search. A memory has to decide what was worth keeping, connect what someone says now to what they meant weeks ago, and keep what’s true while letting go of what isn’t. That is the Distil step from the start of this guide, and none of the versions above does it.

Where it gets hard

Version 3 is where most tutorials stop, and where most of the work starts. Each problem below can be solved. Together they are a product, not a feature.

What breaks with real users
ProblemWhat your users seeWhat fixing it takes
Memory only knows your appThe assistant hasn’t seen the email or the doc that matters mostConnections to mail, chat, docs and code: sign-in to each, tokens that expire, syncing what changed, rate limits, and one shape for every provider’s data
Memory is stuck in your appThey tell Claude, ChatGPT and your app the same things three timesAn API and an MCP server that other apps can read and save to, with keys and sign-in for each
Search misses the obvious“What did Priya say about the launch?” brings back a launch from two years agoSearch by exact words and by meaning together, with names and dates understood
Time“Last Tuesday” and “my current manager” come back wrongEvery fact dated, and questions about time answered against those dates
One person’s memory in another’s promptA privacy incidentThe memory a request reaches set by its key or token, every time, never by a field in the body or anything a model wrote
What’s kept can’t be trustedAn email that says “ignore your instructions” ends up in the promptEverything recalled treated as information, never as instructions, wherever it is handed over
Forgetting“Forget this” doesn’t, because a copy lives on in a backup, an index or a cacheKnowing every place a fact is copied to, and erasing it from all of them
Knowing if it worksAnswers slowly get worse, and nobody noticesA set of real questions with known answers, run on every change
CostFine at 100 users, a line on the bill at 100,000Batching, smaller models where they do the job, and caching

The second to last row is the one teams skip. Without questions whose answers you know, every change to a prompt, a model or the way results are ordered is a guess, as the versions above show. Public benchmarks such as LoCoMo and LongMemEval are a good start (our guide to agent memory explains what each one tests), and your own users’ questions are better.

Why you probably shouldn’t, and when you should

Build it yourself when memory is narrow and stays inside your app. Use a memory service when it has to reach across a person’s apps, or when memory isn’t the product you sell.

Build your own when:

  • The memory is small and local. A coding agent that remembers a repository’s conventions needs a markdown file it reads and edits, not a system.
  • Memory is your product. If how you remember is what customers pay for, it should be yours.

Don’t build it when:

  • The context that matters lives elsewhere. If the answer is in someone’s inbox, Slack or documents, you are signing up to build and keep up connections to each of them, which is a company of its own.
  • Your users use more than one AI app. A memory locked inside your app is one more place they repeat themselves, and most people already use several assistants.
  • Your team is small. Every week spent on forgetting, testing and syncing is a week not spent on what only you can build.

The deeper reason is ownership. Memory is about a person, not an app. When each app builds its own, the person ends up with a dozen partial copies of themselves, none complete and none theirs. Memory earns its keep when it belongs to the person and every app they connect can read it.

Build the afternoon version anyway

Run the 40 lines above. One evening with them will teach you more about what memory needs than any post, this one included, and you’ll find out quickly whether your problem stops at search or keeps going.

If it keeps going, that’s what Alexein is for. It keeps one memory for each person, filled from the apps they connect: mail, chat, code and documents. Claude, ChatGPT, Cursor or your own agent read and save to it through one API or our MCP server.

And you can try it without spending anything. Your first month is free, and generous: 30,000 events and 3,000 searches, with no card. That is room to put your app on Alexein and set it beside your own Version 3 before you decide anything. The quickstart takes you from a key to a first search, or you can sign up and start now.

Questions

How do I build a memory layer for an AI app?

Save each conversation with who said it and when, and before the model answers, search for what bears on the new message and put it in the prompt. A first version fits in about 40 lines of Python. A search by exact words beside the search by meaning, a second look at the top results and a larger model each improve it, from 62.9% to 74% recall on LoCoMo in our tests.

Is search over chat history the same as memory?

No. Saving every turn and looking up the ones that resemble a new message is search, the same as search over documents. A memory also decides what is worth keeping, replaces what stops being true, and connects what someone says now to what they said weeks ago in other words. On LoCoMo-Plus, which tests that last part, search over chat history found what a later message depended on about a third of the time at best.

Should I build my own AI memory or use a service?

Build your own when memory is small, stays inside one app, or is the product you sell. Use a service when memory has to draw on a person’s other apps, be read by other AI apps, or when your team would rather spend its time on its own product.

What is the hardest part of building AI memory?

Not the first version. The hard parts come after: facts that change, keeping each person’s memory apart, deleting every copy when asked, reading from the apps where context really lives, and knowing whether answers are getting better or worse.