Brain Docs

Reference

Switching to Brain

From

Migrating from mem0Migrating from ZepMigrating from supermemory
Brain/Docs
✦ ASKBrain on GitHubDashboard
Switching to BrainMigrating from Zep

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.

PURPOSE

Zep is the nearest neighbour Brain has. Both ingest episodes, extract typed facts onto a graph, and keep superseded claims rather than deleting them. This guide maps the verbs, is explicit about what is genuinely the same, and spends most of its length on the four places where a mechanical port compiles and behaves wrongly. The source-agnostic parts — importing history, preserving event time, cutting over — are on Switching to Brain.

◇Prerequisites

A Zep deployment you can export from, a Brain API key, and a backend to point at. If encode and recall are new, read Your first memory first.

Start here: what is genuinely the same

Most migration guides open by listing differences. This one does not, because the overlap is unusually large and knowing which half of your model survives tells you how big the job is.

01

A temporal graph, not a vector index

Both extract entities and typed relationships from episodes and store them as a graph with provenance back to the text they came from. Neither is a folder of embeddings with a similarity search bolted on.

02

Bi-temporal validity

Both separate when something was true from when the system learned it. Zep's valid_at / invalid_at are event time and its created_at / expired_at are record time; Brain's valid_from / valid_to and occurred_at / created_at are the same split. This is not a Brain differentiator — Zep does it, and does it well.

03

Contradictions invalidate, never delete

A newer claim closes an older one and the history stays queryable. Zep stamps invalid_at; Brain writes superseded_by and sets valid_to. Same idea, different field names.

04

Hybrid retrieval

Both fuse more than one retrieval signal rather than relying on cosine similarity alone.

If that is the whole of what you use Zep for, the port is a verb mapping and an import. The next sections are for everything else.

Verb mapping

Check your Zep SDK version first

Zep's method names have moved. The current zep_cloud SDK uses memory.add / memory.get and graph.add / graph.search; older material shows memory.add_memory, memory.add_session and memory.search_sessions. The left column below uses the current names. Map from whichever you actually call.

ZepBrain
memory.add(session_id, messages)encode under the key's scope, with session set
memory.get(session_id)recall — but see "Context Block" below
graph.add(user_id, data, type)encode — text, or a structured write through the typed-graph verbs
graph.search(query, scope="edges")listStatements / recall
graph.search(query, scope="nodes")listEntities / resolveEntity
user.add / per-user graphA space — created lazily by the first write that names one
session_idsession, a 64-bit integer you choose
graph.edge.get(uuid)getStatement / getRelation
Fact valid_at / invalid_atStatement valid_from / valid_to
Fact created_at / expired_atStatement extracted_at / record-invalidation, reachable via as_of_record_time

The four things that do not port

1. There is no Context Block, and you have to replace it

Zep's memory.get returns a formatted string ready to paste into a system prompt — entities, facts, and their validity windows, pre-arranged. It is the single most convenient thing Zep does, and Brain has no equivalent.

recall returns structured memories with scores and a verdict. Formatting them is yours:

answer = brain.recall(turn.message, max_results=8)

if answer.answer_kind == "none":
    context = ""                      # say so, rather than padding the prompt
else:
    context = "\n".join(f"- {m.text}" for m in answer.memories)

This is a real trade, in both directions

You lose a formatted block that works out of the box. You gain control over what reaches the prompt and what it costs: the Context Block's size and shape are Zep's decision, and on a long-lived user it is not small. Budget an afternoon to write the formatter, and expect to tune max_results against your own token budget rather than accepting a default.

2. user_id and session_id are not arguments any more

In Zep, the user is an argument: graph.add(user_id=…), memory.add(session_id=…). In Brain, the user is the credential. There is no user_id parameter on any verb, and no HTTP route accepts a scope selector.

Three shapes, and picking the wrong one is the most expensive mistake in this migration:

OptionTypeDefault / Env
One key per tenantworks on any tier

Mint a key per organisation, store it against the account, resolve it when you resolve the session. Isolation is enforced by the server. The cost is key lifecycle.

One pooled key + act_aswire tier only

One connection, one credential, every request stamped with the identity it runs as. This is the shape that maps onto Zep's user_id argument, and the HTTP API does not have it — it needs BrainClient over a socket.

One space, prefixed keyssingle-tenant apps

Everything in one space. Fine for an internal tool; not isolation.

A key per end user does not scale and is not the answer

Zep gives every user their own graph, so the instinct is a Brain key per user. At any real signup rate that is key minting, storage, rotation and revocation per account. Use act_as with a pooled key, and treat space as an opaque selector string you choose — not an id you construct. The server derives the storage id from it, which is what stops a client forging one. Identity from a JWT is the whole flow.

3. A read returns a verdict, not facts

graph.search returns edges ranked by relevance. recall returns single / many / none plus the supporting memories.

The port that looks right and is wrong:

# Zep
facts = client.graph.search(query=q, scope="edges").edges
if facts:
    ...

# Brain — mechanically translated, verdict discarded
answer = brain.recall(q)
if answer.memories:                     # ← throws away the thing you migrated for
    ...

