{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "context_dict = {\n", " \"company; goliath; we\" : \n", " \"\"\"\n", " Our company builds AI Recommendation Systems for Matching Platforms using the latest technology. Our company is estabilished and operates in Japan. Our company uses the AWS Cloud to manage Servers. Our company can use GPT3 as well. Our company also builds GPT3-based chatbots. Our company can use open-source models, if requested. Our company uses open source models. Our company operates in Japan. Our company has been operating for 1 year, and we are expanding in Hong Kong. Our company offers other services apart from recommendation systems, like GPT3 chatbots. Our company can also build recommendation systems for mobile apps.\n", " \"\"\"\n", " ,\n", " \"price\" :\n", " \"\"\"\n", " The price of a recommendation system depends on the amount of complexity that is required to build, as well as the volume of customers. Reach us to get a quotation. The price of a chatbot depends by its intended usage and complexity, contact us for a quotation.\n", " \"\"\"\n", " ,\n", " \"recommendation system\" :\n", " \"\"\"\n", " If your company wants to recommend products to customers, we can build a recommendation system for you. GPT3 can be used to build recommendation systems by using embeddings, mapping choices in a mathematical space. Once the recommendation system has been built, we will manage it in the future as well. Recommendation system could also be built for startups, though they will be in smaller size. We use AWS OpenSearch to host recommendation system.\n", " \"\"\"\n", " ,\n", " \"a matching platform\" :\n", " \"\"\"\n", " A matching platform is a business with thousands of users, who could be customers, individuals or companies, who are interacting with one another. For example dating apps, ecommerce platforms, or job recruiting platforms. \n", " \"\"\"\n", "}\n", "\n", "def split_paragraph(text, keyword):\n", " list1 = [x.strip() for x in text.split('.')]\n", " list2 = []\n", " \n", " for sentence in list1:\n", " # Check if the sentence contains the phrase \"chamber of commerce\"\n", " if keyword in sentence.lower():\n", " list2.append(1)\n", " else:\n", " list2.append(0)\n", "\n", " #in case first sentence has no keyword, we add it\n", " if list2[0] == 0:\n", " list1[0] = f'the {keyword}: ' + list1[0]\n", " list2[0] = 1\n", "\n", " # print(list1)\n", " # print(list2)\n", "\n", " list3 = list()\n", " current_string = ''\n", " # Loop through each element of list1 and list2\n", " for i in range(len(list1)):\n", " # If the corresponding element in list2 is 1, add the current string to list3 and reset the current string\n", "\n", " if list2[i] == 1:\n", " list3.append(current_string)\n", " current_string = \"\" #reset\n", " current_string += list1[i]\n", "\n", " # Otherwise, concatenate the current string with the current element of list1\n", " if list2[i] == 0:\n", " current_string += '. '+list1[i]\n", "\n", " # Add the final concatenated string to list3\n", " list3.append(current_string)\n", "\n", " return [x.strip() for x in list3[1:]]\n", "\n", "def context_dict2context_list(context_dict):\n", " list1 = list()\n", " for all_keys in context_dict:\n", " key = all_keys.split(';')[0]\n", " try:\n", " synonyms = all_keys.split(';')[1:]\n", " except:\n", " pass\n", " # print(key)\n", " str1 = context_dict[all_keys]\n", " \n", " split_list = [x.replace('\\n', '').strip() for x in str1.split('\\n\\n')]\n", " split_list\n", "\n", " for sentence in split_list:\n", " for s in split_paragraph(sentence, key):\n", " #add synonyms\n", " for synonym in synonyms:\n", " #manual replacement causes a wrong grammar\n", " #gpt3 replacement\n", " print(s, key, synonym)\n", " prompt = f'in the following sentence: {s}. Replace {key} with {synonym} correcting the grammar'\n", " answer = gpt3_question(prompt).replace('\\n', '')\n", " list1.append(answer)\n", " list1.append(s)\n", " return list1\n", "\n", "#prepare context\n", "context_list = context_dict2context_list(context_dict)\n", "context_list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s = 'Our company builds AI Recommendation Systems for Matching Platforms using the latest technology'\n", "key = 'company'\n", "synonym = 'we'\n", "\n", "prompt = f'in the following sentence: {s}. Replace {key} with {synonym} correcting the grammar'\n", "gpt3_question(prompt).replace('\\n', '')" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [], "source": [ "import requests\n", "import os\n", "import torch\n", "# os.system('pip install openpyxl')\n", "# os.system('pip install sentence-transformers==2.2.2')\n", "# os.system('pip install torch==1.13.0')\n", "\n", "def chatgpt3_question(context, question):\n", " api_key = \"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\"\n", " url = \"https://api.openai.com/v1/chat/completions\"\n", "\n", " prompt = f\"\"\"\n", " based on this context: {context}\n", " answer this use question: {question}\n", " \"\"\"\n", "\n", " headers = {\n", " \"Content-Type\": \"application/json\",\n", " \"Authorization\": f\"Bearer {api_key}\"\n", " }\n", "\n", " data = {\n", " \"model\": \"gpt-3.5-turbo\",\n", " \"messages\": [{\"role\": \"user\", \"content\": prompt}]\n", " }\n", "\n", " response = requests.post(url, headers=headers, json=data)\n", " generated_text = response.json()['choices'][0]['message']['content']\n", "\n", " return generated_text\n", "\n", "import os\n", "import requests\n", "import pandas as pd\n", "\n", "def text2vec(query):\n", " headers = {\n", " 'Content-Type': 'application/json',\n", " 'Authorization': 'Bearer ' + \"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\",\n", " }\n", "\n", " json_data = {\n", " 'input': query,\n", " 'model': 'text-embedding-ada-002',\n", " }\n", "\n", " response = requests.post('https://api.openai.com/v1/embeddings', headers=headers, json=json_data)\n", " query = response.json()['data'][0]['embedding'] #len=1536 #pricing=0.0004\n", " return query\n", "\n", "import pandas as pd\n", "from sentence_transformers import SentenceTransformer, util\n", "\n", "df = pd.read_parquet('df.parquet')\n", "df_qa = pd.read_parquet('df_qa.parquet')\n", "\n", "df_qa_ = df_qa.copy()\n", "df_ = df.copy()\n", "\n", "def qa(df_, df_qa_, min_qa_score, min_context_score, verbose, query):\n", " query_vec = text2vec(query)\n", " query_vec = torch.DoubleTensor(query_vec)\n", "\n", " #first check if there is already a question in df_qa\n", " df_qa_['score'] = df_qa_['text_vector_'].apply(lambda x : float(util.cos_sim(x, query_vec)))\n", " df_qa_ = df_qa_.sort_values('score', ascending=False)\n", " \n", " df_qa_ = df_qa_[df_qa_['score']>=min_qa_score]\n", " #if we find at least one possible preset answer\n", " if len(df_qa_) > 0:\n", " if verbose : display(df_qa_)\n", " answer = df_qa_[0:1]['answer'].values.tolist()[0]\n", " return answer\n", " \n", " #then check if we can use the context to answer a question\n", " df_['score'] = df_['text_vector_'].apply(lambda x : float(util.cos_sim(x, query_vec)))\n", " df_ = df_.sort_values('score', ascending=False)\n", " df_ = df_[df_['score']>=min_context_score]\n", " #if we find at least one possible preset answer\n", " if len(df_) > 0:\n", " if verbose : display(df_)\n", " #in case we might decide to merge multiple context\n", " context = ' '.join(df_['description'][0:1].values.tolist())\n", " answer = chatgpt3_question(context, query)\n", " return answer\n", " else:\n", " return 'impossible to give an answer'\n", "\n", "# print(\n", "# qa(\n", "# df_, \n", "# df_qa_, \n", "# min_qa_score=0.92, \n", "# min_context_score=.75, \n", "# verbose=False, \n", "# query='What is a recommender system?'\n", "# )\n", "# )" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Query after coreference resolution: \"How much does your company charge for recommendation systems?\"'" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def gpt3_reference(last_context, query):\n", " #needs to be referred to the second\n", " # last_context = 'you are a company'\n", " # query = \"\"\"what do you do\"\"\"\n", "\n", " prompt = f\"\"\"\n", " context : {last_context} \n", " query : {query}\n", " instructions:\n", " apply a coreference resolution on the query and replace the pronoun with no temperature, no adjectives\n", " \"\"\"\n", " #only if pronoun is unclear, replace query pronoun with its reference\n", " answer = chatgpt3_question(prompt)\n", "\n", " #replacements\n", " answer = answer.replace('\\n', '')\n", " answer = answer.replace('Answer:', '')\n", " answer = answer.replace('answer:', '')\n", " answer = answer.replace('answer', '')\n", " answer = answer.strip()\n", " return answer\n", "\n", "gpt3_reference(\"you are a company. recommendation systems are expensive\", \"How much do you charge?\")" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
questionanswertext_vector_
0how much does it cost?The price depends by its intended usage and co...[0.02400375, -0.022719184, 0.010704716, -0.012...
1do you use GPT3 API?yes, we can[0.008728346, -0.0068335673, -0.008393759, -0....
2do you use GPT3?yes, we can[0.00771756, -0.0016906569, -0.0074193655, -0....
3do you use GPT4?yes, we can[0.007858252, -0.0008719981, -0.010744374, -0....
4what do you do?Our company builds AI recommendaion systems[-0.0043235356, -0.018366648, -0.006951173, -0...
5what does goliath do?Our company builds AI recommendaion systems[-0.027456148, -0.017353108, -0.007992724, 0.0...
6what does your company do?Our company builds AI recommendaion systems[0.0022247417, -0.012323239, -0.004670404, -0....
\n", "
" ], "text/plain": [ " question \\\n", "0 how much does it cost? \n", "1 do you use GPT3 API? \n", "2 do you use GPT3? \n", "3 do you use GPT4? \n", "4 what do you do? \n", "5 what does goliath do? \n", "6 what does your company do? \n", "\n", " answer \\\n", "0 The price depends by its intended usage and co... \n", "1 yes, we can \n", "2 yes, we can \n", "3 yes, we can \n", "4 Our company builds AI recommendaion systems \n", "5 Our company builds AI recommendaion systems \n", "6 Our company builds AI recommendaion systems \n", "\n", " text_vector_ \n", "0 [0.02400375, -0.022719184, 0.010704716, -0.012... \n", "1 [0.008728346, -0.0068335673, -0.008393759, -0.... \n", "2 [0.00771756, -0.0016906569, -0.0074193655, -0.... \n", "3 [0.007858252, -0.0008719981, -0.010744374, -0.... \n", "4 [-0.0043235356, -0.018366648, -0.006951173, -0... \n", "5 [-0.027456148, -0.017353108, -0.007992724, 0.0... \n", "6 [0.0022247417, -0.012323239, -0.004670404, -0.... " ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_qa_" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
questionanswertext_vector_score
5what does goliath do?Our company builds AI recommendaion systems[-0.027456148, -0.017353108, -0.007992724, 0.0...0.902588
\n", "
" ], "text/plain": [ " question answer \\\n", "5 what does goliath do? Our company builds AI recommendaion systems \n", "\n", " text_vector_ score \n", "5 [-0.027456148, -0.017353108, -0.007992724, 0.0... 0.902588 " ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "'Our company builds AI recommendaion systems'" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bot_answer = qa(\n", " df_, \n", " df_qa_, \n", " min_qa_score=0.88, \n", " min_context_score=.75, \n", " verbose=True, \n", " query='how much does goliath charge?'\n", " )\n", "bot_answer" ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7876\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "sending request\n", "\n", "@@@ How much does Goliath charge?\n" ] } ], "source": [ "import subprocess\n", "import random\n", "import gradio as gr\n", "import requests\n", "\n", "history = None\n", "\n", "def predict(input, history, last_context):\n", " last_context += 'you are a company'\n", "\n", " #WE CAN PLAY WITH user_input AND bot_answer, as well as history\n", " user_input = input\n", "\n", " query = gpt3_reference(last_context, user_input)\n", " print('@@@', query)\n", " bot_answer = qa(\n", " df_, \n", " df_qa_, \n", " min_qa_score=0.92, \n", " min_context_score=.75, \n", " verbose=False, \n", " query=input\n", " )\n", "\n", " response = list()\n", " response = [(input, bot_answer)]\n", " \n", " history.append(response[0])\n", " response = history\n", "\n", " last_context = input\n", "\n", " # print('#history', history)\n", " # print('#response', response)\n", "\n", " return response, history, last_context\n", "\n", "demo = gr.Blocks()\n", "with demo:\n", " gr.Markdown(\n", " \"\"\"\n", " Chatbot\n", " \"\"\"\n", " )\n", " state = gr.Variable(value=[]) #beginning\n", " last_context = gr.Variable(value='') #beginning\n", " chatbot = gr.Chatbot() #color_map=(\"#00ff7f\", \"#00d5ff\")\n", " text = gr.Textbox(\n", " label=\"Question\",\n", " value=\"What is a recommendation system?\",\n", " placeholder=\"\",\n", " max_lines=1,\n", " )\n", " text.submit(predict, [text, state, last_context], [chatbot, state, last_context])\n", " text.submit(lambda x: \"\", text, text)\n", " # btn = gr.Button(value=\"submit\")\n", " # btn.click(chatbot_foo, None, [chatbot, state])\n", "\n", "demo.launch(share=False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "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.9.13" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }