1131 lines
76 KiB
Plaintext
1131 lines
76 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c2316df2",
|
||
"metadata": {
|
||
"_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
|
||
"_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
|
||
"papermill": {
|
||
"duration": 0.00817,
|
||
"end_time": "2024-05-04T12:19:36.590158",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:36.581988",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"# <center style=\"font-family: consolas; font-size: 32px; font-weight: bold;\"> Prompt Engineering Best Practices: Building An End to End Customer Service System </center>\n",
|
||
"\n",
|
||
"***\n",
|
||
"\n",
|
||
"\n",
|
||
"Prompt engineering plays a pivotal role in crafting queries that help large language models (LLMs) understand not just the language but also the nuance and intent behind the query and help us build complex applications with ease. \n",
|
||
"\n",
|
||
"In this notebook, we will put into action what we covered in previous notebooks and build an end-to-end customer service assistant. Starting with checking the input to see if it flags the moderation API then extracting the list of products searching for the products the user asked about answering the user question with the model and checking the output with the moderation API. \n",
|
||
"\n",
|
||
"Finally, we will put all of these together and build a conversational chatbot the takes the user input passes it through all of these steps, and returns it back to him.\n",
|
||
"\n",
|
||
"#### <a id=\"top\"></a>\n",
|
||
"# <div style=\"box-shadow: rgb(60, 121, 245) 0px 0px 0px 3px inset, rgb(255, 255, 255) 10px -10px 0px -3px, rgb(31, 193, 27) 10px -10px, rgb(255, 255, 255) 20px -20px 0px -3px, rgb(255, 217, 19) 20px -20px, rgb(255, 255, 255) 30px -30px 0px -3px, rgb(255, 156, 85) 30px -30px, rgb(255, 255, 255) 40px -40px 0px -3px, rgb(255, 85, 85) 40px -40px; padding:20px; margin-right: 40px; font-size:30px; font-family: consolas; text-align:center; display:fill; border-radius:15px; color:rgb(60, 121, 245);\"><b>Table of contents</b></div>\n",
|
||
"\n",
|
||
"<div style=\"background-color: rgba(60, 121, 245, 0.03); padding:30px; font-size:15px; font-family: consolas;\">\n",
|
||
"<ul>\n",
|
||
" <li><a href=\"#1\" target=\"_self\" rel=\" noreferrer nofollow\">1. Setting Up Working Environment </a> </li>\n",
|
||
" <li><a href=\"#2\" target=\"_self\" rel=\" noreferrer nofollow\">2. Chain of Prompts For Processing the User Query </a></li>\n",
|
||
" <li><a href=\"#3\" target=\"_self\" rel=\" noreferrer nofollow\">3. Building Conversational Chatbot </a></li> \n",
|
||
"</ul>\n",
|
||
"</div>\n",
|
||
"\n",
|
||
"***"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "77f8d369",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.00727,
|
||
"end_time": "2024-05-04T12:19:36.605121",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:36.597851",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"<a id=\"1\"></a>\n",
|
||
"# <div style=\"box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px inset, rgb(51, 51, 51) 0px 0px 0px 3px inset; padding:20px; font-size:32px; font-family: consolas; text-align:center; display:fill; border-radius:15px; color:rgb(34, 34, 34);\"> <b> 1. Setting Up Working Environment </b></div>\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"As usual, we will start with setting up the working environment and importing the packages and libraries we will work on within this notebook. In addition to the usual packages such as os and openai, we will import the panel package which is a Python package we'll use for a chatbot UI. Also, we will import the utils file which will have some helper function that can be used to define the products and more."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 1,
|
||
"id": "6ff9c48a",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:19:36.622774Z",
|
||
"iopub.status.busy": "2024-05-04T12:19:36.622070Z",
|
||
"iopub.status.idle": "2024-05-04T12:19:53.356430Z",
|
||
"shell.execute_reply": "2024-05-04T12:19:53.354491Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 16.746751,
|
||
"end_time": "2024-05-04T12:19:53.359438",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:36.612687",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Requirement already satisfied: openai in c:\\python312\\lib\\site-packages (1.30.3)\n",
|
||
"Requirement already satisfied: anyio<5,>=3.5.0 in c:\\python312\\lib\\site-packages (from openai) (4.2.0)\n",
|
||
"Requirement already satisfied: distro<2,>=1.7.0 in c:\\python312\\lib\\site-packages (from openai) (1.9.0)\n",
|
||
"Requirement already satisfied: httpx<1,>=0.23.0 in c:\\python312\\lib\\site-packages (from openai) (0.27.0)\n",
|
||
"Requirement already satisfied: pydantic<3,>=1.9.0 in c:\\python312\\lib\\site-packages (from openai) (2.7.1)\n",
|
||
"Requirement already satisfied: sniffio in c:\\python312\\lib\\site-packages (from openai) (1.3.0)\n",
|
||
"Requirement already satisfied: tqdm>4 in c:\\python312\\lib\\site-packages (from openai) (4.66.1)\n",
|
||
"Requirement already satisfied: typing-extensions<5,>=4.7 in c:\\python312\\lib\\site-packages (from openai) (4.9.0)\n",
|
||
"Requirement already satisfied: idna>=2.8 in c:\\python312\\lib\\site-packages (from anyio<5,>=3.5.0->openai) (3.4)\n",
|
||
"Requirement already satisfied: certifi in c:\\python312\\lib\\site-packages (from httpx<1,>=0.23.0->openai) (2022.9.24)\n",
|
||
"Requirement already satisfied: httpcore==1.* in c:\\python312\\lib\\site-packages (from httpx<1,>=0.23.0->openai) (1.0.5)\n",
|
||
"Requirement already satisfied: h11<0.15,>=0.13 in c:\\python312\\lib\\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.14.0)\n",
|
||
"Requirement already satisfied: annotated-types>=0.4.0 in c:\\python312\\lib\\site-packages (from pydantic<3,>=1.9.0->openai) (0.6.0)\n",
|
||
"Requirement already satisfied: pydantic-core==2.18.2 in c:\\python312\\lib\\site-packages (from pydantic<3,>=1.9.0->openai) (2.18.2)\n",
|
||
"Requirement already satisfied: colorama in c:\\python312\\lib\\site-packages (from tqdm>4->openai) (0.4.6)\n",
|
||
"Note: you may need to restart the kernel to use updated packages.\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"pip install openai"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 2,
|
||
"id": "9e92d5c6",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:19:53.380510Z",
|
||
"iopub.status.busy": "2024-05-04T12:19:53.379997Z",
|
||
"iopub.status.idle": "2024-05-04T12:19:56.919333Z",
|
||
"shell.execute_reply": "2024-05-04T12:19:56.917529Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 3.555409,
|
||
"end_time": "2024-05-04T12:19:56.924181",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:53.368772",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"application/javascript": "(function(root) {\n function now() {\n return new Date();\n }\n\n var force = true;\n var py_version = '3.4.1'.replace('rc', '-rc.').replace('.dev', '-dev.');\n var reloading = false;\n var Bokeh = root.Bokeh;\n\n if (typeof (root._bokeh_timeout) === \"undefined\" || force) {\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_failed_load = false;\n }\n\n function run_callbacks() {\n try {\n root._bokeh_onload_callbacks.forEach(function(callback) {\n if (callback != null)\n callback();\n });\n } finally {\n delete root._bokeh_onload_callbacks;\n }\n console.debug(\"Bokeh: all callbacks have finished\");\n }\n\n function load_libs(css_urls, js_urls, js_modules, js_exports, callback) {\n if (css_urls == null) css_urls = [];\n if (js_urls == null) js_urls = [];\n if (js_modules == null) js_modules = [];\n if (js_exports == null) js_exports = {};\n\n root._bokeh_onload_callbacks.push(callback);\n\n if (root._bokeh_is_loading > 0) {\n console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n return null;\n }\n if (js_urls.length === 0 && js_modules.length === 0 && Object.keys(js_exports).length === 0) {\n run_callbacks();\n return null;\n }\n if (!reloading) {\n console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n }\n\n function on_load() {\n root._bokeh_is_loading--;\n if (root._bokeh_is_loading === 0) {\n console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n run_callbacks()\n }\n }\n window._bokeh_on_load = on_load\n\n function on_error() {\n console.error(\"failed to load \" + url);\n }\n\n var skip = [];\n if (window.requirejs) {\n window.requirejs.config({'packages': {}, 'paths': {}, 'shim': {}});\n root._bokeh_is_loading = css_urls.length + 0;\n } else {\n root._bokeh_is_loading = css_urls.length + js_urls.length + js_modules.length + Object.keys(js_exports).length;\n }\n\n var existing_stylesheets = []\n var links = document.getElementsByTagName('link')\n for (var i = 0; i < links.length; i++) {\n var link = links[i]\n if (link.href != null) {\n\texisting_stylesheets.push(link.href)\n }\n }\n for (var i = 0; i < css_urls.length; i++) {\n var url = css_urls[i];\n if (existing_stylesheets.indexOf(url) !== -1) {\n\ton_load()\n\tcontinue;\n }\n const element = document.createElement(\"link\");\n element.onload = on_load;\n element.onerror = on_error;\n element.rel = \"stylesheet\";\n element.type = \"text/css\";\n element.href = url;\n console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n document.body.appendChild(element);\n } var existing_scripts = []\n var scripts = document.getElementsByTagName('script')\n for (var i = 0; i < scripts.length; i++) {\n var script = scripts[i]\n if (script.src != null) {\n\texisting_scripts.push(script.src)\n }\n }\n for (var i = 0; i < js_urls.length; i++) {\n var url = js_urls[i];\n if (skip.indexOf(url) !== -1 || existing_scripts.indexOf(url) !== -1) {\n\tif (!window.requirejs) {\n\t on_load();\n\t}\n\tcontinue;\n }\n var element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error;\n element.async = false;\n element.src = url;\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n for (var i = 0; i < js_modules.length; i++) {\n var url = js_modules[i];\n if (skip.indexOf(url) !== -1 || existing_scripts.indexOf(url) !== -1) {\n\tif (!window.requirejs) {\n\t on_load();\n\t}\n\tcontinue;\n }\n var element = document.createElement('script');\n element.onload = on_load;\n element.onerror = on_error;\n element.async = false;\n element.src = url;\n element.type = \"module\";\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.head.appendChild(element);\n }\n for (const name in js_exports) {\n var url = js_exports[name];\n if (skip.indexOf(url) >= 0 || root[name] != null) {\n\tif (!window.requirejs) {\n\t on_load();\n\t}\n\tcontinue;\n }\n var element = document.createElement('script');\n element.onerror = on_error;\n element.async = false;\n element.type = \"module\";\n console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n element.textContent = `\n import ${name} from \"${url}\"\n window.${name} = ${name}\n window._bokeh_on_load()\n `\n document.head.appendChild(element);\n }\n if (!js_urls.length && !js_modules.length) {\n on_load()\n }\n };\n\n function inject_raw_css(css) {\n const element = document.createElement(\"style\");\n element.appendChild(document.createTextNode(css));\n document.body.appendChild(element);\n }\n\n var js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-3.4.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-3.4.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-3.4.1.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-3.4.1.min.js\", \"https://cdn.holoviz.org/panel/1.4.1/dist/panel.min.js\"];\n var js_modules = [];\n var js_exports = {};\n var css_urls = [];\n var inline_js = [ function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\nfunction(Bokeh) {} // ensure no trailing comma for IE\n ];\n\n function run_inline_js() {\n if ((root.Bokeh !== undefined) || (force === true)) {\n for (var i = 0; i < inline_js.length; i++) {\n\ttry {\n inline_js[i].call(root, root.Bokeh);\n\t} catch(e) {\n\t if (!reloading) {\n\t throw e;\n\t }\n\t}\n }\n // Cache old bokeh versions\n if (Bokeh != undefined && !reloading) {\n\tvar NewBokeh = root.Bokeh;\n\tif (Bokeh.versions === undefined) {\n\t Bokeh.versions = new Map();\n\t}\n\tif (NewBokeh.version !== Bokeh.version) {\n\t Bokeh.versions.set(NewBokeh.version, NewBokeh)\n\t}\n\troot.Bokeh = Bokeh;\n }} else if (Date.now() < root._bokeh_timeout) {\n setTimeout(run_inline_js, 100);\n } else if (!root._bokeh_failed_load) {\n console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n root._bokeh_failed_load = true;\n }\n root._bokeh_is_initializing = false\n }\n\n function load_or_wait() {\n // Implement a backoff loop that tries to ensure we do not load multiple\n // versions of Bokeh and its dependencies at the same time.\n // In recent versions we use the root._bokeh_is_initializing flag\n // to determine whether there is an ongoing attempt to initialize\n // bokeh, however for backward compatibility we also try to ensure\n // that we do not start loading a newer (Panel>=1.0 and Bokeh>3) version\n // before older versions are fully initialized.\n if (root._bokeh_is_initializing && Date.now() > root._bokeh_timeout) {\n root._bokeh_is_initializing = false;\n root._bokeh_onload_callbacks = undefined;\n console.log(\"Bokeh: BokehJS was loaded multiple times but one version failed to initialize.\");\n load_or_wait();\n } else if (root._bokeh_is_initializing || (typeof root._bokeh_is_initializing === \"undefined\" && root._bokeh_onload_callbacks !== undefined)) {\n setTimeout(load_or_wait, 100);\n } else {\n root._bokeh_is_initializing = true\n root._bokeh_onload_callbacks = []\n var bokeh_loaded = Bokeh != null && (Bokeh.version === py_version || (Bokeh.versions !== undefined && Bokeh.versions.has(py_version)));\n if (!reloading && !bokeh_loaded) {\n\troot.Bokeh = undefined;\n }\n load_libs(css_urls, js_urls, js_modules, js_exports, function() {\n\tconsole.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n\trun_inline_js();\n });\n }\n }\n // Give older versions of the autoload script a head-start to ensure\n // they initialize before we start loading newer version.\n setTimeout(load_or_wait, 100)\n}(window));",
|
||
"application/vnd.holoviews_load.v0+json": ""
|
||
},
|
||
"metadata": {},
|
||
"output_type": "display_data"
|
||
},
|
||
{
|
||
"data": {
|
||
"application/javascript": "\nif ((window.PyViz === undefined) || (window.PyViz instanceof HTMLElement)) {\n window.PyViz = {comms: {}, comm_status:{}, kernels:{}, receivers: {}, plot_index: []}\n}\n\n\n function JupyterCommManager() {\n }\n\n JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {\n if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n comm_manager.register_target(comm_id, function(comm) {\n comm.on_msg(msg_handler);\n });\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {\n comm.onMsg = msg_handler;\n });\n } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n google.colab.kernel.comms.registerTarget(comm_id, (comm) => {\n var messages = comm.messages[Symbol.asyncIterator]();\n function processIteratorResult(result) {\n var message = result.value;\n console.log(message)\n var content = {data: message.data, comm_id};\n var buffers = []\n for (var buffer of message.buffers || []) {\n buffers.push(new DataView(buffer))\n }\n var metadata = message.metadata || {};\n var msg = {content, buffers, metadata}\n msg_handler(msg);\n return messages.next().then(processIteratorResult);\n }\n return messages.next().then(processIteratorResult);\n })\n }\n }\n\n JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {\n if (comm_id in window.PyViz.comms) {\n return window.PyViz.comms[comm_id];\n } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);\n if (msg_handler) {\n comm.on_msg(msg_handler);\n }\n } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);\n comm.open();\n if (msg_handler) {\n comm.onMsg = msg_handler;\n }\n } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n var comm_promise = google.colab.kernel.comms.open(comm_id)\n comm_promise.then((comm) => {\n window.PyViz.comms[comm_id] = comm;\n if (msg_handler) {\n var messages = comm.messages[Symbol.asyncIterator]();\n function processIteratorResult(result) {\n var message = result.value;\n var content = {data: message.data};\n var metadata = message.metadata || {comm_id};\n var msg = {content, metadata}\n msg_handler(msg);\n return messages.next().then(processIteratorResult);\n }\n return messages.next().then(processIteratorResult);\n }\n }) \n var sendClosure = (data, metadata, buffers, disposeOnDone) => {\n return comm_promise.then((comm) => {\n comm.send(data, metadata, buffers, disposeOnDone);\n });\n };\n var comm = {\n send: sendClosure\n };\n }\n window.PyViz.comms[comm_id] = comm;\n return comm;\n }\n window.PyViz.comm_manager = new JupyterCommManager();\n \n\n\nvar JS_MIME_TYPE = 'application/javascript';\nvar HTML_MIME_TYPE = 'text/html';\nvar EXEC_MIME_TYPE = 'application/vnd.holoviews_exec.v0+json';\nvar CLASS_NAME = 'output';\n\n/**\n * Render data to the DOM node\n */\nfunction render(props, node) {\n var div = document.createElement(\"div\");\n var script = document.createElement(\"script\");\n node.appendChild(div);\n node.appendChild(script);\n}\n\n/**\n * Handle when a new output is added\n */\nfunction handle_add_output(event, handle) {\n var output_area = handle.output_area;\n var output = handle.output;\n if ((output.data == undefined) || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n return\n }\n var id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n if (id !== undefined) {\n var nchildren = toinsert.length;\n var html_node = toinsert[nchildren-1].children[0];\n html_node.innerHTML = output.data[HTML_MIME_TYPE];\n var scripts = [];\n var nodelist = html_node.querySelectorAll(\"script\");\n for (var i in nodelist) {\n if (nodelist.hasOwnProperty(i)) {\n scripts.push(nodelist[i])\n }\n }\n\n scripts.forEach( function (oldScript) {\n var newScript = document.createElement(\"script\");\n var attrs = [];\n var nodemap = oldScript.attributes;\n for (var j in nodemap) {\n if (nodemap.hasOwnProperty(j)) {\n attrs.push(nodemap[j])\n }\n }\n attrs.forEach(function(attr) { newScript.setAttribute(attr.name, attr.value) });\n newScript.appendChild(document.createTextNode(oldScript.innerHTML));\n oldScript.parentNode.replaceChild(newScript, oldScript);\n });\n if (JS_MIME_TYPE in output.data) {\n toinsert[nchildren-1].children[1].textContent = output.data[JS_MIME_TYPE];\n }\n output_area._hv_plot_id = id;\n if ((window.Bokeh !== undefined) && (id in Bokeh.index)) {\n window.PyViz.plot_index[id] = Bokeh.index[id];\n } else {\n window.PyViz.plot_index[id] = null;\n }\n } else if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n var bk_div = document.createElement(\"div\");\n bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n var script_attrs = bk_div.children[0].attributes;\n for (var i = 0; i < script_attrs.length; i++) {\n toinsert[toinsert.length - 1].childNodes[1].setAttribute(script_attrs[i].name, script_attrs[i].value);\n }\n // store reference to server id on output_area\n output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n }\n}\n\n/**\n * Handle when an output is cleared or removed\n */\nfunction handle_clear_output(event, handle) {\n var id = handle.cell.output_area._hv_plot_id;\n var server_id = handle.cell.output_area._bokeh_server_id;\n if (((id === undefined) || !(id in PyViz.plot_index)) && (server_id !== undefined)) { return; }\n var comm = window.PyViz.comm_manager.get_client_comm(\"hv-extension-comm\", \"hv-extension-comm\", function () {});\n if (server_id !== null) {\n comm.send({event_type: 'server_delete', 'id': server_id});\n return;\n } else if (comm !== null) {\n comm.send({event_type: 'delete', 'id': id});\n }\n delete PyViz.plot_index[id];\n if ((window.Bokeh !== undefined) & (id in window.Bokeh.index)) {\n var doc = window.Bokeh.index[id].model.document\n doc.clear();\n const i = window.Bokeh.documents.indexOf(doc);\n if (i > -1) {\n window.Bokeh.documents.splice(i, 1);\n }\n }\n}\n\n/**\n * Handle kernel restart event\n */\nfunction handle_kernel_cleanup(event, handle) {\n delete PyViz.comms[\"hv-extension-comm\"];\n window.PyViz.plot_index = {}\n}\n\n/**\n * Handle update_display_data messages\n */\nfunction handle_update_output(event, handle) {\n handle_clear_output(event, {cell: {output_area: handle.output_area}})\n handle_add_output(event, handle)\n}\n\nfunction register_renderer(events, OutputArea) {\n function append_mime(data, metadata, element) {\n // create a DOM node to render to\n var toinsert = this.create_output_subarea(\n metadata,\n CLASS_NAME,\n EXEC_MIME_TYPE\n );\n this.keyboard_manager.register_events(toinsert);\n // Render to node\n var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n render(props, toinsert[0]);\n element.append(toinsert);\n return toinsert\n }\n\n events.on('output_added.OutputArea', handle_add_output);\n events.on('output_updated.OutputArea', handle_update_output);\n events.on('clear_output.CodeCell', handle_clear_output);\n events.on('delete.Cell', handle_clear_output);\n events.on('kernel_ready.Kernel', handle_kernel_cleanup);\n\n OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n safe: true,\n index: 0\n });\n}\n\nif (window.Jupyter !== undefined) {\n try {\n var events = require('base/js/events');\n var OutputArea = require('notebook/js/outputarea').OutputArea;\n if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n register_renderer(events, OutputArea);\n }\n } catch(err) {\n }\n}\n",
|
||
"application/vnd.holoviews_load.v0+json": ""
|
||
},
|
||
"metadata": {},
|
||
"output_type": "display_data"
|
||
},
|
||
{
|
||
"data": {
|
||
"text/html": [
|
||
"<style>*[data-root-id],\n",
|
||
"*[data-root-id] > * {\n",
|
||
" box-sizing: border-box;\n",
|
||
" font-family: var(--jp-ui-font-family);\n",
|
||
" font-size: var(--jp-ui-font-size1);\n",
|
||
" color: var(--vscode-editor-foreground, var(--jp-ui-font-color1));\n",
|
||
"}\n",
|
||
"\n",
|
||
"/* Override VSCode background color */\n",
|
||
".cell-output-ipywidget-background:has(\n",
|
||
" > .cell-output-ipywidget-background > .lm-Widget > *[data-root-id]\n",
|
||
" ),\n",
|
||
".cell-output-ipywidget-background:has(> .lm-Widget > *[data-root-id]) {\n",
|
||
" background-color: transparent !important;\n",
|
||
"}\n",
|
||
"</style>"
|
||
]
|
||
},
|
||
"metadata": {},
|
||
"output_type": "display_data"
|
||
},
|
||
{
|
||
"data": {
|
||
"application/vnd.holoviews_exec.v0+json": "",
|
||
"text/html": [
|
||
"<div id='ef59f866-0a1c-44fb-8d83-3cf51422bf0c'>\n",
|
||
" <div id=\"aea85b85-0f68-4a78-88b1-70bfeeed615a\" data-root-id=\"ef59f866-0a1c-44fb-8d83-3cf51422bf0c\" style=\"display: contents;\"></div>\n",
|
||
"</div>\n",
|
||
"<script type=\"application/javascript\">(function(root) {\n",
|
||
" var docs_json = {\"68ae3073-59ef-4a95-b4d5-7788063cd504\":{\"version\":\"3.4.1\",\"title\":\"Bokeh Application\",\"roots\":[{\"type\":\"object\",\"name\":\"panel.models.browser.BrowserInfo\",\"id\":\"ef59f866-0a1c-44fb-8d83-3cf51422bf0c\"},{\"type\":\"object\",\"name\":\"panel.models.comm_manager.CommManager\",\"id\":\"c2e3c739-db06-492b-8e2b-3f426fafaa0d\",\"attributes\":{\"plot_id\":\"ef59f866-0a1c-44fb-8d83-3cf51422bf0c\",\"comm_id\":\"0ee138824a2148c7b84b5ca2a49005f3\",\"client_comm_id\":\"9c7c0852f64343a69b4502fce7427efa\"}}],\"defs\":[{\"type\":\"model\",\"name\":\"ReactiveHTML1\"},{\"type\":\"model\",\"name\":\"FlexBox1\",\"properties\":[{\"name\":\"align_content\",\"kind\":\"Any\",\"default\":\"flex-start\"},{\"name\":\"align_items\",\"kind\":\"Any\",\"default\":\"flex-start\"},{\"name\":\"flex_direction\",\"kind\":\"Any\",\"default\":\"row\"},{\"name\":\"flex_wrap\",\"kind\":\"Any\",\"default\":\"wrap\"},{\"name\":\"gap\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"justify_content\",\"kind\":\"Any\",\"default\":\"flex-start\"}]},{\"type\":\"model\",\"name\":\"FloatPanel1\",\"properties\":[{\"name\":\"config\",\"kind\":\"Any\",\"default\":{\"type\":\"map\"}},{\"name\":\"contained\",\"kind\":\"Any\",\"default\":true},{\"name\":\"position\",\"kind\":\"Any\",\"default\":\"right-top\"},{\"name\":\"offsetx\",\"kind\":\"Any\",\"default\":null},{\"name\":\"offsety\",\"kind\":\"Any\",\"default\":null},{\"name\":\"theme\",\"kind\":\"Any\",\"default\":\"primary\"},{\"name\":\"status\",\"kind\":\"Any\",\"default\":\"normalized\"}]},{\"type\":\"model\",\"name\":\"GridStack1\",\"properties\":[{\"name\":\"mode\",\"kind\":\"Any\",\"default\":\"warn\"},{\"name\":\"ncols\",\"kind\":\"Any\",\"default\":null},{\"name\":\"nrows\",\"kind\":\"Any\",\"default\":null},{\"name\":\"allow_resize\",\"kind\":\"Any\",\"default\":true},{\"name\":\"allow_drag\",\"kind\":\"Any\",\"default\":true},{\"name\":\"state\",\"kind\":\"Any\",\"default\":[]}]},{\"type\":\"model\",\"name\":\"drag1\",\"properties\":[{\"name\":\"slider_width\",\"kind\":\"Any\",\"default\":5},{\"name\":\"slider_color\",\"kind\":\"Any\",\"default\":\"black\"},{\"name\":\"value\",\"kind\":\"Any\",\"default\":50}]},{\"type\":\"model\",\"name\":\"click1\",\"properties\":[{\"name\":\"terminal_output\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"debug_name\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"clears\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"FastWrapper1\",\"properties\":[{\"name\":\"object\",\"kind\":\"Any\",\"default\":null},{\"name\":\"style\",\"kind\":\"Any\",\"default\":null}]},{\"type\":\"model\",\"name\":\"NotificationAreaBase1\",\"properties\":[{\"name\":\"js_events\",\"kind\":\"Any\",\"default\":{\"type\":\"map\"}},{\"name\":\"position\",\"kind\":\"Any\",\"default\":\"bottom-right\"},{\"name\":\"_clear\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"NotificationArea1\",\"properties\":[{\"name\":\"js_events\",\"kind\":\"Any\",\"default\":{\"type\":\"map\"}},{\"name\":\"notifications\",\"kind\":\"Any\",\"default\":[]},{\"name\":\"position\",\"kind\":\"Any\",\"default\":\"bottom-right\"},{\"name\":\"_clear\",\"kind\":\"Any\",\"default\":0},{\"name\":\"types\",\"kind\":\"Any\",\"default\":[{\"type\":\"map\",\"entries\":[[\"type\",\"warning\"],[\"background\",\"#ffc107\"],[\"icon\",{\"type\":\"map\",\"entries\":[[\"className\",\"fas fa-exclamation-triangle\"],[\"tagName\",\"i\"],[\"color\",\"white\"]]}]]},{\"type\":\"map\",\"entries\":[[\"type\",\"info\"],[\"background\",\"#007bff\"],[\"icon\",{\"type\":\"map\",\"entries\":[[\"className\",\"fas fa-info-circle\"],[\"tagName\",\"i\"],[\"color\",\"white\"]]}]]}]}]},{\"type\":\"model\",\"name\":\"Notification\",\"properties\":[{\"name\":\"background\",\"kind\":\"Any\",\"default\":null},{\"name\":\"duration\",\"kind\":\"Any\",\"default\":3000},{\"name\":\"icon\",\"kind\":\"Any\",\"default\":null},{\"name\":\"message\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"notification_type\",\"kind\":\"Any\",\"default\":null},{\"name\":\"_destroyed\",\"kind\":\"Any\",\"default\":false}]},{\"type\":\"model\",\"name\":\"TemplateActions1\",\"properties\":[{\"name\":\"open_modal\",\"kind\":\"Any\",\"default\":0},{\"name\":\"close_modal\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"BootstrapTemplateActions1\",\"properties\":[{\"name\":\"open_modal\",\"kind\":\"Any\",\"default\":0},{\"name\":\"close_modal\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"TemplateEditor1\",\"properties\":[{\"name\":\"layout\",\"kind\":\"Any\",\"default\":[]}]},{\"type\":\"model\",\"name\":\"MaterialTemplateActions1\",\"properties\":[{\"name\":\"open_modal\",\"kind\":\"Any\",\"default\":0},{\"name\":\"close_modal\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"copy_to_clipboard1\",\"properties\":[{\"name\":\"fill\",\"kind\":\"Any\",\"default\":\"none\"},{\"name\":\"value\",\"kind\":\"Any\",\"default\":null}]}]}};\n",
|
||
" var render_items = [{\"docid\":\"68ae3073-59ef-4a95-b4d5-7788063cd504\",\"roots\":{\"ef59f866-0a1c-44fb-8d83-3cf51422bf0c\":\"aea85b85-0f68-4a78-88b1-70bfeeed615a\"},\"root_ids\":[\"ef59f866-0a1c-44fb-8d83-3cf51422bf0c\"]}];\n",
|
||
" var docs = Object.values(docs_json)\n",
|
||
" if (!docs) {\n",
|
||
" return\n",
|
||
" }\n",
|
||
" const py_version = docs[0].version.replace('rc', '-rc.').replace('.dev', '-dev.')\n",
|
||
" function embed_document(root) {\n",
|
||
" var Bokeh = get_bokeh(root)\n",
|
||
" Bokeh.embed.embed_items_notebook(docs_json, render_items);\n",
|
||
" for (const render_item of render_items) {\n",
|
||
" for (const root_id of render_item.root_ids) {\n",
|
||
"\tconst id_el = document.getElementById(root_id)\n",
|
||
"\tif (id_el.children.length && (id_el.children[0].className === 'bk-root')) {\n",
|
||
"\t const root_el = id_el.children[0]\n",
|
||
"\t root_el.id = root_el.id + '-rendered'\n",
|
||
"\t}\n",
|
||
" }\n",
|
||
" }\n",
|
||
" }\n",
|
||
" function get_bokeh(root) {\n",
|
||
" if (root.Bokeh === undefined) {\n",
|
||
" return null\n",
|
||
" } else if (root.Bokeh.version !== py_version) {\n",
|
||
" if (root.Bokeh.versions === undefined || !root.Bokeh.versions.has(py_version)) {\n",
|
||
"\treturn null\n",
|
||
" }\n",
|
||
" return root.Bokeh.versions.get(py_version);\n",
|
||
" } else if (root.Bokeh.version === py_version) {\n",
|
||
" return root.Bokeh\n",
|
||
" }\n",
|
||
" return null\n",
|
||
" }\n",
|
||
" function is_loaded(root) {\n",
|
||
" var Bokeh = get_bokeh(root)\n",
|
||
" return (Bokeh != null && Bokeh.Panel !== undefined)\n",
|
||
" }\n",
|
||
" if (is_loaded(root)) {\n",
|
||
" embed_document(root);\n",
|
||
" } else {\n",
|
||
" var attempts = 0;\n",
|
||
" var timer = setInterval(function(root) {\n",
|
||
" if (is_loaded(root)) {\n",
|
||
" clearInterval(timer);\n",
|
||
" embed_document(root);\n",
|
||
" } else if (document.readyState == \"complete\") {\n",
|
||
" attempts++;\n",
|
||
" if (attempts > 200) {\n",
|
||
" clearInterval(timer);\n",
|
||
"\t var Bokeh = get_bokeh(root)\n",
|
||
"\t if (Bokeh == null || Bokeh.Panel == null) {\n",
|
||
" console.warn(\"Panel: ERROR: Unable to run Panel code because Bokeh or Panel library is missing\");\n",
|
||
"\t } else {\n",
|
||
"\t console.warn(\"Panel: WARNING: Attempting to render but not all required libraries could be resolved.\")\n",
|
||
"\t embed_document(root)\n",
|
||
"\t }\n",
|
||
" }\n",
|
||
" }\n",
|
||
" }, 25, root)\n",
|
||
" }\n",
|
||
"})(window);</script>"
|
||
]
|
||
},
|
||
"metadata": {
|
||
"application/vnd.holoviews_exec.v0+json": {
|
||
"id": "ef59f866-0a1c-44fb-8d83-3cf51422bf0c"
|
||
}
|
||
},
|
||
"output_type": "display_data"
|
||
}
|
||
],
|
||
"source": [
|
||
"import os\n",
|
||
"import openai\n",
|
||
"from openai import OpenAI\n",
|
||
"import sys\n",
|
||
"sys.path.append('/kaggle/input/chatdata')\n",
|
||
"import utils\n",
|
||
"import panel as pn # GUI\n",
|
||
"pn.extension()\n",
|
||
"\n",
|
||
"from kaggle_secrets import UserSecretsClient\n",
|
||
"user_secrets = UserSecretsClient()\n",
|
||
"openai.api_key = user_secrets.get_secret(\"openai_api\")\n",
|
||
"client = OpenAI(\n",
|
||
" # This is the default and can be omitted\n",
|
||
" api_key=openai.api_key,\n",
|
||
")\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "55d51395",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.016719,
|
||
"end_time": "2024-05-04T12:19:56.958344",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:56.941625",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"Next, we will define the get_completion_from_messages which will take the messages with different types and return the LLM response."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"id": "f00ea71b",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:19:56.991225Z",
|
||
"iopub.status.busy": "2024-05-04T12:19:56.990756Z",
|
||
"iopub.status.idle": "2024-05-04T12:19:56.998659Z",
|
||
"shell.execute_reply": "2024-05-04T12:19:56.996824Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 0.026514,
|
||
"end_time": "2024-05-04T12:19:57.000907",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:56.974393",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def get_completion_from_messages(messages, \n",
|
||
" model=\"gpt-3.5-turbo\", \n",
|
||
" temperature=0, max_tokens=500):\n",
|
||
"\n",
|
||
" response = client.chat.completions.create(\n",
|
||
" model=model,\n",
|
||
" messages=messages,\n",
|
||
" temperature=temperature, \n",
|
||
" max_tokens=max_tokens, \n",
|
||
" )\n",
|
||
" return response.choices[0].message.content\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5010b244",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.010245,
|
||
"end_time": "2024-05-04T12:19:57.021837",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:57.011592",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"<a id=\"2\"></a>\n",
|
||
"# <div style=\"box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px inset, rgb(51, 51, 51) 0px 0px 0px 3px inset; padding:20px; font-size:32px; font-family: consolas; text-align:center; display:fill; border-radius:15px; color:rgb(34, 34, 34);\"> <b> 2. Chain of Prompts For Processing the User Query </b></div>\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"### The first step will check input to see if it flags the Moderation API or is a prompt injection:\n",
|
||
"\n",
|
||
"```python\n",
|
||
" # Step 1: Check input to see if it flags the Moderation API or is a prompt injection\n",
|
||
" response = openai.Moderation.create(input=user_input)\n",
|
||
" moderation_output = response[\"results\"][0]\n",
|
||
"\n",
|
||
" if moderation_output[\"flagged\"]:\n",
|
||
" print(\"Step 1: Input flagged by Moderation API.\")\n",
|
||
" return \"Sorry, we cannot process this request.\"\n",
|
||
"\n",
|
||
" if debug: print(\"Step 1: Input passed moderation check.\")\n",
|
||
" \n",
|
||
" category_and_product_response = utils.find_category_and_product_only(user_input, utils.get_products_and_category())\n",
|
||
"```\n",
|
||
"\n",
|
||
"### The second step will be to extract the list of products\n",
|
||
"\n",
|
||
"```python\n",
|
||
" category_and_product_list = utils.read_string_to_list(category_and_product_response)\n",
|
||
" #print(category_and_product_list)\n",
|
||
" \n",
|
||
" if debug: print(\"Step 2: Extracted list of products.\")\n",
|
||
"```\n",
|
||
"\n",
|
||
"### The third step will be to check if these products are available we will look up the product information\n",
|
||
"\n",
|
||
"```python\n",
|
||
" # Step 3: If products are found, look them up\n",
|
||
" product_information = utils.generate_output_string(category_and_product_list)\n",
|
||
" if debug: print(\"Step 3: Looked up product information.\")\n",
|
||
" ``` \n",
|
||
" \n",
|
||
"### The fourth step will be to define the system message and define the messages that will be sent to the LLM to answer the user question\n",
|
||
"\n",
|
||
"```python\n",
|
||
" # Step 4: Answer the user question\n",
|
||
" system_message = f\"\"\"\n",
|
||
" You are a customer service assistant for a large electronic store. \\\n",
|
||
" Respond in a friendly and helpful tone, with concise answers. \\\n",
|
||
" Make sure to ask the user relevant follow-up questions.\n",
|
||
" \"\"\"\n",
|
||
" messages = [\n",
|
||
" {'role': 'system', 'content': system_message},\n",
|
||
" {'role': 'user', 'content': f\"{delimiter}{user_input}{delimiter}\"},\n",
|
||
" {'role': 'assistant', 'content': f\"Relevant product information:\\n{product_information}\"}\n",
|
||
" ]\n",
|
||
"\n",
|
||
" final_response = get_completion_from_messages(all_messages + messages)\n",
|
||
" if debug:print(\"Step 4: Generated response to user question.\")\n",
|
||
" all_messages = all_messages + messages[1:]\n",
|
||
"```\n",
|
||
"\n",
|
||
"### The fifth step will be to put the LLM response through the moderation method to make sure that it is free of harmful content\n",
|
||
"\n",
|
||
"```python\n",
|
||
"\n",
|
||
" # Step 5: Put the answer through the Moderation API\n",
|
||
" response = openai.Moderation.create(input=final_response)\n",
|
||
" moderation_output = response[\"results\"][0]\n",
|
||
"\n",
|
||
" if moderation_output[\"flagged\"]:\n",
|
||
" if debug: print(\"Step 5: Response flagged by Moderation API.\")\n",
|
||
" return \"Sorry, we cannot provide this information.\"\n",
|
||
"\n",
|
||
" if debug: print(\"Step 5: Response passed moderation check.\")\n",
|
||
" ```\n",
|
||
"\n",
|
||
"### Step 6 we will validate the LLM answer and make sure it follows the instruction and answer the user's question\n",
|
||
"\n",
|
||
"```python\n",
|
||
"\n",
|
||
" # Step 6: Ask the model if the response answers the initial user query well\n",
|
||
" user_message = f\"\"\"\n",
|
||
" Customer message: {delimiter}{user_input}{delimiter}\n",
|
||
" Agent response: {delimiter}{final_response}{delimiter}\n",
|
||
"\n",
|
||
" Does the response sufficiently answer the question?\n",
|
||
" \"\"\"\n",
|
||
" messages = [\n",
|
||
" {'role': 'system', 'content': system_message},\n",
|
||
" {'role': 'user', 'content': user_message}\n",
|
||
" ]\n",
|
||
" evaluation_response = get_completion_from_messages(messages)\n",
|
||
" if debug: print(\"Step 6: Model evaluated the response.\")\n",
|
||
" ```\n",
|
||
"\n",
|
||
"### The final step is to return the answer to the user if it meets the previous conditions \n",
|
||
"\n",
|
||
"```python\n",
|
||
"\n",
|
||
" # Step 7: If yes, use this answer; if not, say that you will connect the user to a human\n",
|
||
" if \"Y\" in evaluation_response: # Using \"in\" instead of \"==\" to be safer for model output variation (e.g., \"Y.\" or \"Yes\")\n",
|
||
" if debug: print(\"Step 7: Model approved the response.\")\n",
|
||
" return final_response, all_messages\n",
|
||
" else:\n",
|
||
" if debug: print(\"Step 7: Model disapproved the response.\")\n",
|
||
" neg_str = \"I'm unable to provide the information you're looking for. I'll connect you with a human representative for further assistance.\"\n",
|
||
" return neg_str, all_messages\n",
|
||
" \n",
|
||
" ```\n",
|
||
" "
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8abd4181",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.010234,
|
||
"end_time": "2024-05-04T12:19:57.042774",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:57.032540",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"Let's put everything together and try it with different user messages to see how it will act"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"id": "40c5f73c",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:19:57.067574Z",
|
||
"iopub.status.busy": "2024-05-04T12:19:57.067163Z",
|
||
"iopub.status.idle": "2024-05-04T12:19:57.083631Z",
|
||
"shell.execute_reply": "2024-05-04T12:19:57.082567Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 0.032778,
|
||
"end_time": "2024-05-04T12:19:57.086405",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:57.053627",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def process_user_message(user_input, all_messages, debug=True):\n",
|
||
" delimiter = \"```\"\n",
|
||
" \n",
|
||
" # Step 1: Check input to see if it flags the Moderation API or is a prompt injection\n",
|
||
" \n",
|
||
" response = client.moderations.create(input=user_input)\n",
|
||
" moderation_output = response.results[0]\n",
|
||
"\n",
|
||
"\n",
|
||
" if moderation_output.flagged:\n",
|
||
" print(\"Step 1: Input flagged by Moderation API.\")\n",
|
||
" return \"Sorry, we cannot process this request.\"\n",
|
||
"\n",
|
||
" if debug: print(\"Step 1: Input passed moderation check.\")\n",
|
||
" \n",
|
||
" category_and_product_response = utils.find_category_and_product_only(user_input, utils.get_products_and_category())\n",
|
||
" #print(print(category_and_product_response)\n",
|
||
" \n",
|
||
" # Step 2: Extract the list of products\n",
|
||
" category_and_product_list = utils.read_string_to_list(category_and_product_response)\n",
|
||
" #print(category_and_product_list)\n",
|
||
"\n",
|
||
" if debug: print(\"Step 2: Extracted list of products.\")\n",
|
||
"\n",
|
||
" # Step 3: If products are found, look them up\n",
|
||
" product_information = utils.generate_output_string(category_and_product_list)\n",
|
||
" if debug: print(\"Step 3: Looked up product information.\")\n",
|
||
"\n",
|
||
" # Step 4: Answer the user question\n",
|
||
" system_message = f\"\"\"\n",
|
||
" You are a customer service assistant for a large electronic store. \\\n",
|
||
" Respond in a friendly and helpful tone, with concise answers. \\\n",
|
||
" Make sure to ask the user relevant follow-up questions.\n",
|
||
" \"\"\"\n",
|
||
" messages = [\n",
|
||
" {'role': 'system', 'content': system_message},\n",
|
||
" {'role': 'user', 'content': f\"{delimiter}{user_input}{delimiter}\"},\n",
|
||
" {'role': 'assistant', 'content': f\"Relevant product information:\\n{product_information}\"}\n",
|
||
" ]\n",
|
||
"\n",
|
||
" final_response = get_completion_from_messages(all_messages + messages)\n",
|
||
" if debug:print(\"Step 4: Generated response to user question.\")\n",
|
||
" all_messages = all_messages + messages[1:]\n",
|
||
"\n",
|
||
" # Step 5: Put the answer through the Moderation API \n",
|
||
" response = client.moderations.create(input=final_response)\n",
|
||
" moderation_output = response.results[0]\n",
|
||
" \n",
|
||
"\n",
|
||
" if moderation_output.flagged:\n",
|
||
" if debug: print(\"Step 5: Response flagged by Moderation API.\")\n",
|
||
" return \"Sorry, we cannot provide this information.\"\n",
|
||
"\n",
|
||
" if debug: print(\"Step 5: Response passed moderation check.\")\n",
|
||
"\n",
|
||
" # Step 6: Ask the model if the response answers the initial user query well\n",
|
||
" user_message = f\"\"\"\n",
|
||
" Customer message: {delimiter}{user_input}{delimiter}\n",
|
||
" Agent response: {delimiter}{final_response}{delimiter}\n",
|
||
"\n",
|
||
" Does the response sufficiently answer the question?\n",
|
||
" \"\"\"\n",
|
||
" messages = [\n",
|
||
" {'role': 'system', 'content': system_message},\n",
|
||
" {'role': 'user', 'content': user_message}\n",
|
||
" ]\n",
|
||
" evaluation_response = get_completion_from_messages(messages)\n",
|
||
" if debug: print(\"Step 6: Model evaluated the response.\")\n",
|
||
"\n",
|
||
" # Step 7: If yes, use this answer; if not, say that you will connect the user to a human\n",
|
||
" if \"Y\" in evaluation_response: # Using \"in\" instead of \"==\" to be safer for model output variation (e.g., \"Y.\" or \"Yes\")\n",
|
||
" if debug: print(\"Step 7: Model approved the response.\")\n",
|
||
" return final_response, all_messages\n",
|
||
" else:\n",
|
||
" if debug: print(\"Step 7: Model disapproved the response.\")\n",
|
||
" neg_str = \"I'm unable to provide the information you're looking for. I'll connect you with a human representative for further assistance.\"\n",
|
||
" return neg_str, all_messages"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "78f85209",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.010093,
|
||
"end_time": "2024-05-04T12:19:57.108489",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:57.098396",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"So we have the user input that we've been using. \"**Tell me about the SmartX Pro phone and the camera. Also, tell me about TVs**.\" So let's run this."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"id": "bd6c4b9d",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:19:57.131466Z",
|
||
"iopub.status.busy": "2024-05-04T12:19:57.130759Z",
|
||
"iopub.status.idle": "2024-05-04T12:20:04.270485Z",
|
||
"shell.execute_reply": "2024-05-04T12:20:04.269350Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 7.154331,
|
||
"end_time": "2024-05-04T12:20:04.273224",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:19:57.118893",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Step 1: Input passed moderation check.\n",
|
||
"Error: Invalid JSON string\n",
|
||
"Step 2: Extracted list of products.\n",
|
||
"Step 3: Looked up product information.\n",
|
||
"Step 4: Generated response to user question.\n",
|
||
"Step 5: Response passed moderation check.\n",
|
||
"Step 6: Model evaluated the response.\n",
|
||
"Step 7: Model approved the response.\n",
|
||
"- The SmartX Pro phone is a high-end smartphone with a powerful processor, advanced camera features, and a sleek design. It offers a large display, long battery life, and fast performance for multitasking and gaming.\n",
|
||
"- The FotoSnap camera is a DSLR camera with a high-resolution sensor, interchangeable lenses, and manual controls for professional photography. It offers features like optical zoom, image stabilization, and 4K video recording.\n",
|
||
"- Our range of TVs includes various sizes, resolutions (HD, Full HD, 4K), and smart TV capabilities. They offer features like HDR for enhanced picture quality, built-in streaming apps, and voice control options.\n",
|
||
"\n",
|
||
"Do you have any specific questions about the SmartX Pro phone, FotoSnap camera, or our TVs? Are you looking for a particular feature or considering a specific model?\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"user_input = \"tell me about the smartx pro phone and the fotosnap camera, the dslr one. Also what tell me about your tvs\"\n",
|
||
"response,_ = process_user_message(user_input,[])\n",
|
||
"print(response)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "22051c6d",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.011569,
|
||
"end_time": "2024-05-04T12:20:04.296198",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:04.284629",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"As you can see, we're going through the steps to answer the user question. The first step is the moderation step, and the second step is extracting the list of products. The third step is looking up the product information. With this product information, the model is trying to answer the question. Finally, it puts the response through the moderation API again to make sure it's safe to show to the user.\n",
|
||
"Let's try another example but this time we will ask about a product that is not on the product list"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"id": "e39ce19a",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:20:04.321567Z",
|
||
"iopub.status.busy": "2024-05-04T12:20:04.320881Z",
|
||
"iopub.status.idle": "2024-05-04T12:20:09.023907Z",
|
||
"shell.execute_reply": "2024-05-04T12:20:09.022314Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 4.719014,
|
||
"end_time": "2024-05-04T12:20:09.027060",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:04.308046",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Step 1: Input passed moderation check.\n",
|
||
"Step 2: Extracted list of products.\n",
|
||
"Step 3: Looked up product information.\n",
|
||
"Step 4: Generated response to user question.\n",
|
||
"Step 5: Response passed moderation check.\n",
|
||
"Step 6: Model evaluated the response.\n",
|
||
"Step 7: Model approved the response.\n",
|
||
"The iPhone 15 has not been released yet. Are you interested in learning more about the latest iPhone model currently available, such as the iPhone 13?\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"user_input = \"tell me about the Iphone 15\"\n",
|
||
"response,_ = process_user_message(user_input,[])\n",
|
||
"print(response)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d4381019",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.012905,
|
||
"end_time": "2024-05-04T12:20:09.051516",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:09.038611",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"Let's try another prompt in which I will ask about a product that is out of the category list included in the product list"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"id": "3c99ab3f",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:20:09.077189Z",
|
||
"iopub.status.busy": "2024-05-04T12:20:09.076414Z",
|
||
"iopub.status.idle": "2024-05-04T12:20:14.827657Z",
|
||
"shell.execute_reply": "2024-05-04T12:20:14.826526Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 5.766924,
|
||
"end_time": "2024-05-04T12:20:14.830257",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:09.063333",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Step 1: Input passed moderation check.\n",
|
||
"Step 2: Extracted list of products.\n",
|
||
"Step 3: Looked up product information.\n",
|
||
"Step 4: Generated response to user question.\n",
|
||
"Step 5: Response passed moderation check.\n",
|
||
"Step 6: Model evaluated the response.\n",
|
||
"Step 7: Model approved the response.\n",
|
||
"The Harry Potter novel series, written by J.K. Rowling, consists of seven books that follow the magical adventures of a young wizard named Harry Potter and his friends at Hogwarts School of Witchcraft and Wizardry. The series is beloved by readers of all ages and has inspired movies, merchandise, and a dedicated fan base. Are you looking to purchase the books or learn more about the series?\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"user_input = \"tell me about the Harry Potter novel series\"\n",
|
||
"response,_ = process_user_message(user_input,[])\n",
|
||
"print(response)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1c26f653",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.012171,
|
||
"end_time": "2024-05-04T12:20:14.855399",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:14.843228",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"Although this product is not on the list the LLM managed to answer the query as they are a well-known product. Let's finally try a question about a product that does not exist and see how the final response will be"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"id": "441a4b0d",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:20:14.883114Z",
|
||
"iopub.status.busy": "2024-05-04T12:20:14.882335Z",
|
||
"iopub.status.idle": "2024-05-04T12:20:19.127279Z",
|
||
"shell.execute_reply": "2024-05-04T12:20:19.125259Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 4.261859,
|
||
"end_time": "2024-05-04T12:20:19.129796",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:14.867937",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Step 1: Input passed moderation check.\n",
|
||
"Step 2: Extracted list of products.\n",
|
||
"Step 3: Looked up product information.\n",
|
||
"Step 4: Generated response to user question.\n",
|
||
"Step 5: Response passed moderation check.\n",
|
||
"Step 6: Model evaluated the response.\n",
|
||
"Step 7: Model approved the response.\n",
|
||
"The Xtg Fridge is a popular model known for its energy efficiency and spacious design. It comes in various sizes and configurations to suit different needs. \n",
|
||
"\n",
|
||
"To provide you with the most accurate information on the current available models, could you please specify the size or specific features you are looking for in a fridge? This way, I can assist you in finding the perfect Xtg Fridge model for your requirements.\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"user_input = \"tell me about the Xtg Fridge and what are the current available models\"\n",
|
||
"response,_ = process_user_message(user_input,[])\n",
|
||
"print(response)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "049c6a9c",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:11:06.377393Z",
|
||
"iopub.status.busy": "2024-05-04T12:11:06.376983Z",
|
||
"iopub.status.idle": "2024-05-04T12:11:06.385960Z",
|
||
"shell.execute_reply": "2024-05-04T12:11:06.384392Z",
|
||
"shell.execute_reply.started": "2024-05-04T12:11:06.377359Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 0.011983,
|
||
"end_time": "2024-05-04T12:20:19.154314",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:19.142331",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"There is no Xtg Fridge and it is not the product list and this due to the LLM hallucination and you can solve this by editing the prompt."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b04d97d9",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.011937,
|
||
"end_time": "2024-05-04T12:20:19.178735",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:19.166798",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"<a id=\"3\"></a>\n",
|
||
"# <div style=\"box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px inset, rgb(51, 51, 51) 0px 0px 0px 3px inset; padding:20px; font-size:32px; font-family: consolas; text-align:center; display:fill; border-radius:15px; color:rgb(34, 34, 34);\"> <b> 3. Building Conversational Chatbot </b></div>\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"In the previous section, I introduced the process_user_message. It takes in the user input, which is the current message, and an array of all of the messages so far. So here we have a function that will just accumulate the messages as we interact with the assistant."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"id": "7149d2e6",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:20:19.205732Z",
|
||
"iopub.status.busy": "2024-05-04T12:20:19.205261Z",
|
||
"iopub.status.idle": "2024-05-04T12:20:19.330850Z",
|
||
"shell.execute_reply": "2024-05-04T12:20:19.329342Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 0.142329,
|
||
"end_time": "2024-05-04T12:20:19.333342",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:19.191013",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def collect_messages(debug=False):\n",
|
||
" user_input = inp.value_input\n",
|
||
" if debug: print(f\"User Input = {user_input}\")\n",
|
||
" if user_input == \"\":\n",
|
||
" return\n",
|
||
" inp.value = ''\n",
|
||
" global context\n",
|
||
" #response, context = process_user_message(user_input, context, utils.get_products_and_category(),debug=True)\n",
|
||
" response, context = process_user_message(user_input, context, debug=False)\n",
|
||
" context.append({'role':'assistant', 'content':f\"{response}\"})\n",
|
||
" panels.append(\n",
|
||
" pn.Row('User:', pn.pane.Markdown(user_input, width=600)))\n",
|
||
" panels.append(\n",
|
||
" pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))\n",
|
||
" \n",
|
||
" return pn.Column(*panels)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d89f326d",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.011928,
|
||
"end_time": "2024-05-04T12:20:19.357741",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:19.345813",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"Finally, we will build a simple UI that will take the user messages and pass them to the collect_messages function return the response, and show it to the user."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"id": "f1ad5e81",
|
||
"metadata": {
|
||
"execution": {
|
||
"iopub.execute_input": "2024-05-04T12:20:19.384059Z",
|
||
"iopub.status.busy": "2024-05-04T12:20:19.383670Z",
|
||
"iopub.status.idle": "2024-05-04T12:20:19.484352Z",
|
||
"shell.execute_reply": "2024-05-04T12:20:19.483050Z"
|
||
},
|
||
"papermill": {
|
||
"duration": 0.116837,
|
||
"end_time": "2024-05-04T12:20:19.486828",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:19.369991",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [
|
||
{
|
||
"data": {},
|
||
"metadata": {},
|
||
"output_type": "display_data"
|
||
},
|
||
{
|
||
"data": {
|
||
"application/vnd.holoviews_exec.v0+json": "",
|
||
"text/html": [
|
||
"<div id='fabe7fe8-e719-475a-9880-237b4b88bed1'>\n",
|
||
" <div id=\"de1630b8-8f6a-4403-82d8-49a65628797c\" data-root-id=\"fabe7fe8-e719-475a-9880-237b4b88bed1\" style=\"display: contents;\"></div>\n",
|
||
"</div>\n",
|
||
"<script type=\"application/javascript\">(function(root) {\n",
|
||
" var docs_json = {\"99cbf0c7-71ce-4985-8c35-53c781ce279d\":{\"version\":\"3.4.1\",\"title\":\"Bokeh Application\",\"roots\":[{\"type\":\"object\",\"name\":\"panel.models.layout.Column\",\"id\":\"fabe7fe8-e719-475a-9880-237b4b88bed1\",\"attributes\":{\"name\":\"Column00126\",\"stylesheets\":[\"\\n:host(.pn-loading):before, .pn-loading:before {\\n background-color: #c3c3c3;\\n mask-size: auto calc(min(50%, 400px));\\n -webkit-mask-size: auto calc(min(50%, 400px));\\n}\",{\"type\":\"object\",\"name\":\"ImportedStyleSheet\",\"id\":\"9f4a8db6-4de5-4450-9f35-05bbc33ab086\",\"attributes\":{\"url\":\"https://cdn.holoviz.org/panel/1.4.1/dist/css/loading.css\"}},{\"type\":\"object\",\"name\":\"ImportedStyleSheet\",\"id\":\"ec49f643-2215-41be-b0ec-1438829e6118\",\"attributes\":{\"url\":\"https://cdn.holoviz.org/panel/1.4.1/dist/css/listpanel.css\"}},{\"type\":\"object\",\"name\":\"ImportedStyleSheet\",\"id\":\"32f4b12a-75d0-4ae7-a07a-3230b82d435f\",\"attributes\":{\"url\":\"https://cdn.holoviz.org/panel/1.4.1/dist/bundled/theme/default.css\"}},{\"type\":\"object\",\"name\":\"ImportedStyleSheet\",\"id\":\"a89f091f-567c-4a6c-8f7c-49e2a00cd795\",\"attributes\":{\"url\":\"https://cdn.holoviz.org/panel/1.4.1/dist/bundled/theme/native.css\"}}],\"margin\":0,\"align\":\"start\",\"children\":[{\"type\":\"object\",\"name\":\"TextInput\",\"id\":\"2870fee9-fc28-4e9b-a616-9d840bebf0b7\",\"attributes\":{\"stylesheets\":[\"\\n:host(.pn-loading):before, .pn-loading:before {\\n background-color: #c3c3c3;\\n mask-size: auto calc(min(50%, 400px));\\n -webkit-mask-size: auto calc(min(50%, 400px));\\n}\",{\"id\":\"9f4a8db6-4de5-4450-9f35-05bbc33ab086\"},{\"id\":\"32f4b12a-75d0-4ae7-a07a-3230b82d435f\"},{\"id\":\"a89f091f-567c-4a6c-8f7c-49e2a00cd795\"}],\"width\":300,\"min_width\":300,\"margin\":[5,10],\"align\":\"start\",\"placeholder\":\"Enter text here\\u2026\",\"max_length\":5000}},{\"type\":\"object\",\"name\":\"Row\",\"id\":\"841398bb-a7b7-454c-bb1d-322bd16fe6b5\",\"attributes\":{\"name\":\"Row00119\",\"stylesheets\":[\"\\n:host(.pn-loading):before, .pn-loading:before {\\n background-color: #c3c3c3;\\n mask-size: auto calc(min(50%, 400px));\\n -webkit-mask-size: auto calc(min(50%, 400px));\\n}\",{\"id\":\"9f4a8db6-4de5-4450-9f35-05bbc33ab086\"},{\"id\":\"ec49f643-2215-41be-b0ec-1438829e6118\"},{\"id\":\"32f4b12a-75d0-4ae7-a07a-3230b82d435f\"},{\"id\":\"a89f091f-567c-4a6c-8f7c-49e2a00cd795\"}],\"margin\":0,\"align\":\"start\",\"children\":[{\"type\":\"object\",\"name\":\"panel.models.widgets.Button\",\"id\":\"08640378-1507-4a29-a81f-2409c1aff8f4\",\"attributes\":{\"js_event_callbacks\":{\"type\":\"map\",\"entries\":[[\"button_click\",[{\"type\":\"object\",\"name\":\"CustomJS\",\"id\":\"a776eaef-0507-451e-bef2-fbb3fbbe002e\",\"attributes\":{\"tags\":[[139241392417632,[null,\"event:button_click\"],[null,\"loading\"]]],\"args\":{\"type\":\"map\",\"entries\":[[\"bidirectional\",false],[\"properties\",{\"type\":\"map\",\"entries\":[[\"event:button_click\",\"loading\"]]}],[\"source\",{\"id\":\"08640378-1507-4a29-a81f-2409c1aff8f4\"}],[\"target\",{\"type\":\"object\",\"name\":\"panel.models.layout.Column\",\"id\":\"f5467d06-3ecd-418a-8226-2ae7bfa2f2f8\",\"attributes\":{\"name\":\"Column00124\",\"stylesheets\":[\"\\n:host(.pn-loading):before, .pn-loading:before {\\n background-color: #c3c3c3;\\n mask-size: auto calc(min(50%, 400px));\\n -webkit-mask-size: auto calc(min(50%, 400px));\\n}\",{\"id\":\"9f4a8db6-4de5-4450-9f35-05bbc33ab086\"},{\"id\":\"ec49f643-2215-41be-b0ec-1438829e6118\"},{\"id\":\"32f4b12a-75d0-4ae7-a07a-3230b82d435f\"},{\"id\":\"a89f091f-567c-4a6c-8f7c-49e2a00cd795\"}],\"height\":300,\"min_height\":300,\"margin\":0,\"align\":\"start\",\"children\":[{\"type\":\"object\",\"name\":\"panel.models.markup.HTML\",\"id\":\"d82757c3-c3dc-4888-bcc3-fa15cf723d7a\",\"attributes\":{\"stylesheets\":[\"\\n:host(.pn-loading):before, .pn-loading:before {\\n background-color: #c3c3c3;\\n mask-size: auto calc(min(50%, 400px));\\n -webkit-mask-size: auto calc(min(50%, 400px));\\n}\",{\"id\":\"9f4a8db6-4de5-4450-9f35-05bbc33ab086\"},{\"id\":\"32f4b12a-75d0-4ae7-a07a-3230b82d435f\"},{\"id\":\"a89f091f-567c-4a6c-8f7c-49e2a00cd795\"}],\"margin\":[5,10],\"align\":\"start\",\"text\":\"<pre> </pre>\"}}]}}]]},\"code\":\"\\n if ('event:button_click'.startsWith('event:')) {\\n var value = true\\n } else {\\n var value = source['event:button_click'];\\n value = value;\\n }\\n if (typeof value !== 'boolean' || source.labels !== ['Loading']) {\\n value = true\\n }\\n var css_classes = target.css_classes.slice()\\n var loading_css = ['pn-loading', 'pn-arc']\\n if (value) {\\n for (var css of loading_css) {\\n if (!(css in css_classes)) {\\n css_classes.push(css)\\n }\\n }\\n } else {\\n for (var css of loading_css) {\\n var index = css_classes.indexOf(css)\\n if (index > -1) {\\n css_classes.splice(index, 1)\\n }\\n }\\n }\\n target['css_classes'] = css_classes\\n \"}}]]]},\"subscribed_events\":{\"type\":\"set\",\"entries\":[\"button_click\"]},\"css_classes\":[\"solid\"],\"stylesheets\":[\"\\n:host(.pn-loading):before, .pn-loading:before {\\n background-color: #c3c3c3;\\n mask-size: auto calc(min(50%, 400px));\\n -webkit-mask-size: auto calc(min(50%, 400px));\\n}\",{\"id\":\"9f4a8db6-4de5-4450-9f35-05bbc33ab086\"},{\"type\":\"object\",\"name\":\"ImportedStyleSheet\",\"id\":\"3c1f3c29-fdc6-4468-97b1-fdbb62476d3a\",\"attributes\":{\"url\":\"https://cdn.holoviz.org/panel/1.4.1/dist/css/button.css\"}},{\"id\":\"32f4b12a-75d0-4ae7-a07a-3230b82d435f\"},{\"id\":\"a89f091f-567c-4a6c-8f7c-49e2a00cd795\"}],\"margin\":[5,10],\"align\":\"start\",\"label\":\"Service Assistant\"}}]}},{\"id\":\"f5467d06-3ecd-418a-8226-2ae7bfa2f2f8\"}]}},{\"type\":\"object\",\"name\":\"panel.models.comm_manager.CommManager\",\"id\":\"adf7340e-f11c-42fa-8823-90181e51d1fd\",\"attributes\":{\"plot_id\":\"fabe7fe8-e719-475a-9880-237b4b88bed1\",\"comm_id\":\"c14296a6bade4b99bff6fbebb5305f90\",\"client_comm_id\":\"dcca93b3c95141868c0b9803db6206d5\"}}],\"defs\":[{\"type\":\"model\",\"name\":\"ReactiveHTML1\"},{\"type\":\"model\",\"name\":\"FlexBox1\",\"properties\":[{\"name\":\"align_content\",\"kind\":\"Any\",\"default\":\"flex-start\"},{\"name\":\"align_items\",\"kind\":\"Any\",\"default\":\"flex-start\"},{\"name\":\"flex_direction\",\"kind\":\"Any\",\"default\":\"row\"},{\"name\":\"flex_wrap\",\"kind\":\"Any\",\"default\":\"wrap\"},{\"name\":\"gap\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"justify_content\",\"kind\":\"Any\",\"default\":\"flex-start\"}]},{\"type\":\"model\",\"name\":\"FloatPanel1\",\"properties\":[{\"name\":\"config\",\"kind\":\"Any\",\"default\":{\"type\":\"map\"}},{\"name\":\"contained\",\"kind\":\"Any\",\"default\":true},{\"name\":\"position\",\"kind\":\"Any\",\"default\":\"right-top\"},{\"name\":\"offsetx\",\"kind\":\"Any\",\"default\":null},{\"name\":\"offsety\",\"kind\":\"Any\",\"default\":null},{\"name\":\"theme\",\"kind\":\"Any\",\"default\":\"primary\"},{\"name\":\"status\",\"kind\":\"Any\",\"default\":\"normalized\"}]},{\"type\":\"model\",\"name\":\"GridStack1\",\"properties\":[{\"name\":\"mode\",\"kind\":\"Any\",\"default\":\"warn\"},{\"name\":\"ncols\",\"kind\":\"Any\",\"default\":null},{\"name\":\"nrows\",\"kind\":\"Any\",\"default\":null},{\"name\":\"allow_resize\",\"kind\":\"Any\",\"default\":true},{\"name\":\"allow_drag\",\"kind\":\"Any\",\"default\":true},{\"name\":\"state\",\"kind\":\"Any\",\"default\":[]}]},{\"type\":\"model\",\"name\":\"drag1\",\"properties\":[{\"name\":\"slider_width\",\"kind\":\"Any\",\"default\":5},{\"name\":\"slider_color\",\"kind\":\"Any\",\"default\":\"black\"},{\"name\":\"value\",\"kind\":\"Any\",\"default\":50}]},{\"type\":\"model\",\"name\":\"click1\",\"properties\":[{\"name\":\"terminal_output\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"debug_name\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"clears\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"FastWrapper1\",\"properties\":[{\"name\":\"object\",\"kind\":\"Any\",\"default\":null},{\"name\":\"style\",\"kind\":\"Any\",\"default\":null}]},{\"type\":\"model\",\"name\":\"NotificationAreaBase1\",\"properties\":[{\"name\":\"js_events\",\"kind\":\"Any\",\"default\":{\"type\":\"map\"}},{\"name\":\"position\",\"kind\":\"Any\",\"default\":\"bottom-right\"},{\"name\":\"_clear\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"NotificationArea1\",\"properties\":[{\"name\":\"js_events\",\"kind\":\"Any\",\"default\":{\"type\":\"map\"}},{\"name\":\"notifications\",\"kind\":\"Any\",\"default\":[]},{\"name\":\"position\",\"kind\":\"Any\",\"default\":\"bottom-right\"},{\"name\":\"_clear\",\"kind\":\"Any\",\"default\":0},{\"name\":\"types\",\"kind\":\"Any\",\"default\":[{\"type\":\"map\",\"entries\":[[\"type\",\"warning\"],[\"background\",\"#ffc107\"],[\"icon\",{\"type\":\"map\",\"entries\":[[\"className\",\"fas fa-exclamation-triangle\"],[\"tagName\",\"i\"],[\"color\",\"white\"]]}]]},{\"type\":\"map\",\"entries\":[[\"type\",\"info\"],[\"background\",\"#007bff\"],[\"icon\",{\"type\":\"map\",\"entries\":[[\"className\",\"fas fa-info-circle\"],[\"tagName\",\"i\"],[\"color\",\"white\"]]}]]}]}]},{\"type\":\"model\",\"name\":\"Notification\",\"properties\":[{\"name\":\"background\",\"kind\":\"Any\",\"default\":null},{\"name\":\"duration\",\"kind\":\"Any\",\"default\":3000},{\"name\":\"icon\",\"kind\":\"Any\",\"default\":null},{\"name\":\"message\",\"kind\":\"Any\",\"default\":\"\"},{\"name\":\"notification_type\",\"kind\":\"Any\",\"default\":null},{\"name\":\"_destroyed\",\"kind\":\"Any\",\"default\":false}]},{\"type\":\"model\",\"name\":\"TemplateActions1\",\"properties\":[{\"name\":\"open_modal\",\"kind\":\"Any\",\"default\":0},{\"name\":\"close_modal\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"BootstrapTemplateActions1\",\"properties\":[{\"name\":\"open_modal\",\"kind\":\"Any\",\"default\":0},{\"name\":\"close_modal\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"TemplateEditor1\",\"properties\":[{\"name\":\"layout\",\"kind\":\"Any\",\"default\":[]}]},{\"type\":\"model\",\"name\":\"MaterialTemplateActions1\",\"properties\":[{\"name\":\"open_modal\",\"kind\":\"Any\",\"default\":0},{\"name\":\"close_modal\",\"kind\":\"Any\",\"default\":0}]},{\"type\":\"model\",\"name\":\"copy_to_clipboard1\",\"properties\":[{\"name\":\"fill\",\"kind\":\"Any\",\"default\":\"none\"},{\"name\":\"value\",\"kind\":\"Any\",\"default\":null}]}]}};\n",
|
||
" var render_items = [{\"docid\":\"99cbf0c7-71ce-4985-8c35-53c781ce279d\",\"roots\":{\"fabe7fe8-e719-475a-9880-237b4b88bed1\":\"de1630b8-8f6a-4403-82d8-49a65628797c\"},\"root_ids\":[\"fabe7fe8-e719-475a-9880-237b4b88bed1\"]}];\n",
|
||
" var docs = Object.values(docs_json)\n",
|
||
" if (!docs) {\n",
|
||
" return\n",
|
||
" }\n",
|
||
" const py_version = docs[0].version.replace('rc', '-rc.').replace('.dev', '-dev.')\n",
|
||
" function embed_document(root) {\n",
|
||
" var Bokeh = get_bokeh(root)\n",
|
||
" Bokeh.embed.embed_items_notebook(docs_json, render_items);\n",
|
||
" for (const render_item of render_items) {\n",
|
||
" for (const root_id of render_item.root_ids) {\n",
|
||
"\tconst id_el = document.getElementById(root_id)\n",
|
||
"\tif (id_el.children.length && (id_el.children[0].className === 'bk-root')) {\n",
|
||
"\t const root_el = id_el.children[0]\n",
|
||
"\t root_el.id = root_el.id + '-rendered'\n",
|
||
"\t}\n",
|
||
" }\n",
|
||
" }\n",
|
||
" }\n",
|
||
" function get_bokeh(root) {\n",
|
||
" if (root.Bokeh === undefined) {\n",
|
||
" return null\n",
|
||
" } else if (root.Bokeh.version !== py_version) {\n",
|
||
" if (root.Bokeh.versions === undefined || !root.Bokeh.versions.has(py_version)) {\n",
|
||
"\treturn null\n",
|
||
" }\n",
|
||
" return root.Bokeh.versions.get(py_version);\n",
|
||
" } else if (root.Bokeh.version === py_version) {\n",
|
||
" return root.Bokeh\n",
|
||
" }\n",
|
||
" return null\n",
|
||
" }\n",
|
||
" function is_loaded(root) {\n",
|
||
" var Bokeh = get_bokeh(root)\n",
|
||
" return (Bokeh != null && Bokeh.Panel !== undefined)\n",
|
||
" }\n",
|
||
" if (is_loaded(root)) {\n",
|
||
" embed_document(root);\n",
|
||
" } else {\n",
|
||
" var attempts = 0;\n",
|
||
" var timer = setInterval(function(root) {\n",
|
||
" if (is_loaded(root)) {\n",
|
||
" clearInterval(timer);\n",
|
||
" embed_document(root);\n",
|
||
" } else if (document.readyState == \"complete\") {\n",
|
||
" attempts++;\n",
|
||
" if (attempts > 200) {\n",
|
||
" clearInterval(timer);\n",
|
||
"\t var Bokeh = get_bokeh(root)\n",
|
||
"\t if (Bokeh == null || Bokeh.Panel == null) {\n",
|
||
" console.warn(\"Panel: ERROR: Unable to run Panel code because Bokeh or Panel library is missing\");\n",
|
||
"\t } else {\n",
|
||
"\t console.warn(\"Panel: WARNING: Attempting to render but not all required libraries could be resolved.\")\n",
|
||
"\t embed_document(root)\n",
|
||
"\t }\n",
|
||
" }\n",
|
||
" }\n",
|
||
" }, 25, root)\n",
|
||
" }\n",
|
||
"})(window);</script>"
|
||
],
|
||
"text/plain": [
|
||
"Column\n",
|
||
" [0] TextInput(placeholder='Enter text here…')\n",
|
||
" [1] Row\n",
|
||
" [0] Button(name='Service Assistant')\n",
|
||
" [2] ParamFunction(function, _pane=Str, defer_load=False, height=300, loading_indicator=True)"
|
||
]
|
||
},
|
||
"execution_count": 10,
|
||
"metadata": {
|
||
"application/vnd.holoviews_exec.v0+json": {
|
||
"id": "fabe7fe8-e719-475a-9880-237b4b88bed1"
|
||
}
|
||
},
|
||
"output_type": "execute_result"
|
||
}
|
||
],
|
||
"source": [
|
||
"panels = [] # collect display \n",
|
||
"\n",
|
||
"context = [ {'role':'system', 'content':\"You are Service Assistant\"} ] \n",
|
||
"\n",
|
||
"inp = pn.widgets.TextInput( placeholder='Enter text here…')\n",
|
||
"button_conversation = pn.widgets.Button(name=\"Service Assistant\")\n",
|
||
"\n",
|
||
"interactive_conversation = pn.bind(collect_messages, button_conversation)\n",
|
||
"\n",
|
||
"dashboard = pn.Column(\n",
|
||
" inp,\n",
|
||
" pn.Row(button_conversation),\n",
|
||
" pn.panel(interactive_conversation, loading_indicator=True, height=300),\n",
|
||
")\n",
|
||
"\n",
|
||
"dashboard"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6026cff1",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.01256,
|
||
"end_time": "2024-05-04T12:20:19.512442",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:19.499882",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"source": [
|
||
"# <div style=\"box-shadow: rgba(240, 46, 170, 0.4) -5px 5px inset, rgba(240, 46, 170, 0.3) -10px 10px inset, rgba(240, 46, 170, 0.2) -15px 15px inset, rgba(240, 46, 170, 0.1) -20px 20px inset, rgba(240, 46, 170, 0.05) -25px 25px inset; padding:20px; font-size:30px; font-family: consolas; display:fill; border-radius:15px; color: rgba(240, 46, 170, 0.7)\"> <b> ༼ つ ◕‿◕ ༽つ Thank You!</b></div>\n",
|
||
"\n",
|
||
"<p style=\"font-family:verdana; color:rgb(34, 34, 34); font-family: consolas; font-size: 16px;\"> 💌 Thank you for taking the time to read through my notebook. I hope you found it interesting and informative. If you have any feedback or suggestions for improvement, please don't hesitate to let me know in the comments. <br><br> 🚀 If you liked this notebook, please consider upvoting it so that others can discover it too. Your support means a lot to me, and it helps to motivate me to create more content in the future. <br><br> ❤️ Once again, thank you for your support, and I hope to see you again soon!</p>"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"id": "ba5b1165",
|
||
"metadata": {
|
||
"papermill": {
|
||
"duration": 0.01248,
|
||
"end_time": "2024-05-04T12:20:19.537641",
|
||
"exception": false,
|
||
"start_time": "2024-05-04T12:20:19.525161",
|
||
"status": "completed"
|
||
},
|
||
"tags": []
|
||
},
|
||
"outputs": [],
|
||
"source": []
|
||
}
|
||
],
|
||
"metadata": {
|
||
"kaggle": {
|
||
"accelerator": "none",
|
||
"dataSources": [
|
||
{
|
||
"datasetId": 4937384,
|
||
"sourceId": 8311327,
|
||
"sourceType": "datasetVersion"
|
||
}
|
||
],
|
||
"dockerImageVersionId": 30698,
|
||
"isGpuEnabled": false,
|
||
"isInternetEnabled": true,
|
||
"language": "python",
|
||
"sourceType": "notebook"
|
||
},
|
||
"kernelspec": {
|
||
"display_name": "Python 3",
|
||
"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.3"
|
||
},
|
||
"papermill": {
|
||
"default_parameters": {},
|
||
"duration": 47.018141,
|
||
"end_time": "2024-05-04T12:20:20.474866",
|
||
"environment_variables": {},
|
||
"exception": null,
|
||
"input_path": "__notebook__.ipynb",
|
||
"output_path": "__notebook__.ipynb",
|
||
"parameters": {},
|
||
"start_time": "2024-05-04T12:19:33.456725",
|
||
"version": "2.5.0"
|
||
}
|
||
},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 5
|
||
}
|