Migrating from mem0
Verb mapping, the identity model, and the differences that are not renames — the answer verdict, supersession, and where Brain is deliberately stricter.
mem0 and Brain both ingest conversation, extract memories from it, and serve retrieval — so the mapping is closer than most vendor migrations. The main differences are the verb surface, the identity model, and the shape of a read.
Verb mapping
| mem0 | Brain |
|---|---|
m.add(messages, user_id=...) | client.encode(EncodeBuilder(text).build()) under the key's scope |
m.search(query, user_id=...) | client.recall(RecallBuilder(query).build()) |
m.delete(memory_id=...) | client.forget(ForgetBuilder(memory_id).build()) |
m.get_all(user_id=...) | list memories (memory_list, wire) |
user_id= argument | the (namespace, space) scope carried by the key |
Both add and encode run LLM-backed extraction — you send text, the system
infers the structured memories. The biggest shift is on the read: mem0's
search returns a ranked list of hits; Brain's recall returns a
membership verdict (Single / Many / None) with the supporting
memories, and a None is an explicit "don't know" rather than a low-score hit.
Data shape
mem0 stores extracted facts with a vector embedding and metadata; retrieval is vector search (plus an optional graph store).
Brain stores a memory — the text you wrote, with a kind of Episodic,
Semantic or Consolidated — and, where a schema is active, derives a typed
graph from it: entities, statements and relations, each with
confidence and provenance back to the memory it came from.
A statement's kind is one of Fact, Preference or Event, and those three
are the whole set. Do not confuse them with the memory kinds above: they
describe different records.
Retrieval fuses three retrievers — semantic, lexical and entity-graph — with reciprocal-rank fusion. There is no separate graph store to stand up; the graph is part of the same single binary.
The cross-encoder reranker ships disabled
Brain has one, and [rerank] enabled = false is the shipped default: a
reranker only reorders already-retrieved candidates and cannot surface what
retrieval missed. Expect fused ranks, not reranked ones, unless you have
turned it on deliberately. See Policies.
Identity model
mem0 scopes memory by user_id (and optional agent_id / run_id) passed on
every call.
Brain's scope is a (namespace, space) pair carried by the API key — the
server derives it; clients never send a scope. Translation:
- A
user_idargument → a(namespace, space)scope. Give each tenant its own key, or hold one pooled key and stamp each request withact_as(namespace, space)— wherespaceis an opaque selector string you choose, not an id you construct; the server derives the storage id from it. See Identity from a JWT. - Per-org isolation → one
namespaceper org (the isolation boundary). - Per-app isolation → one
spaceper app within the namespace.
There is no client-side scope= argument on any Brain SDK — the constraint is
enforced, not advisory.
act_as is wire-tier only
The HTTP API takes its space from the credential and accepts no selector on
any route. The pooled-key pattern therefore needs the native wire client,
which is why the examples below use BrainClient rather than
BrainHttpClient.
Write
from mem0 import Memory
m = Memory()
m.add("I prefer dark mode", user_id="alice")import os
from brain_db_sdk import Auth, BrainClient, EncodeBuilder
# The key already carries alice's (namespace, space) scope.
with BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
) as client:
client.encode(EncodeBuilder("I prefer dark mode").build())Brain deduplicates byte-identical text per (space, session) automatically —
re-encoding the same fact returns the existing memory with
was_deduplicated: true rather than writing a second copy. You don't manage
client-side idempotency keys for the common case.
Read
results = m.search("user preferences", user_id="alice")
for r in results["results"]:
print(r["memory"], r["score"])from brain_db_sdk import RecallBuilder
answer = client.recall(RecallBuilder("user preferences").limit(10).build())
if answer.answer_kind == "None":
print("don't know") # explicit absence, not an empty ranked list
else:
for m in answer.memories:
print(m.text, m.similarity_score)The deeper difference: because Brain fuses a lexical and an entity-graph retriever alongside the vector one, a cue that depends on an exact name or an identifier can resolve even where embedding similarity alone is weak — the extractor pulled the name out and the graph retriever finds it.
The single most common porting bug is translating
for r in results: ... into for m in answer.memories: ... and dropping
the answer_kind. You now have an agent that cannot tell "I have nothing"
from "I have weak matches" — which is the capability you migrated for. Note
also the spelling differs by tier: the wire client answers "Single" /
"Many" / "None", the HTTP client the lowercase forms.
The chat loop, ported
from mem0 import Memory
m = Memory()
def turn(user_id: str, message: str) -> str:
hits = m.search(message, user_id=user_id)
context = "\n".join(r["memory"] for r in hits["results"])
reply = model(system=build_prompt(context), user=message)
m.add(message, user_id=user_id)
return replyfrom brain_db_sdk.http import BrainHttpClient
brain = BrainHttpClient(BRAIN_API_KEY, base_url=BASE_URL)
def turn(session_id: int, message: str) -> str:
# 1. Recall FIRST. Encode-then-recall with the same text returns the
# sentence you just wrote as the top hit.
answer = brain.recall(message, max_results=8)
# 2. The verdict is the answer, not the length of the list.
context = (
""
if answer.answer_kind == "none"
else "\n".join(f"- {m.text}" for m in answer.memories)
)
reply = model(system=build_prompt(context), user=message)
# 3. Not every turn is a memory.
if is_durable(message):
brain.encode(message, session=session_id)
return replyThree changes, all deliberate.
user_id is gone. brain was already scoped when it was constructed —
the key resolved to a (namespace, space) before the function ran.
The order is load-bearing. mem0's search-then-add happens to be right;
reversing it in Brain returns your own sentence as the top hit, which looks
exactly like retrieval working perfectly.
is_durable is new, and it is the whole game. mem0's add on every turn
is cheap because mem0 is extracting from the turn anyway. Porting that call
site unchanged fills the space with dialogue that has no clean subject, which
extraction cannot type and recall then has to rank around. Something has to
decide what is worth remembering — see
What to write.
The identity port, in detail
This is the largest structural change and the one most likely to be done wrong, because the obvious translation is the expensive one.
mem0 takes user_id on every call. Brain takes it from the credential. Three
shapes:
One key per tenantworks on any tierMint a key per organisation, store it against the account, resolve it when you resolve the session. Isolation is enforced by the server rather than by your code. The cost is key lifecycle — minting, storage, rotation, revocation.
One pooled key + act_aswire tier onlyOne connection, one credential, every request stamped with the identity it
runs as. This is the direct analogue of user_id= and the shape most
people want — and the HTTP API does not have it.
One spacesingle-tenant appsEverything together. Fine for an internal tool; not isolation.
mem0's user_id is a free-form string, so the instinct is a Brain key per
user. At any real signup rate that is credential lifecycle per account. Use
act_as with a pooled key, and treat space as an opaque selector
string you choose rather than an id you construct — the server derives the
storage id from it, which is exactly what stops a client forging one.
Identity from a JWT is the whole flow.
act_as needs the wire tier, and that decides your deployment
The HTTP edge takes its space from the credential and accepts no selector on
any route, so pooled-key multi-tenancy needs BrainClient over a socket —
a long-lived process, not a serverless function. If your app is on a
serverless runtime, either use per-tenant keys there or put the pooled-key
path behind a service of your own. FastAPI is a
natural home for it; Next.js explains why it cannot
be one.
Filters: thresholds become two different knobs
mem0 gives you a relevance threshold on search. Brain splits the idea into two signals that are not interchangeable.
confidencefloatoptionalHow strongly the evidence supports a claim — noisy-OR over the statement's evidence list. The right knob for "only act on claims we are sure of".
salience_floorfloatoptionalHow important a memory is. It filters and does not rank: above your floor, a more-salient memory does not outrank a less-salient one.
There is no similarity threshold, and that is deliberate
The instinct ported from mem0 is to filter hits by similarity_score. Do
not: the verdict already encodes that judgement, and re-thresholding on top
of it is how an application discards the one memory that answered the
question. If you are reaching for a threshold, the thing you actually want
is usually a smaller max_results.
Salience is also not a ranking term, however much it reads like one. Brain keeps it out of ranking because salience decays on a schedule the caller does not control, so folding it into relevance would make the same cue return a different order tomorrow for reasons unrelated to the cue.
Where Brain is stricter
- Typed schema — every memory has a type; the classifier assigns it. The
seeded
brain:schema is always active, and you can declare your own types. - Scope is the key — no client-side scope construction, ever.
- Recall is membership, not ranking — you get
Single/Many/None, not a page you threshold yourself.
Where Brain is more flexible
- Provenance and bi-temporality — every memory records what produced it and when it was valid; corrections supersede rather than overwrite; history is queryable.
- Typed graph, built in — entities, statements, and relations are extracted and traversable (the typed graph) without a second datastore.
- Single binary — one process (arena + WAL + redb + HNSW + tantivy + bundled embeddings). No external vector DB or graph DB to run.
Migrating data
Feed your mem0 history back through encode and let Brain re-extract. Do not
try to rebuild the entity graph by hand — the write pipeline derives it as you
encode, and a hand-built graph would be a second extraction of the same source.
Anything Brain extracts whose type is not declared in an active schema is silently dropped. Import before declaring and you get memories with no statements, and no error saying so. Upload it, and validate before you upload.
m.get_all(user_id=…) gives you text and timestamps. Sort ascending by
timestamp before you start: supersession is ordered, and loading a
correction before the claim it corrects builds the chain backwards and
leaves the stale claim current.
mem0 extracts short memories from conversation, which is a good start — but anything that reads as dialogue ("ok let's do Tuesday then") cannot be typed by extraction and will sit in the space as noise recall has to rank around. One LLM pass that restates each record in the third person is the highest-value hour of this migration.
occurred_at_unix_nanos on every write. This is the one that cannot be
fixed afterwards: without it a year of history lands at import time,
recency ranking becomes noise, and every time-bounded read is wrong in a way
that looks plausible.
The builders mint a fresh request_id on every build(), so re-building is
not retrying — it is a second, distinct write. Build once, reuse across
retries. Content dedup catches byte-identical text as a second line of
defence and reports it as was_deduplicated rather than as an error.
import os
from brain_db_sdk.http import BrainHttpClient
brain = BrainHttpClient(os.environ["BRAIN_API_KEY"], base_url=BASE_URL)
for record in sorted(mem0_export(user_id), key=lambda r: r["created_at"]):
claim = restate(record["memory"]) # standalone, third person
if claim is None: # not everything is a memory
continue
brain.encode(claim, occurred_at=record["created_at_unix_nanos"])Verify after derivation settles, not after the last write
encode returns when the memory is durable, not when the graph has derived
from it. A verification pass that runs straight after the final write sees
an empty graph and reports a failed import. Watch the
change feed, or use the derived wait mode on the
wire tier.
Verifying it worked
me = brain.whoami()
print(me.namespace, me.space_id) # 1. the right scope?
page = brain.memory_list(limit=50) # 2. did event time survive?
secs = {m.created_at_unix_nanos // 1_000_000_000 for m in page.items}
print(len(secs), "distinct write seconds")
caps = brain.capabilities() # 3. will statements exist at all?
print("llm tier:", caps.llm_extractor)
answer = brain.recall("where does Priya work") # 4. does a known fact return?
print(answer.answer_kind, [m.text for m in answer.memories])One distinct write second across fifty records from a year of history means
occurred_at was never passed. llm_extractor: False means the namespace has
no provider credential, so the import produces memories and no statements —
completing successfully and leaving you a graph with no claims in it.
What you gain
An answer, not a ranked list
none is a first-class result meaning nothing stored answers this cue. An
empty mem0 result set conflates that with "nothing scored high enough", and
those are different things to an agent deciding whether to answer or to ask.
One process, no managed dependency
mem0 self-hosted still wants a vector store, and usually a graph store beside it for the graph features. Brain is one Apache-2.0 Rust binary — arena, write-ahead log, redb, an HNSW index, a tantivy full-text index and bundled embeddings, in-process — running embedded, self-hosted or clustered from the same crates. Nothing to provision, nothing to keep in sync.
Three retrievers, fused and inspectable
Semantic, lexical and entity-graph, fused by reciprocal-rank fusion at
k = 60, plus a bounded recency term. A cue that depends on an exact name or
an identifier resolves even where embedding similarity alone is weak, because
the extractor pulled the name out and the graph retriever finds it.
answer = brain.recall(cue, include_trace=True)returns which retrievers ran, how their ranks fused, what the filter chain dropped and what the reranker moved — so a wrong answer is something you read rather than something you guess at. It is large (a three-hit recall over ~700 memories measured 121 KB), so use it for one request, never an endpoint.
Isolation you can audit
No scope argument exists anywhere in the REST contract, so there is
nothing to forge and nothing to forget on one code path. whoami reports what
the server resolved, which means it cannot agree with a mistake.
What you give up
The simplest possible APIaccept itm.add(text, user_id=…) is two arguments and no setup. Brain asks you to
resolve a credential, declare a schema and decide what is worth writing.
Each of those buys something, and all of them are work you did not have.
Ecosystemreal cost on day onemem0 has far more integrations, examples and answered questions than Brain does. Expect to read source rather than find a snippet.
A managed free tierrun it yourself/healthz, Prometheus metrics, and the Arc console in early access.
Stabilitypre-1.0Wire protocol, on-disk formats and schema model change in place with no compatibility shims. Pin an exact version and read the release notes.
The honest summary
mem0 is the easiest of these three to start with and the furthest from Brain
conceptually — the API is close, the model underneath is not. Move for the
verdict, for credential-enforced isolation, for one binary you control, or
for a graph with provenance and bi-temporal validity. Do not move because of
a feature table: if add and search are genuinely all you use, this
migration costs more than it returns.
Was this page helpful?
Switching to Brain
Moving from another memory layer — what ports mechanically, the four concepts that have no equivalent elsewhere, how Brain actually differs from mem0, Zep and supermemory, and a cutover plan that does not require trusting it on day one.
Migrating from Zep
Zep and Brain both build a bi-temporal knowledge graph, so this is the closest architectural port of the three — and the differences that remain are the ones worth understanding before you move.