none means nothing stored answers this cue — a real answer, and the one that lets an agent say "I don't know" instead of reasoning over weak matches. Branch on answer_kind.

`many` is not "several results" — it is a cardinality verdict

single says one memory answers the cue. many says several do and the answer is genuinely plural — not that the index returned more than one row. An agent that treats many as "pick the top one" will confidently answer a question that has three correct answers.

4. Point-in-time reads are a parameter, not a filter

Both systems store enough to answer "what did we believe on 3 March". They differ in how much work that is.

In Zep, the timestamps are fields on an edge, and a point-in-time read means supplying date filters over valid_at / invalid_at yourself — the ordinary search path does not assemble "facts true at T" for you.

In Brain it is one read parameter. as_of_record_time_unix_nanos resolves statements and relations against what the substrate believed at record-time t, and re-bases the recency decay to the same anchor so the ranking is also as-of rather than as-of-now:

from brain_db_sdk import RecallBuilder

march = RecallBuilder("what plan is this customer on") \
    .as_of(1_709_424_000_000_000_000) \
    .build()
answer = await brain.recall(march)

Two different time axes, and it is worth keeping them straight

as_of is record time — what we knew then. age_bound is event time — when the thing happened. "What did we believe in March" and "what happened before March" are different questions and take different arguments. Zep's created_at/expired_at and valid_at/invalid_at are the same two axes under different names.

The chat loop, ported

The shape most people are actually migrating. Zep on the left, Brain on the right, with the three decisions the port forces.

from zep_cloud.client import Zep

zep = Zep(api_key=ZEP_API_KEY)

def turn(user_id: str, session_id: str, message: str) -> str:
    # One call returns a prompt-ready block for this user.
    memory = zep.memory.get(session_id=session_id)
    reply = model(system=memory.context, user=message)

    zep.memory.add(
        session_id=session_id,
        messages=[
            {"role": "user", "content": message},
            {"role": "assistant", "content": reply},
        ],
    )
    return reply
from 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. Encoding the turn and then recalling with it
    #    returns the sentence you just wrote as the top hit.
    answer = brain.recall(message, max_results=8)

    # 2. The verdict is the answer. `none` is "I have nothing on this",
    #    which is a different prompt from "here is what I know".
    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. Write the user's turn, not the model's. And not every turn.
    if is_durable(message):
        brain.encode(message, session=session_id)

    return reply

Three things changed, and all three are deliberate.

The user id is gone. brain is already scoped — the key resolved to a (namespace, space) before the function ran.

The order flipped. Zep's memory.get reads the state before this turn, so adding after is natural. In the Brain version the ordering is load-bearing for a different reason: encode first and recall with the same text and the top hit is the sentence you just stored, echoed back. It looks like retrieval working perfectly, which is what makes it hard to notice.

The assistant's reply is not stored. Zep's memory.add takes both turns, because its context block is a conversation summary. Brain stores claims. A model's own output is not an observation about the user — store it and the next recall is fed the model's words, so a wrong answer becomes a "fact" the next turn retrieves and repeats. See What to write.

`is_durable` is the part no framework gives you

Zep's memory.add on every turn is reasonable because it is building a conversation summary. Porting that call site unchanged — encode on every turn — 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, and it is not "every turn".

Filters: fact ratings become two different knobs

Zep filters low-quality facts with a rating you configure and threshold at read time. Brain splits that into two signals that are not interchangeable, and conflating them is the commonest tuning mistake here.

ParameterTypeRequired
confidencefloatoptional

How strongly the evidence supports the claim — noisy-OR over the statement's evidence list. This is the nearest thing to a fact rating, and the right knob for "only act on claims we are sure of".

salience_floorfloatoptional

How important a memory is. It filters and does not rank: above your floor, a more-salient memory does not outrank a less-salient one. Use it to exclude noise, never to prefer things.

from brain_db_sdk import RecallBuilder

request = (
    RecallBuilder("which plan is this customer on")
    .confidence(0.7)      # only well-evidenced claims
    .salience(0.2)        # drop the noise floor entirely
    .limit(6)
    .build()
)

Salience is a filter, not a ranking term

It is the one people get wrong, because every other system's "importance" score is a ranking input. Brain keeps it out of ranking deliberately: 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. Recency is the ranking term with a time component — 90-day half-life on event time, worth at most half of one top-rank vote.

Entity resolution is explicit

Zep resolves entities during ingestion and hands you the graph. Brain does the same on the write path, but also exposes the resolution step as a verb — which matters when you are importing, because an import is exactly when "Priya", "Priya K" and "p.kumar@" arrive as three surface forms of one person.

match = brain.resolve_entity("Priya K")
# → the entity it refers to, or an explicit no-match

Call it before create_entity, not after: creating an entity that already exists under the same canonical name is a conflict, not a silent no-op. Ambiguous resolutions land in a merge-review queue that a background sweeper re-checks as the entity index grows, so a near-miss during a bulk import is not permanent.

Importing a Zep graph

