Back to Mem0

Langchain Tools

docs/integrations/langchain-tools.mdx

2.0.18.6 KB
Original Source

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:

bash
pip install langchain_core
pip install mem0ai

Authentication

Import the necessary dependencies and initialize the client:

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

os.environ["MEM0_API_KEY"] = "your-api-key"

client = MemoryClient()

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

python
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")
    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",
                "metadata": {"food": "vegan"}
            }]
        }

Implementation

python
def add_memory(messages: List[Message], user_id: 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, 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

<CodeGroup> ```python Code add_input = { "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", "metadata": {"food": "vegan"} } add_result = add_tool.invoke(add_input) ```
json
{
  "results": [
    {
      "memory": "Name is Alex",
      "event": "ADD"
    },
    {
      "memory": "Is a vegetarian", 
      "event": "ADD"
    },
    {
      "memory": "Is allergic to nuts",
      "event": "ADD"
    }
  ]
}
</CodeGroup>

2. SEARCH Memory Tool

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

Schema

python
class SearchMemoryInput(BaseModel):
    query: str = Field(description="The search query string")
    filters: Dict[str, Any] = Field(description="Filters to apply to the 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"}}
                    ]
                }
            }]
        }

Implementation

python
def search_memory(query: str, filters: Dict[str, Any]) -> Any:
    """Search memory with the given query and filters."""
    return client.search(query=query, 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

<CodeGroup> ```python Code search_input = { "query": "what is my name?", "filters": { "AND": [ {"user_id": "alex"}, {"created_at": {"gte": "2024-07-20", "lte": "2024-12-10"}} ] } } result = search_tool.invoke(search_input) ```
json
[
  {
    "id": "1a75e827-7eca-45ea-8c5c-cfd43299f061",
    "memory": "Name is Alex",
    "user_id": "alex", 
    "hash": "d0fccc8fa47f7a149ee95750c37bb0ca",
    "metadata": {
      "food": "vegan"
    },
    "categories": [
      "personal_details"
    ],
    "created_at": "2024-11-27T16:53:43.276872-08:00",
    "updated_at": "2024-11-27T16:53:43.276885-08:00",
    "score": 0.3810526501504994
  }
]
</CodeGroup>

3. GET_ALL Memory Tool

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

Schema

python
class GetAllMemoryInput(BaseModel):
    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": [{
                "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

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

<CodeGroup> ```python Code get_all_input = { "filters": { "AND": [ {"user_id": "alex"}, {"created_at": {"gte": "2024-07-01", "lte": "2024-12-31"}} ] }, "page": 1, "page_size": 50 } get_all_result = get_all_tool.invoke(get_all_input) ```
json
{
  "count": 3,
  "next": null,
  "previous": null,
  "results": [
    {
      "id": "1a75e827-7eca-45ea-8c5c-cfd43299f061",
      "memory": "Name is Alex",
      "user_id": "alex", 
      "hash": "d0fccc8fa47f7a149ee95750c37bb0ca",
      "metadata": {
        "food": "vegan"
      },
      "categories": [
        "personal_details"
      ],
      "created_at": "2024-11-27T16:53:43.276872-08:00",
      "updated_at": "2024-11-27T16:53:43.276885-08:00"
    },
    {
      "id": "91509588-0b39-408a-8df3-84b3bce8c521",
      "memory": "Is a vegetarian",
      "user_id": "alex",
      "hash": "ce6b1c84586772ab9995a9477032df99", 
      "metadata": {
        "food": "vegan"
      },
      "categories": [
        "user_preferences",
        "food"
      ],
      "created_at": "2024-11-27T16:53:43.308027-08:00",
      "updated_at": "2024-11-27T16:53:43.308037-08:00"
    },
    {
      "id": "8d74f7a0-6107-4589-bd6f-210f6bf4fbbb",
      "memory": "Is allergic to nuts",
      "user_id": "alex",
      "hash": "7873cd0e5a29c513253d9fad038e758b",
      "metadata": {
        "food": "vegan"
      },
      "categories": [
        "health"
      ],
      "created_at": "2024-11-27T16:53:43.337253-08:00",
      "updated_at": "2024-11-27T16:53:43.337262-08:00"
    }
  ]
}
</CodeGroup>

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.

<CardGroup cols={2}> <Card title="LangChain Integration" icon="link" href="/integrations/langchain"> Build conversational agents with LangChain and Mem0 </Card> <Card title="LangGraph Integration" icon="diagram-project" href="/integrations/langgraph"> Create stateful workflows with LangGraph </Card> </CardGroup>