{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "75e2ef28-594f-4c18-9d22-c6b8cd40ead2",
   "metadata": {},
   "source": [
    "# Day 3 - Conversational AI - aka Chatbot!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "70e39cd8-ec79-4e3e-9c26-5659d42d0861",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "\n",
    "import os\n",
    "import ollama\n",
    "import gradio as gr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6541d58e-2297-4de1-b1f7-77da1b98b8bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize\n",
    "MODEL_LLAMA = 'llama3.2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e16839b5-c03b-4d9d-add6-87a0f6f37575",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_message = \"You are a helpful assistant\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1eacc8a4-4b48-4358-9e06-ce0020041bc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "def chat(message, history):\n",
    "    messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
    "\n",
    "    print(\"History is:\")\n",
    "    print(history)\n",
    "    print(\"And messages is:\")\n",
    "    print(messages)\n",
    "\n",
    "    stream =  ollama.chat(model=MODEL_LLAMA, messages=messages, stream=True)\n",
    "\n",
    "    response_text = \"\"\n",
    "    for chunk in stream:\n",
    "        response_text += chunk['message']['content']\n",
    "        yield response_text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1334422a-808f-4147-9c4c-57d63d9780d0",
   "metadata": {},
   "source": [
    "## And then enter Gradio's magic!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0866ca56-100a-44ab-8bd0-1568feaf6bf2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7861\n",
      "* Running on public URL: https://6539f61952f430fa2d.gradio.live\n",
      "\n",
      "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"https://6539f61952f430fa2d.gradio.live\" 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": 7,
     "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': 'hello'}]\n"
     ]
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat, type=\"messages\").launch(share=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1f91b414-8bab-472d-b9c9-3fa51259bdfe",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "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 event.'\\\n",
    "Encourage the customer to buy hats if they are unsure what to get.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "4e5be3ec-c26c-42bc-ac16-c39d369883f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "    messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
    "\n",
    "\n",
    "    stream =  ollama.chat(model=MODEL_LLAMA, messages=messages, stream=True)\n",
    "\n",
    "    response_text = \"\"\n",
    "    for chunk in stream:\n",
    "        response_text += chunk['message']['content']\n",
    "        yield response_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "413e9e4e-7836-43ac-a0c3-e1ab5ed6b136",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7862\n",
      "* Running on public URL: https://79f09af36adcf63688.gradio.live\n",
      "\n",
      "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"https://79f09af36adcf63688.gradio.live\" 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": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat, type=\"messages\").launch(share=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "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": 12,
   "id": "c602a8dd-2df7-4eb7-b539-4e01865a6351",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7863\n",
      "* Running on public URL: https://30446ba4b8f125e235.gradio.live\n",
      "\n",
      "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"https://30446ba4b8f125e235.gradio.live\" 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": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat, type=\"messages\").launch(share=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "5b128796-1bea-445d-9e3b-8321ca822257",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "\n",
    "    relevant_system_message = system_message\n",
    "    if 'belt' in message:\n",
    "        relevant_system_message += \" The store does not sell belts; if you are asked for belts, be sure to point out other items on sale.\"\n",
    "    \n",
    "    messages = [{\"role\": \"system\", \"content\": relevant_system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
    "\n",
    "\n",
    "    stream =  ollama.chat(model=MODEL_LLAMA, messages=messages, stream=True)\n",
    "\n",
    "    response_text = \"\"\n",
    "    for chunk in stream:\n",
    "        response_text += chunk['message']['content']\n",
    "        yield response_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "20570de2-eaad-42cc-a92c-c779d71b48b6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://127.0.0.1:7865\n",
      "* Running on public URL: https://3933c80bf256709cf9.gradio.live\n",
      "\n",
      "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"https://3933c80bf256709cf9.gradio.live\" 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"
    }
   ],
   "source": [
    "gr.ChatInterface(fn=chat, type=\"messages\").launch(share=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82a57ee0-b945-48a7-a024-01b56a5d4b3e",
   "metadata": {},
   "source": [
    "<table style=\"margin: 0; text-align: left;\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "            <img src=\"../business.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#181;\">Business Applications</h2>\n",
    "            <span style=\"color:#181;\">Conversational Assistants are of course a hugely common use case for Gen AI, and the latest frontier models are remarkably good at nuanced conversation. And Gradio makes it easy to have a user interface. Another crucial skill we covered is how to use prompting to provide context, information and examples.\n",
    "<br/><br/>\n",
    "Consider how you could apply an AI Assistant to your business, and make yourself a prototype. Use the system prompt to give context on your business, and set the tone for the LLM.</span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6dfb9e21-df67-4c2b-b952-5e7e7961b03d",
   "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.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}