Migrating from Mem0 to Brain
The Problem: Why Migrate from Mem0?
Mem0 is a memory management layer for agents, but it has constraints:
- Semantic-only retrieval: Mem0 retrieves by semantic similarity. If you need "all memories from the last 24 hours" or "find memory type = 'decision'", you need custom post-retrieval filtering.
- Network latency: Mem0 Cloud adds 200–500ms per operation. For real-time agents, that's slow.
- Limited schema control: Memory is largely unstructured text. Structured metadata filtering is an afterthought.
- Single retrieval mode: One vector search. No hybrid (keyword + semantic), no temporal windows, no type filtering.
- Vendor lock-in: Mem0's API is proprietary; exporting history requires custom tooling.
Brain fixes these:
| Feature | Mem0 | Brain |
|---|---|---|
| Retrieval modes | Semantic only | Hybrid, temporal, lexical, type-filtered, graph |
| Latency (Cloud) | 200–500ms | 50–150ms |
| Metadata filtering | Limited | Full structured support |
| Schema control | Unstructured text + tags | Typed, extensible |
| Export/import | Difficult | Standard APIs |
| Open source | No | Yes |
This guide maps Mem0 APIs to Brain and provides a migration script.
API Mapping: Mem0 → Brain
| Mem0 API | Purpose | Brain Equivalent | Notes |
|---|---|---|---|
memory.add(text, metadata) | Store a memory | client.encode(EncodeBuilder(text).build()) | You send text; Brain derives typed metadata during extraction |
memory.get(query) | Retrieve memories | client.recall(RecallBuilder(query).limit(k).build()) | Brain fuses semantic + lexical + graph retrieval by default |
memory.search(query, filters) | Search with filters | client.recall(RecallBuilder(query).kinds([...]).confidence(0.5).build()) | Query text drives retrieval; the builder narrows it with kinds, confidence, salience, sessions and as_of |
memory.update(id, text) | Update memory | No direct equivalent | Encode the new text, then forget the stale memory |
memory.delete(id) | Delete memory | client.forget(ForgetBuilder(memory_id).build()) | Same |
memory.list() | List all | client.memory_list(...) | A cursor-paged enumeration, newest first; recall itself stays query-driven |
Step 1: Export Mem0 Data
First, extract all memories from Mem0. If you're using Mem0 Cloud, use their export endpoint or iterate over memories:
import requests
from mem0 import Memory
# Initialize Mem0
mem0 = Memory.from_config({
"llm": {"provider": "openai", "config": {"model": "gpt-4"}},
"embedder": {"provider": "openai"},
"vector_store": {"provider": "qdrant"},
})
# Export all memories
all_memories = []
space_id = "your_space_id"
# Mem0 doesn't have a bulk export, so iterate
memories = mem0.search("*", limit=10000) # High limit to get all
for memory in memories:
all_memories.append({
"id": memory.get("id"),
"content": memory.get("content"),
"metadata": memory.get("metadata", {}),
})
# Save to JSON
import json
with open("mem0_export.json", "w") as f:
json.dump(all_memories, f, indent=2)
print(f"Exported {len(all_memories)} memories")Step 2: Transform Mem0 Schema to Brain Schema
Mem0 memories are typically:
{
"id": "mem_xyz",
"content": "User prefers late-night meetings after 10pm",
"metadata": {
"agent_id": "agent_1",
"tags": ["user_preference", "scheduling"]
}
}Transform to Brain schema:
{
"content": "User prefers late-night meetings after 10pm",
"spaceId": "agent_1",
"metadata": {
"type": "user_preference",
"tags": ["scheduling"],
"source": "mem0_migration",
"imported_at": "2026-05-13T10:00:00Z"
}
}Step 3: Run Migration Script
This Python script exports from Mem0 and imports into Brain via the SDK:
import os
from mem0 import Memory
from brain_db_sdk import Auth, BrainClient, EncodeBuilder
# Mem0 setup (export phase)
mem0 = Memory.from_config({
"llm": {"provider": "openai", "config": {"model": "gpt-4"}},
"embedder": {"provider": "openai"},
"vector_store": {"provider": "qdrant"},
})
def export_mem0() -> list[str]:
"""Export the text of every memory from Mem0."""
memories = mem0.search("*", limit=10000)
return [mem.get("content", "") for mem in memories if mem.get("content")]
def import_brain(client, texts: list[str]) -> tuple[int, int]:
"""Encode each memory into Brain. Brain derives typed metadata itself."""
imported_count = 0
failed_count = 0
for text in texts:
try:
client.encode(EncodeBuilder(text).build())
imported_count += 1
except Exception as e:
print(f"Failed to import memory: {text[:50]}... Error: {e}")
failed_count += 1
return imported_count, failed_count
# Run migration
texts = export_mem0()
print(f"Exported {len(texts)} memories from Mem0")
with BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
) as client:
print(f"Importing {len(texts)} memories into Brain...")
imported, failed = import_brain(client, texts)
print(f"Migration complete: {imported} imported, {failed} failed")Step 4: Update Your Code
Before:
from mem0 import Memory
mem0 = Memory.from_config(config)
# Store
mem0.add("User likes coffee", {"agent_id": "agent_1", "tags": ["preference"]})
# Retrieve
results = mem0.search("What does the user like?")After:
import os
from brain_db_sdk import Auth, BrainClient, EncodeBuilder, RecallBuilder
with BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
) as client:
# Store — Brain computes the embedding and derives typed metadata
client.encode(EncodeBuilder("User likes coffee").build())
# Retrieve — hybrid (semantic + lexical + graph) fusion is the default
answer = client.recall(RecallBuilder("What does the user like?").limit(5).build())
# answer.answer_kind: "Single" | "Many" | "None" — the hits are in answer.memoriesCost Comparison: Mem0 vs Brain
Assume: 100 agents, 5K memories each = 500K total memories, 1K retrievals/day
| Service | Cost per Month | Notes |
|---|---|---|
| Mem0 Cloud | 2000 | Pay per memory stored + retrieved; pricing opaque |
| Brain Cloud | 800 | 0.0005 per retrieval |
| Brain Open Source | $0 | Self-host; only pay for infra (compute, storage) |
Savings by migrating: 60–75% cost reduction on memory operations.
Migration Checklist
- Export all memories from Mem0 (use script above)
- Review exported schema; map Mem0 metadata to Brain metadata structure
- Transform memories to Brain schema (update field names, add type/source)
- Set up Brain Cloud account (or self-host open-source version)
- Run migration script to import memories to Brain
- Verify import: sample 10 random memories, retrieve them, confirm content matches
- Update agent code: replace
mem0.add()withclient.encode(),mem0.search()withclient.recall() - Test retrieval quality: run your retrieval queries against Brain, compare results to Mem0
- Backfill any missing edge cases (e.g., memory types Mem0 had but Brain schema doesn't capture)
- Decommission Mem0 connection after validation
Why Brain Wins
Hybrid retrieval: Brain combines keyword search (BM25) with semantic search. For memory "User prefers late-night meetings", a keyword query for "late-night" retrieves directly; Mem0 requires semantic similarity to "when should meetings be?".
Structured metadata: Brain's metadata is fully queryable. Filter by type="preference" or created_after="2026-05-01". Mem0 requires post-retrieval filtering in application code.
Lower latency: Brain Cloud is architected for <\100ms P99 latency. Mem0's network hops are slower.
Open source control: Brain's open-source version runs anywhere (local, Docker, K8s). Mem0 requires their cloud.
Next Steps
- Learn more: See Migrating from Pinecone for vector DB migration patterns
- Cost comparison: Check Cost Optimization for Agent Memory
- Build: Read Schema Design Patterns to design Brain schemas that match your agent's needs