> ## Documentation Index
> Fetch the complete documentation index at: https://mem0-feature-memo-claude-plugin-v1.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# CrewAI

> Combine CrewAI agent-based architecture with Mem0 for persistent memory across agent interactions.

Build an AI system that combines CrewAI's agent-based architecture with Mem0's memory capabilities. This integration enables persistent memory across agent interactions and personalized task execution based on user history.

## Overview

In this guide, we'll create a CrewAI agent that:

1. Uses CrewAI to manage AI agents and tasks
2. Leverages Mem0 to store and retrieve conversation history
3. Creates personalized experiences based on stored user preferences

## Setup and Configuration

Install necessary libraries:

```bash theme={null}
pip install crewai crewai-tools mem0ai
```

Import required modules and set up configurations:

<Note>Remember to get your API keys from <a href="https://app.mem0.ai?utm_source=oss&utm_medium=integration-crewai" rel="nofollow">Mem0 Platform</a>, [OpenAI](https://platform.openai.com) and [Serper Dev](https://serper.dev) for search capabilities.</Note>

```python theme={null}
import os
from mem0 import MemoryClient
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool

# Configuration
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["SERPER_API_KEY"] = "your-serper-api-key"

# Initialize Mem0 client
client = MemoryClient()
```

<Note>
  Newer versions of CrewAI removed the `memory_config={"provider": "mem0"}` shortcut on `Crew(...)` that older guides referenced. CrewAI still offers a native Mem0 path through its `ExternalMemory` API, so that option remains open; check [CrewAI's memory documentation](https://docs.crewai.com/en/concepts/memory) for the shape your version expects. This guide wires Mem0 in explicitly through `MemoryClient` instead, which keeps retrieval under your control and stays valid as CrewAI's memory API changes.
</Note>

## Store User Preferences

Set up initial conversation and preferences storage:

```python theme={null}
def store_user_preferences(user_id: str, conversation: list):
    """Store user preferences from conversation history"""
    client.add(conversation, user_id=user_id)

# Example conversation storage
messages = [
    {
        "role": "user",
        "content": "Hi there! 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."},
]

store_user_preferences("crew_user_1", messages)
```

## Retrieve Relevant Memories

Look up what Mem0 already knows about the user before planning a trip, so the crew's output reflects their actual preferences:

```python theme={null}
def get_user_context(user_id: str, query: str) -> str:
    """Fetch relevant memories and format them for a task description"""
    relevant_memories = client.search(query, filters={"user_id": user_id})
    memories = [m["memory"] for m in relevant_memories.get("results", [])]
    return "\n".join(f"- {memory}" for memory in memories)
```

## Create CrewAI Agent

Define an agent with search capabilities:

```python theme={null}
def create_travel_agent():
    """Create a travel planning agent with search capabilities"""
    search_tool = SerperDevTool()

    return Agent(
        role="Personalized Travel Planner Agent",
        goal="Plan personalized travel itineraries",
        backstory="""You are a seasoned travel planner, known for your meticulous attention to detail.""",
        allow_delegation=False,
        tools=[search_tool],
    )
```

## Define Tasks

Create a task that folds the retrieved memories into its description, so the agent plans around the user's known preferences:

```python theme={null}
def create_planning_task(agent, destination: str, user_context: str):
    """Create a travel planning task personalized with the user's stored preferences"""
    return Task(
        description=f"""Find places to live, eat, and visit in {destination}.

        Known preferences for this user:
        {user_context or "No stored preferences yet."}
        """,
        expected_output=f"A detailed list of places to live, eat, and visit in {destination}, tailored to the user's preferences.",
        agent=agent,
    )
```

## Set Up Crew

Configure the crew. Mem0 handles persistence outside of CrewAI, so the crew itself does not need `memory=True` or a `memory_config`:

```python theme={null}
def setup_crew(agents: list, tasks: list):
    """Set up a crew; memory is managed through Mem0, not CrewAI's memory_config"""
    return Crew(
        agents=agents,
        tasks=tasks,
        process=Process.sequential,
    )
```

## Main Execution Function

Implement the main function to run the travel planning system: retrieve context from Mem0, run the crew, then store the new conversation back:

```python theme={null}
def plan_trip(destination: str, user_id: str):
    travel_agent = create_travel_agent()
    user_context = get_user_context(user_id, f"travel preferences for {destination}")
    planning_task = create_planning_task(travel_agent, destination, user_context)
    crew = setup_crew([travel_agent], [planning_task])
    result = crew.kickoff()

    client.add(
        [{"role": "user", "content": f"Planned a trip to {destination}."}],
        user_id=user_id,
    )

    return result

# Example usage
if __name__ == "__main__":
    result = plan_trip("San Francisco", "crew_user_1")
    print(result)
```

## Key Features

1. **Persistent Memory**: Uses Mem0 to maintain user preferences and conversation history
2. **Agent-Based Architecture**: Leverages CrewAI's agent system for task execution
3. **Search Integration**: Includes SerperDev tool for real-world information retrieval
4. **Personalization**: Utilizes stored preferences for tailored recommendations

## Benefits

1. **Persistent Context & Memory**: Maintains user preferences and interaction history across sessions
2. **Flexible & Scalable Design**: Easily extendable with new agents, tasks, and capabilities

## Conclusion

By combining CrewAI with Mem0, you can create sophisticated AI systems that maintain context and provide personalized experiences while leveraging the power of autonomous agents.

<CardGroup cols={2}>
  <Card title="AutoGen Integration" icon="users" href="/integrations/autogen">
    Build multi-agent systems with AutoGen and Mem0
  </Card>

  <Card title="LangGraph Integration" icon="diagram-project" href="/integrations/langgraph">
    Create stateful agent workflows with memory
  </Card>
</CardGroup>

<Snippet file="star-on-github.mdx" />
