Mem0 integration with Crew ai

Hey, hope u are going well! I’m trying implement a simple memory system for a
a project, but I’m getting a error (look below) so I create a simple project to install again all dependencies, use a simple code to validade and test, but have the same issue…

Full traceback is in the bottom of post

Error:
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\memory\contextual\contextual_memory.py”, line 97, in _fetch_user_context
user_memories = self.um.search(query)
^^^^^^^^^^^^^^
AttributeError: ‘NoneType’ object has no attribute ‘search’ "

At last I create a new project very simple (code below), to just try test the implementation, but I think can be some mistake by my side… Let me know if you have the answer, or anything who can guide me to this

Code
from crewai import Agent, Task, LLM
from crewai import Crew, Process
from crewai.project import CrewBase, agent, crew, task,before_kickoff
from dotenv import load_dotenv
import os
load_dotenv()

model = os.getenv("OPENAI_MODEL")
api_key = os.getenv("OPENAI_API_KEY")
base_url = os.getenv("OPENAI_BASE_URL_LINK")
filepath = ""


# Configurar logger customizado

llm = LLM(
    model=model,
    temperature=0.5,
    timeout=240,
    max_tokens=10000,
    top_p=0.9,
    frequency_penalty=0.1,
    presence_penalty=0.1,
    seed=42,
    base_url=base_url,
    api_key=api_key
)


@CrewBase
class MemoryCrew:
    """Query Crew"""

    agents_config = "config/agents.yaml"
    tasks_config = "config/tasks.yaml"
    @before_kickoff
    def prepare_inputs(self, inputs):
        global filepath

        return inputs

    @agent
    def find_agent(self) -> Agent:
        return Agent(
            config=self.agents_config["find_agent"],
            llm=llm,

        )


    @task
    def find_task(self) -> Task:
        return Task(
            config=self.tasks_config["find_task"],
        )


    @crew
    def crew(self) -> Crew:
        """Creates the Research Crew"""
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,
            verbose=True,
            memory=True,
            memory_config={
                "provider": "mem0",
                "config": {"user_id": "dummy_user_id",},
            },
        )


result = (
    MemoryCrew()
    .crew()
    .kickoff(inputs={"prompt": "What is my interests ? "}))

print(result.raw)

