All Products
Search
Document Center

AnalyticDB:AnalyticDB for MySQL + Mem0 User Guide

Last Updated:Mar 11, 2026

Mem0 ("mem-zero") is an intelligent memory layer designed for AI applications. It transforms stateless AI Agents into intelligent systems with context awareness and persistent memory capabilities through automated memory extraction, integration, and retrieval. This tutorial guides you through Agent memory management using AnalyticDB for MySQL + Mem0. It covers core operations such as adding, retrieving, updating, searching, deleting, and tracing memory history, helping you quickly build AI applications with long-term memory capabilities.

Preparations

Before you begin, complete the following preparations:

  1. Create an AnalyticDB for MySQL cluster, and ensure its version supports vector retrieval (such as cosine similarity). For more information, see Quick Start for Enterprise, Basic, and Data Lakehouse Editions.

  2. Obtain the Mem0 framework version that supports AnalyticDB for MySQL.

    Note

    Contact Alibaba Cloud Service Support via DingTalk (DingTalk account: x5v_rm8wqzuqf) to get the installation package.

  3. Obtain a model service API key. This tutorial uses Alibaba Cloud Model Studio. Activate the service and get an API key. For more information, see Get an API Key.

User Guide

Environment Setup

  • Prepare AnalyticDB for MySQL

    1. Create a database in your AnalyticDB for MySQL cluster for this tutorial.

      CREATE DATABASE mem0;
    2. If you plan to connect via the public network, enable public network access for the cluster in the AnalyticDB for MySQL console, and add the public IP address of your demo environment to the whitelist.

  • Install Mem0 and dependencies

    1. Check your Python environment: Ensure Python is installed in your environment. This tutorial is validated with Python 3.12.2.

      # For Mac, check Python version. If not installed, install from https://www.python.org/
      python3 --version
      
      # For Linux, check Python version. If not installed, install using yum: sudo yum install python
      python --version
    2. Install the Mem0 framework: Unzip the Mem0 framework file you obtained and install the necessary dependency libraries.

      # Unzip and install
      unzip mem0.zip 
      cd mem0
      pip install .
      pip install pymysql dbutils

Configure and Initialize

  • Configure environment variables:

    For security, configure the Large Language Model (LLM) API key as an environment variable.

    echo "export DASHSCOPE_API_KEY='<YOUR_DASHSCOPE_API_KEY>'" >> ~/.bashrc
    # Optional; defaults to Singapore
    echo "export DASHSCOPE_BASE_URL='https://dashscope-intl.aliyuncs.com/compatible-mode/v1'" >> ~/.bashrc   
    
    source ~/.bashrc
    
    # Check if it took effect
    echo $DASHSCOPE_API_KEY
    echo $DASHSCOPE_BASE_URL  
  • Initialize a Mem0 instance:

    In your Python script, configure and initialize a Memory instance.

    • LLM configuration: Use the Alibaba Cloud Model Studio qwen-plus model.

    • Embedder configuration: Use the Alibaba Cloud Model Studio text-embedding-v4 model, with vector dimensions of 1536.

    • Vector Store configuration: Use aliyun_adb, and enter your AnalyticDB for MySQL connection information.

    from mem0 import Memory
    
    # This example must connect to an adb instance with 1536 vector dimensions specified.
    config = {
        "llm": {
            "provider": "bailian",
            "config": {"model": "qwen-plus"},
        },
        "embedder": {
            "provider": "bailian",
            "config": {"model": "text-embedding-v4", "embedding_dims": 1536},
        },
        "vector_store": {
            "provider": "aliyun_adb",
            "config": {
                "host": "<adb host>",
                "port": 3306,
                "database": "mem0",
                "user": "<your user name>",
                "password": "<your password>",
                "collection_name": "adb_mem0_demo"
            }
        }
    }
    
    
    """
    Suppose we have two users, Mike and Julia
    1、Mike is a vegetarian, who likes fruit and playing basketball
    2、Julia is a carnivore, who likes steak and playing badminton
    """
    
    m = Memory.from_config(config_dict=config)

