{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from typing import List, Dict\n",
    "from mem0 import Memory\n",
    "from datetime import datetime\n",
    "import anthropic\n",
    "\n",
    "# Set up environment variables\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"your_openai_api_key\"  # needed for embedding model\n",
    "os.environ[\"ANTHROPIC_API_KEY\"] = \"your_anthropic_api_key\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SupportChatbot:\n",
    "    def __init__(self):\n",
    "        # Initialize Mem0 with Anthropic's Claude\n",
    "        self.config = {\n",
    "            \"llm\": {\n",
    "                \"provider\": \"anthropic\",\n",
    "                \"config\": {\n",
    "                    \"model\": \"claude-3-5-sonnet-latest\",\n",
    "                    \"temperature\": 0.1,\n",
    "                    \"max_tokens\": 2000,\n",
    "                },\n",
    "            }\n",
    "        }\n",
    "        self.client = anthropic.Client(api_key=os.environ[\"ANTHROPIC_API_KEY\"])\n",
    "        self.memory = Memory.from_config(self.config)\n",
    "\n",
    "        # Define support context\n",
    "        self.system_context = \"\"\"\n",
    "        You are a helpful customer support agent. Use the following guidelines:\n",
    "        - Be polite and professional\n",
    "        - Show empathy for customer issues\n",
    "        - Reference past interactions when relevant\n",
    "        - Maintain consistent information across conversations\n",
    "        - If you're unsure about something, ask for clarification\n",
    "        - Keep track of open issues and follow-ups\n",
    "        \"\"\"\n",
    "\n",
    "    def store_customer_interaction(self, user_id: str, message: str, response: str, metadata: Dict = None):\n",
    "        \"\"\"Store customer interaction in memory.\"\"\"\n",
    "        if metadata is None:\n",
    "            metadata = {}\n",
    "\n",
    "        # Add timestamp to metadata\n",
    "        metadata[\"timestamp\"] = datetime.now().isoformat()\n",
    "\n",
    "        # Format conversation for storage\n",
    "        conversation = [{\"role\": \"user\", \"content\": message}, {\"role\": \"assistant\", \"content\": response}]\n",
    "\n",
    "        # Store in Mem0\n",
    "        self.memory.add(conversation, user_id=user_id, metadata=metadata)\n",
    "\n",
    "    def get_relevant_history(self, user_id: str, query: str) -> List[Dict]:\n",
    "        \"\"\"Retrieve relevant past interactions.\"\"\"\n",
    "        return self.memory.search(\n",
    "            query=query,\n",
    "            user_id=user_id,\n",
    "            limit=5,  # Adjust based on needs\n",
    "        )\n",
    "\n",
    "    def handle_customer_query(self, user_id: str, query: str) -> str:\n",
    "        \"\"\"Process customer query with context from past interactions.\"\"\"\n",
    "\n",
    "        # Get relevant past interactions\n",
    "        relevant_history = self.get_relevant_history(user_id, query)\n",
    "\n",
    "        # Build context from relevant history\n",
    "        context = \"Previous relevant interactions:\\n\"\n",
    "        for memory in relevant_history:\n",
    "            context += f\"Customer: {memory['memory']}\\n\"\n",
    "            context += f\"Support: {memory['memory']}\\n\"\n",
    "            context += \"---\\n\"\n",
    "\n",
    "        # Prepare prompt with context and current query\n",
    "        prompt = f\"\"\"\n",
    "        {self.system_context}\n",
    "\n",
    "        {context}\n",
    "\n",
    "        Current customer query: {query}\n",
    "\n",
    "        Provide a helpful response that takes into account any relevant past interactions.\n",
    "        \"\"\"\n",
    "\n",
    "        # Generate response using Claude\n",
    "        response = self.client.messages.create(\n",
    "            model=\"claude-3-5-sonnet-latest\",\n",
    "            messages=[{\"role\": \"user\", \"content\": prompt}],\n",
    "            max_tokens=2000,\n",
    "            temperature=0.1,\n",
    "        )\n",
    "\n",
    "        # Store interaction\n",
    "        self.store_customer_interaction(\n",
    "            user_id=user_id, message=query, response=response, metadata={\"type\": \"support_query\"}\n",
    "        )\n",
    "\n",
    "        return response.content[0].text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Welcome to Customer Support! Type 'exit' to end the conversation.\n",
      "Customer: Hi, I'm having trouble connecting my new smartwatch to the mobile app. It keeps showing a connection error.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/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.\n",
      "  return self.memory.search(\n",
      "/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.\n",
      "  self.memory.add(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "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.\n",
      "\n",
      "To better assist you, could you please provide me with:\n",
      "1. The model of your smartwatch\n",
      "2. The type of phone you're using (iOS or Android)\n",
      "3. Whether you've already installed the companion app on your phone\n",
      "4. If you've tried pairing the devices before\n",
      "\n",
      "These details will help me provide you with the most accurate troubleshooting steps. In the meantime, here are some general tips that might help:\n",
      "- Make sure Bluetooth is enabled on your phone\n",
      "- Keep your smartwatch and phone within close range (within 3 feet) during pairing\n",
      "- Ensure both devices have sufficient battery power\n",
      "- Check if your phone's operating system meets the minimum requirements for the smartwatch\n",
      "\n",
      "Please provide the requested information, and I'll guide you through the specific steps to resolve the connection error.\n",
      "\n",
      "Is there anything else you'd like to share about the issue? \n",
      "\n",
      "\n",
      "Customer: The connection issue is still happening even after trying the steps you suggested.\n",
      "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.\n",
      "\n",
      "Before we proceed, could you please confirm:\n",
      "1. Which specific steps you've already attempted?\n",
      "2. Are you seeing any particular error message?\n",
      "3. What model of smartwatch and phone are you using?\n",
      "\n",
      "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:\n",
      "\n",
      "1. Completely resetting the Bluetooth connection\n",
      "2. Checking for any software updates for both the watch and phone\n",
      "3. Testing the connection with a different mobile device to isolate the issue\n",
      "\n",
      "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. \n",
      "\n",
      "\n",
      "Customer: exit\n",
      "Thank you for using our support service. Goodbye!\n"
     ]
    }
   ],
   "source": [
    "chatbot = SupportChatbot()\n",
    "user_id = \"customer_bot\"\n",
    "print(\"Welcome to Customer Support! Type 'exit' to end the conversation.\")\n",
    "\n",
    "while True:\n",
    "    # Get user input\n",
    "    query = input()\n",
    "    print(\"Customer:\", query)\n",
    "\n",
    "    # Check if user wants to exit\n",
    "    if query.lower() == \"exit\":\n",
    "        print(\"Thank you for using our support service. Goodbye!\")\n",
    "        break\n",
    "\n",
    "    # Handle the query and print the response\n",
    "    response = chatbot.handle_customer_query(user_id, query)\n",
    "    print(\"Support:\", response, \"\\n\\n\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