Export episodes, not facts. Brain re-derives the graph on write, so importing Zep's extracted edges would give you two extractions of the same source, and the second would be Brain trying to type a sentence that was already a conclusion.

Zep's extraction uses its own ontology. Anything Brain extracts whose type is not declared is silently dropped, so list the entity and predicate types you actually query on, and declare them first. get_schema then shows what is live.

The episode is the memory; the edges are derived. Order matters — supersession is ordered, and loading a correction before the claim it corrects builds the chain backwards.

Zep's user_id becomes the space selector; its session_id can become Brain's session directly, since a session id is a 64-bit integer you choose and the space or session is created lazily by the first write that names it.

Zep's reference_time (the episode's event time) becomes occurred_at_unix_nanos. Skip this and every imported episode lands at import time — see the warning on the hub page.

Brain's extraction is not Zep's. A claim Zep typed as an edge may come out of Brain as a different predicate, or — if the type is undeclared — not at all. Pick the twenty facts your product actually reads and verify each one with list_statements after the import settles.

import os
from brain_db_sdk.http import BrainHttpClient

brain = BrainHttpClient(os.environ["BRAIN_API_KEY"], base_url=BASE_URL)

for episode in zep_episodes_oldest_first(user_id):
    brain.encode(
        episode.content,
        session=int(episode.session_id),
        occurred_at=episode.reference_time_unix_nanos,
    )

Extraction is asynchronous — verify after it settles

encode returns when the memory is durable, not when the graph has derived from it. A verification pass that runs immediately after the last write sees an empty graph and reports a failed import. Watch the change feed, or use the derived wait mode on the wire tier.

What you gain

Stated as things you can check rather than things to believe.

One process, and it is yours

Zep Cloud is a managed service; Graphiti self-hosted needs a graph database (Neo4j or FalkorDB) and an LLM, which you provision, scale and keep in sync.

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. Embedded, self-hosted or clustered from the same crates. There is no second datastore to keep consistent and nothing that stops working when a vendor does.

The read path is inspectable

answer = brain.recall(cue, include_trace=True)
# answer.trace: which retrievers ran, how ranks fused, what the filter chain
# dropped, what the reranker moved — as a JSON string.

When an answer is wrong, you read what happened rather than inferring it from a score. It is large — a three-hit recall over ~700 memories measured 121 KB, because it reports every candidate each lane considered — so switch it on for one request, never for an endpoint.

Confidence is aggregated from evidence

A statement's confidence is noisy-OR over its evidence list: each piece of evidence is an independent vote, and the stored value is the probability that at least one is right. Every statement cites the memories it came from, so "why does Brain believe this" resolves to a list of sentences rather than a number.

Isolation you can audit

There is no scope argument anywhere in the REST contract, so there is nothing for a client to forge or a developer to forget. whoami reports what the server resolved, which means it cannot agree with a mistake — call it first whenever something looks like it is reading the wrong workspace.

What you give up

OptionTypeDefault / Env
The Context Blockrebuild it

A formatted, prompt-ready string. Replace with your own formatter over recall results — an afternoon, and then it is tuned to your prompt budget rather than to Zep's defaults.

A managed dashboardrun it yourself

Usage views, graph browsing and support come with Zep Cloud. Brain gives you /healthz, Prometheus metrics and the console in early access.

Per-user graphs by constructionuse act_as

Zep gives every user a graph for free. Brain gives you spaces, and the pooled-key pattern that maps onto them is wire-tier only.

Stabilitypre-1.0

The wire protocol, on-disk formats and schema model change in place with no compatibility shims. Pin an exact version and read release notes.

The honest summary

If what you need is a hosted temporal graph with a prompt-ready context string and you are happy on a managed service, Zep already does that and this migration buys you little. The reasons to move are specific: you want the answer verdict, you want one binary you control with no second datastore, you want credential-enforced isolation rather than an argument, or you want to read the retrieval trace when an answer is wrong.

01
The import mechanics

Event time, idempotency, verification and the cutover plan.

02
Identity from a JWT

The pooled-key pattern that replaces user_id.

03
Supersession

What replaces what, and why the raw memories still resemble each other.

See also
How recall decidesThree fused retrievers, and the bounded recency term.The typed graphEntities, statements and relations, and what the schema gates.Coming from mem0 insteadA simpler surface, a larger conceptual jump.

Was this page helpful?

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.

Migrating from supermemory

Two retrieval paths collapsing into one, an ingestion pipeline you now own, container tags becoming a credential, and what isLatest turns into.

On this page

Start here: what is genuinely the sameVerb mappingThe four things that do not port1. There is no Context Block, and you have to replace it2. user_id and session_id are not arguments any more3. A read returns a verdict, not facts4. Point-in-time reads are a parameter, not a filterThe chat loop, portedFilters: fact ratings become two different knobsEntity resolution is explicitImporting a Zep graphWhat you gainOne process, and it is yoursThe read path is inspectableConfidence is aggregated from evidenceIsolation you can auditWhat you give up
Suggest an editOpen in Playground