Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users.
Get started with Mem0 Platform in minutes using the Node.js client.
Install the Mem0 package:
npm i mem0ai
- Sign in to Mem0 Platform
- Copy your API Key from the dashboard
import MemoryClient from 'mem0ai';
const apiKey = 'your-api-key-here';
const client = new MemoryClient(apiKey);
Alternatively, you can set the MEM0_API_KEY
environment variable and instantiate the client without passing the API key:
import MemoryClient from 'mem0ai';
const client = new MemoryClient(process.env.MEM0_API_KEY);
Mem0 provides a simple and customizable interface for performing CRUD operations on memory.
You can create long-term and short-term memories for your users, AI Agents, etc. Here are some examples:
const messages = [
{ role: "user", content: "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts." },
{ role: "assistant", content: "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions." }
];
client.add(messages, { user_id: "alex" })
.then(result => console.log(result))
.catch(error => console.error(error));
const messages = [
{ role: "user", content: "I'm planning a trip to Japan next month." },
{ role: "assistant", content: "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?" },
{ role: "user", content: "Yes, please! Especially in Tokyo." },
{ role: "assistant", content: "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction." }
];
client.add(messages, { user_id: "alex123", session_id: "trip-planning-2024" })
.then(result => console.log(result))
.catch(error => console.error(error));
const messages = [
{ role: "system", content: "You are a personalized travel assistant. Remember user preferences and provide tailored recommendations." },
{ role: "assistant", content: "Understood. I'll maintain personalized travel preferences for each user and provide customized recommendations based on their dietary restrictions, interests, and past interactions." }
];
client.add(messages, { agent_id: "travel-assistant" })
.then(result => console.log(result))
.catch(error => console.error(error));
You can search for relevant memories using both v1 and v2 of the API:
const query = "What do you know about me?";
const options = { user_id: "alex" };
client.search(query, options)
.then(results => console.log(results))
.catch(error => console.error(error));
const query = "What do you know about me?";
const options = {
filters: {
OR: [
{ agent_id: "travel-assistant" },
{ user_id: "alex" }
]
},
threshold: 0.1,
api_version: 'v2'
};
client.search(query, options)
.then(results => console.log(results))
.catch(error => console.error(error));
This example demonstrates a more advanced V2 search:
- It searches for dietary preferences
- Filters results to only include memories associated with either the "travel-assistant" agent or the user "alex"
- Sets a similarity threshold of 0.1 to include more potentially relevant results
You can adjust the query
, filters
, and threshold
as needed for your specific use case.
Fetch all memories for a user, agent, or session using the getAll() method.
client.getAll({ agent_id: "travel-assistant" })
.then(memories => console.log(memories))
.catch(error => console.error(error));
client.getAll({ user_id: "alex" })
.then(memories => console.log(memories))
.catch(error => console.error(error));
client.getAll({ user_id: "alex123", session_id: "trip-planning-2024" })
.then(memories => console.log(memories))
.catch(error => console.error(error));
The v2 endpoint offers more filters and users can search for memories by using custom filters such as OR
, AND
etc.
const options = {
filters: {
OR: [
{ user_id: "alex" },
{ agent_id: "shopping-assistant" }
]
},
api_version: 'v2'
};
const memories = await client.getAll(options);
client.get("memory-id-here")
.then(memory => console.log(memory))
.catch(error => console.error(error));
Get all users for which you have memories.
client.users()
.then(users => console.log(users))
.catch(error => console.error(error));
Get history of how a memory has changed over time:
// Add some message to create history
let messages = [{ role: "user", content: "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.." }];
client.add(messages, { user_id: "alex" })
.then(result => {
// Add second message to update history
messages.push({ role: 'user', content: 'I turned vegetarian now.' });
return client.add(messages, { user_id: "alex" });
})
.then(result => {
// Get history of how memory changed over time
const memoryId = result.id; // Assuming the API returns the memory ID
return client.history(memoryId);
})
.then(history => console.log(history))
.catch(error => console.error(error));
Delete specific memory:
client.delete("memory-id-here")
.then(result => console.log(result))
.catch(error => console.error(error));
Delete all users for which you have memories:
client.deleteUsers()
.then(result => console.log(result))
.catch(error => console.error(error));
Delete all memories of a user:
client.deleteAll({ user_id: "alex" })
.then(result => console.log(result))
.catch(error => console.error(error));
Fun fact: You can also delete the memory using the add()
method by passing a natural language command:
client.add("Delete all of my food preferences", { user_id: "alex" })
.then(result => console.log(result))
.catch(error => console.error(error));
The MemoryClient throws errors for any API-related issues. You can catch and handle these errors as follows:
try {
const result = await client.add(messages, { user_id: "alex" });
console.log(result);
} catch (error) {
if (error.name === 'APIError') {
console.error('API Error:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
All methods of the MemoryClient return promises, so you can use them with async/await:
async function addMemory() {
try {
const messages = [
{ role: "user", content: "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts." },
{ role: "assistant", content: "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions." }
];
const result = await client.add(messages, { user_id: "alex" });
console.log('Memory added:', result);
const searchResult = await client.search("What are Alex's dietary restrictions?", { user_id: "alex" });
console.log('Search result:', searchResult);
} catch (error) {
console.error('Error:', error);
}
}
addMemory();
To test the MemoryClient in a Node.js environment, you can create a simple script:
// test-mem0.js
import MemoryClient from 'mem0ai';
const apiKey = 'your-api-key-here';
const client = new MemoryClient(apiKey);
async function testMemoryOperations() {
try {
// Add a memory
const addResult = await client.add([
{ role: "user", content: "My favorite color is blue." }
], { user_id: "test-user" });
console.log('Memory added:', addResult);
// Search for memories
const searchResult = await client.search("What's my favorite color?", { user_id: "test-user" });
console.log('Search result:', searchResult);
// Get all memories
const allMemories = await client.getAll({ user_id: "test-user" });
console.log('All memories:', allMemories);
} catch (error) {
console.error('Error:', error);
}
}
testMemoryOperations();
Run this script using Node.js:
node test-mem0.js
This will perform basic operations (add, search, getAll) and log the results, allowing you to verify that the client is working correctly with your API key.
Remember to replace 'your-api-key-here' with your actual Mem0 API key when testing.
If you have any questions or need assistance, please reach out to us:
- Email: founders@mem0.ai
- Join our discord community
- Join our slack community
- GitHub Issues: Report bugs or request features