🎉 Looking for TypeScript support? Mem0 has you covered! Check out an example here.

1. Installation

pip install mem0ai

2. API Key Setup

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

3. Instantiate Client

import os
from mem0 import MemoryClient

os.environ["MEM0_API_KEY"] = "your-api-key"

client = MemoryClient()

3.1 Instantiate Async Client (Python only)

For asynchronous operations in Python, you can use the AsyncMemoryClient:

Python
import os
from mem0 import AsyncMemoryClient

os.environ["MEM0_API_KEY"] = "your-api-key"

client = AsyncMemoryClient()


async def main():
    response = await client.add("I'm travelling to SF", user_id="john")
    print(response)

await main()

4. Memory Operations

Mem0 provides a simple and customizable interface for performing CRUD operations on memory.

4.1 Create Memories

Long-term memory for a user

These memory instances persist across multiple sessions. Ideal for maintaining memory over long time spans.

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."}
]

# The default output_format is v1.0
client.add(messages, user_id="alex", output_format="v1.0", version="v2")

# To use the latest output_format, set the output_format parameter to "v1.1"
client.add(messages, user_id="alex", output_format="v1.1", metadata={"food": "vegan"}, version="v2")
The add method offers support for two output formats: v1.0 (default) and v1.1. To enable the latest format, which provides enhanced detail for each memory operation, set the output_format parameter to v1.1.

Messages passed along with user_id, run_id, or app_id are stored as user memories, while messages from the assistant are excluded from memory. To store messages for the assistant, use agent_id exclusively and avoid including other IDs, such as user_id, alongside it. This ensures the memory is properly attributed to the assistant.

Metadata allows you to store structured information (location, timestamp, user state) with memories. Add it during creation to enable precise filtering and retrieval during searches.

Short-term memory for a user session

These memory instances persist only for the duration of a user session. Ideal for non-repetitive interactions and managing context windows efficiently.

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."}
]

# The default output_format is v1.0
client.add(messages, user_id="alex", run_id="trip-planning-2024", output_format="v1.0", version="v2")

# To use the latest output_format, set the output_format parameter to "v1.1"
client.add(messages, user_id="alex", run_id="trip-planning-2024", output_format="v1.1", version="v2")

Long-term memory for agents

Add a memory layer for the assistants and agents so that their responses remain consistent across sessions.