Full traceback :
Traceback (most recent call last):
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test\memory_crew\home.py”, line 77, in
.kickoff(inputs={“prompt”: "What is my interests ? "}))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\crew.py”, line 640, in kickoff
result = self._run_sequential_process()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\crew.py”, line 752, in _run_sequential_process
return self._execute_tasks(self.tasks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\crew.py”, line 850, in _execute_tasks
task_output = task.execute_sync(
^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\task.py”, line 310, in execute_sync
return self._execute_core(agent, context, tools)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\task.py”, line 454, in _execute_core
raise e # Re-raise the exception after emitting the event
^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\task.py”, line 374, in _execute_core
result = agent.execute_task(
^^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\agent.py”, line 209, in execute_task
memory = contextual_memory.build_context_for_task(task, context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\memory\contextual\contextual_memory.py”, line 39, in build_context_for_task
context.append(self._fetch_user_context(query))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\user_name\PycharmProjects\CrewAi\memory_test.venv\Lib\site-packages\crewai\memory\contextual\contextual_memory.py”, line 97, in _fetch_user_context
user_memories = self.um.search(query)
^^^^^^^^^^^^^^
AttributeError: ‘NoneType’ object has no attribute ‘search’

Hi, I face the same problem right now :laughing:.
If I find the solution, I will write; in case you find it first plz post it.

Thanks,
Anna

1 Like

Somehow, the error is not more reproducible when one places the same memory_config in the Agent instead of the Crew.

Hope that helps,
Anna

1 Like

Hey Anna, one way I find to bypass this error is create a custom tool, and use the function “search” by Mem0 to retrieve the needed information about the user, I think isnt the most right way but work

Below is the code, I execute the query used in the search function, and use a text var to add the memory and the categories (thinking in facility easy the way for the agent use this information)

If you follow this approach, attention in this var

result = client.search(query, user_id=get_user_data()['mail'])

My user id was a mail fetched by one function, so use the correct for you

Hope this help you in some way, best regards

Bruno

from crewai.tools import BaseTool

from utils.auth.functions import get_user_data
from pydantic import Field
from typing import Type, Any
from pydantic import BaseModel
import os
from mem0 import MemoryClient
memo_api_key = os.getenv("MEM0_API_KEY")
memory_flag = int(os.getenv("USE_CREW_MEMORY_FOR_RAG_FILES"))
class MemoryRelationalInput(BaseModel):
    """Input schema for MyCustomTool."""
    query : str = Field(..., description="Query used to consult the user memories database, retrieve the memory and categories about.")

class MemoryTool(BaseTool):
    name: str = "Memory tool"
    description: str = "This tool get relationated memories from user, using a query."
    args_schema: Type[BaseModel] = MemoryRelationalInput

    def _run(self,query:str) -> str:
        if memory_flag== 1:
            print("Mem0 memory On")
            client = MemoryClient(api_key=memo_api_key)
            result = client.search(query, user_id=get_user_data()['mail'])
            relational_memories = ""
            for i in result:
                relational_memories += f"\n{i['memory']}; memory categories : "
                count = 1
                for f in i['categories']:
                    if count < len(i['categories']):
                        relational_memories += f"{f}, "
                    else:
                        relational_memories += f"{f}"
                    count += 1
            return relational_memories
        else:
            print("Mem0 memory off")
            return "No additional memories about user."
1 Like

The Problem and Some Theory

Tracing the error, I noticed that when running a Task, the Agent tries to build context using ContextualMemory. This involves fetching user context via _fetch_user_context, which in turn calls self.um.search(query). However, self.um (which should be an instance of UserMemory) is None, leading to the AttributeError: 'NoneType' object has no attribute 'search' error we’re seeing.

The problem originates during the initialization of the Crew class. When the create_crew_memory method is called, it does the following:

  • It checks self.memory. Since we’re passing the parameter memory=True, this evaluates to True.
  • It then initializes _long_term_memory, _short_term_memory, and _entity_memory. From what I’ve seen, this part works correctly and doesn’t affect our issue, so let’s move on.
  • Crucially, it then checks: if self.memory_config and "user_memory" in self.memory_config, and here lies the bug. If the condition is NOT met (which is the case with the Mem0 example config), it explicitly sets self._user_memory = None. This is the direct cause of self.um being None later on.

After this point, a ContextualMemory object is created with: self.crew._short_term_memory (:grinning_face:), self.crew._long_term_memory (:smiley:), self.crew._entity_memory (:grinning_face_with_smiling_eyes:), and self.crew._user_memory (:pensive_face:).

And that, in a nutshell, is how self.um becomes None, causing the self.um.search(query) method to throw the error (goes without saying this should probably be wrapped in a try block, right?).

A Workaround for Mem0 (Includes Functional Code)

As you saw above, we need to force the check if self.memory_config and "user_memory" in self.memory_config to evaluate to True. Therefore, we need to ensure the user_memory key is present in the dictionary passed to the memory_config parameter.

Here’s the functional code. Hope it helps you guys out.

from crewai import Agent, Task, Crew, LLM, Process
from mem0 import MemoryClient
import os

os.environ['MEM0_API_KEY'] = ''
os.environ['GEMINI_API_KEY'] = ''

# Step 1: Record preferences based on user input

client = MemoryClient()
messages = [
    {
        'role': 'user', 
        'content': 'Hi! I\'m planning a vacation and could use some advice.'
    },
    {
        'role': 'assistant', 
        'content': 'Hello! I\'d be happy to help with your vacation planning. '
                   'What kind of destination do you prefer?'
    },
    {
        'role': 'user', 
        'content': 'I am more of a beach person than a mountain person.'
    },
    {
        'role': 'assistant', 
        'content': 'That\'s interesting. Do you like hotels or Airbnb?'
    },
    {
        'role': 'user', 
        'content': 'I like Airbnb more.'
    }
]
client.add(messages, user_id='John Doe', output_format='v1.1')

# Step 2: Create a Crew with User Memory

gemini_llm = LLM(
    model='gemini/gemini-2.0-flash',
    temperature=0.7,
	max_tokens=1024
)

travel_planner_agent = Agent(
    role='Travel Planner',
    goal='Create a detailed travel itinerary',
    backstory='Expert in travel logistics',
    llm=gemini_llm,
    verbose=True,
    allow_delegation=False
)

planning_task = Task(
    description=(
        'Plan a weekend trip to {destination} focusing on beaches, '
        'considering the user preference for Airbnb.'
    ),
    expected_output=(
        'A day-by-day itinerary in markdown format, including beach '
        'and activity suggestions.'
    ),
    agent=travel_planner_agent
)

# --- Workaround Explanation ---
#
# The Crew class currently has a bug where it doesn't automatically
# create the UserMemory component when 'provider': 'mem0' is set.
# It incorrectly looks for a 'user_memory' key in the config.
# To trigger the correct initialization path *within* UserMemory,
# we add the 'user_memory': {} key manually. This satisfies the
# faulty check in Crew, causing it to call UserMemory(crew=self),
# which then correctly uses the 'provider' and 'config' details.

crew = Crew(
    agents=[travel_planner_agent],
    tasks=[planning_task],
    verbose=True,
    process=Process.sequential,
    memory=True,
    memory_config={
        'provider': 'mem0',
        'config': {
            'user_id': 'John Doe'
        },
        'user_memory': {}   # Workaround for buggy memory initialization
    },
)

result = crew.kickoff(
    inputs={
        'destination': 'Cancun'
    }
)

print(f'\n🤖 Your Travel Plan:\n\n{result.raw}\n')

Yes,

thanks Max,

I came up to something similar yesterday while debugging:

memory_config = {
“provider”: “mem0”,
“config”: {
“user_id”: “xxx”
},
“user_memory”: {}
}

… then the user memory was not None.

Regards,
Anna

1 Like