Overview

Mem0 provides a suite of tools for storing, searching, and retrieving memories, enabling agents to maintain context and learn from past interactions. The tools are built as Langchain tools, making them easily integrable with any AI agent implementation.

Installation

Install the required dependencies:

pip install langchain_core
pip install mem0ai

Authentication

Import the necessary dependencies and initialize the client:

from langchain_core.tools import StructuredTool
from mem0 import MemoryClient
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional

client = MemoryClient(
    "---",
    org_id="---",
    project_id="---"
)

Available Tools

Mem0 provides three main tools for memory management:

1. ADD Memory Tool

The ADD tool allows you to store new memories with associated metadata. It’s particularly useful for saving conversation history and user preferences.

Schema

class Message(BaseModel):
    role: str = Field(description="Role of the message sender (user or assistant)")
    content: str = Field(description="Content of the message")

class AddMemoryInput(BaseModel):
    messages: List[Message] = Field(description="List of messages to add to memory")
    user_id: str = Field(description="ID of the user associated with these messages")
    output_format: str = Field(description="Version format for the output")
    metadata: Optional[Dict[str, Any]] = Field(description="Additional metadata for the messages", default=None)

    class Config:
        json_schema_extra = {
            "examples": [{
                "messages": [
                    {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
                    {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy."}
                ],
                "user_id": "alex",
                "output_format": "v1.1",
                "metadata": {"food": "vegan"}
            }]
        }

Implementation

def add_memory(messages: List[Message], user_id: str, output_format: str, metadata: Optional[Dict[str, Any]] = None) -> Any:
    """Add messages to memory with associated user ID and metadata."""
    message_dicts = [msg.dict() for msg in messages]
    return client.add(message_dicts, user_id=user_id, output_format=output_format, metadata=metadata)

add_tool = StructuredTool(
    name="add_memory",
    description="Add new messages to memory with associated metadata",
    func=add_memory,
    args_schema=AddMemoryInput
)

Example Usage

2. SEARCH Memory Tool

The SEARCH tool enables querying stored memories using natural language queries and advanced filtering options.

Schema

class SearchMemoryInput(BaseModel):
    query: str = Field(description="The search query string")
    filters: Dict[str, Any] = Field(description="Filters to apply to the search")
    version: str = Field(description="Version of the memory to search")

    class Config:
        json_schema_extra = {
            "examples": [{
                "query": "tell me about my allergies?",
                "filters": {
                    "AND": [
                        {"user_id": "alex"},
                        {"created_at": {"gte": "2024-01-01", "lte": "2024-12-31"}}
                    ]
                },
                "version": "v2"
            }]
        }

Implementation

def search_memory(query: str, filters: Dict[str, Any], version: str) -> Any:
    """Search memory with the given query and filters."""
    return client.search(query=query, version=version, filters=filters)

search_tool = StructuredTool(
    name="search_memory",
    description="Search through memories with a query and filters",
    func=search_memory,
    args_schema=SearchMemoryInput
)

Example Usage

3. GET_ALL Memory Tool

The GET_ALL tool retrieves all memories matching specified criteria, with support for pagination.

Schema

class GetAllMemoryInput(BaseModel):
    version: str = Field(description="Version of the memory to retrieve")
    filters: Dict[str, Any] = Field(description="Filters to apply to the retrieval")
    page: Optional[int] = Field(description="Page number for pagination", default=1)
    page_size: Optional[int] = Field(description="Number of items per page", default=50)

    class Config:
        json_schema_extra = {
            "examples": [{
                "version": "v2",
                "filters": {
                    "AND": [
                        {"user_id": "alex"},
                        {"created_at": {"gte": "2024-07-01", "lte": "2024-07-31"}},
                        {"categories": {"contains": "food_preferences"}}
                    ]
                },
                "page": 1,
                "page_size": 50
            }]
        }

Implementation

def get_all_memory(version: str, filters: Dict[str, Any], page: int = 1, page_size: int = 50) -> Any:
    """Retrieve all memories matching the specified criteria."""
    return client.get_all(version=version, filters=filters, page=page, page_size=page_size)

get_all_tool = StructuredTool(
    name="get_all_memory",
    description="Retrieve all memories matching specified filters",
    func=get_all_memory,
    args_schema=GetAllMemoryInput
)

Example Usage

Integration with AI Agents

All tools are implemented as Langchain StructuredTool instances, making them compatible with any AI agent that supports the Langchain tools interface. To use these tools with your agent:

  1. Initialize the tools as shown above
  2. Add the tools to your agent’s toolset
  3. The agent can now use these tools to manage memories through natural language interactions

Each tool provides structured input validation through Pydantic models and returns consistent responses that can be processed by your agent.