Core Memory Operations Demo

  • Add and retrieve memories:

    Use the m.add() method to add memories for a user, and the m.get_all() method to retrieve all memories for a user.

    • Code

      # Add memories for Mike
      result = m.add("I'm a vegetarian", user_id="Mike")
      memory_id = result["results"]["id"]
      print("add a memory for Mike:" + "I'm a vegetarian" + ", result => ", result , "\n")
      
      
      result = m.add("I like durian", user_id="Mike")
      print("add a memory for Mike:" + "I like durian" + ", result => " , result , "\n")
      
      # Get all memories for a user
      result = m.get_all(user_id="Mike")
      print("Get all memories for a user:" + "Mike" + ", result => " , result , "\n")
    • Result analysis
      The returned result is a list containing Mike's two memories and their metadata, such as ID, content, and creation time.

      add a memory for Mike:I'm a vegetarian, result =>  {'results': [{'id': '32ac2932-10da-422b-beba-bb5a2b4666aa', 'memory': "I'm a vegetarian", 'event': 'ADD'}]} 
      
      add a memory for Mike:I like durian, result =>  {'results': [{'id': '40098c00-9f96-4486-af8b-5c79612fea10', 'memory': 'I like durian', 'event': 'ADD'}]} 
      
      Get all memories for a user:Mike, result =>  {'results': [{'id': '40098c00-9f96-4486-af8b-5c79612fea10', 'memory': 'I like durian', 'hash': 'dfd43e3d0a6ddc82cda440e0a1d39e7f', 'metadata': None, 'created_at': '2025-10-29T20:52:54.156926-07:00', 'updated_at': None, 'user_id': 'Mike'}, {'id': '32ac2932-10da-422b-beba-bb5a2b4666aa', 'memory': "I'm a vegetarian", 'hash': '27f3478f622dd27dd71969f131bd886f', 'metadata': None, 'created_at': '2025-10-29T20:52:51.126628-07:00', 'updated_at': None, 'user_id': 'Mike'}]} 
  • Update and delete memories:

    Mem0 supports manual deletion by memory ID or automatic conflict resolution when adding new memories.

    • Code

      result = m.delete(memory_id=memory_id)
      print("Manual Delete a memory:" + "I like durian" + ", result => " , result , "\n")
      
      result = m.add("I hate things that taste like durian", user_id="Mike")
      print("Automatic Delete a contradictory historical memory for Mike:" + "I like durian" + ", result => " , result , "\n")
      
      # Get all memories for a user
      result = m.get_all(user_id="Mike")
      print("Get all memories for a user:" + "Mike" + ", result => " , result , "\n")
    • Result analysis

      Manual Delete a memory:I like durian, result =>  {'message': 'Memory deleted successfully!'} 
      
      Automatic Delete a contradictory historical memory for Mike:I like durian, result =>  {'results': [{'id': 'dc308443-ae8c-4cb3-851f-060adfc39eaf', 'memory': 'I like durian', 'event': 'DELETE'}]} 
      
      Get all memories for a user:Mike, result =>  {'results': []} 
      • After adding a conflicting memory, the return result of the add method includes a DELETE event, indicating that the old, conflicting memory ("I like durian") was automatically removed.

      • When calling get_all again, you will find that the old memory no longer exists, demonstrating Mem0's adaptive and self-consistent capabilities.

  • Retrieve and search memories:

    Mem0 supports precise filtered retrieval using metadata and similarity search using semantics.

    1. Prepare data: Add memories with agent_id and metadata for Mike and Julia.

      • Code

        # Mike Memory
        result = m.add("I'm a vegetarian", user_id="Mike", agent_id="diet-assistant")
        print("add a memory for Mike:" + "I'm a vegetarian" + ", result => ", result , "\n")
        
        result = m.add("I like durian, watermelon and strawberries", user_id="Mike", metadata={"category": "hobbies"})
        print("add a memory for Mike with meta:" + "I like durian, watermelon and strawberries" + ", result => " , result , "\n")
        
        result = m.add("I like playing basketball", user_id="Mike", agent_id="fitness-assistant")
        print("add a memory for Mike:" + "I like playing basketball" + ", result => " , result , "\n")
        
        
        # Julia Memory
        result = m.add("I'm a carnivore", user_id="Julia", agent_id="diet-assistant")
        print("add a memory for Julia:" + "I'm a carnivore" + ", result => " , result , "\n")
        
        result = m.add("I like steak", user_id="Julia", metadata={"category": "hobbies"})
        print("add a memory for Julia:" + "I like steak" + ", result => " , result , "\n")
        
        result = m.add("I like playing badminton", user_id="Julia", agent_id="fitness-assistant")
        print("add a memory for Julia:" + "I like playing badminton" + ", result => " , result , "\n")
        
      • Result analysis

        add a memory for Mike:I'm a vegetarian, result =>  {'results': [{'id': 'a0fadb7e-c6b7-46b2-b0b8-6b036d879015', 'memory': "I'm a vegetarian", 'event': 'ADD'}]} 
        
        add a memory for Mike with meta:I like durian, watermelon and strawberries, result =>  {'results': [{'id': 'efec6c25-c2a7-454f-8344-367018c5b607', 'memory': 'I like durian, watermelon and strawberries', 'event': 'ADD'}]} 
        
        add a memory for Mike:I like playing basketball, result =>  {'results': [{'id': '75da451c-dbf7-45aa-b9ab-72aab54df7b8', 'memory': 'I like playing basketball', 'event': 'ADD'}]} 
        
        add a memory for Julia:I'm a carnivore, result =>  {'results': [{'id': '93a03639-195e-40ef-9f5f-55d366b76333', 'memory': "I'm a carnivore", 'event': 'ADD'}]} 
        
        add a memory for Julia:I like steak, result =>  {'results': [{'id': 'e30faceb-ba71-4b27-b052-28863f26abf9', 'memory': 'I like steak', 'event': 'ADD'}]} 
        
        add a memory for Julia:I like playing badminton, result =>  {'results': [{'id': '90d45867-b198-415f-99e8-7375b4c6c35b', 'memory': 'I like playing badminton', 'event': 'ADD'}]} 
    2. Precise filtered retrieval: Use the get_all method and pass filter conditions.

      • Code

        # Get all memories for a specific agent belonging to a user
        result = m.get_all(user_id="Mike", agent_id="fitness-assistant")
        print("Get all memories for a specific agent belonging to a user:" + "Mike" + ", result => " , result , "\n")
        
        
        # Get all memories belonging to a user with filter
        result = m.get_all(user_id="Julia", filters={"category": "hobbies"})
        print("Get all memories belonging to a user with filter:" + "Julia" + ", result => " , result , "\n")
      • Result analysis

        Get all memories for a specific agent belonging to a user:Mike, result =>  {'results': [{'id': '75da451c-dbf7-45aa-b9ab-72aab54df7b8', 'memory': 'I like playing basketball', 'hash': '000b24fa8e8f76134286d2c4626c036d', 'metadata': None, 'created_at': '2025-10-30T00:13:08.390949-07:00', 'updated_at': None, 'user_id': 'Mike', 'agent_id': 'fitness-assistant'}]} 
        
        Get all memories belonging to a user with filter:Julia, result =>  {'results': [{'id': 'e30faceb-ba71-4b27-b052-28863f26abf9', 'memory': 'I like steak', 'hash': '6e7129fc2010e93e94c943dbf6f69246', 'metadata': {'category': 'hobbies'}, 'created_at': '2025-10-30T00:13:14.631531-07:00', 'updated_at': None, 'user_id': 'Julia'}]} 
    3. Similarity search: Use the search method for semantic search. The results are sorted by similarity score (score) in descending order.

      • Code

        # Search memories for a user
        result = m.search("Who likes playing badminton better", agent_id="fitness-assistant")
        print("Search memories:" + "Who likes playing badminton better" + ", result => " , result , "\n")
        
        # Search memories for a specific agent belonging to a user
        result = m.search("Who will celebrate on International Vegetarian Day", agent_id="diet-assistant")
        print("Search memories:" + "Who will celebrate on International Vegetarian Day" + ", result => " , result , "\n")
        
        # Search memories for a user
        result = m.search("what kind of fruit do you like", user_id="Mike")
        print("Search memories:" + "what kind of fruit do you like." + ", result => " , result , "\n")
        
        # Search memories for a user
        result = m.search("what sport do you like", user_id="Julia", agent_id="fitness-assistant")
        print("Search memories:" + "what sport do you like." + ", result => " , result , "\n")
        
      • Result analysis

        Search memories:Who likes playing badminton better, result =>  {'results': [{'id': '90d45867-b198-415f-99e8-7375b4c6c35b', 'memory': 'I like playing badminton', 'hash': '304d03421834255d1650b46877b3785b', 'metadata': None, 'score': 0.82532454, 'created_at': '2025-10-30T00:13:18.218251-07:00', 'updated_at': None, 'user_id': 'Julia', 'agent_id': 'fitness-assistant'}, {'id': '75da451c-dbf7-45aa-b9ab-72aab54df7b8', 'memory': 'I like playing basketball', 'hash': '000b24fa8e8f76134286d2c4626c036d', 'metadata': None, 'score': 0.56634325, 'created_at': '2025-10-30T00:13:08.390949-07:00', 'updated_at': None, 'user_id': 'Mike', 'agent_id': 'fitness-assistant'}]} 
        
        Search memories:Who will celebrate on International Vegetarian Day, result =>  {'results': [{'id': 'a0fadb7e-c6b7-46b2-b0b8-6b036d879015', 'memory': "I'm a vegetarian", 'hash': '27f3478f622dd27dd71969f131bd886f', 'metadata': None, 'score': 0.5640734, 'created_at': '2025-10-30T00:13:01.011810-07:00', 'updated_at': None, 'user_id': 'Mike', 'agent_id': 'diet-assistant'}, {'id': '93a03639-195e-40ef-9f5f-55d366b76333', 'memory': "I'm a carnivore", 'hash': '5f81d3e6f06baba2e10ec6c155d012e3', 'metadata': None, 'score': 0.41749594, 'created_at': '2025-10-30T00:13:11.462159-07:00', 'updated_at': None, 'user_id': 'Julia', 'agent_id': 'diet-assistant'}]} 
        
        Search memories:what kind of fruit do you like., result =>  {'results': [{'id': 'efec6c25-c2a7-454f-8344-367018c5b607', 'memory': 'I like durian, watermelon and strawberries', 'hash': '07cc049e2beaa043bb359b50a33664ac', 'metadata': {'category': 'hobbies'}, 'score': 0.6519712, 'created_at': '2025-10-30T00:13:04.981195-07:00', 'updated_at': None, 'user_id': 'Mike'}, {'id': '75da451c-dbf7-45aa-b9ab-72aab54df7b8', 'memory': 'I like playing basketball', 'hash': '000b24fa8e8f76134286d2c4626c036d', 'metadata': None, 'score': 0.3975049, 'created_at': '2025-10-30T00:13:08.390949-07:00', 'updated_at': None, 'user_id': 'Mike', 'agent_id': 'fitness-assistant'}, {'id': 'a0fadb7e-c6b7-46b2-b0b8-6b036d879015', 'memory': "I'm a vegetarian", 'hash': '27f3478f622dd27dd71969f131bd886f', 'metadata': None, 'score': 0.3382097, 'created_at': '2025-10-30T00:13:01.011810-07:00', 'updated_at': None, 'user_id': 'Mike', 'agent_id': 'diet-assistant'}]} 
        
        Search memories:what sport do you like., result =>  {'results': [{'id': '90d45867-b198-415f-99e8-7375b4c6c35b', 'memory': 'I like playing badminton', 'hash': '304d03421834255d1650b46877b3785b', 'metadata': None, 'score': 0.61615115, 'created_at': '2025-10-30T00:13:18.218251-07:00', 'updated_at': None, 'user_id': 'Julia', 'agent_id': 'fitness-assistant'}]} 
        • Search for badminton: The agent_id filters out non-sports-related memories. "I like playing badminton" has the highest score and ranks first in the results.

        • Search for Vegetarian Day: The agent_id filters out non-diet-related memories. "I'm a vegetarian" has the highest score and ranks first in the results.

        • Search for Mike's fruit preferences: The user_id filters out Julia's memories. "I like durian, watermelon and strawberries" has the highest score.

        • Search for Julia's sports preferences: The user_id and agent_id provide a double filter, precisely returning "I like playing badminton".

  • Delete memories:

    Use the delete_all method to delete all memories for a specified user or agent.

    • Code

      # Delete all memories for a specific agent belonging to a user
      m.delete_all(user_id="Julia")
      result = m.get_all(user_id="Julia")
      print(result)
      
      # Delete all memories for a user
      m.delete_all(user_id="Mike")
      result = m.get_all(user_id="Mike")
      print(result)
    • Result analysis

      Resetting collection mem0_adb_demo...
      {'results': []}
      Resetting collection mem0_adb_demo...
      {'results': []}

