Mem0: Memory Layer for Personalized AI Applications

# Mem0: Memory Layer untuk Aplikasi AI yang Personalized Salah satu tantangan terbesar dalam membangun aplikasi AI adalah kemampuan untuk **mengingat** konteks dan preferensi pengguna lintas sesi. Se...

By Ruby Abdullah · · tutorial
Mem0AI MemoryLLMPersonalizationPython

Mem0: Memory Layer for Personalized AI Applications

One of the biggest challenges in building AI applications is the ability to remember user context and preferences across sessions. By default, LLMs like GPT or Claude have no persistent memory. Every conversation starts from scratch. This is where Mem0 comes in as a solution.

Mem0 is an open-source memory layer that allows your AI applications to store, retrieve, and manage memories intelligently. With Mem0, your chatbot can remember user preferences, interaction history, and other important context.

Why Mem0?

Imagine you're building an AI assistant for customer service. Without a memory layer, every time a customer reaches out, the AI has to ask for basic information again. With Mem0:

  • AI remembers customer names, preferences, and history
  • Responses become more personal and contextual
  • User experience improves dramatically
  • Operational efficiency increases

Mem0 uses semantic search to find relevant memories, not just keyword matching. This means the AI can understand context and retrieve information that is truly relevant.

Installation

First, install Mem0 using pip:

pip install mem0ai

To use full features with a vector database, also install optional dependencies:

pip install mem0ai[qdrant]

You'll also need an API key from OpenAI (default) or another LLM provider:

export OPENAIAPIKEY="sk-your-api-key-here"

Initializing Mem0

There are two ways to use Mem0: an in-memory version for development and a persistent version for production.

Basic Setup (In-Memory)

from mem0 import Memory

Initialize with default configuration

m = Memory()

Setup with Qdrant (Persistent)

from mem0 import Memory

config = {

"vectorstore": {

"provider": "qdrant",

"config": {

"host": "localhost",

"port": 6333,

"collectionname": "mem0memories"

}

},

"llm": {

"provider": "openai",

"config": {

"model": "gpt-4o-mini",

"temperature": 0.1

}

},

"embedder": {

"provider": "openai",

"config": {

"model": "text-embedding-3-small"

}

}

}

m = Memory.fromconfig(config)

Basic Memory Operations

Mem0 provides four main operations: add, get, search, and delete.

Adding Memories (Add)

# Add a memory for a specific user

result = m.add(

"I like black coffee without sugar and usually drink it in the morning",

userid="user123"

)

print(result)

Output: {'results': [{'id': '...', 'memory': 'Likes black coffee without sugar', 'event': 'ADD'}]}

Mem0 automatically extracts important information from the given text. Note that Mem0 doesn't store raw text but rather extracts facts from it.

Retrieving All Memories (Get)

# Get all memories for a specific user

memories = m.getall(userid="user123")

for memory in memories:

print(f"ID: {memory['id']}")

print(f"Memory: {memory['memory']}")

print(f"Created: {memory['createdat']}")

print("---")

# Semantic search - find relevant memories

results = m.search(

"What is this user's favorite drink?",

userid="user123"

)

for result in results:

print(f"Memory: {result['memory']}")

print(f"Score: {result['score']}")

Search uses semantic similarity, so the query "favorite drink" will find memories about "black coffee" even though the words are different.

Deleting Memories (Delete)

# Delete a specific memory by ID

m.delete(memoryid="memoryidhere")

Delete all memories for a user

m.deleteall(userid="user123")

Memory Types

Mem0 supports three different memory levels, each for different use cases.

1. User-Level Memory

Memories tied to a specific user that persist across all sessions:

# Store user preferences

m.add("I'm allergic to nuts and don't like spicy food", userid="user123")

m.add("I live in South Jakarta", userid="user123")

m.add("My favorite programming language is Python", userid="user123")

Retrieve user memories

usermemories = m.getall(userid="user123")

2. Session Memory

