npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

saket-test

v1.0.36

Published

The Memory Layer For Your AI Apps

Downloads

51

Readme

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:

npm i mem0ai

2. API Key Setup

  1. Sign in to Mem0 Platform
  2. Copy your API Key from the dashboard

3. Instantiate Client

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);

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

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

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));

Long-term memory for agents

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));

4.2 Search Relevant Memories

You can search for relevant memories using both v1 and v2 of the API:

V1 Search (Default)

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

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

client.getAll({ agent_id: "travel-assistant" })
  .then(memories => console.log(memories))
  .catch(error => console.error(error));

Get all memories of a user

client.getAll({ user_id: "alex" })
  .then(memories => console.log(memories))
  .catch(error => console.error(error));

Get short-term memories for a session

client.getAll({ user_id: "alex123", session_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.

const options = {
  filters: {
    OR: [
      { user_id: "alex" },
      { agent_id: "shopping-assistant" }
    ]
  },
  api_version: 'v2'
};
const memories = await client.getAll(options);

Get specific memory

client.get("memory-id-here")
  .then(memory => console.log(memory))
  .catch(error => console.error(error));

4.4 Get all users

Get all users for which you have memories.

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:

// 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:

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));

5. Error Handling

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);
  }
}

6. Using with async/await

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();

7. Testing the Client

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.

Getting Help

If you have any questions or need assistance, please reach out to us: