Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for retrieving user preferences and memories using Mem0 #1209

Open
wants to merge 36 commits into
base: main
Choose a base branch
from

Conversation

Dev-Khant
Copy link
Contributor

@Dev-Khant Dev-Khant commented Aug 19, 2024

Changes

  • Introduce a new memory type in CrewAI called 'UserMemory' which basically fetches the user's preferences and past memories based on the action that agent is going to take. Eg: in case of a travel planner agent, if the user prefers to stay in Airbnb over Hotel, the agent will be provided user preferences and the Agent response will be more personalized.
  • Short Term Memory uses Mem0
  • Entity Memory uses Mem0
  • Update Embedchain package and Mem0 package
  • Demonstrated improved personalization in Travel Planner Agent output when using memory

Comparison

User preferences provided through Mem0:

client = MemoryClient()
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."},
    {
        "role": "assistant",
        "content": "Got it. What food do you prefer?",
    },
    {"role": "user", "content": "I like to eat Indian and Italian food"}
]
client.add(messages, user_id="john")

Full notebook: https://colab.research.google.com/drive/1nJi71bZOsFf6MPS385X-eqJVrAUXGRGJ?usp=sharing

TL;DR

Agent with UserMemory shows significant improvements in personalization:

  • Recommends Airbnb options instead of hotels, aligning with user's stated preference
  • Includes a dedicated section for beaches, reflecting user's preference for beaches over mountains
  • Suggests Bollywood movie theaters, matching user's preference for Bollywood over Hollywood
  • Provides more diverse dining options, including Indian cuisine, based on user's food preferences
  • Overall, the recommendations are more tailored to the user's specific interests and preferences, demonstrating the effectiveness of the new UserMemory feature

This TL;DR highlights the key differences between the agent outputs, specifically showing how the agent with memory provides more personalized and relevant recommendations based on the user preferences you provided in the example.

Travel Planner Agent Output without Memory

#### **Places to Live (Accommodations)**

