Updated integration docs (#3392)
This commit is contained in:
@@ -24,8 +24,7 @@ Before you begin, make sure you have:
|
|||||||
|
|
||||||
Installed Google ADK and Mem0 SDK:
|
Installed Google ADK and Mem0 SDK:
|
||||||
```bash
|
```bash
|
||||||
pip install google-adk
|
pip install google-adk mem0ai python-dotenv
|
||||||
pip install mem0ai
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Code Breakdown
|
## Code Breakdown
|
||||||
@@ -35,21 +34,25 @@ Let's get started and understand the different components required in building a
|
|||||||
```python
|
```python
|
||||||
# Import dependencies
|
# Import dependencies
|
||||||
import os
|
import os
|
||||||
|
import asyncio
|
||||||
from google.adk.agents import Agent
|
from google.adk.agents import Agent
|
||||||
from google.adk.sessions import InMemorySessionService
|
|
||||||
from google.adk.runners import Runner
|
from google.adk.runners import Runner
|
||||||
|
from google.adk.sessions import InMemorySessionService
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
from mem0 import MemoryClient
|
from mem0 import MemoryClient
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
# Set up API keys (replace with your actual keys)
|
load_dotenv()
|
||||||
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
|
# Define a global user ID for simplicity
|
||||||
USER_ID = "Alex"
|
USER_ID = "Alex"
|
||||||
|
|
||||||
# Initialize Mem0 client
|
# Initialize Mem0 client
|
||||||
mem0_client = MemoryClient()
|
mem0 = MemoryClient()
|
||||||
```
|
```
|
||||||
|
|
||||||
## Define Memory Tools
|
## Define Memory Tools
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ Before setting up Mem0 with AgentOps, ensure you have:
|
|||||||
|
|
||||||
1. Installed the required packages:
|
1. Installed the required packages:
|
||||||
```bash
|
```bash
|
||||||
pip install mem0ai agentops
|
pip install mem0ai agentops python-dotenv
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Valid API keys:
|
2. Valid API keys:
|
||||||
@@ -37,7 +37,9 @@ import asyncio
|
|||||||
import logging
|
import logging
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import agentops
|
import agentops
|
||||||
|
import openai
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
#Set up environment variables for API keys
|
#Set up environment variables for API keys
|
||||||
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
|
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
|
||||||
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ Before setting up Mem0 with Agno, ensure you have:
|
|||||||
|
|
||||||
1. Installed the required packages:
|
1. Installed the required packages:
|
||||||
```bash
|
```bash
|
||||||
pip install agno mem0ai
|
pip install agno mem0ai python-dotenv
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Valid API keys:
|
2. Valid API keys:
|
||||||
@@ -81,7 +81,7 @@ agent = Agent(
|
|||||||
|
|
||||||
def chat_user(
|
def chat_user(
|
||||||
user_input: Optional[str] = None,
|
user_input: Optional[str] = None,
|
||||||
user_id: str = "user_123",
|
user_id: str = "alex",
|
||||||
image_path: Optional[str] = None
|
image_path: Optional[str] = None
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
@@ -120,13 +120,13 @@ def chat_user(
|
|||||||
})
|
})
|
||||||
|
|
||||||
# Store messages in memory
|
# 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.")
|
print("✅ Image and text stored in memory.")
|
||||||
|
|
||||||
if user_input:
|
if user_input:
|
||||||
# Search for relevant memories
|
# Search for relevant memories
|
||||||
memories = client.search(user_input, user_id=user_id)
|
memories = client.search(user_input, user_id=user_id, output_format='v1.1')
|
||||||
memory_context = "\n".join(f"- {m['memory']}" for m in memories.get('results', []))
|
memory_context = "\n".join(f"- {m['memory']}" for m in memories['results'])
|
||||||
|
|
||||||
# Construct the prompt
|
# Construct the prompt
|
||||||
prompt = f"""
|
prompt = f"""
|
||||||
@@ -150,7 +150,8 @@ User question:
|
|||||||
response = agent.run(prompt)
|
response = agent.run(prompt)
|
||||||
|
|
||||||
# Store the interaction in memory
|
# 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 response.content
|
||||||
|
|
||||||
return "No user input or image provided."
|
return "No user input or image provided."
|
||||||
@@ -159,9 +160,9 @@ User question:
|
|||||||
# Example Usage
|
# Example Usage
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
response = chat_user(
|
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",
|
image_path="travel_items.jpeg",
|
||||||
user_id="user_123"
|
user_id="alex"
|
||||||
)
|
)
|
||||||
print(response)
|
print(response)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -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.
|
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
|
## Overview
|
||||||
@@ -10,7 +14,7 @@ In this guide, we'll explore an example of creating a conversational AI system w
|
|||||||
Install necessary libraries:
|
Install necessary libraries:
|
||||||
|
|
||||||
```bash
|
```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.
|
First, we'll import the necessary libraries and set up our configurations.
|
||||||
@@ -22,15 +26,18 @@ import os
|
|||||||
from autogen import ConversableAgent
|
from autogen import ConversableAgent
|
||||||
from mem0 import MemoryClient
|
from mem0 import MemoryClient
|
||||||
from openai import OpenAI
|
from openai import OpenAI
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
# Configuration
|
# Configuration
|
||||||
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI 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 from https://app.mem0.ai
|
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key from https://app.mem0.ai
|
||||||
USER_ID = "customer_service_bot"
|
USER_ID = "alice"
|
||||||
|
|
||||||
# Set up OpenAI API key
|
# Set up OpenAI API key
|
||||||
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
|
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
|
||||||
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
|
# os.environ['MEM0_API_KEY'] = MEM0_API_KEY
|
||||||
|
|
||||||
# Initialize Mem0 and AutoGen agents
|
# Initialize Mem0 and AutoGen agents
|
||||||
memory_client = MemoryClient()
|
memory_client = MemoryClient()
|
||||||
@@ -55,7 +62,7 @@ conversation = [
|
|||||||
{"role": "assistant", "content": "Thank you for the information. Let's troubleshoot this issue..."}
|
{"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.")
|
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
|
```python
|
||||||
def get_context_aware_response(question):
|
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', [])])
|
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
|
||||||
|
|
||||||
prompt = f"""Answer the user question considering the previous interactions:
|
prompt = f"""Answer the user question considering the previous interactions:
|
||||||
@@ -97,7 +104,7 @@ manager = ConversableAgent(
|
|||||||
)
|
)
|
||||||
|
|
||||||
def escalate_to_manager(question):
|
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', [])])
|
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
|
||||||
|
|
||||||
prompt = f"""
|
prompt = f"""
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ In this guide, we'll build a voice agent that:
|
|||||||
Install necessary libraries:
|
Install necessary libraries:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install elevenlabs mem0 python-dotenv
|
pip install elevenlabs mem0ai python-dotenv
|
||||||
```
|
```
|
||||||
|
|
||||||
Configure your environment variables:
|
Configure your environment variables:
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ Before setting up Mem0 with Google ADK, ensure you have:
|
|||||||
|
|
||||||
1. Installed the required packages:
|
1. Installed the required packages:
|
||||||
```bash
|
```bash
|
||||||
pip install google-adk mem0ai
|
pip install google-adk mem0ai python-dotenv
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Valid API keys:
|
2. Valid API keys:
|
||||||
@@ -30,15 +30,19 @@ The following example demonstrates how to create a Google ADK agent with Mem0 me
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
import os
|
import os
|
||||||
|
import asyncio
|
||||||
from google.adk.agents import Agent
|
from google.adk.agents import Agent
|
||||||
from google.adk.runners import Runner
|
from google.adk.runners import Runner
|
||||||
from google.adk.sessions import InMemorySessionService
|
from google.adk.sessions import InMemorySessionService
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
from mem0 import MemoryClient
|
from mem0 import MemoryClient
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
# Set up environment variables
|
# Set up environment variables
|
||||||
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
|
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
|
||||||
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
|
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
|
||||||
|
|
||||||
# Initialize Mem0 client
|
# Initialize Mem0 client
|
||||||
mem0 = MemoryClient()
|
mem0 = MemoryClient()
|
||||||
@@ -46,17 +50,18 @@ mem0 = MemoryClient()
|
|||||||
# Define memory function tools
|
# Define memory function tools
|
||||||
def search_memory(query: str, user_id: str) -> dict:
|
def search_memory(query: str, user_id: str) -> dict:
|
||||||
"""Search through past conversations and memories"""
|
"""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', []):
|
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": "success", "memories": memory_context}
|
||||||
return {"status": "no_memories", "message": "No relevant memories found"}
|
return {"status": "no_memories", "message": "No relevant memories found"}
|
||||||
|
|
||||||
def save_memory(content: str, user_id: str) -> dict:
|
def save_memory(content: str, user_id: str) -> dict:
|
||||||
"""Save important information to memory"""
|
"""Save important information to memory"""
|
||||||
try:
|
try:
|
||||||
mem0.add([{"role": "user", "content": content}], user_id=user_id)
|
result = mem0.add([{"role": "user", "content": content}], user_id=user_id, output_format='v1.1')
|
||||||
return {"status": "success", "message": "Information saved to memory"}
|
return {"status": "success", "message": "Information saved to memory", "result": result}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"status": "error", "message": f"Failed to save memory: {str(e)}"}
|
return {"status": "error", "message": f"Failed to save memory: {str(e)}"}
|
||||||
|
|
||||||
@@ -72,7 +77,7 @@ personal_assistant = Agent(
|
|||||||
tools=[search_memory, save_memory]
|
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.
|
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
|
# Set up session and runner
|
||||||
session_service = InMemorySessionService()
|
session_service = InMemorySessionService()
|
||||||
session = session_service.create_session(
|
session = await session_service.create_session(
|
||||||
app_name="memory_assistant",
|
app_name="memory_assistant",
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
session_id=f"session_{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
|
# Example usage
|
||||||
if __name__ == "__main__":
|
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",
|
"I love Italian food and I'm planning a trip to Rome next month",
|
||||||
user_id="alice"
|
user_id="alice"
|
||||||
)
|
))
|
||||||
print(response)
|
print(response)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ In this guide, we'll create a Travel Agent AI that:
|
|||||||
Install necessary libraries:
|
Install necessary libraries:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install langchain langchain_openai mem0ai
|
pip install langchain langchain_openai mem0ai python-dotenv
|
||||||
```
|
```
|
||||||
|
|
||||||
Import required modules and set up configurations:
|
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.messages import SystemMessage, HumanMessage, AIMessage
|
||||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||||
from mem0 import MemoryClient
|
from mem0 import MemoryClient
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
# Configuration
|
# Configuration
|
||||||
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
|
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
|
||||||
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
|
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
|
||||||
|
|
||||||
# Initialize LangChain and Mem0
|
# Initialize LangChain and Mem0
|
||||||
llm = ChatOpenAI(model="gpt-4o-mini")
|
llm = ChatOpenAI(model="gpt-4o-mini")
|
||||||
@@ -61,19 +64,26 @@ Create functions to handle context retrieval, response generation, and addition
|
|||||||
```python
|
```python
|
||||||
def retrieve_context(query: str, user_id: str) -> List[Dict]:
|
def retrieve_context(query: str, user_id: str) -> List[Dict]:
|
||||||
"""Retrieve relevant context from Mem0"""
|
"""Retrieve relevant context from Mem0"""
|
||||||
memories = mem0.search(query, user_id=user_id)
|
try:
|
||||||
serialized_memories = ' '.join([mem["memory"] for mem in memories.get('results', [])])
|
memories = mem0.search(query, user_id=user_id, output_format='v1.1')
|
||||||
context = [
|
memory_list = memories['results']
|
||||||
{
|
|
||||||
"role": "system",
|
serialized_memories = ' '.join([mem["memory"] for mem in memory_list])
|
||||||
"content": f"Relevant information: {serialized_memories}"
|
context = [
|
||||||
},
|
{
|
||||||
{
|
"role": "system",
|
||||||
"role": "user",
|
"content": f"Relevant information: {serialized_memories}"
|
||||||
"content": query
|
},
|
||||||
}
|
{
|
||||||
]
|
"role": "user",
|
||||||
return context
|
"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:
|
def generate_response(input: str, context: List[Dict]) -> str:
|
||||||
"""Generate a response using the language model"""
|
"""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):
|
def save_interaction(user_id: str, user_input: str, assistant_response: str):
|
||||||
"""Save the interaction to Mem0"""
|
"""Save the interaction to Mem0"""
|
||||||
interaction = [
|
try:
|
||||||
{
|
interaction = [
|
||||||
"role": "user",
|
{
|
||||||
"content": user_input
|
"role": "user",
|
||||||
},
|
"content": user_input
|
||||||
{
|
},
|
||||||
"role": "assistant",
|
{
|
||||||
"content": assistant_response
|
"role": "assistant",
|
||||||
}
|
"content": assistant_response
|
||||||
]
|
}
|
||||||
mem0.add(interaction, user_id=user_id)
|
]
|
||||||
|
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
|
## Create Chat Turn Function
|
||||||
@@ -124,7 +138,7 @@ Set up the main program loop for user interaction:
|
|||||||
```python
|
```python
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print("Welcome to your personal Travel Agent Planner! How can I assist you with your travel plans today?")
|
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:
|
while True:
|
||||||
user_input = input("You: ")
|
user_input = input("You: ")
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ In this guide, we'll create a Customer Support AI Agent that:
|
|||||||
Install necessary libraries:
|
Install necessary libraries:
|
||||||
|
|
||||||
```bash
|
```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 langchain_openai import ChatOpenAI
|
||||||
from mem0 import MemoryClient
|
from mem0 import MemoryClient
|
||||||
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
|
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
# Configuration
|
# Configuration
|
||||||
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI 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
|
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
|
||||||
|
|
||||||
# Initialize LangChain and Mem0
|
# Initialize LangChain and Mem0
|
||||||
llm = ChatOpenAI(model="gpt-4", api_key=OPENAI_API_KEY)
|
llm = ChatOpenAI(model="gpt-4")
|
||||||
mem0 = MemoryClient(api_key=MEM0_API_KEY)
|
mem0 = MemoryClient()
|
||||||
```
|
```
|
||||||
|
|
||||||
## Define State and Graph
|
## Define State and Graph
|
||||||
@@ -62,22 +65,47 @@ def chatbot(state: State):
|
|||||||
messages = state["messages"]
|
messages = state["messages"]
|
||||||
user_id = state["mem0_user_id"]
|
user_id = state["mem0_user_id"]
|
||||||
|
|
||||||
# Retrieve relevant memories
|
try:
|
||||||
memories = mem0.search(messages[-1].content, user_id=user_id)
|
# 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"
|
context = "Relevant information from previous conversations:\n"
|
||||||
for memory in memories.get('results', []):
|
for memory in memory_list:
|
||||||
context += f"- {memory['memory']}\n"
|
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}""")
|
{context}""")
|
||||||
|
|
||||||
full_messages = [system_message] + messages
|
full_messages = [system_message] + messages
|
||||||
response = llm.invoke(full_messages)
|
response = llm.invoke(full_messages)
|
||||||
|
|
||||||
# Store the interaction in Mem0
|
# Store the interaction in Mem0
|
||||||
mem0.add(f"User: {messages[-1].content}\nAssistant: {response.content}", user_id=user_id)
|
try:
|
||||||
return {"messages": [response]}
|
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
|
## Set Up Graph Structure
|
||||||
@@ -115,7 +143,7 @@ Set up the main program loop for user interaction:
|
|||||||
```python
|
```python
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print("Welcome to Customer Support! How can I assist you today?")
|
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:
|
while True:
|
||||||
user_input = input("You: ")
|
user_input = input("You: ")
|
||||||
if user_input.lower() in ['quit', 'exit', 'bye']:
|
if user_input.lower() in ['quit', 'exit', 'bye']:
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ LlamaIndex supports Mem0 as a [memory store](https://llamahub.ai/l/memory/llama-
|
|||||||
To install the required package, run:
|
To install the required package, run:
|
||||||
|
|
||||||
```bash
|
```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
|
### Setup with Mem0 Platform
|
||||||
@@ -25,18 +25,23 @@ Set your Mem0 Platform API key as an environment variable. You can replace `<you
|
|||||||
</Note>
|
</Note>
|
||||||
|
|
||||||
```python
|
```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:
|
Import the necessary modules and create a Mem0Memory instance:
|
||||||
```python
|
```python
|
||||||
from llama_index.memory.mem0 import Mem0Memory
|
from llama_index.memory.mem0 import Mem0Memory
|
||||||
|
|
||||||
context = {"user_id": "user_1"}
|
context = {"user_id": "alice"}
|
||||||
memory_from_client = Mem0Memory.from_client(
|
memory_from_client = Mem0Memory.from_client(
|
||||||
context=context,
|
context=context,
|
||||||
api_key="<your-mem0-api-key>",
|
|
||||||
search_msg_limit=4, # optional, default is 5
|
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
|
```python
|
||||||
context = {
|
context = {
|
||||||
"user_id": "user_1",
|
"user_id": "alice",
|
||||||
"agent_id": "agent_1",
|
"agent_id": "llama_agent_1",
|
||||||
"run_id": "run_1",
|
"run_id": "run_1",
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -98,17 +103,20 @@ memory_from_config = Mem0Memory.from_config(
|
|||||||
context=context,
|
context=context,
|
||||||
config=config,
|
config=config,
|
||||||
search_msg_limit=4, # optional, default is 5
|
search_msg_limit=4, # optional, default is 5
|
||||||
|
output_format='v1.1', # Remove deprecation warnings
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
Initialize the LLM
|
Initialize the LLM
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import os
|
|
||||||
from llama_index.llms.openai import OpenAI
|
from llama_index.llms.openai import OpenAI
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
|
load_dotenv()
|
||||||
llm = OpenAI(model="gpt-4o")
|
|
||||||
|
# os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
|
||||||
|
llm = OpenAI(model="gpt-4o-mini")
|
||||||
```
|
```
|
||||||
|
|
||||||
### SimpleChatEngine
|
### SimpleChatEngine
|
||||||
@@ -122,7 +130,7 @@ agent = SimpleChatEngine.from_defaults(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Start the chat
|
# Start the chat
|
||||||
response = agent.chat("Hi, My name is Mayank")
|
response = agent.chat("Hi, My name is Alice")
|
||||||
print(response)
|
print(response)
|
||||||
```
|
```
|
||||||
Now we will learn how to use Mem0 with FunctionCalling and ReAct agents.
|
Now we will learn how to use Mem0 with FunctionCalling and ReAct agents.
|
||||||
@@ -165,7 +173,7 @@ agent = FunctionCallingAgent.from_tools(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Start the chat
|
# Start the chat
|
||||||
response = agent.chat("Hi, My name is Mayank")
|
response = agent.chat("Hi, My name is Alice")
|
||||||
print(response)
|
print(response)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -182,7 +190,7 @@ agent = ReActAgent.from_tools(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Start the chat
|
# Start the chat
|
||||||
response = agent.chat("Hi, My name is Mayank")
|
response = agent.chat("Hi, My name is Alice")
|
||||||
print(response)
|
print(response)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ async def websocket_endpoint(websocket: WebSocket):
|
|||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
|
|
||||||
# Basic setup with minimal configuration
|
# Basic setup with minimal configuration
|
||||||
user_id = "user123"
|
user_id = "alice"
|
||||||
|
|
||||||
# WebSocket transport
|
# WebSocket transport
|
||||||
transport = FastAPIWebsocketTransport(
|
transport = FastAPIWebsocketTransport(
|
||||||
|
|||||||
Reference in New Issue
Block a user