Summary

This tutorial demonstrates how to combine Mem0 with AnalyticDB for MySQL to easily implement a series of intelligent management operations for AI Agent memories, such as adding, deleting, modifying, and querying. This combination provides a powerful, reliable, and easily extensible foundation for building complex AI applications capable of long-term, coherent conversations and personalized services.


Appendix: Complete Sample Code

For a quick experience, here is the complete Python script integrating all steps. Replace the placeholders (such as <YOUR_ADB_HOST>) with your actual configuration.

from mem0 import Memory

# This example must connect to an adb instance with 1536 vector dimensions specified.
config = {
    "llm": {
        "provider": "bailian",
        "config": {"model": "qwen-plus"},
    },
    "embedder": {
        "provider": "bailian",
        "config": {"model": "text-embedding-v4", "embedding_dims": 1536},
    },
    "vector_store": {
        "provider": "aliyun_adb",
        "config": {
            "host": "<adb host>",
            "port": 3306,
            "database": "mem0",
            "user": "<your user name>",
            "password": "<your passward>",
            "collection_name": "adb_mem0_demo"
        }
    }
}

"""
Suppose we have two users, Mike and Julia
1、Mike is a vegetarian, who likes fruit and playing basketball
2、Julia is a carnivore, who likes steak and playing badminton
"""