1. **Palace Hotel, a Luxury Collection Hotel, San Francisco**
   - Address: 2 New Montgomery St, San Francisco, CA 94105
   - Description: A historic luxury hotel known for its opulent interiors and exceptional service.
   - Website: [Palace Hotel](https://www.marriott.com/hotels/travel/sfolc-palace-hotel-a-luxury-collection-hotel-san-francisco/)

2. **The St. Regis San Francisco**
   - Address: 125 3rd St, San Francisco, CA 94103
   - Description: A high-end hotel renowned for its modern elegance and prime location near Yerba Buena Gardens.
   - Website: [The St. Regis San Francisco](https://www.marriott.com/hotels/travel/sfoxr-the-st-regis-san-francisco/)

3. **Omni San Francisco Hotel**
   - Address: 500 California St, San Francisco, CA 94104
   - Description: Located in the Financial District, this hotel offers luxurious accommodations with a classic ambiance.
   - Website: [Omni San Francisco Hotel](https://www.omnihotels.com/hotels/san-francisco)

4. **Four Seasons Hotel San Francisco**
   - Address: 757 Market St, San Francisco, CA 94103
   - Description: A plush hotel offering refined rooms and suites with stunning city views.
   - Website: [Four Seasons Hotel San Francisco](https://www.fourseasons.com/sanfrancisco/)

5. **InterContinental San Francisco, an IHG Hotel**
   - Address: 888 Howard St, San Francisco, CA 94103
   - Description: Known for its modern design and excellent amenities, perfect for both business and leisure travelers.
   - Website: [InterContinental San Francisco](https://www.ihg.com/intercontinental/hotels/us/en/san-francisco/sfohb/hoteldetail)

#### **Places to Eat (Dining)**

1. **Tartine Bakery**
   - Address: 600 Guerrero St, San Francisco, CA 94110
   - Description: Famous for its artisanal bread, pastries, and coffee, a must-visit for breakfast or a sweet treat.
   - Website: [Tartine Bakery](https://tartinebakery.com/)

2. **Zuni Café**
   - Address: 1658 Market St, San Francisco, CA 94102
   - Description: An iconic restaurant known for its roast chicken and eclectic menu featuring local ingredients.
   - Website: [Zuni Café](https://zunicafe.com/)

3. **Swan Oyster Depot**
   - Address: 1517 Polk St, San Francisco, CA 94109
   - Description: A historic seafood counter offering fresh oysters, crab, and clam chowder.
   - Website: [Swan Oyster Depot](https://swanoysterdepot.us/)

4. **House of Prime Rib**
   - Address: 1906 Van Ness Ave, San Francisco, CA 94109
   - Description: A classic steakhouse serving prime rib in a traditional setting.
   - Website: [House of Prime Rib](https://houseofprimerib.net/)

5. **State Bird Provisions**
   - Address: 1529 Fillmore St, San Francisco, CA 94115
   - Description: Known for its innovative small plates and dim sum-style service.
   - Website: [State Bird Provisions](https://statebirdsf.com/)

#### **Places to Visit (Attractions)**

1. **Golden Gate Bridge**
   - Location: Golden Gate Bridge, San Francisco, CA
   - Description: An iconic suspension bridge offering breathtaking views of the bay and the city.

2. **Alcatraz Island**
   - Location: San Francisco, CA 94133
   - Description: A historic island featuring the infamous former prison, accessible by ferry.
   - Website: [Alcatraz Island](https://www.nps.gov/alca/index.htm)

3. **Fisherman's Wharf**
   - Location: San Francisco, CA 94133
   - Description: A bustling waterfront area with shops, restaurants, and attractions like Pier 39.

4. **Golden Gate Park**
   - Location: San Francisco, CA
   - Description: A vast urban park home to gardens, museums, and recreational facilities.
   - Website: [Golden Gate Park](https://sfrecpark.org/512/Golden-Gate-Park)

5. **Exploratorium**
   - Address: Pier 15, The Embarcadero, San Francisco, CA 94111
   - Description: An interactive science museum perfect for visitors of all ages.
   - Website: [Exploratorium](https://www.exploratorium.edu/)

6. **Chinatown**
   - Location: Grant Ave, San Francisco, CA 94108
   - Description: One of the oldest and most vibrant Chinatowns in the U.S., with shops, eateries, and cultural sites.

7. **Lombard Street**
   - Location: Lombard St, San Francisco, CA 94133
   - Description: Known as the "crookedest street in the world," famous for its steep, winding turns.

8. **Muir Woods National Monument**
   - Address: 1 Muir Woods Rd, Mill Valley, CA 94941
   - Description: A serene forest with towering redwoods, located just outside the city.
   - Website: [Muir Woods National Monument](https://www.nps.gov/muwo/index.htm)

Travel Planner Agent Output with Memory

## Detailed 5-Day Travel Plan to San Francisco

### Accommodations (Airbnb)
Based on the search results, here are some highly-rated Airbnb options in San Francisco:

1. **Ocean-Front Home in Pacifica**
   - Description: Stunning ocean views with modern amenities.
   - [Link](https://www.timeout.com/san-francisco/hotels/best-airbnb-san-francisco-rentals)

2. **Bernal Heights Studio**
   - Description: Cozy and private studio in a quiet neighborhood.
   - [Link](https://www.timeout.com/san-francisco/hotels/best-airbnb-san-francisco-rentals)

3. **Contemporary Villa on Mount Sutro**
   - Description: Modern villa with panoramic city views.
   - [Link](https://www.timeout.com/san-francisco/hotels/best-airbnb-san-francisco-rentals)

4. **Minimalist Suite in Outer Sunset**
   - Description: Simple and elegant suite near the beach.
   - [Link](https://www.cntraveler.com/gallery/best-airbnbs-in-san-francisco)

5. **Guest Suite in Outer Sunset**
   - Description: Comfortable and spacious guest suite close to the beach.
   - [Link](https://www.airbnb.com/san-francisco-ca/stays)

### Beaches to Visit
Given the preference for beaches, here are some top beach destinations in San Francisco:

1. **Baker Beach**
   - Description: Offers stunning views of the Golden Gate Bridge and is great for picnics and sunbathing.
   - Activities: Picnicking, walking, photography.

2. **Ocean Beach**
   - Description: A long stretch of beach popular for surfing and bonfires.
   - Activities: Surfing, beachcombing, bonfires.

3. **China Beach**
   - Description: A hidden gem with beautiful views and a more secluded atmosphere.
   - Activities: Sunbathing, picnicking.

4. **Crissy Field Beach**
   - Description: Located in the Presidio, it offers views of the Golden Gate Bridge and ample space for outdoor activities.
   - Activities: Walking, cycling, picnics.

### Bollywood Movie Theaters
Since you prefer Bollywood movies over Hollywood movies, here are some theaters that screen Bollywood movies in San Francisco:

1. **Cine Lounge Fremont 7**
   - Description: A popular theater for Bollywood films, located a short drive from San Francisco.
   - [Link](https://www.cinelounge.net)

2. **Towne 3 Cinemas**
   - Description: Located in San Jose, this theater often screens Bollywood movies.
   - [Link](https://www.towne3.com)

3. **Naz 8 Cinemas**
   - Description: Located in Fremont, known for screening the latest Bollywood films.
   - [Link](https://www.naz8.com)

### Restaurants to Dine At
Here are some renowned restaurants to enjoy diverse culinary experiences in San Francisco:

1. **Tadich Grill**
   - Cuisine: Seafood
   - Description: One of the oldest restaurants in San Francisco, famous for its seafood dishes.
   - [Link](https://www.tadichgrill.com)

2. **Zuni Café**
   - Cuisine: Mediterranean
   - Description: Known for its roast chicken and seasonal dishes.
   - [Link](https://www.zunicafe.com)

3. **Nopa**
   - Cuisine: Californian
   - Description: Offers a farm-to-table dining experience with a focus on organic ingredients.
   - [Link](https://www.nopasf.com)

4. **La Taqueria**
   - Cuisine: Mexican
   - Description: Famous for its Mission-style burritos and tacos.
   - [Link](https://www.lataqueriasf.com)

5. **Foreign Cinema**
   - Cuisine: American
   - Description: Combines dining with a unique experience of watching films in an outdoor courtyard.
   - [Link](https://www.foreigncinema.com)

@Dev-Khant Dev-Khant changed the title Intergrate mem0 Add support for retrieving user preferences and memories using Mem0 Aug 20, 2024
@theCyberTech theCyberTech self-assigned this Aug 30, 2024
@theCyberTech theCyberTech added the Under review Feature requests under review label Aug 30, 2024
)
return f"Entities:\n{formatted_results}" if em_results else ""

def _fetch_user_memories(self, query) -> str:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is never being called?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, there was a pending local commit for this. Pushed now.

@Dev-Khant
Copy link
Contributor Author

Hey @joaomdmoura @theCyberTech could you please add the Mem0 API key to the CI variables to enable the Mem0 tests to run?

@joaomdmoura
Copy link
Collaborator

Sure! I'm testing this again tomorrow so we cna merge :)

pyproject.toml Outdated Show resolved Hide resolved
@Dev-Khant
Copy link
Contributor Author

Hey @joaomdmoura @bhancockio Can you please review the PR, I have made the necessary changes.

@bhancockio
Copy link
Collaborator

@bhancockio
Copy link
Collaborator

Screenshot 2024-10-25 at 2 05 46 PM

Could you please also address these mem0 run type issues?

@bhancockio bhancockio closed this Oct 25, 2024
@bhancockio bhancockio reopened this Oct 25, 2024
@bhancockio
Copy link
Collaborator

If I create a crew like this:

crew = Crew(
    agents=[qa_agent],
    tasks=[qa_task],
    verbose=True,
    memory=True,
    memory_config={
        "provider": "mem0",
        "config": {"user_id": "Personal Travel Planner Agent"},
    },
    process=Process.sequential,
)

And I do not include a mem0 API key, I get the following error:

Traceback (most recent call last):
  File "/Users/brandonhancock/Desktop/flow examples/memo_zero.py", line 31, in <module>
    crew = Crew(
           ^^^^^
  File "/Users/brandonhancock/miniconda3/envs/crewai/lib/python3.12/site-packages/pydantic/main.py", line 212, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for Crew
  Value error, API Key not provided. Please provide an API Key. [type=value_error, input_value={'agents': [Agent(role=Q&...quential: 'sequential'>}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.9/v/value_error

It's not clear that the Mem0 API key is missing which will make it hard for our users to know how to fix this bug

@Dev-Khant
Copy link
Contributor Author

Hey @bhancockio I have fixed mypy issue and fixed the error message for api key in latest version of mem0. Will resolve the other issue in a while.

self.entity_memory
if self.entity_memory
else EntityMemory(crew=self, embedder_config=self.embedder)
self._entity_memory = EntityMemory(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add back in the check for if entity memory exists?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.

em: EntityMemory,
um: UserMemory,
):
self.memory_provider = stm.memory_provider
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to tie together memory provider with the short term memory?

Shouldn't we update the parameters of ContextualMemory to include memory_config?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes makes sense. I have updated the params for ContextualMemory.

storage
if storage
else RAGStorage(
if hasattr(crew, "memory_config") and crew.memory_config is not None:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we tying together entity memory with user memory? Shouldn't they be separate?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root issue is that we are an agnostic platform and this PR directly couples CrewAI memory with mem0.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, thanks for reviewing the PR!

In this case, we're using Mem0 within entity_memory when the user opts for Mem0. So, it's not only the user memory being utilized but also the entity memory.

Let me know if we only want to use user_memory when user opts for Mem0 and keep other memories as is.

if storage
else RAGStorage(
type="short_term", embedder_config=embedder_config, crew=crew
if hasattr(crew, "memory_config") and crew.memory_config is not None:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once again, why are we connecting short term with mem0? Shouldn't we only be checking user memory?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here when user opts for Mem0 we use mem0 inside short_term memory as well.

So let me know if we only want to use user_memory when user opts for Mem0 and keep other memories as is.

@@ -7,8 +7,10 @@ class Storage:
def save(self, value: Any, metadata: Dict[str, Any]) -> None:
pass

def search(self, key: str) -> List[Dict[str, Any]]: # type: ignore
pass
def search(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Search is supposed to return a list of dictionaries not just a single dictionary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey here I included to have either Dict[str, Any] or List[Any]

@@ -160,7 +162,7 @@ def search(
self,
query: str,
limit: int = 3,
filter: Optional[dict] = None,
filters: Optional[dict] = None,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't look like filters is being used.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I have removed it.

pyproject.toml Outdated
@@ -21,6 +21,7 @@ dependencies = [
"python-dotenv>=1.0.0",
"appdirs>=1.4.4",
"jsonref>=1.1.0",
"mem0ai>=0.1.24",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be an optional dependency that users who want to use mem0 can add.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, moved to optional dependency.

storage
if storage
else RAGStorage(
if hasattr(crew, "memory_config") and crew.memory_config is not None:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root issue is that we are an agnostic platform and this PR directly couples CrewAI memory with mem0.

@Dev-Khant
Copy link
Contributor Author

Error with changes:

https://www.loom.com/share/4fd6d38df8954bdfb3d9baec7bbd7538?sid=3d72f1e4-12ff-4286-bb4c-e17d38c8fb9d

Hey @bhancockio, latest commit resolves the issue mentioned here.

pyproject.toml Outdated
@@ -39,6 +39,7 @@ Repository = "https://github.com/crewAIInc/crewAI"
[project.optional-dependencies]
tools = ["crewai-tools>=0.13.4"]
agentops = ["agentops>=0.3.0"]
mem0 = ["mem0ai>=0.1.24"]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Dev-Khant Should this be 0.1.29 now?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes bumped up the version

@bhancockio
Copy link
Collaborator

@Dev-Khant here are my final remarks. We are super close to getting this merged in!

https://www.loom.com/share/4610bf10afc147379aec202f0aca005b?sid=f1a0773a-c66b-447c-a199-905485e8b8f3

@Dev-Khant
Copy link
Contributor Author

Dev-Khant commented Nov 7, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Under review Feature requests under review
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants