Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions docs/examples/mem0-google-adk-healthcare-assistant.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ Before you begin, make sure you have:

Installed Google ADK and Mem0 SDK:
```bash
pip install google-adk
pip install mem0ai
pip install google-adk mem0ai python-dotenv
```

## Code Breakdown
Expand All @@ -35,21 +34,25 @@ Let's get started and understand the different components required in building a
```python
# Import dependencies
import os
import asyncio
from google.adk.agents import Agent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from mem0 import MemoryClient
from dotenv import load_dotenv

load_dotenv()

# Set up API keys (replace with your actual keys)
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Set up environment variables
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"

# Define a global user ID for simplicity
USER_ID = "Alex"

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

## Define Memory Tools
Expand Down
4 changes: 3 additions & 1 deletion docs/integrations/agentops.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Before setting up Mem0 with AgentOps, ensure you have:

1. Installed the required packages:
```bash
pip install mem0ai agentops
pip install mem0ai agentops python-dotenv
```

2. Valid API keys:
Expand All @@ -37,7 +37,9 @@ import asyncio
import logging
from dotenv import load_dotenv
import agentops
import openai

load_dotenv()
#Set up environment variables for API keys
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
Expand Down
17 changes: 9 additions & 8 deletions docs/integrations/agno.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Before setting up Mem0 with Agno, ensure you have:

1. Installed the required packages:
```bash
pip install agno mem0ai
pip install agno mem0ai python-dotenv
```

2. Valid API keys:
Expand Down Expand Up @@ -81,7 +81,7 @@ agent = Agent(

def chat_user(
user_input: Optional[str] = None,
user_id: str = "user_123",
user_id: str = "alex",
image_path: Optional[str] = None
) -> str:
"""
Expand Down Expand Up @@ -120,13 +120,13 @@ def chat_user(
})

# Store messages in memory
client.add(messages, user_id=user_id)
client.add(messages, user_id=user_id, output_format='v1.1')
print("✅ Image and text stored in memory.")

if user_input:
# Search for relevant memories
memories = client.search(user_input, user_id=user_id)
memory_context = "\n".join(f"- {m['memory']}" for m in memories.get('results', []))
memories = client.search(user_input, user_id=user_id, output_format='v1.1')
memory_context = "\n".join(f"- {m['memory']}" for m in memories['results'])

# Construct the prompt
prompt = f"""
Expand All @@ -150,7 +150,8 @@ User question:
response = agent.run(prompt)

# Store the interaction in memory
client.add(f"User: {user_input}\nAssistant: {response.content}", user_id=user_id)
interaction_message = [{"role": "user", "content": f"User: {user_input}\nAssistant: {response.content}"}]
client.add(interaction_message, user_id=user_id, output_format='v1.1')
return response.content

return "No user input or image provided."
Expand All @@ -159,9 +160,9 @@ User question:
# Example Usage
if __name__ == "__main__":
response = chat_user(
"This is the picture of what I brought with me in the trip to Bahamas",
"I like to travel and my favorite destination is London",
image_path="travel_items.jpeg",
user_id="user_123"
user_id="alex"
)
print(response)
```
Expand Down
25 changes: 16 additions & 9 deletions docs/integrations/autogen.mdx
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
---
title: AutoGen
---

Build conversational AI agents with memory capabilities. This integration combines AutoGen for creating AI agents with Mem0 for memory management, enabling context-aware and personalized interactions.

## Overview
Expand All @@ -10,7 +14,7 @@ In this guide, we'll explore an example of creating a conversational AI system w
Install necessary libraries:

```bash
pip install pyautogen mem0ai openai
pip install autogen mem0ai openai python-dotenv
```

First, we'll import the necessary libraries and set up our configurations.
Expand All @@ -22,15 +26,18 @@ import os
from autogen import ConversableAgent
from mem0 import MemoryClient
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

# Configuration
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key from https://app.mem0.ai
USER_ID = "customer_service_bot"
# OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key from https://app.mem0.ai
USER_ID = "alice"

# Set up OpenAI API key
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
# os.environ['MEM0_API_KEY'] = MEM0_API_KEY

# Initialize Mem0 and AutoGen agents
memory_client = MemoryClient()
Expand All @@ -55,7 +62,7 @@ conversation = [
{"role": "assistant", "content": "Thank you for the information. Let's troubleshoot this issue..."}
]

memory_client.add(messages=conversation, user_id=USER_ID)
memory_client.add(messages=conversation, user_id=USER_ID, output_format="v1.1")
print("Conversation added to memory.")
```

Expand All @@ -65,7 +72,7 @@ Create a function to get context-aware responses based on user's question and pr

```python
def get_context_aware_response(question):
relevant_memories = memory_client.search(question, user_id=USER_ID)
relevant_memories = memory_client.search(question, user_id=USER_ID, output_format='v1.1')
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])

prompt = f"""Answer the user question considering the previous interactions:
Expand Down Expand Up @@ -97,7 +104,7 @@ manager = ConversableAgent(
)

def escalate_to_manager(question):
relevant_memories = memory_client.search(question, user_id=USER_ID)
relevant_memories = memory_client.search(question, user_id=USER_ID, output_format='v1.1')
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])

prompt = f"""
Expand Down
2 changes: 1 addition & 1 deletion docs/integrations/elevenlabs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ In this guide, we'll build a voice agent that:
Install necessary libraries:

```bash
pip install elevenlabs mem0 python-dotenv
pip install elevenlabs mem0ai python-dotenv
```

Configure your environment variables:
Expand Down
27 changes: 16 additions & 11 deletions docs/integrations/google-ai-adk.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Before setting up Mem0 with Google ADK, ensure you have:

1. Installed the required packages:
```bash
pip install google-adk mem0ai
pip install google-adk mem0ai python-dotenv
```

2. Valid API keys:
Expand All @@ -30,33 +30,38 @@ The following example demonstrates how to create a Google ADK agent with Mem0 me

```python
import os
import asyncio
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from mem0 import MemoryClient
from dotenv import load_dotenv

load_dotenv()

# Set up environment variables
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"

# Initialize Mem0 client
mem0 = MemoryClient()

# Define memory function tools
def search_memory(query: str, user_id: str) -> dict:
"""Search through past conversations and memories"""
memories = mem0.search(query, user_id=user_id)
memories = mem0.search(query, user_id=user_id, output_format='v1.1')
if memories.get('results', []):
memory_context = "\n".join([f"- {mem['memory']}" for mem in memories.get('results', [])])
memory_list = memories['results']
memory_context = "\n".join([f"- {mem['memory']}" for mem in memory_list])
return {"status": "success", "memories": memory_context}
return {"status": "no_memories", "message": "No relevant memories found"}

def save_memory(content: str, user_id: str) -> dict:
"""Save important information to memory"""
try:
mem0.add([{"role": "user", "content": content}], user_id=user_id)
return {"status": "success", "message": "Information saved to memory"}
result = mem0.add([{"role": "user", "content": content}], user_id=user_id, output_format='v1.1')
return {"status": "success", "message": "Information saved to memory", "result": result}
except Exception as e:
return {"status": "error", "message": f"Failed to save memory: {str(e)}"}

Expand All @@ -72,7 +77,7 @@ personal_assistant = Agent(
tools=[search_memory, save_memory]
)

def chat_with_agent(user_input: str, user_id: str) -> str:
async def chat_with_agent(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic memory integration.

Expand All @@ -85,7 +90,7 @@ def chat_with_agent(user_input: str, user_id: str) -> str:
"""
# Set up session and runner
session_service = InMemorySessionService()
session = session_service.create_session(
session = await session_service.create_session(
app_name="memory_assistant",
user_id=user_id,
session_id=f"session_{user_id}"
Expand All @@ -107,10 +112,10 @@ def chat_with_agent(user_input: str, user_id: str) -> str:

# Example usage
if __name__ == "__main__":
response = chat_with_agent(
response = asyncio.run(chat_with_agent(
"I love Italian food and I'm planning a trip to Rome next month",
user_id="alice"
)
))
print(response)
```

Expand Down
70 changes: 42 additions & 28 deletions docs/integrations/langchain.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ In this guide, we'll create a Travel Agent AI that:
Install necessary libraries:

```bash
pip install langchain langchain_openai mem0ai
pip install langchain langchain_openai mem0ai python-dotenv
```

Import required modules and set up configurations:
Expand All @@ -30,10 +30,13 @@ from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from mem0 import MemoryClient
from dotenv import load_dotenv

load_dotenv()

# Configuration
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
Copy link
Member

Choose a reason for hiding this comment

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

Any particular reason for commenting this out? 😅

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added a load_dotenv() to get the environment variables. Which eliminates the need for the os.environ.

Copy link
Member

Choose a reason for hiding this comment

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

I see but this particular snippet sets the envs not loads that, but I see your point

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 so commented just in case to keep it as option there.

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

# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4o-mini")
Expand Down Expand Up @@ -61,19 +64,26 @@ Create functions to handle context retrieval, response generation, and addition
```python
def retrieve_context(query: str, user_id: str) -> List[Dict]:
"""Retrieve relevant context from Mem0"""
memories = mem0.search(query, user_id=user_id)
serialized_memories = ' '.join([mem["memory"] for mem in memories.get('results', [])])
context = [
{
"role": "system",
"content": f"Relevant information: {serialized_memories}"
},
{
"role": "user",
"content": query
}
]
return context
try:
memories = mem0.search(query, user_id=user_id, output_format='v1.1')
memory_list = memories['results']

serialized_memories = ' '.join([mem["memory"] for mem in memory_list])
context = [
{
"role": "system",
"content": f"Relevant information: {serialized_memories}"
},
{
"role": "user",
"content": query
}
]
return context
except Exception as e:
print(f"Error retrieving memories: {e}")
# Return empty context if there's an error
return [{"role": "user", "content": query}]

def generate_response(input: str, context: List[Dict]) -> str:
"""Generate a response using the language model"""
Expand All @@ -86,17 +96,21 @@ def generate_response(input: str, context: List[Dict]) -> str:

def save_interaction(user_id: str, user_input: str, assistant_response: str):
"""Save the interaction to Mem0"""
interaction = [
{
"role": "user",
"content": user_input
},
{
"role": "assistant",
"content": assistant_response
}
]
mem0.add(interaction, user_id=user_id)
try:
interaction = [
{
"role": "user",
"content": user_input
},
{
"role": "assistant",
"content": assistant_response
}
]
result = mem0.add(interaction, user_id=user_id, output_format='v1.1')
print(f"Memory saved successfully: {len(result.get('results', []))} memories added")
except Exception as e:
print(f"Error saving interaction: {e}")
```

## Create Chat Turn Function
Expand Down Expand Up @@ -124,7 +138,7 @@ Set up the main program loop for user interaction:
```python
if __name__ == "__main__":
print("Welcome to your personal Travel Agent Planner! How can I assist you with your travel plans today?")
user_id = "john"
user_id = "alice"

while True:
user_input = input("You: ")
Expand Down
Loading
Loading