m = Memory.from_config(config_dict=config)

# add memory for mike
result = m.add("I'm a vegetarian", user_id="Mike")
memory_id = result["results"][0]["id"]
print("add a memory for Mike:" + "I'm a vegetarian" + ", result => ", result , "\n")


result = m.add("I like durian", user_id="Mike")
print("add a memory for Mike:" + "I like durian" + ", result => " , result , "\n")

# Get all memories for a user
result = m.get_all(user_id="Mike")
print("Get all memories for a user:" + "Mike" + ", result => " , result , "\n")

result = m.delete(memory_id=memory_id)
print("Manual Delete a memory:" + "I like durian" + ", result => " , result , "\n")

result = m.add("I hate things that taste like durian", user_id="Mike")
print("Automatic Delete a contradictory historical memory for Mike:" + "I like durian" + ", result => " , result , "\n")

# Get all memories for a user
result = m.get_all(user_id="Mike")
print("Get all memories for a user:" + "Mike" + ", result => " , result , "\n")

# Mike Memory
result = m.add("I'm a vegetarian", user_id="Mike", agent_id="diet-assistant")
print("add a memory for Mike:" + "I'm a vegetarian" + ", result => ", result , "\n")

result = m.add("I like durian, watermelon and strawberries", user_id="Mike", metadata={"category": "hobbies"})
print("add a memory for Mike with meta:" + "I like durian, watermelon and strawberries" + ", result => " , result , "\n")

result = m.add("I like playing basketball", user_id="Mike", agent_id="fitness-assistant")
print("add a memory for Mike:" + "I like playing basketball" + ", result => " , result , "\n")


# Julia Memory
result = m.add("I'm a carnivore", user_id="Julia", agent_id="diet-assistant")
print("add a memory for Julia:" + "I'm a carnivore" + ", result => " , result , "\n")

result = m.add("I like steak", user_id="Julia", metadata={"category": "hobbies"})
print("add a memory for Julia:" + "I like steak" + ", result => " , result , "\n")

result = m.add("I like playing badminton", user_id="Julia", agent_id="fitness-assistant")
print("add a memory for Julia:" + "I like playing badminton" + ", result => " , result , "\n")


# Get all memories for a specific agent belonging to a user
result = m.get_all(user_id="Mike", agent_id="fitness-assistant")
print("Get all memories for a specific agent belonging to a user:" + "Mike" + ", result => " , result , "\n")


# Get all memories belonging to a user with filter
result = m.get_all(user_id="Julia", filters={"category": "hobbies"})
print("Get all memories belonging to a user with filter:" + "Julia" + ", result => " , result , "\n")


# Search memories for a user
result = m.search("Who likes playing badminton better", agent_id="fitness-assistant")
print("Search memories:" + "Who likes playing badminton better" + ", result => " , result , "\n")

# Search memories for a specific agent belonging to a user
result = m.search("Who will celebrate on International Vegetarian Day", agent_id="diet-assistant")
print("Search memories:" + "Who will celebrate on International Vegetarian Day" + ", result => " , result , "\n")

# Search memories for a user
result = m.search("what kind of fruit do you like", user_id="Mike")
print("Search memories:" + "what kind of fruit do you like." + ", result => " , result , "\n")

# Search memories for a user
result = m.search("what sport do you like", user_id="Julia", agent_id="fitness-assistant")
print("Search memories:" + "what sport do you like." + ", result => " , result , "\n")

# Delete all memories for a specific agent belonging to a user
m.delete_all(user_id="Julia")
result = m.get_all(user_id="Julia")
print(result)

# Delete all memories for a user
m.delete_all(user_id="Mike")
result = m.get_all(user_id="Mike")
print(result)