Memories tied to a specific conversation session:

# Store session context

sessionid = "session20260513001"

m.add(

"User is asking about how to deploy ML models to production",

userid="user123",

metadata={"sessionid": sessionid}

)

m.add(

"User has tried using Flask but experienced scaling issues",

userid="user123",

metadata={"sessionid": sessionid}

)

3. Agent Memory

Memories tied to a specific AI agent, useful when you have multiple agents:

# Agent-specific memory

m.add(

"Customer service agent should always greet customers by name",

agentid="csagent01"

)

m.add(

"Technical support agent should always ask for software version",

agentid="techagent01"

)

Retrieve agent memories

agentmemories = m.getall(agentid="csagent01")

Memory Categories

You can organize memories with metadata and categories:

# Add memories with category metadata

m.add(

"User has an Enterprise subscription plan",

userid="user123",

metadata={

"category": "account",

"priority": "high"

}

)

m.add(

"User prefers communication via email over phone calls",

userid="user123",

metadata={

"category": "preference",

"priority": "medium"

}

)

m.add(

"User uses macOS with Python 3.11",

userid="user123",

metadata={

"category": "technical",

"priority": "low"

}

)

Integration with OpenAI

Mem0 can be integrated directly with OpenAI to create chatbots with memory:

from openai import OpenAI

from mem0 import Memory

client = OpenAI()

memory = Memory()

def chatwithmemory(usermessage: str, userid: str) -> str:

# Search for relevant memories

relevantmemories = memory.search(usermessage, userid=userid)

# Build context from memories

memorycontext = ""

if relevantmemories:

memorycontext = "Known information about the user:\n"

for mem in relevantmemories:

memorycontext += f"- {mem['memory']}\n"

# Create system prompt with memory context

systemprompt = f"""You are a helpful and personal AI assistant.

Use the following information about the user to provide personalized responses:

{memorycontext}

If the user shares new information about themselves, acknowledge it in your response."""

# Call OpenAI

response = client.chat.completions.create(

model="gpt-4o-mini",

messages=[

{"role": "system", "content": systemprompt},

{"role": "user", "content": usermessage}

]

)

assistantmessage = response.choices[0].message.content

# Store new memories from the conversation

conversation = f"User: {usermessage}\nAssistant: {assistantmessage}"

memory.add(conversation, userid=userid)

return assistantmessage

Example usage

print(chatwithmemory("Hi, my name is Budi. I'm a data scientist.", "user456"))

print(chatwithmemory("Can you recommend tools for data visualization?", "user456"))

Integration with Anthropic Claude

Mem0 also works seamlessly with Anthropic Claude:

import anthropic

from mem0 import Memory

client = anthropic.Anthropic()

memory = Memory()

def chatwithclaude(usermessage: str, userid: str) -> str:

# Retrieve relevant memories

relevantmemories = memory.search(usermessage, userid=userid)

memorycontext = ""

if relevantmemories:

memorylines = [mem['memory'] for mem in relevantmemories]

memorycontext = "Known information about the user:\n" + "\n".join(

f"- {line}" for line in memorylines

)

systemprompt = f"""You are a helpful, personalized AI assistant.

Use the following context to personalize your responses:

{memorycontext}"""

response = client.messages.create(

model="claude-sonnet-4-20250514",

maxtokens=1024,

system=systemprompt,

messages=[

{"role": "user", "content": usermessage}

]

)

assistantmessage = response.content[0].text

# Store memories

conversation = f"User: {usermessage}\nAssistant: {assistantmessage}"

memory.add(conversation, userid=userid)

return assistantmessage

Semantic Search Over Memories

The core strength of Mem0 is its semantic search capability. Unlike regular keyword search, semantic search understands the meaning of queries:

# Add various memories

m.add("I work as a machine learning engineer at a fintech startup", userid="user789")

m.add("I just completed a deep learning course on Coursera", userid="user789")

m.add("My last project was building a fraud detection system", userid="user789")

m.add("I'm interested in NLP and computer vision", userid="user789")

m.add("On weekends I usually go hiking and photography", userid="user789")

Semantic search - queries don't need to be exact matches

results = m.search("What is this user's professional background?", userid="user789")

Will find memories about work, courses, and projects

results = m.search("What are this user's hobbies?", userid="user789")

Will find memories about hiking and photography

Search with limit

results = m.search(

"technical skills",

userid="user789",

limit=3

)

Memory Conflict Resolution

When new information conflicts with existing memories, Mem0 handles it automatically:

# Initial memory

m.add("I live in Jakarta", userid="user100")

Updated information - Mem0 will detect the conflict

m.add("I just moved to Bandung last month", userid="user100")

Mem0 will update the memory, not create a duplicate

memories = m.getall(userid="user100")

Memory will show that the user lives in Bandung (latest information)

Mem0 uses an LLM to detect whether new information represents:

  • UPDATE: Updating an existing fact
  • ADD: New information that doesn't exist yet
  • DELETE: Removing information that is no longer relevant
  • NOOP: No changes needed

# Examples of different update types

m.add("My email is budi@example.com", userid="user100")

Event: ADD

m.add("My email has changed to budi@newcompany.com", userid="user100")

Event: UPDATE - old email is updated

m.add("I no longer use Twitter", userid="user100")

Event: DELETE - if there's a memory about Twitter

Practical Example: AI Assistant with Personalized Memory

Let's build a complete AI assistant that remembers user preferences across sessions:

from mem0 import Memory

from openai import OpenAI

from datetime import datetime

class PersonalizedAssistant:

def init(self):

self.client = OpenAI()

self.memory = Memory()

self.conversationhistory = []

def getmemorycontext(self, userid: str, query: str) -> str:

"""Retrieve relevant memories and format as context."""

memories = self.memory.search(query, userid=userid, limit=10)

if not memories:

return "No information known about this user yet."

contextlines = []

for mem in memories:

contextlines.append(f"- {mem['memory']}")

return "Known information about the user:\n" + "\n".join(contextlines)

def chat(self, usermessage: str, userid: str) -> str:

"""Send a message and get a personalized response."""

# Retrieve memory context

memorycontext = self.getmemorycontext(userid, usermessage)

# System prompt

