> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pipecat.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Mem0

> Long-term conversation memory service powered by Mem0

## Overview

`Mem0MemoryService` provides long-term memory capabilities for conversational agents by integrating with Mem0's API. It automatically stores conversation history and retrieves relevant past context based on the current conversation, enhancing LLM responses with persistent memory across sessions.

<CardGroup cols={2}>
  <Card title="Mem0 Memory API Reference" icon="code" href="https://reference-server.pipecat.ai/en/latest/api/pipecat.services.mem0.memory.html">
    Pipecat's API methods for Mem0 memory integration
  </Card>

  <Card title="Example Implementation" icon="play" href="https://github.com/pipecat-ai/pipecat/blob/main/examples/rag/rag-mem0.py">
    Browse examples using Mem0 memory
  </Card>

  <Card title="Mem0 Documentation" icon="book" href="https://docs.mem0.ai/">
    Official Mem0 API documentation and guides
  </Card>

  <Card title="Mem0 Platform" icon="microphone" href="https://mem0.ai">
    Access memory services and manage API keys
  </Card>
</CardGroup>

## Installation

To use Mem0 memory services, install the required dependencies:

```bash theme={null}
uv add "pipecat-ai[mem0]"
```

## Prerequisites

### Mem0 Account Setup

Before using Mem0 memory services, you need:

1. **Mem0 Account**: Sign up at [Mem0 Platform](https://mem0.ai)
2. **API Key**: Generate an API key from your account dashboard
3. **Host Configuration**: Set up your Mem0 host endpoint
4. **User Management**: Configure user IDs for memory association

### Required Environment Variables

* `MEM0_API_KEY`: Your Mem0 API key for authentication

### Configuration Options

* **User ID**: Unique identifier for associating memories with specific users
* **Agent ID**: Identifier for the agent using the memory service
* **Run ID**: Identifier for specific conversation sessions
* **Memory Retrieval**: Configure how past context is retrieved and used

### Key Features

* **Persistent Memory**: Long-term conversation history across sessions
* **Context Retrieval**: Automatic retrieval of relevant past conversations
* **User Association**: Memory tied to specific users for personalization
* **Session Management**: Track conversations across different runs and agents

## Configuration

<ParamField path="api_key" type="str" default="None">
  The API key for accessing Mem0's cloud API.
</ParamField>

<ParamField path="local_config" type="dict" default="None">
  Local configuration for Mem0 client as an alternative to the cloud API.
</ParamField>

<ParamField path="user_id" type="str" default="None">
  The user ID to associate with memories in Mem0. At least one of `user_id`,
  `agent_id`, or `run_id` must be provided.
</ParamField>

<ParamField path="agent_id" type="str" default="None">
  The agent ID to associate with memories in Mem0.
</ParamField>

<ParamField path="run_id" type="str" default="None">
  The run ID to associate with memories in Mem0.
</ParamField>

<ParamField path="params" type="InputParams" default="None">
  Configuration parameters for memory retrieval and storage. See
  [InputParams](#inputparams) below.
</ParamField>

<ParamField path="host" type="str" default="None">
  The host of the Mem0 server.
</ParamField>

### InputParams

| Parameter               | Type    | Default                                             | Description                                                                      |
| ----------------------- | ------- | --------------------------------------------------- | -------------------------------------------------------------------------------- |
| `search_limit`          | `int`   | `10`                                                | Maximum number of memories to retrieve per query (min: 1).                       |
| `search_threshold`      | `float` | `0.1`                                               | Minimum similarity threshold for memory retrieval (0.0-1.0).                     |
| `api_version`           | `str`   | `"v2"`                                              | API version to use for Mem0 client operations.                                   |
| `system_prompt`         | `str`   | `"Based on previous conversations, I recall: \n\n"` | Prefix text for memory context messages.                                         |
| `add_as_system_message` | `bool`  | `True`                                              | Whether to add memories as system messages. When `False`, adds as user messages. |
| `position`              | `int`   | `1`                                                 | Position to insert memory messages in context.                                   |

## Usage

### Cloud API Setup

```python theme={null}
from pipecat.services.mem0 import Mem0MemoryService

memory = Mem0MemoryService(
    api_key=os.getenv("MEM0_API_KEY"),
    user_id="user-123",
)
```

### With Custom Parameters

```python theme={null}
memory = Mem0MemoryService(
    api_key=os.getenv("MEM0_API_KEY"),
    user_id="user-123",
    agent_id="assistant-1",
    params=Mem0MemoryService.InputParams(
        search_limit=5,
        search_threshold=0.3,
        add_as_system_message=True,
    ),
)
```

### Local Configuration

```python theme={null}
memory = Mem0MemoryService(
    local_config={
        "vector_store": {
            "provider": "chroma",
            "config": {"collection_name": "memories"},
        },
    },
    user_id="user-123",
)
```

### Retrieving Memories Outside the Pipeline

The `get_memories()` method allows you to access stored memories outside the normal pipeline flow, such as when creating a personalized greeting at connection time:

```python theme={null}
# Get all stored memories for the configured user/agent/run IDs
memories = await memory.get_memories()

# Create a personalized greeting
if memories:
    greeting = "Hello! Based on our previous conversations, I remember: "
    for mem in memories[:3]:
        greeting += f"{mem['memory']} "
else:
    greeting = "Hello! It's nice to meet you."
```

## Notes

* **At least one ID required**: You must provide at least one of `user_id`, `agent_id`, or `run_id`. A `ValueError` is raised if none are provided.
* **Cloud vs local**: Use `api_key` for Mem0's cloud API, or `local_config` for a self-hosted Mem0 instance using `Memory.from_config()`.
* **Pipeline placement**: Place the `Mem0MemoryService` before your LLM service in the pipeline. It intercepts `LLMContextFrame` and `LLMMessagesFrame` to enhance context with relevant memories before passing them downstream.
* **Non-blocking operation**: All Mem0 API calls (storage, retrieval, search) run in background threads to avoid blocking the event loop. Message storage is fire-and-forget, so it doesn't delay downstream processing.
* **Message role filtering**: Only messages with `user` or `assistant` roles are stored in Mem0. Messages with other roles (such as `system` or `developer`) are automatically filtered out, as the Mem0 API does not accept them.
