Skip to main content
Glama
README.md11 kB
# Mem0 - The Memory Layer for Your AI Apps 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. ## 1. Installation Install the Mem0 package: ```bash npm i mem0ai ``` ## 2. API Key Setup 1. Sign in to [Mem0 Platform](https://app.mem0.ai/dashboard/api-keys) 2. Copy your API Key from the dashboard ## 3. Instantiate Client For **ESM** usage: ```javascript import MemoryClient from 'mem0ai'; const apiKey = 'your-api-key-here'; const client = new MemoryClient({ apiKey: apiKey, organizationId: 'your-organization-id-here', // Optional projectId: 'your-project-id-here' // Optional }); ``` **Note**: If you are passing `organizationId`, you must also pass `projectId`. Either pass both `organizationId` and `projectId` or none. Alternatively, you can set the `MEM0_API_KEY` environment variable and instantiate the client without passing the API key: ## 4. Memory Operations Mem0 provides a simple and customizable interface for performing CRUD operations on memory. ### 4.1 Create Memories You can create long-term and short-term memories for your users, AI Agents, etc. Here are some examples: #### Long-term memory for a user ```javascript 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)); ``` #### Short-term memory for a user session ```javascript 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", run_id: "trip-planning-2024" }) .then(result => console.log(result)) .catch(error => console.error(error)); ``` #### Long-term memory for agents ```javascript 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)); ``` #### Infer Memories By default, Mem0 will infer memories based on the content of the messages. You can disable this behavior by passing `infer: false` in the options and directly store the messages. ```javascript 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", infer: false }) .then(result => console.log(result)) .catch(error => console.error(error)); ``` ### 4.2 Search Relevant Memories You can search for relevant memories using both v1 and v2 of the API: #### V1 Search (Default) ```javascript 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)); ``` #### V2 Search ```javascript 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. ### 4.3 Get All Memories Fetch all memories for a user, agent, or session using the getAll() method. #### Get all memories of an AI Agent ```javascript client.getAll({ agent_id: "travel-assistant" }) .then(memories => console.log(memories)) .catch(error => console.error(error)); ``` #### Get all memories of a user ```javascript client.getAll({ user_id: "alex" }) .then(memories => console.log(memories)) .catch(error => console.error(error)); ``` #### Get short-term memories for a session ```javascript client.getAll({ user_id: "alex123", run_id: "trip-planning-2024" }) .then(memories => console.log(memories)) .catch(error => console.error(error)); ``` #### Get all memories (V2 endpoint) The v2 endpoint offers more filters and users can search for memories by using custom filters such as `OR`, `AND` etc. ```javascript const options = { filters: { OR: [ { user_id: "alex" }, { agent_id: "shopping-assistant" } ] }, api_version: 'v2' }; const memories = await client.getAll(options); ``` #### Get specific memory ```javascript client.get("memory-id-here") .then(memory => console.log(memory)) .catch(error => console.error(error)); ``` #### Get all memories with pagination ```javascript // Get memories with pagination (50 items per page) client.getAll({ user_id: "alex", page: 1, page_size: 50 }) .then(memories => console.log(memories)) .catch(error => console.error(error)); ``` The paginated response includes: - `count`: Total number of memories - `next`: URL for the next page (null if no more pages) - `previous`: URL for the previous page (null if on first page) - `results`: Array of memories for the current page ### 4.4 Get all users Get all users for which you have memories. ```javascript client.users() .then(users => console.log(users)) .catch(error => console.error(error)); ``` ### 4.5 Memory History Get history of how a memory has changed over time: ```javascript // 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)); ``` ### 4.6 Delete Memory Delete specific memory: ```javascript client.delete("memory-id-here") .then(result => console.log(result)) .catch(error => console.error(error)); ``` Delete all users for which you have memories: ```javascript client.deleteUsers() .then(result => console.log(result)) .catch(error => console.error(error)); ``` Delete all memories of a user: ```javascript 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: ```javascript client.add("Delete all of my food preferences", { user_id: "alex" }) .then(result => console.log(result)) .catch(error => console.error(error)); ``` ## 5. Error Handling The MemoryClient throws errors for any API-related issues. You can catch and handle these errors as follows: ```javascript 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); } } ``` ## 6. Using with async/await All methods of the MemoryClient return promises, so you can use them with async/await: ```javascript 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(); ``` ## 7. Testing the Client To test the MemoryClient in a Node.js environment, you can create a simple script: ```javascript // 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: ```bash 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. ## Getting Help If you have any questions or need assistance, please reach out to us: - Email: founders@mem0.ai - [Join our discord community](https://mem0.ai/discord) - [Join our slack community](https://mem0.ai/slack) - GitHub Issues: [Report bugs or request features](https://github.com/mem0ai/mem0ai-node/issues)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sadiuysal/mem0-mcp-server-ts'

If you have feedback or need assistance with the MCP directory API, please join our Discord server