---
title: "Add Memories"
description: "Mem0 enhances your AI assistants and agents by providing an intelligent memory layer. This feature allows your AI to remember past interactions, user preferences, and adapt to individual needs over..."
last_updated: "2026-05-07T04:49:20.107547+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/guide/section-3/add-memories"
---

Mem0 enhances your AI assistants and agents by providing an intelligent memory layer. This feature allows your AI to remember past interactions, user preferences, and adapt to individual needs over time. By adding memories, you enable your AI to have more personalized, consistent, and context-rich conversations, making it more effective for tasks like customer support, personalized recommendations, or adaptive workflows.

Essentially, adding memories teaches your AI about ongoing conversations and user-specific information, allowing it to learn and improve its responses based on historical data.

<Steps>
<Step>
### Set up your Memory instance
Before you can add memories, you need to initialize the Mem0 library and an OpenAI client (or another supported Large Language Model). This sets up the connection your application will use to interact with the memory system.

```python
from openai import OpenAI
from mem0 import Memory

# Initialize your OpenAI client
openai_client = OpenAI()

# Initialize the Mem0 memory instance
memory = Memory()
```

</Step>
<Step>
### Prepare your conversation messages
Memories are typically added from a conversation's history. You'll need a list of messages, where each message is a dictionary containing a `role` (e.g., "user", "assistant", "system") and the `content` of that message.

For example, after a user asks a question and the AI responds, you would have a list like this:

```python
# Example conversation history
messages = [
    {"role": "system", "content": "You are a helpful AI."},
    {"role": "user", "content": "What is the capital of France?"},
    {"role": "assistant", "content": "The capital of France is Paris."}
]
```

</Step>
<Step>
### Add the conversation to memory
Once you have your `messages` and a `user_id` to identify the user, you can add them to Mem0's memory. This action processes the conversation and stores relevant information as memories associated with that user.

```python
user_id = "your_unique_user_id_here" # Use a unique identifier for each user

# Add the conversation messages to memory
memory.add(messages, user_id=user_id)
```

<Callout title="Important: User ID" variant="info">
The `user_id` is crucial for personalization. Ensure you use a unique identifier for each user so Mem0 can correctly associate memories with the right individual. If you don't specify a `user_id`, a default one will be used, which might lead to mixed memories if multiple users interact without distinct IDs.
</Callout>

</Step>
<Step>
### Verify memories (optional)
After adding memories, you can optionally search for them to confirm they have been stored. This helps you see what information Mem0 has retained.

```python
# Search for relevant memories based on a query
relevant_memories = memory.search(query="What did I ask about France?", user_id=user_id, limit=3)

print("Relevant Memories:")
for entry in relevant_memories["results"]:
    print(f"- {entry['memory']}")
```

</Step>
</Steps>

### Key Concepts

*   **Memory**: In Mem0, a "memory" refers to any piece of information, preference, or conversational context that the AI system stores and can recall later. These are extracted from the `messages` you provide.
*   **User ID**: A unique identifier for each user interacting with your AI. This allows Mem0 to maintain separate and personalized memory profiles for different individuals.
*   **Messages**: A list of conversational turns, typically in the format `[{ "role": "user", "content": "..." }, { "role": "assistant", "content": "..." }]`. Mem0 processes these messages to extract and store relevant memories.

### Example: Full Conversation Flow

Here's a complete example demonstrating how to add memories within a continuous chat interaction:

```python
from openai import OpenAI
from mem0 import Memory

openai_client = OpenAI()
memory = Memory()

def chat_with_memories(message: str, user_id: str = "default_user") -> str:
    # 1. Retrieve relevant memories for the current user and message
    relevant_memories = memory.search(query=message, user_id=user_id, limit=3)
    memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories["results"])

    # 2. Construct a system prompt including retrieved memories
    system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
    
    # 3. Prepare messages for the LLM, including the current user message
    messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": message}]
    
    # 4. Get a response from the LLM
    response = openai_client.chat.completions.create(model="gpt-4.1-nano-2025-04-14", messages=messages)
    assistant_response = response.choices[0].message.content

    # 5. Add the full conversation turn (user message + assistant response) to memory
    messages.append({"role": "assistant", "content": assistant_response})
    memory.add(messages, user_id=user_id) # This is where memories are added

    return assistant_response

def main():
    print("Chat with AI (type 'exit' to quit)")
    current_user_id = input("Enter your user ID (e.g., 'user123'): ").strip()
    if not current_user_id:
        current_user_id = "default_user"
        print(f"Using default user ID: {current_user_id}")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() == 'exit':
            print("Goodbye!")
            break
        print(f"AI: {chat_with_memories(user_input, user_id=current_user_id)}")

if __name__ == "__main__":
    main()
```

In this example, after the AI generates a response, the entire `messages` list (including the new assistant response) is passed to `memory.add()`. This ensures that Mem0 learns from the complete conversation turn, continuously updating its understanding and memory for that specific user.

## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/llms.txt) for all pages in this wiki.
