快速开始
Set up your Mem0 Platform account, install the SDK, and store your first memory in under five minutes.
In about five minutes you will get an API key, store your first memory, and search it back. Follow along in Python, JavaScript, cURL, or the terminal.
Are you an AI agent? See Sign up as an agent: create a working API key in four commands, with no email or dashboard.
Prerequisites
- Mem0 Platform account (https://app.mem0.ai?utm_source=oss&utm_medium=platform-quickstart)
- API key (https://app.mem0.ai/dashboard/settings?tab=api-keys&subtab=configuration)
- Python 3.10+, Node.js 18+, or cURL. The CLI needs either Node.js 18+ or Python 3.10+.
Store your first memory
Pick a tab and use the same one for every step below.
pip install mem0ai
npm install mem0ai
# Nothing to install. cURL ships with macOS and most Linux distributions.
npm install -g @mem0/cli
# or, if you prefer Python: pip install mem0-cli
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: 'your-api-key' });
export MEM0_API_KEY="your-api-key"
mem0 init --api-key "your-api-key"
messages = [
{"role": "user", "content": "I'm a vegetarian and allergic to nuts."},
{"role": "assistant", "content": "Got it! I'll remember your dietary preferences."}
]
client.add(messages, user_id="user123")
const messages = [
{"role": "user", "content": "I'm a vegetarian and allergic to nuts."},
{"role": "assistant", "content": "Got it! I'll remember your dietary preferences."}
];
await client.add(messages, { userId: "user123" });
curl -X POST https://api.mem0.ai/v3/memories/add/ \
-H "Authorization: Token $MEM0_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "Im a vegetarian and allergic to nuts."},
{"role": "assistant", "content": "Got it! Ill remember your dietary preferences."}
],
"user_id": "user123"
}'
mem0 add "I'm a vegetarian and allergic to nuts." --user-id user123
Mem0 pulls the individual facts out of the conversation and stores each one separately:
{
"results": [
{"id": "0f2c1b6e-9a3d-4b18-8f77-1c2d3e4f5a6b", "memory": "Is a vegetarian", "event": "ADD"},
{"id": "14e1b28a-2014-40ad-ac42-69c9ef42193d", "memory": "Allergic to nuts", "event": "ADD"}
]
}
results = client.search("What are my dietary restrictions?", filters={"user_id": "user123"})
print(results)
const results = await client.search("What are my dietary restrictions?", { filters: { user_id: "user123" } });
console.log(results);
curl -X POST https://api.mem0.ai/v3/memories/search/ \
-H "Authorization: Token $MEM0_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "What are my dietary restrictions?",
"filters": {"user_id": "user123"}
}'
mem0 search "What are my dietary restrictions?" --user-id user123
Both facts come back, ranked by how well they match the question:
{
"results": [
{
"id": "14e1b28a-2014-40ad-ac42-69c9ef42193d",
"memory": "Allergic to nuts",
"user_id": "user123",
"agent_id": null,
"app_id": null,
"run_id": null,
"categories": ["health"],
"metadata": {},
"created_at": "2025-10-22T04:40:22.864647-07:00",
"updated_at": "2025-10-22T04:40:22.864647-07:00",
"expiration_date": null,
"score": 0.87
},
{
"id": "0f2c1b6e-9a3d-4b18-8f77-1c2d3e4f5a6b",
"memory": "Is a vegetarian",
"user_id": "user123",
"agent_id": null,
"app_id": null,
"run_id": null,
"categories": ["food_preferences"],
"metadata": {},
"created_at": "2025-10-22T04:40:22.864647-07:00",
"updated_at": "2025-10-22T04:40:22.864647-07:00",
"expiration_date": null,
"score": 0.81
}
]
}
Pass these memories to your model as context, and it answers with what it already knows about the user instead of asking again.
Rather than calling add and search yourself, you can hand Mem0 to your agent as a set of tools and let it decide when to save and look things up. See Mem0 MCP.
What's next?
You stored and searched your first memory. Start with scoping, since every call you make from here needs it:
What `user_id` actually does, plus the `agent_id`, `app_id`, and `run_id` fields that came back empty above.
Why one sentence became two memories, and how Mem0 decides what to keep.
The operations beyond add and search, for when stored facts change or go stale.
Wire memory into LangChain, CrewAI, LangGraph, or the OpenAI Agents SDK.
Something not working? The FAQs and troubleshooting page covers the common setup errors.
Use Mem0 as a memory store in LlamaIndex with support for ReAct and FunctionCalling agent types.
LlamaIndex supports Mem0 as a memory store. In this guide, we'll show you how to use it.
Mem0Memory now supports ReAct and FunctionCalling agents.
Installation
To install the required package, run:
pip install llama-index-core llama-index-memory-mem0 python-dotenv
Setup with Mem0 Platform
Set your Mem0 Platform API key as an environment variable. You can replace <your-mem0-api-key> with your actual API key:
You can obtain your Mem0 Platform API key from the https://app.mem0.ai/login?utm_source=oss&utm_medium=integration-llama-index.
from dotenv import load_dotenv
import os
load_dotenv()
# os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
Import the necessary modules and create a Mem0Memory instance:
from llama_index.memory.mem0 import Mem0Memory
context = {"user_id": "alice"}
memory_from_client = Mem0Memory.from_client(
context=context,
search_msg_limit=4, # optional, default is 5
)
Context is used to identify the user, agent or the conversation in the Mem0. It is required to be passed in at least one of the fields in the Mem0Memory constructor. It can be any of the following:
context = {
"user_id": "alice",
"agent_id": "llama_agent_1",
"run_id": "run_1",
}
search_msg_limit is optional, default is 5. It is the number of messages from the chat history to be used for memory retrieval from Mem0. More number of messages will result in more context being used for retrieval but will also increase the retrieval time and might result in some unwanted results.
search_msg_limit is different from limit. limit is the number of messages to be retrieved from Mem0 and is used in search.
Setup with Mem0 OSS
Set your Mem0 OSS by providing configuration details:
To know more about Mem0 OSS, read Mem0 OSS Quickstart.
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"collection_name": "test_9",
"host": "localhost",
"port": 6333,
"embedding_model_dims": 1536, # Change this according to your local model's dimensions
},
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-5-mini",
"temperature": 0.2,
"max_tokens": 2000,
},
},
"embedder": {
"provider": "openai",
"config": {"model": "text-embedding-3-small"},
},
}
Create a Mem0Memory instance:
memory_from_config = Mem0Memory.from_config(
context=context,
config=config,
search_msg_limit=4, # optional, default is 5
# Remove deprecation warnings
)
Initialize the LLM
from llama_index.llms.openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
# os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-5-mini")
SimpleChatEngine
Use the SimpleChatEngine to start a chat with the agent with the memory.
from llama_index.core.chat_engine import SimpleChatEngine
agent = SimpleChatEngine.from_defaults(
llm=llm, memory=memory_from_client # or memory_from_config
)
# Start the chat
response = agent.chat("Hi, My name is Alice")
print(response)
Now we will learn how to use Mem0 with FunctionCalling and ReAct agents.
Initialize the tools:
from llama_index.core.tools import FunctionTool
def call_fn(name: str):
"""Call the provided name.
Args:
name: str (Name of the person)
"""
print(f"Calling... {name}")
def email_fn(name: str):
"""Email the provided name.
Args:
name: str (Name of the person)
"""
print(f"Emailing... {name}")
call_tool = FunctionTool.from_defaults(fn=call_fn)
email_tool = FunctionTool.from_defaults(fn=email_fn)
FunctionCallingAgent
from llama_index.core.agent import FunctionCallingAgent
agent = FunctionCallingAgent.from_tools(
[call_tool, email_tool],
llm=llm,
memory=memory_from_client, # or memory_from_config
verbose=True,
)
# Start the chat
response = agent.chat("Hi, My name is Alice")
print(response)
ReActAgent
from llama_index.core.agent import ReActAgent
agent = ReActAgent.from_tools(
[call_tool, email_tool],
llm=llm,
memory=memory_from_client, # or memory_from_config
verbose=True,
)
# Start the chat
response = agent.chat("Hi, My name is Alice")
print(response)
Key Features
- Memory Integration: Uses Mem0 to store and retrieve relevant information from past interactions.
- Personalization: Provides context-aware agent responses based on user history and preferences.
- Flexible Architecture: LlamaIndex allows for easy integration of the memory with the agent.
- Continuous Learning: Each interaction is stored, improving future responses.
Conclusion
By integrating LlamaIndex with Mem0, you can build a personalized agent that can maintain context across interactions with the agent and provide tailored recommendations and assistance.
Build multi-agent systems with LlamaIndex and Mem0
Create ReAct agents with LlamaIndex
<Snippet />
Store and search Mem0 memories from a TypeScript or JavaScript app in minutes.
Spin up Mem0 with the Node SDK in just a few steps. You'll install the package, initialize the client, add a memory, and confirm retrieval with a single search.
Prerequisites
- Node.js 18 or higher
- (Optional) OpenAI API key stored in your environment when you want to customize providers
Install and run your first memory
npm install mem0ai
import { Memory } from "mem0ai/oss";
const memory = new Memory();
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }
];
await memory.add(messages, { userId: "alice", metadata: { category: "movie_recommendations" } });
const results = await memory.search("What do you know about me?", { filters: { user_id: "alice" } });
console.log(results);
**Output**
{
"results": [
{
"id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e",
"memory": "User is planning to watch a movie tonight.",
"score": 0.38920719231944799,
"metadata": {
"category": "movie_recommendations"
},
"userId": "alice"
}
]
}
<Snippet />
By default the Node SDK uses local-friendly settings (OpenAI gpt-5-mini, text-embedding-3-small, in-memory vector store, and SQLite history). Pass a config to swap any of them.
Configure providers
Pass a config object to new Memory() to use your own LLM, embedder, and vector store:
import { Memory } from "mem0ai/oss";
const memory = new Memory({
llm: {
provider: "openai",
config: { apiKey: process.env.OPENAI_API_KEY || "", model: "gpt-4-turbo-preview" }
},
embedder: {
provider: "openai",
config: { apiKey: process.env.OPENAI_API_KEY || "", model: "text-embedding-3-small" }
},
vectorStore: {
provider: "memory",
config: { collectionName: "memories", dimension: 1536 }
}
});
For the full provider catalog, history stores, and every config option, see Configuration.
What's next?
Search, update, and manage memories with the full CRUD API.
Swap in your own LLM, embedder, and vector store.
Wire Mem0 into LangChain, CrewAI, LangGraph, and 20+ more.
If you have any questions, please feel free to reach out:
<Snippet />
Spin up the showcase companion app to see Mem0 memories in action.
Works with: Mem0 Platform
You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started.
<video />
You can try the Mem0 Demo live here.
Overview
The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates memories for each user interaction and integrates with OpenAI's GPT models to provide detailed and context-aware responses to user queries.
Setup
Before you begin, follow these steps to set up the demo application:
- Clone the Mem0 repository:
git clone https://github.com/mem0ai/mem0.git
- Navigate to the demo application folder:
cd mem0/examples/mem0-demo
- Install dependencies:
pnpm install
- Set up environment variables by creating a
.envfile in the project root with the following content:
OPENAI_API_KEY=your_openai_api_key
MEM0_API_KEY=your_mem0_api_key
You can obtain your MEM0_API_KEY by signing up at https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=cookbook-companions-quickstart.
- Start the development server:
pnpm run dev
Enhancing the Next.js Application
Once the demo is running, you can customize and enhance the Next.js application by modifying the components in the mem0-demo folder. Consider:
- Adding new memory features to improve contextual retention
- Customizing the UI to better suit your application needs
- Integrating additional APIs or third-party services to extend functionality
Full Code
You can find the complete source code for this demo on GitHub: Mem0 Demo GitHub
Conclusion
This setup demonstrates how to build an AI Companion that maintains memory across interactions using Mem0. The system continuously adapts to user interactions, making future responses more relevant and personalized. Experiment with the application and enhance it further to suit your use case!
Deep dive into production patterns for fitness coaches, tutors, and assistants.
Implement a command-line companion using the Node.js SDK.
<Snippet />
Install the Mem0 Python SDK, configure your environment, and store your first memory in under five minutes.
Get started with Mem0's Python SDK in under 5 minutes. This guide shows you how to install Mem0 and store your first memory.
Prerequisites
- Python 3.10 or higher
- OpenAI API key (Get one here)
Set your OpenAI API key:
export OPENAI_API_KEY="your-openai-api-key"
Uses OpenAI by default. Want to use Ollama, Anthropic, or local models? See Configuration.
Installation
pip install mem0ai
from mem0 import Memory
m = Memory()
messages = [
{"role": "user", "content": "Hi, I'm Alex. I love basketball and gaming."},
{"role": "assistant", "content": "Hey Alex! I'll remember your interests."}
]
m.add(messages, user_id="alex")
results = m.search("What do you know about me?", filters={"user_id": "alex"})
print(results)
**Output:**
{
"results": [
{
"id": "mem_123abc",
"memory": "Name is Alex. Enjoys basketball and gaming.",
"user_id": "alex",
"categories": ["personal_info"],
"created_at": "2025-10-22T04:40:22.864647-07:00",
"score": 0.89
}
]
}
<Snippet />
By default Memory() wires up:
- OpenAI
gpt-5-minifor fact extraction and updates - OpenAI
text-embedding-3-smallembeddings (1536 dimensions) - Qdrant vector store with on-disk data at
/tmp/qdrant - SQLite history at
~/.mem0/history.db - No reranker (add one in the config when you need it)
What's next?
Search, update, and manage memories with the full CRUD API.
Swap in your own LLM, embedder, and vector store.
Wire Mem0 into LangChain, CrewAI, LangGraph, and 20+ more.
If you have any questions, please feel free to reach out:
<Snippet />
Add persistent, self-improving memory to your AI app with Mem0 Platform or self-hosted Open Source.
<div> # Build with <span>Mem0</span>
<p> Mem0 gives your AI agents long-term memory that persists across sessions, tools, and runs. </p> </div>
<section> <div> [/platform/quickstart]( <img alt="Mem0 Platform thumbnail" />
<img alt="Mem0 Platform thumbnail" />
<div>
### Store your first memory
<p>
Five-minute quickstart: get an API key, then save and search a memory in Python or JavaScript.
</p>
</div>
)
[/integrations/claude-code](
<img alt="Integrations thumbnail" />
<img alt="Integrations thumbnail" />
<div>
### Add memory to your coding agent
<p>
Start with Claude Code, then choose the individual guide for Cursor, Codex, Kimi Code, OpenCode, OpenClaw, Pi Agent, DeepSeek Harness, or Antigravity.
</p>
</div>
)
[/platform/agent-signup](
<img alt="Sign up as an agent thumbnail" />
<img alt="Sign up as an agent thumbnail" />
<div>
### Let an AI agent sign itself up
<p>
Four terminal commands create an account and API key. No email, no dashboard. Claim it as owner later.
</p>
</div>
)
[/integrations](
<img alt="Integrations thumbnail" />
<img alt="Integrations thumbnail" />
<div>
### Use Mem0 with your framework
<p>
Setup guides for 22 tools, including LangChain, CrewAI, LlamaIndex, and the Vercel AI SDK.
</p>
</div>
)
[/cookbooks/overview](
<img alt="Cookbooks thumbnail" />
<img alt="Cookbooks thumbnail" />
<div>
### Copy a working example
<p>
Full walkthroughs for companion chatbots, support agents, voice agents, and research tools.
</p>
</div>
)
[/open-source/overview](
<img alt="Mem0 Open Source thumbnail" />
<img alt="Mem0 Open Source thumbnail" />
<div>
### Run Mem0 on your own servers
<p>
The open-source version. Run it as a library or a Docker stack, with your data on your infrastructure.
</p>
</div>
)
</div> </section>