messages = [
    {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."},
    {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."}
]

# The default output_format is v1.0
client.add(messages, agent_id="ai-tutor", output_format="v1.0", version="v2")

# To use the latest output_format, set the output_format parameter to "v1.1"
client.add(messages, agent_id="ai-tutor", output_format="v1.1", version="v2")

The agent_id retains memories exclusively based on messages generated by the assistant or those explicitly provided as input to the assistant. Messages outside these criteria are not stored as memory.

Long-term memory for both users and agents

When you provide both user_id and agent_id, Mem0 will store memories with both identifiers attached:

  • Each memory will be tagged with both the specified user_id and agent_id
  • During retrieval, you’ll need to provide both IDs to access the memories
  • This enables tracking the full context of conversations between specific users and agents
messages = [
    {"role": "user", "content": "I'm travelling to San Francisco"},
    {"role": "assistant", "content": "That's great! I'm going to Dubai next month."},
]

client.add(messages=messages, user_id="user1", agent_id="agent1", version="v2")

Setting Memory Expiration Date

You can set an expiration date for memories, after which they will no longer be retrieved in searches. This is useful for creating temporary memories or memories that are only relevant for a specific time period.

import datetime

messages = [
    {
        "role": "user", 
        "content": "I'll be in San Francisco until August 31st."
    }
]

# Set an expiration date for this memory
client.add(messages=messages, user_id="alex", expiration_date=str(datetime.datetime.now().date() + datetime.timedelta(days=30)))

# You can also use an explicit date string
client.add(messages=messages, user_id="alex", expiration_date="2023-08-31")

Once a memory reaches its expiration date, it won’t be included in search or get results.

Monitor Memories

You can monitor memory operations on the platform dashboard:

4.2 Search Memories

Pass user messages, interactions, and queries into our search method to retrieve relevant memories.

The search method supports two output formats: v1.0 (default) and v1.1. To use the latest format, which provides more detailed information about each memory operation, set the output_format parameter to v1.1:
query = "What should I cook for dinner today?"

# The default output_format is v1.0
client.search(query, user_id="alex", output_format="v1.0")

# To use the latest output_format, set the output_format parameter to "v1.1"
client.search(query, user_id="alex", output_format="v1.1")

Use category and metadata filters:

query = "What do you know about me?"

client.search(query, categories=["food_preferences"], metadata={"food": "vegan"})

Search using custom filters

Our advanced search allows you to set custom search filters. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and text. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see V2 Search Memories.

Here you need to define version as v2 in the search method.

Example 1: Search using user_id and agent_id filters

query = "What do you know about me?"
filters = {
   "AND":[
      {
         "user_id":"alex"
      },
      {
         "agent_id":{
            "in":[
               "travel-assistant",
               "customer-support"
            ]
         }
      }
   ]
}
client.search(query, version="v2", filters=filters)

Example 2: Search using date filters

query = "What do you know about me?"
filters = {
    "AND": [
        {"created_at": {"gte": "2024-07-20", "lte": "2024-07-10"}},
        {"user_id": "alex"}
    ]
}
client.search(query, version="v2", filters=filters)

Example 3: Search using metadata and categories Filters

query = "What do you know about me?"
filters = {
    "AND": [
        {"metadata": {"food": "vegan"}},
        {
         "categories":{
            "contains": "food_preferences"
         }
    }
    ]
}
client.search(query, version="v2", filters=filters)

4.3 Get All Users

Get all users, agents, and runs which have memories associated with them.

client.users()

4.4 Get All Memories

Fetch all memories for a user, agent, or run using the getAll() method.

The get_all method supports two output formats: v1.0 (default) and v1.1. To use the latest format, which provides more detailed information about each memory operation, set the output_format parameter to v1.1:
We’re soon deprecating the default output format for get_all() method, which returned a list. Once the changes are live, paginated response will be the only supported format, with 100 memories per page by default. You can customize this using the page and page_size parameters.

The following examples showcase the paginated output format.

Get all memories of a user

memories = client.get_all(user_id="alex", page=1, page_size=50)

Get all memories of an AI Agent

agent_memories = client.get_all(agent_id="ai-tutor", page=1, page_size=50)

Get the short-term memories for a session

short_term_memories = client.get_all(user_id="alex", run_id="trip-planning-2024", page=1, page_size=50)

Get specific memory

memory = client.get(memory_id="582bbe6d-506b-48c6-a4c6-5df3b1e63428")

Get all memories by categories

You can filter memories by their categories when using get_all:

# Get memories with specific categories
memories = client.get_all(user_id="alex", categories=["likes"])

# Get memories with multiple categories
memories = client.get_all(user_id="alex", categories=["likes", "food_preferences"])

# Custom pagination with categories
memories = client.get_all(user_id="alex", categories=["likes"], page=1, page_size=50)

# Get memories with specific keywords
memories = client.get_all(user_id="alex", keywords="to play", page=1, page_size=50)

Get all memories using custom filters

Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see v2 Get Memories.

Here you need to define version as v2 in the get_all method.

Example 1. Get all memories using user_id and date filters

filters = {
   "AND":[
      {
         "user_id":"alex"
      },
      {
         "created_at":{
            "gte":"2024-07-01",
            "lte":"2024-07-31"
         }
      },
      {
         "categories":{
            "contains": "food_preferences"
         }
      }
   ]
}

# Default (No Pagination)
client.get_all(version="v2", filters=filters)

# Pagination (You can also use the page and page_size parameters)
client.get_all(version="v2", filters=filters, page=1, page_size=50)

Example 2: Search using metadata and categories Filters

filters = {
    "AND": [
        {"metadata": {"food": "vegan"}},
        {
         "categories":{
            "contains": "food_preferences"
         }
    }
    ]
}
# Default (No Pagination)
client.get_all(version="v2", filters=filters)

# Pagination (You can also use the page and page_size parameters)
client.get_all(version="v2", filters=filters, page=1, page_size=50)

4.5 Memory History

Get history of how a memory has changed over time.

# Add some message to create history
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")

# Add second message to update history
messages.append({'role': 'user', 'content': 'I turned vegetarian now.'})
client.add(messages, user_id="alex")

# Get history of how memory changed over time
memory_id = "<memory-id-here>"
history = client.history(memory_id)

4.6 Update Memory

Update a memory with new data.

message = "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."
client.update(memory_id, message)

4.7 Delete Memory

Delete specific memory.

client.delete(memory_id)

Delete all memories of a user.

client.delete_all(user_id="alex")

Delete all users.

client.delete_users()

Delete specific user or agent or app or run.

# Delete specific user
client.delete_users(user_id="alex")

# Delete specific agent
# client.delete_users(agent_id="travel-assistant")

4.8 Reset Client

client.reset()

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

4.9 Batch Update Memories

Update multiple memories in a single API call. You can update up to 1000 memories at once.

update_memories = [
    {
        "memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496",
        "text": "Watches football"
    },
    {
        "memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07",
        "text": "Loves to travel"
    }
]

response = client.batch_update(update_memories)
print(response)

4.10 Batch Delete Memories

Delete multiple memories in a single API call. You can delete up to 1000 memories at once.

delete_memories = [
    {"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"},
    {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"}
]

response = client.batch_delete(delete_memories)
print(response)

4.11 Working with Mem0 in TypeScript

Manage memories using TypeScript with Mem0. Mem0 has completet TypeScript support Below is an example demonstrating how to add and search memories.

import MemoryClient, { Message, SearchOptions, MemoryOptions }  from 'mem0ai';

const apiKey = 'your-api-key-here';
const client = new MemoryClient(apiKey);

// Messages
const messages: Message[] = [
    { 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." }
];

// ADD
const memoryOptions: MemoryOptions = {
    user_id: "alex",
    agent_id: "travel-assistant"
}

client.add(messages, memoryOptions)
  .then(result => console.log(result))
  .catch(error => console.error(error));

// SEARCH
const query: string = "What do you know about me?";
const searchOptions: SearchOptions = {
    user_id: "alex",
    filters: {
        OR: [
          { agent_id: "travel-assistant" },
          { user_id: "alex" }
        ]
      },
      threshold: 0.1,
      api_version: 'v2'
}
  
client.search(query, searchOptions)
.then(results => console.log(results))
.catch(error => console.error(error));

If you have any questions, please feel free to reach out to us using one of the following methods: