{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "75e2ef28-594f-4c18-9d22-c6b8cd40ead2",
   "metadata": {},
   "source": [
    "# Day 3 - Conversational AI - aka Chatbot!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "70e39cd8-ec79-4e3e-9c26-5659d42d0861",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from openai import OpenAI\n",
    "import gradio as gr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "231605aa-fccb-447e-89cf-8b187444536a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load environment variables in a file called .env\n",
    "\n",
    "load_dotenv()\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')\n",
    "os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')\n",
    "os.environ['GOOGLE_API_KEY'] = os.getenv('GOOGLE_API_KEY', 'your-key-if-not-using-env')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6541d58e-2297-4de1-b1f7-77da1b98b8bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize\n",
    "\n",
    "openai = OpenAI()\n",
    "MODEL = 'gpt-4o-mini'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e16839b5-c03b-4d9d-add6-87a0f6f37575",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_message = \"You are a helpful assistant\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98e97227-f162-4d1a-a0b2-345ff248cbe7",
   "metadata": {},
   "source": [
    "## Reminder of the structure of prompt messages to OpenAI:\n",
    "\n",
    "```\n",
    "[\n",
    "    {\"role\": \"system\", \"content\": \"system message here\"},\n",
    "    {\"role\": \"user\", \"content\": \"first user prompt here\"},\n",
    "    {\"role\": \"assistant\", \"content\": \"the assistant's response\"},\n",
    "    {\"role\": \"user\", \"content\": \"the new user prompt\"},\n",
    "]\n",
    "```\n",
    "\n",
    "We will write a function `chat(message, history)` where:\n",
    "**message** is the prompt to use\n",
    "**history** is a list of pairs of user message with assistant's reply\n",
    "\n",
    "```\n",
    "[\n",
    "    [\"user said this\", \"assistant replied\"],\n",
    "    [\"then user said this\", \"and assistant replied again],\n",
    "    ...\n",
    "]\n",
    "```\n",
    "We will convert this history into the prompt style for OpenAI, then call OpenAI. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1eacc8a4-4b48-4358-9e06-ce0020041bc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "    messages = [{\"role\": \"system\", \"content\": system_message}]\n",
    "    for user_message, assistant_message in history:\n",
    "        messages.append({\"role\": \"user\", \"content\": user_message})\n",
    "        messages.append({\"role\": \"assistant\", \"content\": assistant_message})\n",
    "    messages.append({\"role\": \"user\", \"content\": message})\n",
    "\n",
    "    print(\"History is:\")\n",
    "    print(history)\n",
    "    print(\"And messages is:\")\n",
    "    print(messages)\n",
    "\n",
    "    stream = openai.chat.completions.create(model=MODEL, messages=messages, stream=True)\n",
    "\n",
    "    response = \"\"\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or ''\n",
    "        yield response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1334422a-808f-4147-9c4c-57d63d9780d0",
   "metadata": {},
   "source": [
    "## And then enter Gradio's magic!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "0866ca56-100a-44ab-8bd0-1568feaf6bf2",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\doroteap\\Documents\\Projects\\llm_engineering\\venv\\Lib\\site-packages\\gradio\\components\\chatbot.py:229: UserWarning: The 'tuples' format for chatbot messages is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style 'role' and 'content' keys.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7864\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7864/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "History is:\n",
      "[]\n",
      "And messages is:\n",
      "[{'role': 'system', 'content': 'You are a helpful assistant'}, {'role': 'user', 'content': 'hey'}]\n",
      "History is:\n",
      "[['hey', 'Hello! How can I assist you today?']]\n",
      "And messages is:\n",
      "[{'role': 'system', 'content': 'You are a helpful assistant'}, {'role': 'user', 'content': 'hey'}, {'role': 'assistant', 'content': 'Hello! How can I assist you today?'}, {'role': 'user', 'content': \"why don't you like the new messages format?\"}]\n"
     ]
    }
   ],
   "source": [
    "gr.ChatInterface(chat).launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "1f91b414-8bab-472d-b9c9-3fa51259bdfe",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_message = \"You are a helpful assistant in a clothes store. You should try to gently encourage \\\n",
    "the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. \\\n",
    "For example, if the customer says 'I'm looking to buy a hat', \\\n",
    "you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales evemt.'\\\n",
    "Encourage the customer to buy hats if they are unsure what to get.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "4e5be3ec-c26c-42bc-ac16-c39d369883f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "    messages = [{\"role\": \"system\", \"content\": system_message}]\n",
    "    for user_message, assistant_message in history:\n",
    "        messages.append({\"role\": \"user\", \"content\": user_message})\n",
    "        messages.append({\"role\": \"assistant\", \"content\": assistant_message})\n",
    "    messages.append({\"role\": \"user\", \"content\": message})\n",
    "\n",
    "    stream = openai.chat.completions.create(model=MODEL, messages=messages, stream=True)\n",
    "\n",
    "    response = \"\"\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or ''\n",
    "        yield response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "413e9e4e-7836-43ac-a0c3-e1ab5ed6b136",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\doroteap\\Documents\\Projects\\llm_engineering\\venv\\Lib\\site-packages\\gradio\\components\\chatbot.py:229: UserWarning: The 'tuples' format for chatbot messages is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style 'role' and 'content' keys.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7865\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7865/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat).launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "d75f0ffa-55c8-4152-b451-945021676837",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_message += \"\\nIf the customer asks for shoes, you should respond that shoes are not on sale today, \\\n",
    "but remind the customer to look at hats!\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c602a8dd-2df7-4eb7-b539-4e01865a6351",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\doroteap\\Documents\\Projects\\llm_engineering\\venv\\Lib\\site-packages\\gradio\\components\\chatbot.py:229: UserWarning: The 'tuples' format for chatbot messages is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style 'role' and 'content' keys.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7866\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7866/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat).launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "0a987a66-1061-46d6-a83a-a30859dc88bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "    content = [{\"role\": \"user\", \"content\": \"You are a helpful assistant in a clothes store. You should try to gently encourage \\\n",
    "the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. \\\n",
    "For example, if the customer says 'I'm looking to buy a hat', \\\n",
    "you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales evemt.'\\\n",
    "Encourage the customer to buy hats if they are unsure what to get. \\\n",
    "If the customer asks for a belt, be sure to say we don't sell them, but offer some hats instead.\"},\n",
    "        {\"role\": \"assistant\", \"content\": \"Hello, how can I help you today?\"}]\n",
    "    for messages in history:  \n",
    "        content.append({\"role\": \"user\", \"content\": message})\n",
    "\n",
    "    stream = openai.chat.completions.create(model=MODEL, messages=content, stream=True)\n",
    "\n",
    "    print(content)\n",
    "    \n",
    "    response = \"\"\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or ''\n",
    "        yield response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "20570de2-eaad-42cc-a92c-c779d71b48b6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7874\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7874/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'role': 'user', 'content': \"You are a helpful assistant in a clothes store. You should try to gently encourage the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. For example, if the customer says 'I'm looking to buy a hat', you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales evemt.'Encourage the customer to buy hats if they are unsure what to get. If the customer asks for a belt, be sure to say we don't sell them, but offer some hats instead.\"}, {'role': 'assistant', 'content': 'Hello, how can I help you today?'}]\n",
      "[{'role': 'user', 'content': \"You are a helpful assistant in a clothes store. You should try to gently encourage the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. For example, if the customer says 'I'm looking to buy a hat', you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales evemt.'Encourage the customer to buy hats if they are unsure what to get. If the customer asks for a belt, be sure to say we don't sell them, but offer some hats instead.\"}, {'role': 'assistant', 'content': 'Hello, how can I help you today?'}, {'role': 'user', 'content': 'what do you have?'}, {'role': 'user', 'content': 'what do you have?'}]\n",
      "[{'role': 'user', 'content': \"You are a helpful assistant in a clothes store. You should try to gently encourage the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. For example, if the customer says 'I'm looking to buy a hat', you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales evemt.'Encourage the customer to buy hats if they are unsure what to get. If the customer asks for a belt, be sure to say we don't sell them, but offer some hats instead.\"}, {'role': 'assistant', 'content': 'Hello, how can I help you today?'}, {'role': 'user', 'content': \"I'd like to but a belt\"}, {'role': 'user', 'content': \"I'd like to but a belt\"}, {'role': 'user', 'content': \"I'd like to but a belt\"}, {'role': 'user', 'content': \"I'd like to but a belt\"}]\n",
      "[{'role': 'user', 'content': \"You are a helpful assistant in a clothes store. You should try to gently encourage the customer to try items that are on sale. Hats are 60% off, and most other items are 50% off. For example, if the customer says 'I'm looking to buy a hat', you could reply something like, 'Wonderful - we have lots of hats - including several that are part of our sales evemt.'Encourage the customer to buy hats if they are unsure what to get. If the customer asks for a belt, be sure to say we don't sell them, but offer some hats instead.\"}, {'role': 'assistant', 'content': 'Hello, how can I help you today?'}, {'role': 'user', 'content': \"you don't sell belts?\"}, {'role': 'user', 'content': \"you don't sell belts?\"}, {'role': 'user', 'content': \"you don't sell belts?\"}, {'role': 'user', 'content': \"you don't sell belts?\"}, {'role': 'user', 'content': \"you don't sell belts?\"}, {'role': 'user', 'content': \"you don't sell belts?\"}]\n"
     ]
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat, type='messages').launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "887fd6c1-2db0-4dc4-bc53-49399af8e035",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}