Updated integration docs (#3392)

This commit is contained in:
Parshva Daftari
2025-09-02 04:26:43 +05:30
committed by GitHub
parent 97fd320bbf
commit c8f9f20dff
10 changed files with 163 additions and 95 deletions
@@ -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
@@ -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
# 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"
load_dotenv()
# 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
+3 -1
View File
@@ -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:
@@ -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")
+9 -8
View File
@@ -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:
@@ -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:
"""
@@ -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"""
@@ -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."
@@ -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)
```
+16 -9
View File
@@ -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
@@ -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.
@@ -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()
@@ -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.")
```
@@ -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:
@@ -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"""
+1 -1
View File
@@ -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:
+16 -11
View File
@@ -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:
@@ -30,15 +30,19 @@ 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()
@@ -46,17 +50,18 @@ 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)}"}
@@ -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.
@@ -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}"
@@ -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)
```
+42 -28
View File
@@ -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:
@@ -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"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4o-mini")
@@ -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"""
@@ -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
@@ -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: ")
+45 -17
View File
@@ -16,7 +16,7 @@ In this guide, we'll create a Customer Support AI Agent that:
Install necessary libraries:
```bash
pip install langgraph langchain-openai mem0ai
pip install langgraph langchain-openai mem0ai python-dotenv
```
@@ -31,14 +31,17 @@ from langgraph.graph.message import add_messages
from langchain_openai import ChatOpenAI
from mem0 import MemoryClient
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
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
# 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
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4", api_key=OPENAI_API_KEY)
mem0 = MemoryClient(api_key=MEM0_API_KEY)
llm = ChatOpenAI(model="gpt-4")
mem0 = MemoryClient()
```
## Define State and Graph
@@ -62,22 +65,47 @@ def chatbot(state: State):
messages = state["messages"]
user_id = state["mem0_user_id"]
# Retrieve relevant memories
memories = mem0.search(messages[-1].content, user_id=user_id)
try:
# Retrieve relevant memories
memories = mem0.search(messages[-1].content, user_id=user_id, output_format='v1.1')
# Handle dict response format
memory_list = memories['results']
context = "Relevant information from previous conversations:\n"
for memory in memories.get('results', []):
context += f"- {memory['memory']}\n"
context = "Relevant information from previous conversations:\n"
for memory in memory_list:
context += f"- {memory['memory']}\n"
system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
{context}""")
full_messages = [system_message] + messages
response = llm.invoke(full_messages)
full_messages = [system_message] + messages
response = llm.invoke(full_messages)
# Store the interaction in Mem0
mem0.add(f"User: {messages[-1].content}\nAssistant: {response.content}", user_id=user_id)
return {"messages": [response]}
# Store the interaction in Mem0
try:
interaction = [
{
"role": "user",
"content": messages[-1].content
},
{
"role": "assistant",
"content": response.content
}
]
result = mem0.add(interaction, user_id=user_id, output_format='v1.1')
print(f"Memory saved: {len(result.get('results', []))} memories added")
except Exception as e:
print(f"Error saving memory: {e}")
return {"messages": [response]}
except Exception as e:
print(f"Error in chatbot: {e}")
# Fallback response without memory context
response = llm.invoke(messages)
return {"messages": [response]}
```
## Set Up Graph Structure
@@ -115,7 +143,7 @@ Set up the main program loop for user interaction:
```python
if __name__ == "__main__":
print("Welcome to Customer Support! How can I assist you today?")
mem0_user_id = "customer_123" # You can generate or retrieve this based on your user management system
mem0_user_id = "alice" # You can generate or retrieve this based on your user management system
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit', 'bye']:
+20 -12
View File
@@ -13,7 +13,7 @@ LlamaIndex supports Mem0 as a [memory store](https://llamahub.ai/l/memory/llama-
To install the required package, run:
```bash
pip install llama-index-core llama-index-memory-mem0
pip install llama-index-core llama-index-memory-mem0 python-dotenv
```
### Setup with Mem0 Platform
@@ -25,18 +25,23 @@ Set your Mem0 Platform API key as an environment variable. You can replace `<you
</Note>
```python
os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
from dotenv import load_dotenv
import os
load_dotenv()
# os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
```
Import the necessary modules and create a Mem0Memory instance:
```python
from llama_index.memory.mem0 import Mem0Memory
context = {"user_id": "user_1"}
context = {"user_id": "alice"}
memory_from_client = Mem0Memory.from_client(
context=context,
api_key="<your-mem0-api-key>",
search_msg_limit=4, # optional, default is 5
output_format='v1.1', # Remove deprecation warnings
)
```
@@ -44,8 +49,8 @@ Context is used to identify the user, agent or the conversation in the Mem0. It
```python
context = {
"user_id": "user_1",
"agent_id": "agent_1",
"user_id": "alice",
"agent_id": "llama_agent_1",
"run_id": "run_1",
}
```
@@ -98,17 +103,20 @@ memory_from_config = Mem0Memory.from_config(
context=context,
config=config,
search_msg_limit=4, # optional, default is 5
output_format='v1.1', # Remove deprecation warnings
)
```
Initialize the LLM
```python
import os
from llama_index.llms.openai import OpenAI
from dotenv import load_dotenv
os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4o")
load_dotenv()
# os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4o-mini")
```
### SimpleChatEngine
@@ -122,7 +130,7 @@ agent = SimpleChatEngine.from_defaults(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
Now we will learn how to use Mem0 with FunctionCalling and ReAct agents.
@@ -165,7 +173,7 @@ agent = FunctionCallingAgent.from_tools(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
@@ -182,7 +190,7 @@ agent = ReActAgent.from_tools(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
+1 -1
View File
@@ -92,7 +92,7 @@ async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
# Basic setup with minimal configuration
user_id = "user123"
user_id = "alice"
# WebSocket transport
transport = FastAPIWebsocketTransport(