systemprompt = f"""You are a smart and friendly personal AI assistant.

You remember information about each user and use it to provide

personal and relevant responses.

{memorycontext}

Guidelines:

  • Use known information to personalize responses
  • If the user shares new information, acknowledge and remember it
  • Give recommendations based on known preferences
  • Be natural, not overly formal
  • Current time: {datetime.now().strftime('%Y-%m-%d %H:%M')}"""

    # Add to conversation history

    self.conversationhistory.append({

    "role": "user",

    "content": usermessage

    })

    # Call LLM

    messages = [{"role": "system", "content": systemprompt}]

    messages.extend(self.conversationhistory[-10:]) # Keep last 10 messages

    response = self.client.chat.completions.create(

    model="gpt-4o-mini",

    messages=messages,

    temperature=0.7

    )

    assistantmessage = response.choices[0].message.content

    # Add response to history

    self.conversationhistory.append({

    "role": "assistant",

    "content": assistantmessage

    })

    # Store memories from this conversation

    self.memory.add(

    f"User: {usermessage}\nAssistant: {assistantmessage}",

    userid=userid,

    metadata={

    "timestamp": datetime.now().isoformat(),

    "type": "conversation"

    }

    )

    return assistantmessage

    def getuserprofile(self, userid: str) -> dict:

    """Get user profile based on stored memories."""

    allmemories = self.memory.getall(userid=userid)

    return {

    "userid": userid,

    "totalmemories": len(allmemories),

    "memories": [mem['memory'] for mem in allmemories]

    }

    def resetuser(self, userid: str):

    """Delete all memories for a specific user."""

    self.memory.deleteall(userid=userid)

    print(f"All memories for {userid} have been deleted.")

    Usage simulation

    def main():

    assistant = PersonalizedAssistant()

    userid = "demouser001"

    # Session 1: Introduction

    print("=== Session 1: Introduction ===")

    response = assistant.chat(

    "Hi! My name is Rina. I'm a data analyst at an e-commerce company.",

    userid

    )

    print(f"Assistant: {response}\n")

    response = assistant.chat(

    "I'm learning Python and interested in machine learning. "

    "I usually use Excel and SQL for data analysis.",

    userid

    )

    print(f"Assistant: {response}\n")

    # Session 2: Return visit (simulating a new session)

    assistant.conversationhistory = [] # Reset conversation history

    print("\n=== Session 2: Return Visit ===")

    response = assistant.chat(

    "Hi again! Can you recommend Python libraries for data visualization?",

    userid

    )

    print(f"Assistant: {response}\n")

    # View user profile

    profile = assistant.getuserprofile(userid)

    print(f"\n=== User Profile ===")

    print(f"Total memories: {profile['totalmemories']}")

    for mem in profile['memories']:

    print(f" - {mem}")

    if name == "main":

    main()

    Tips and Best Practices

    1. Manage Memory Size

    # Limit memories per user
    

    memories = m.getall(userid="user123")

    if len(memories) > 100:

    # Remove old, less relevant memories

    oldmemories = sorted(memories, key=lambda x: x['createdat'])

    for mem in oldmemories[:20]: # Delete 20 oldest memories

    m.delete(memoryid=mem['id'])

    2. Use Metadata for Filtering

    # Add useful metadata
    

    m.add(

    "User has a budget of $5000 for this project",

    userid="user123",

    metadata={

    "category": "project",

    "projectid": "proj001",

    "importance": "high",

    "expiresat": "2026-06-30"

    }

    )

    3. Separate Memories by Context

    # Use different userids for different contexts
    

    m.add("Preferences for project A", userid="user123projecta")

    m.add("Preferences for project B", userid="user123projectb")

    4. Handle Errors Gracefully

    def safememorysearch(memory, query, userid, fallback=""):
    

    try:

    results = memory.search(query, userid=userid)

    return results

    except Exception as e:

    print(f"Memory search failed: {e}")

    return []

    Conclusion

    Mem0 is a powerful tool for adding memory capabilities to your AI applications. With semantic search, automatic conflict resolution, and support for multiple memory levels, Mem0 makes it easy to build truly personalized AI applications.

    Keys to success with Mem0:

    • Start with a simple setup, then scale as needed
    • Use metadata to organize memories
    • Implement memory cleanup for optimal performance
    • Leverage semantic search for accurate memory retrieval
    • Always handle errors for a good user experience

    By combining Mem0 with your LLM of choice (OpenAI, Anthropic, etc.), you can build AI assistants that truly remember and understand each user uniquely.

    Related Articles

    MergeKit Tutorial: Merging LLM Models to Create Custom AI Models

    Tutorial MergeKit: Menggabungkan Model LLM untuk Membuat Model AI Kustom Model bahasa besar (LLM) open-source terus berk...

    Semantic Router Tutorial: Smart Routing for LLM Applications

    Tutorial Semantic Router: Routing Cerdas untuk Aplikasi LLM Semantic Router adalah library Python yang memungkinkan Anda...

    Complete Unstructured Tutorial: Document Preprocessing for RAG and LLM Applications

    Tutorial Lengkap Unstructured: Preprocessing Dokumen untuk RAG dan Aplikasi LLM Dalam membangun aplikasi Retrieval-Augme...

    Complete Llama Stack Tutorial: Meta's Official Framework for Building AI Applications with Llama Models

    Tutorial Lengkap Llama Stack: Framework Resmi Meta untuk Membangun Aplikasi AI dengan Model Llama Llama Stack adalah fra...