This guide covers advanced memory operations including complex filtering, batch operations, and detailed API usage. If you’re just getting started, check out the Quickstart first.

Advanced Memory Creation

Async Client (Python)

For asynchronous operations in Python, use the AsyncMemoryClient:
Python
import os
from mem0 import AsyncMemoryClient

os.environ["MEM0_API_KEY"] = "your-api-key"
client = AsyncMemoryClient()

async def main():
    messages = [
        {"role": "user", "content": "I'm travelling to SF"}
    ]
    response = await client.add(messages, user_id="john")
    print(response)

await main()

Detailed Memory Creation Examples

Long-term memory with full context

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", metadata={"food": "vegan"})
When passing user_id, memories are primarily created based on user messages, but may be influenced by assistant messages for contextual understanding. For example, in a conversation about food preferences, both the user’s stated preferences and their responses to the assistant’s questions would form user memories. Similarly, when using agent_id, assistant messages are prioritized, but user messages might influence the agent’s memories based on context.Example:
User: My favorite cuisine is Italian
Assistant: Nice! What about Indian cuisine?
User: Don't like it much since I cannot eat spicy food

Resulting user memories:
memory1 - Likes Italian food
memory2 - Doesn't like Indian food since cannot eat spicy 

(memory2 comes from user's response about Indian cuisine)
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 sessions

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="alex", run_id="trip-planning-2024")

Agent memories

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

client.add(messages, agent_id="ai-tutor")
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.

Dual user and agent memories

When you provide both user_id and agent_id, Mem0 will store memories for both identifiers separately:
  • Memories from messages with "role": "user" are automatically tagged with the provided user_id
  • Memories from messages with "role": "assistant" are automatically tagged with the provided agent_id
  • During retrieval, you can provide either user_id or agent_id to access the respective memories
  • You can continuously enrich existing memory collections by adding new memories to the same user_id or agent_id in subsequent API calls, either together or separately, allowing for progressive memory building over time
  • This dual-tagging approach enables personalized experiences for both users and AI agents in your application
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")

Advanced Search Operations

Search with 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, ). The wildcard character () matches everything for a specific field. 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 = {
   "OR":[
      {
         "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

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

Example 4: Search using NOT filters

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

Example 5: Search using wildcard filters

query = "What do you know about me?"
filters = {
    "AND": [
        {
            "user_id": "alex"
        },
        {
            "run_id": "*"  # Matches all run_ids
        }
    ]
}
client.search(query, version="v2", filters=filters)

Advanced Retrieval Operations

Get All Memories with Pagination

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.

Get all memories of a user

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

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, ). The wildcard character () matches everything for a specific field. Here you need to define version as v2 in the get_all method.
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)

Memory Management Operations

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)

Update Memory

Update a memory with new data. You can update the memory’s text, metadata, or both.
client.update(
    memory_id="<memory-id-here>",
    text="I am now a vegetarian.", 
    metadata={"diet": "vegetarian"}
)

Batch Operations

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)

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)

Entity Management

Get All Users

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

Delete Operations

Delete specific memory:
client.delete(memory_id)
Delete all memories of a user:
client.delete_all(user_id="alex")
Delete specific user or agent:
# Delete specific user
client.delete_users(user_id="alex")

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

Reset Client

client.reset()

Natural Language Delete

You can also delete memories using natural language commands:
messages = [
    {"role": "user", "content": "Delete all of my food preferences"}
]
client.add(messages, user_id="alex")

Monitor Memory Operations

You can monitor memory operations on the platform dashboard: Mem0 Platform Activity For more detailed information, see our API Reference or explore specific features in the Platform Features section.