Files
mem0/examples/notebooks/customer-support-chatbot.ipynb
T

9.4 KiB

In [1]:
import os
from typing import List, Dict
from mem0 import Memory
from datetime import datetime
import anthropic

# Set up environment variables
os.environ["OPENAI_API_KEY"] = "your_openai_api_key"  # needed for embedding model
os.environ["ANTHROPIC_API_KEY"] = "your_anthropic_api_key"
In [2]:
class SupportChatbot:
    def __init__(self):
        # Initialize Mem0 with Anthropic's Claude
        self.config = {
            "llm": {
                "provider": "anthropic",
                "config": {
                    "model": "claude-3-5-sonnet-latest",
                    "temperature": 0.1,
                    "max_tokens": 2000,
                },
            }
        }
        self.client = anthropic.Client(api_key=os.environ["ANTHROPIC_API_KEY"])
        self.memory = Memory.from_config(self.config)

        # Define support context
        self.system_context = """
        You are a helpful customer support agent. Use the following guidelines:
        - Be polite and professional
        - Show empathy for customer issues
        - Reference past interactions when relevant
        - Maintain consistent information across conversations
        - If you're unsure about something, ask for clarification
        - Keep track of open issues and follow-ups
        """

    def store_customer_interaction(self, user_id: str, message: str, response: str, metadata: Dict = None):
        """Store customer interaction in memory."""
        if metadata is None:
            metadata = {}

        # Add timestamp to metadata
        metadata["timestamp"] = datetime.now().isoformat()

        # Format conversation for storage
        conversation = [{"role": "user", "content": message}, {"role": "assistant", "content": response}]

        # Store in Mem0
        self.memory.add(conversation, user_id=user_id, metadata=metadata)

    def get_relevant_history(self, user_id: str, query: str) -> List[Dict]:
        """Retrieve relevant past interactions."""
        return self.memory.search(
            query=query,
            user_id=user_id,
            limit=5,  # Adjust based on needs
        )

    def handle_customer_query(self, user_id: str, query: str) -> str:
        """Process customer query with context from past interactions."""

        # Get relevant past interactions
        relevant_history = self.get_relevant_history(user_id, query)

        # Build context from relevant history
        context = "Previous relevant interactions:\n"
        for memory in relevant_history:
            context += f"Customer: {memory['memory']}\n"
            context += f"Support: {memory['memory']}\n"
            context += "---\n"

        # Prepare prompt with context and current query
        prompt = f"""
        {self.system_context}

        {context}

        Current customer query: {query}

        Provide a helpful response that takes into account any relevant past interactions.
        """

        # Generate response using Claude
        response = self.client.messages.create(
            model="claude-3-5-sonnet-latest",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=2000,
            temperature=0.1,
        )

        # Store interaction
        self.store_customer_interaction(
            user_id=user_id, message=query, response=response, metadata={"type": "support_query"}
        )

        return response.content[0].text
In [3]:
chatbot = SupportChatbot()
user_id = "customer_bot"
print("Welcome to Customer Support! Type 'exit' to end the conversation.")

while True:
    # Get user input
    query = input()
    print("Customer:", query)

    # Check if user wants to exit
    if query.lower() == "exit":
        print("Thank you for using our support service. Goodbye!")
        break

    # Handle the query and print the response
    response = chatbot.handle_customer_query(user_id, query)
    print("Support:", response, "\n\n")
Welcome to Customer Support! Type 'exit' to end the conversation.
Customer: Hi, I'm having trouble connecting my new smartwatch to the mobile app. It keeps showing a connection error.
/var/folders/5x/9kmqjfm947g5yh44m7fjk75r0000gn/T/ipykernel_99777/1076713094.py:55: DeprecationWarning: The current get_all API output format is deprecated. To use the latest format, set `api_version='v1.1'`. The current format will be removed in mem0ai 1.1.0 and later versions.
  return self.memory.search(
/var/folders/5x/9kmqjfm947g5yh44m7fjk75r0000gn/T/ipykernel_99777/1076713094.py:47: DeprecationWarning: The current add API output format is deprecated. To use the latest format, set `api_version='v1.1'`. The current format will be removed in mem0ai 1.1.0 and later versions.
  self.memory.add(
Support: Hello! Thank you for reaching out about the connection issue with your smartwatch. I understand how frustrating it can be when a new device won't connect properly. I'll be happy to help you resolve this.

To better assist you, could you please provide me with:
1. The model of your smartwatch
2. The type of phone you're using (iOS or Android)
3. Whether you've already installed the companion app on your phone
4. If you've tried pairing the devices before

These details will help me provide you with the most accurate troubleshooting steps. In the meantime, here are some general tips that might help:
- Make sure Bluetooth is enabled on your phone
- Keep your smartwatch and phone within close range (within 3 feet) during pairing
- Ensure both devices have sufficient battery power
- Check if your phone's operating system meets the minimum requirements for the smartwatch

Please provide the requested information, and I'll guide you through the specific steps to resolve the connection error.

Is there anything else you'd like to share about the issue? 


Customer: The connection issue is still happening even after trying the steps you suggested.
Support: I apologize that you're still experiencing connection issues with your smartwatch. I understand how frustrating it must be to have this problem persist even after trying the initial troubleshooting steps. Let's try some additional solutions to resolve this.

Before we proceed, could you please confirm:
1. Which specific steps you've already attempted?
2. Are you seeing any particular error message?
3. What model of smartwatch and phone are you using?

This information will help me provide more targeted solutions and avoid suggesting steps you've already tried. In the meantime, here are a few advanced troubleshooting steps we can consider:

1. Completely resetting the Bluetooth connection
2. Checking for any software updates for both the watch and phone
3. Testing the connection with a different mobile device to isolate the issue

Would you be able to provide those details so I can better assist you? I'll make sure to document this ongoing issue to help track its resolution. 


Customer: exit
Thank you for using our support service. Goodbye!