---
title: "Memory Basics"
description: "Mem0 (\"mem-zero\") provides an intelligent memory layer designed to enhance AI assistants and agents. It allows your AI to remember past interactions, user preferences, and adapt its behavior over t..."
last_updated: "2026-05-07T04:49:20.024954+00:00"
canonical_url: "https://www.doc0.dev/docs/faa36707-7c28-4f69-a18f-700ff61c704e/guide/section-2/memory-basics"
---

Mem0 ("mem-zero") provides an intelligent memory layer designed to enhance AI assistants and agents. It allows your AI to remember past interactions, user preferences, and adapt its behavior over time. This means your AI can provide more personalized and consistent experiences, making it ideal for applications like customer support chatbots, personal AI assistants, and autonomous systems that need to learn from ongoing interactions.

This memory layer helps your AI maintain context across conversations and sessions, leading to more natural and effective interactions without needing to repeat information.

### Key Concepts

*   **Memory Layer**: This is the core of Mem0. It's a system that stores and manages information for your AI, allowing it to recall relevant details when needed.
*   **Multi-Level Memory**: Mem0 organizes memories into different categories to provide adaptive personalization:
    *   **User State**: Information specific to an individual user, such as their preferences, history, or personal details.
    *   **Session State**: Information relevant to the current conversation or interaction session.
    *   **Agent State**: Information about the AI agent itself, its goals, or its ongoing tasks.

These different levels of memory ensure that your AI can recall the right information at the right time, whether it's a long-term user preference or a detail from the current conversation.

## Getting Started

You can use Mem0 either through its hosted platform or by self-hosting the open-source package.

<Steps>
<Step>
### Choose your setup method

<Tabs items={["Hosted Platform", "Self-Hosted (Open Source)"]}>
<Tab value="Hosted Platform">
For quick setup with automatic updates, analytics, and enterprise security:

1.  Sign up on the [Mem0 Platform](https://app.mem0.ai).
2.  Embed the memory layer into your application using the provided SDKs or API keys.
</Tab>
<Tab value="Self-Hosted (Open Source)">
To install and manage Mem0 yourself:

Install the SDK using your preferred package manager:

<Tabs items={["pip", "npm"]}>
<Tab value="pip">
```bash
pip install mem0ai
```
</Tab>
<Tab value="npm">
```bash
npm install mem0ai
```
</Tab>
</Tabs>
</Tab>
</Tabs>
</Step>
</Steps>

## Basic Usage

Once Mem0 is set up, you can integrate it into your AI application. Mem0 requires an external Large Language Model (LLM) to function, such as OpenAI's models.

<Callout variant="info">
Mem0 is designed to work with various LLMs. While `gpt-4.1-nano-2025-04-14` from OpenAI is often used as a default in examples, you can configure it to use other supported LLMs.
</Callout>

Here's a step-by-step guide to using Mem0 to add memory to a simple chat application:

<Steps>
<Step>
### Instantiate the Memory

First, you need to initialize the Mem0 `Memory` object. This sets up the connection to your memory layer. You'll also need to set up your LLM client (e.g., OpenAI).

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

openai_client = OpenAI()
memory = Memory()
```
</Step>

<Step>
### Define your chat function

Create a function that will handle user input, retrieve memories, generate a response, and then store new memories.

```python
def chat_with_memories(message: str, user_id: str = "default_user") -> str:
    # ... (rest of the code below)
```
</Step>

<Step>
### Retrieve relevant memories

Before generating a response, ask Mem0 to search for memories that are relevant to the current user's message. This helps the AI understand the context.

```python
    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"])
```
*   `query`: The user's current message.
*   `user_id`: Identifies the user, allowing Mem0 to retrieve personalized memories.
*   `limit`: Specifies the maximum number of relevant memories to retrieve.
</Step>

<Step>
### Generate an AI response

Use the retrieved memories to inform your LLM's response. The memories are typically included in the system prompt to provide context.

```python
    system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
    messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": message}]
    response = openai_client.chat.completions.create(model="gpt-4.1-nano-2025-04-14", messages=messages)
    assistant_response = response.choices[0].message.content
```
</Step>

<Step>
### Create new memories from the conversation

After the AI responds, add the entire conversation (user message and AI response) back to Mem0. This allows Mem0 to learn from the interaction and store new information for future use.

```python
    messages.append({"role": "assistant", "content": assistant_response})
    memory.add(messages, user_id=user_id)
```
*   `messages`: The list of messages in the current turn of the conversation.
*   `user_id`: Associates these new memories with the specific user.
</Step>

<Step>
### Run the chat loop

Finally, set up a simple loop to continuously chat with your memory-enhanced AI.

```python
    return assistant_response

def main():
    print("Chat with AI (type 'exit' to quit)")
    while True:
        user_input = input("You: ").strip()
        if user_input.lower() == 'exit':
            print("Goodbye!")
            break
        print(f"AI: {chat_with_memories(user_input)}")

if __name__ == "__main__":
    main()
```
</Step>
</Steps>

## Applications

Mem0 can be used in various scenarios to make AI more intelligent and personalized:

*   **AI Assistants**: Create assistants that remember past conversations and user preferences for consistent, context-rich interactions.
*   **Customer Support**: Build chatbots that recall past tickets and user history, providing tailored and efficient help.
*   **Healthcare**: Develop systems that track patient preferences and medical history to offer personalized care.
*   **Productivity & Gaming**: Design adaptive workflows and environments that learn and adjust based on user behavior.

## Sitemap

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