The Memory Layer for AI Agents - Drop-in memory infrastructure for AI agents and apps. Context that persists. Built for production.
Python agentic-memoryagentic-memory-systemagentsaiai-agentschatgptgenaillmlong-term-memorymemorymemory-managementpythonragstate-management
Companion Example (#1669)
Shlok Khemani7a2fd7018457
diff --git a/docs/examples/ai_companion.mdx b/docs/examples/ai_companion.mdxnew file mode 100644index 000000000..896985e08--- /dev/null+++ b/docs/examples/ai_companion.mdx@@ -0,0 +1,166 @@+---+title: AI Companion+---++You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.++## Overview++The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates separate memories for both the user and the companion. By integrating with OpenAI's GPT-4 model, the companion can provide detailed and context-aware responses to user queries.++## Setup+Before you begin, ensure you have the required dependencies installed. You can install the necessary packages using pip:++```bash+pip install openai mem0ai+```++## Full Code Example++Below is the complete code to create and interact with an AI Companion using Mem0:++```python+from openai import OpenAI+from mem0 import Memory+import os++# Set the OpenAI API key+os.environ['OPENAI_API_KEY'] = 'sk-xxx'++# Initialize the OpenAI client+client = OpenAI()++class Companion:+ def __init__(self, user_id, companion_id):+ """+ Initialize the Companion with memory configuration, OpenAI client, and user IDs.+ :param user_id: ID for storing user-related memories+ :param companion_id: ID for storing companion-related memories+ """+ config = {+ "vector_store": {+ "provider": "qdrant",+ "config": {+ "host": "localhost",+ "port": 6333,+ }+ },+ }+ self.memory = Memory.from_config(config)+ self.client = client+ self.app_id = "app-1"+ self.USER_ID = user_id+ self.companion_id = companion_id++ def analyze_question(self, question):+ """+ Analyze the question to determine whether it's about the user or the companion.+ """+ check_prompt = f"""+ Analyze the given input and determine whether the user is primarily:+ 1) Talking about themselves or asking for personal advice. They may use words like "I" for this.+ 2) Inquiring about the AI companions's capabilities or characteristics They may use words like "you" for this.++ Respond with a single word:+ - 'user' if the input is focused on the user+ - 'companion' if the input is focused on the AI companion++ If the input is ambiguous or doesn't clearly fit either category, respond with 'user'.++ Input: {question}+ """+ response = self.client.chat.completions.create(+ model="gpt-4",+ messages=[{"role": "user", "content": check_prompt}]+ )+ return response.choices[0].message.content++ def ask(self, question):+ """+ Ask a question to the AI and store the relevant facts in memory+ :param question: The question to ask the AI.+ """+ check_answer = self.analyze_question(question)+ user_id_to_use = self.USER_ID if check_answer == "user" else self.companion_id++ previous_memories = self.memory.search(question, user_id=user_id_to_use)+ relevant_memories_text = ""+ if previous_memories:+ relevant_memories_text = '\n'.join(mem["memory"] for mem in previous_memories)++ prompt = f"User input: {question}\nPrevious {check_answer} memories: {relevant_memories_text}"++ messages = [+ {+ "role": "system",+ "content": "You are the user's romantic companion. Use the user's input and previous memories to respond. Answer based on the context provided."+ },+ {+ "role": "user",+ "content": prompt+ }+ ]++ stream = self.client.chat.completions.create(+ model="gpt-4",+ stream=True,+ messages=messages+ )++ answer = ""+ for chunk in stream:+ if chunk.choices[0].delta.content is not None:+ content = chunk.choices[0].delta.content+ print(content, end="")+ answer += content+ # Store the question and answer in memory+ self.memory.add(question, user_id=self.USER_ID, metadata={"app_id": self.app_id})+ self.memory.add(answer, user_id=self.companion_id, metadata={"app_id": self.app_id})++ def get_memories(self, user_id=None):+ """+ Retrieve all memories associated with the given user ID.+ :param user_id: Optional user ID to filter memories.+ :return: List of memories.+ """+ return self.memory.get_all(user_id=user_id)++# Example usage:+user_id = "user"+companion_id = "companion"+ai_companion = Companion(user_id, companion_id)++# Ask a question+ai_companion.ask("Ive been missing you. What have you been up to off late?")+```++### Fetching Memories++You can fetch all the memories at any point in time using the following code:++```python+def print_memories(user_id, label):+ print(f"\n{label} Memories:")+ memories = ai_companion.get_memories(user_id=user_id)+ if memories:+ for m in memories:+ print(f"- {m['text']}")+ else:+ print("No memories found.")++# Print user memories+print_memories(user_id, "User")++# Print companion memories+print_memories(companion_id, "Companion")+```++### Key Points++- **Initialization**: The Companion class is initialized with the necessary memory configuration and OpenAI client setup.+- **Asking Questions**: The ask method sends a question to the AI and stores the relevant information in memory.+- **Retrieving Memories**: The get_memories method fetches all stored memories associated with a user.++### Conclusion++As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized experience. This setup ensures that the AI Companion can offer contextually relevant and accurate responses, enhancing the user's experience.