Every agent forgets. Every restart, every new session, every scroll-off of the context window — the user’s preferences, past decisions, and hard-won context vanish. You can paper over it by stuffing chat history into the prompt, but that breaks down the moment you hit context limits or switch sessions.
Mem0 solves this with a dedicated memory layer: an LLM-powered extraction pipeline that pulls facts from conversations, stores them in a vector database, and retrieves them on demand. It’s Apache-2.0 licensed, has 55K+ GitHub stars, and the latest v2.0.x release (August 2026) ships a significantly improved memory algorithm with single-pass extraction and multi-signal retrieval.
This tutorial wires Mem0 into a working Python agent end-to-end. By the end, you’ll have a chat agent that remembers user facts across sessions, with per-user isolation and a local vector store.
If you’re still deciding whether Mem0 is the right memory tool for your stack, read our Mem0 vs Zep vs LangMem comparison first — then come back to build.
What You’ll Build
A CLI chat agent that:
- Accepts user messages and responds using OpenAI’s API (or any LLM)
- Extracts and stores facts from every conversation via
memory.add() - Retrieves relevant memories before generating each response via
memory.search() - Isolates users by
user_idso Alice’s memories don’t leak into Bob’s session - Runs fully self-hosted with Qdrant as the vector backend
Setup
Install the dependencies:
pip install mem0ai openai qdrant-client
You need a running Qdrant instance. The fastest path for local dev:
docker run -d -p 6333:6333 qdrant/qdrant
Set your OpenAI key (Mem0 uses it for fact extraction and embedding by default):
export OPENAI_API_KEY="sk-..."
Step 1: Initialize Mem0 with Qdrant
Mem0’s Memory class accepts a config dict. We point the LLM at OpenAI, the embedder at OpenAI, and the vector store at our local Qdrant:
from mem0 import Memory
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0.1,
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
}
},
"history_db_path": "mem0_history.db",
}
memory = Memory.from_config(config)
Key points:
- Use
gpt-4o-minifor extraction. The extraction call is a separate LLM inference every time youadd(). Mini handles fact extraction reliably at roughly 1/10th the cost of full GPT-4o. history_db_pathstores conversation history in a local SQLite file. This is optional but useful for debugging — you can inspect which raw messages produced which extracted facts.
Running Fully Local (Optional)
You can swap every OpenAI dependency for Ollama. Replace the config blocks with:
"llm": {
"provider": "ollama",
"config": {
"model": "llama3.1:8b",
}
},
"embedder": {
"provider": "ollama",
"config": {
"model": "nomic-embed-text",
}
},
We’ve tested this on an RTX 3090. Extraction latency is ~1s per add() call with an 8B model — factor that into your UX if you’re not backgrounding it.
Step 2: The Core Pattern — Add, Search, Respond
The integration loop has three steps for every user message:
- Search existing memories for relevant context
- Generate a response using that context
- Store the new conversation turn as memories
from openai import OpenAI
client = OpenAI()
USER_ID = "alice"
def chat(message: str) -> str:
# 1. Retrieve relevant memories
memories = memory.search(message, user_id=USER_ID, limit=5)
memory_context = "\n".join(
f"- {m['memory']}" for m in memories.get("results", [])
)
# 2. Build the prompt with memory context
system_prompt = "You are a helpful assistant. Use the user memories below to personalize responses.\n"
if memory_context:
system_prompt += f"\nKnown facts about this user:\n{memory_context}\n"
system_prompt += "\nIf you learn something new about the user, mention it naturally."
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": message},
],
)
reply = response.choices[0].message.content
# 3. Store the exchange as new memories
memory.add(
[
{"role": "user", "content": message},
{"role": "assistant", "content": reply},
],
user_id=USER_ID,
)
return reply
That’s the entire integration. Three calls: search(), LLM completion, add(). Let’s test it.
Step 3: Run It
if __name__ == "__main__":
print("Chat with memory. Type 'quit' to exit.\n")
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
break
response = chat(user_input)
print(f"Agent: {response}\n")
Run it and have a conversation:
Chat with memory. Type 'quit' to exit.
You: Hi, I'm Alice. I'm a backend engineer and I prefer Python.
Agent: Hi Alice! Great to meet you. I'll remember you're a backend engineer
who prefers Python. How can I help today?
You: What language should I use for a new CLI tool?
Agent: Since you're already comfortable with Python, that's a solid choice
for a CLI tool — especially with libraries like Click or Typer.
You: quit
Now restart the script and start a new conversation:
You: What do you know about me?
Agent: Based on what I remember: you're Alice, a backend engineer who
prefers Python. Is there anything else I should know?
The agent remembered. Not because you stuffed history into the prompt — because Mem0 extracted the facts, stored them, and retrieved them on the next session.
Step 4: Multi-User Isolation
Switch USER_ID and the memories partition cleanly:
USER_ID = "bob"
# In a new session:
memory.add(
[{"role": "user", "content": "I'm Bob, a frontend developer. I prefer TypeScript."}],
user_id="bob",
)
results = memory.search("What language does Bob prefer?", user_id="bob")
print(results["results"][0]["memory"])
# "Bob is a frontend developer. Prefers TypeScript."
# Alice's memories don't leak:
results = memory.search("What language does Bob prefer?", user_id="alice")
print(len(results.get("results", [])))
# 0
user_id acts as a namespace. Every add() and search() call scopes to it. Under the hood, Mem0’s Qdrant collection stores a user_id field on every vector — the filter is applied at query time, so there’s no cross-contamination.
Production Gotchas
We’ve run Mem0 in production. Here’s what bites:
1. add() Is Not Free
Every memory.add() fires a separate LLM call for fact extraction. With gpt-4o-mini, that’s roughly $0.15/1M input tokens — negligible per call, but a busy agent doing 10K conversations/day generates 20K extraction calls. At that volume, run the numbers.
Fix: If your agent doesn’t need instant memory persistence, batch add() calls or run them in a background worker. Mem0’s extraction is fast (~500ms with mini) but still adds latency to every turn.
2. Facts Accumulate, They Don’t Update
Mem0 v2’s single-pass algorithm only adds facts — it never overwrites or deletes. If Alice says “I live in Berlin” and later “I moved to London,” both facts coexist. Search returns both, and it’s up to your prompt to prioritize recency.
Fix: Add a temporal signal in your prompt: “Prefer more recent facts when they contradict older ones.” Mem0 stores timestamps internally, and the retrieval scoring considers recency, but the LLM still sees the raw list.
3. Search Threshold Tuning
The default search() threshold is generous — it returns low-confidence matches. If your agent starts hallucinating user facts it “remembers,” lower the threshold:
memory.search(query, user_id=USER_ID, threshold=0.7, limit=5)
A threshold of 0.7 eliminates noisy retrievals. Start there and tune up if you’re missing real memories, down if you’re getting garbage.
4. The Extraction LLM Matters
We tested gpt-4o-mini vs gpt-4o for extraction. Mini misses roughly 5-8% of implied facts (e.g., “I’ve been doing this for 10 years” → should extract “Has 10 years of experience”). For a support bot, that’s fine. For a healthcare agent, use a stronger model.
What memory.add() Actually Extracts
Let’s see what Mem0 pulls from a realistic exchange:
messages = [
{"role": "user", "content": "I'm deploying to AWS us-east-1. Our latency budget is 50ms p99."},
{"role": "assistant", "content": "Got it — us-east-1 with a 50ms p99 budget. That rules out cross-region architectures."},
{"role": "user", "content": "Right. Also, we're on Kubernetes 1.32 with the Gateway API, not Ingress."},
]
result = memory.add(messages, user_id="alice")
print(result)
Mem0 extracts discrete, queryable facts like:
- “Deploys to AWS us-east-1”
- “Latency budget is 50ms p99”
- “Uses Kubernetes 1.32”
- “Uses Gateway API, not Ingress”
Each fact is embedded separately and retrievable independently. You don’t get back the raw conversation — you get structured facts. This is the key difference between Mem0 and dumping chat history into a vector DB.
When Not to Use Mem0
Mem0 shines when you need cross-session, long-running memory with fact extraction. It’s overkill when:
- You just need conversation history. Use LangGraph’s checkpointing or a simple message store. See our LangGraph state and checkpointing tutorial.
- You need a knowledge graph. Mem0’s graph feature is locked behind the $249/month Pro tier. If graph traversal is core to your architecture, Zep includes it at all pricing tiers — read our full comparison.
- You’re on a strict no-API-calls budget. The local Ollama path works, but every
add()call is a full LLM inference. On CPU, that’s seconds per call. On a 3090, it’s ~1s with 8B models. If your agent needs sub-100ms response times, batch extraction asynchronously.
Next Steps
- Add agent_id for multi-agent setups. Pass
agent_idalongsideuser_idto partition memories by which agent produced them. This is critical for multi-agent architectures — see our multi-agent memory patterns for the full picture. - Swap in your own LLM client. The config accepts any LiteLLM-compatible provider. If you’re routing through a gateway, see our LLM gateway pricing comparison for options.
- Instrument with LangFuse. Memory retrieval quality degrades silently. We recommend tracing
add()andsearch()calls — our LangFuse observability tutorial covers the setup.
The full code from this tutorial is available on GitHub. For production deployment patterns and the managed platform, see the Mem0 documentation.
Used in this tutorial: mem0ai v2.0.15 (released August 1, 2026), OpenAI gpt-4o-mini, Qdrant v1.16+.