{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### openai REST API" ] }, { "cell_type": "code", "execution_count": 264, "metadata": {}, "outputs": [], "source": [ "import requests\n", "\n", "#openai\n", "openai_api_key = \"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\"\n", "\n", "#azure\n", "azure_api_key = \"c6d9cc1f487640cc92800d8d177f5f59\"\n", "azure_api_base = \"https://openai-619.openai.azure.com/\" # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/\n", "azure_api_type = 'azure'\n", "azure_api_version = '2022-12-01' # this may change in the future" ] }, { "cell_type": "code", "execution_count": 265, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"\\n\\nAs an AI language model, I don't have feelings like humans, but I'm functioning optimally. How may I help you?\"" ] }, "execution_count": 265, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def gpt3(prompt, model, service, max_tokens=400):\n", " \n", " if service == 'openai':\n", " if model == 'gpt-3.5-turbo':\n", " api_endpoint = \"https://api.openai.com/v1/chat/completions\"\n", " data = {\n", " \"model\": \"gpt-3.5-turbo\",\n", " \"messages\": [{\"role\": \"user\", \"content\": prompt}]\n", " }\n", " headers = {\n", " \"Content-Type\": \"application/json\",\n", " \"Authorization\": f\"Bearer {openai_api_key}\"\n", " }\n", " response = requests.post(api_endpoint, headers=headers, json=data)\n", " return response.json()['choices'][0]['message']['content']\n", "\n", " elif model == 'gpt-3':\n", " api_endpoint = \"https://api.openai.com/v1/engines/text-davinci-003/completions\"\n", " data = {\n", " \"prompt\": prompt,\n", " \"max_tokens\": max_tokens,\n", " \"temperature\": 0.5\n", " }\n", " headers = {\n", " \"Content-Type\": \"application/json\",\n", " \"Authorization\": f\"Bearer {openai_api_key}\"\n", " }\n", " response = requests.post(api_endpoint, headers=headers, json=data)\n", " return response.json()[\"choices\"][0][\"text\"]\n", " \n", " elif service == 'azure':\n", " \n", " if model == 'gpt-3':\n", " azure_deployment_name='gpt3'\n", "\n", " api_endpoint = f\"\"\"{azure_api_base}openai/deployments/{azure_deployment_name}/completions?api-version={azure_api_version}\"\"\"\n", "\n", " headers = {\n", " \"Content-Type\": \"application/json\",\n", " \"api-key\": azure_api_key\n", " }\n", "\n", " data = {\n", " \"prompt\": prompt,\n", " \"max_tokens\": max_tokens\n", " }\n", " response = requests.post(api_endpoint, headers=headers, json=data)\n", "\n", " generated_text = response.json()[\"choices\"][0][\"text\"]\n", " return generated_text\n", "\n", " elif model == 'gpt-3.5-turbo':\n", " azure_deployment_name='gpt-35-turbo' #cannot be creative with the name\n", " headers = {\n", " \"Content-Type\": \"application/json\",\n", " \"api-key\": azure_api_key\n", " }\n", " json_data = {\n", " 'messages': [\n", " {\n", " 'role': 'user',\n", " 'content': prompt,\n", " },\n", " ],\n", " }\n", " api_endpoint = f\"\"\"{azure_api_base}openai/deployments/{azure_deployment_name}/chat/completions?api-version=2023-03-15-preview\"\"\"\n", " response = requests.post(api_endpoint, headers=headers, json=json_data)\n", " return response.json()['choices'][0]['message']['content']\n", "\n", "#azure is much more sensible to max_tokens\n", "gpt3('how are you?', model='gpt-3.5-turbo', service='azure')" ] }, { "cell_type": "code", "execution_count": 266, "metadata": {}, "outputs": [], "source": [ "def text2vec(input, service):\n", " if service == 'openai':\n", " api_endpoint = 'https://api.openai.com/v1/embeddings'\n", " headers = {\n", " 'Content-Type': 'application/json',\n", " 'Authorization': 'Bearer ' + \"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\",\n", " }\n", " json_data = {\n", " 'input': input,\n", " 'model': 'text-embedding-ada-002',\n", " }\n", " # response = requests.post(api_endpoint, headers=headers, json=json_data)\n", "\n", " elif service == 'azure':\n", " azure_deployment_name = 'gpt3_embedding'\n", " api_endpoint = f\"\"\"{azure_api_base}openai/deployments/{azure_deployment_name}/embeddings?api-version={azure_api_version}\"\"\"\n", " headers = {\n", " \"Content-Type\": \"application/json\",\n", " \"api-key\": azure_api_key\n", " }\n", " json_data = {\n", " \"input\": input\n", " }\n", "\n", " response = requests.post(api_endpoint, headers=headers, json=json_data)\n", " vec = response.json()['data'][0]['embedding'] #len=1536 #pricing=0.0004\n", " return vec\n", "\n", "def list2vec(list1):\n", " headers = {\n", " 'Content-Type': 'application/json',\n", " 'Authorization': 'Bearer ' + \"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\",\n", " }\n", "\n", " json_data = {\n", " 'input': list1,\n", " 'model': 'text-embedding-ada-002',\n", " }\n", "\n", " response = requests.post('https://api.openai.com/v1/embeddings', headers=headers, json=json_data)\n", " return [x['embedding'] for x in response.json()['data']]\n", "\n", " dict1 = dict()\n", " for index in range(len(json_data['input'])):\n", " dict1[json_data['input'][index]] = response.json()['data'][index]['embedding']\n", " return dict1" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### context generator" ] }, { "cell_type": "code", "execution_count": 343, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 343, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import requests\n", "import pandas as pd\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", " #if s does not exist already:\n", " try:\n", " if s not in df['description'].values.tolist():\n", " #add synonyms\n", "\n", " #SYNONYM MAY BE AN OBSOLETE METHOD TO AVOID CONTEXT IDENTIFICATION\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(prompt, model='gpt-3', service='azure').replace('\\n', '')\n", " list1.append(answer)\n", " list1.append(s)\n", " else:\n", " #if duplicate is found\n", " pass\n", " except:\n", " #in case no df is loaded, ignore it\n", " list1.append(s)\n", "\n", " return list1\n", "\n", "def add_context_list(context_list):\n", " list1 = list()\n", " for s in context_list:\n", " try:\n", " if s not in df['description'].values.tolist():\n", " list1.append(s)\n", " except:\n", " #in case no df is loaded, ignore it\n", " list1.append(s)\n", " return list1\n", "\n", "context_dict = {\n", " \"company; goliath; we\" :\n", " \"\"\"\n", " This is what we do: 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. You can contact our company at ma@goliath.jp . There are 5 people working for our company.\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. It takes from a few weeks to one month to build a 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", "#adding invidivual sentences\n", "context_list_ = [\n", " # 'We can also use GPT3, if requested',\n", " 'You can contact us at ma@goliath.jp',\n", " # 'We operate in the AI sector'\n", "]\n", "#adding qa\n", "qa_list = {\n", " 'How much does it cost?' : 'The price depends by its intended usage and complexity, contact us for a quotation.',\n", " 'Do you use GPT3 API?' : 'yes, we can',\n", " 'Do you use GPT3?' : 'yes, we can',\n", " 'Do you use GPT4?' : 'yes, we can',\n", " 'What do you do?' : 'Our company builds AI recommendation systems',\n", " 'What does goliath do?' : 'Our company builds AI recommendation systems',\n", " 'What does your company do?' : 'Our company builds AI recommendation systems',\n", " 'How much does Goliath charge?' : 'The price depends by its intended usage and complexity, contact us for a quotation.',\n", " 'How much does Goliath charge for a recommendation system?' : 'The price depends by its intended usage and complexity, contact us for a quotation.',\n", " 'How much does Goliath charge for a chatbot?' : 'The price depends by its intended usage and complexity, contact us for a quotation.'\n", " 'What is your charge?' : 'The price depends by its intended usage and complexity, contact us for a quotation.'\n", "}\n", "\n", "#\n", "# df = pd.DataFrame(columns=['description'])\n", "df = pd.read_parquet('df.parquet') #if we comment it, it start from scratch\n", "df_qa = pd.read_parquet('df_qa.parquet')\n", "\n", "#prepare context\n", "missing_context = context_dict2context_list(context_dict)\n", "missing_context += add_context_list(context_list_)\n", "missing_context" ] }, { "cell_type": "code", "execution_count": 325, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{}" ] }, "execution_count": 325, "metadata": {}, "output_type": "execute_result" } ], "source": [ "missing_qa = dict()\n", "for question in qa_list:\n", " answer = qa_list[question]\n", " if question not in df_qa['question'].values.tolist():\n", " print(question)\n", " missing_qa[question] = answer\n", "missing_qa" ] }, { "cell_type": "code", "execution_count": 267, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'What does the company do?'" ] }, "execution_count": 267, "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", " #apply a coreference resolution on the query and replace the pronoun with no temperature, no adjectives\n", " prompt = f\"\"\"\n", " context : {last_context} \n", " query : {query}\n", " instructions:\n", " only if pronoun is unclear, replace query pronoun with its context reference. Return the edited query.\n", " \"\"\" \n", " answer = gpt3(prompt, model='gpt-3.5-turbo', service='azure')\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('we are a company. Recommendation systems are expensive.', 'what do you do?')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### edit final df" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "#drop\n", "df = pd.read_parquet('df.parquet')\n", "df = df.drop([9, 10, 11]).reset_index(drop=True)\n", "df.to_parquet('df.parquet')" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "#create df with vectors\n", "# df_new = pd.DataFrame([context_list, list2vec(context_list)]).T #batch embeddings not available with azure\n", "df_new = pd.DataFrame(context_list)\n", "df_new[1] = df_new[0].apply(lambda x : text2vec(x, 'azure'))\n", "\n", "df_new.columns = ['description', 'text_vector_']\n", "df_new['description'] = df_new['description'].apply(lambda x : x.strip())\n", "\n", "df_new = pd.concat([df, df_new], axis=0).reset_index(drop=True)\n", "df_new.to_parquet('df.parquet')" ] }, { "cell_type": "code", "execution_count": 346, "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", " \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.028263725, -0.0101905335, 0.008142526, -0.0...
1Do you use GPT3 API?yes, we can[0.008896397, -0.0057652825, 0.00010452615, -0...
2Do you use GPT3?yes, we can[0.007887953, -0.0010633436, 6.204963e-05, -0....
3Do you use GPT4?yes, we can[0.008745, -0.00041013403, -0.001318879, -0.04...
4What do you do?Our company builds AI recommendation systems[-0.00083139725, -0.017905554, 0.0027184868, -...
5What does goliath do?Our company builds AI recommendation systems[-0.02096649, -0.01710899, -0.00011881243, 0.0...
6What does your company do?Our company builds AI recommendation systems[0.0068105333, -0.010677755, -0.00048340266, -...
7How much does Goliath charge?The price depends by its intended usage and co...[0.0018087317, -0.013888897, -0.00455645, -0.0...
8How much does Goliath charge for a recommendat...The price depends by its intended usage and co...[0.0006508778, -0.0021186466, -0.022374032, -0...
9How much does Goliath charge for a chatbot?The price depends by its intended usage and co...[-0.009120062, -0.012517998, -0.0015486096, -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", "7 How much does Goliath charge? \n", "8 How much does Goliath charge for a recommendat... \n", "9 How much does Goliath charge for a chatbot? \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 recommendation systems \n", "5 Our company builds AI recommendation systems \n", "6 Our company builds AI recommendation systems \n", "7 The price depends by its intended usage and co... \n", "8 The price depends by its intended usage and co... \n", "9 The price depends by its intended usage and co... \n", "\n", " text_vector_ \n", "0 [0.028263725, -0.0101905335, 0.008142526, -0.0... \n", "1 [0.008896397, -0.0057652825, 0.00010452615, -0... \n", "2 [0.007887953, -0.0010633436, 6.204963e-05, -0.... \n", "3 [0.008745, -0.00041013403, -0.001318879, -0.04... \n", "4 [-0.00083139725, -0.017905554, 0.0027184868, -... \n", "5 [-0.02096649, -0.01710899, -0.00011881243, 0.0... \n", "6 [0.0068105333, -0.010677755, -0.00048340266, -... \n", "7 [0.0018087317, -0.013888897, -0.00455645, -0.0... \n", "8 [0.0006508778, -0.0021186466, -0.022374032, -0... \n", "9 [-0.009120062, -0.012517998, -0.0015486096, -0... " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "df_qa = pd.DataFrame([qa_list]).T.reset_index()\n", "df_qa.columns = [0, 1]\n", "df_qa['text_vector_'] = df_qa[0].apply(lambda x : text2vec(x, 'azure'))\n", "df_qa.columns = ['question', 'answer', 'text_vector_']\n", "display(df_qa)\n", "df_qa.to_parquet('df_qa.parquet')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### qa function" ] }, { "cell_type": "code", "execution_count": 348, "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", "import pandas as pd\n", "from sentence_transformers import SentenceTransformer, util\n", "\n", "#reference filter\n", "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 = gpt3(prompt, model='gpt-3.5-turbo', service='azure')\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?\")\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, 'azure')\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", " if verbose : display(df_qa_[0:5])\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", " 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", " if verbose : display(df_[0:5])\n", " df_ = df_[df_['score']>=min_context_score]\n", " #if we find at least one possible preset answer\n", " if len(df_) > 0:\n", " #in case we might decide to merge multiple context\n", " context = ' '.join(df_['description'][0:1].values.tolist())\n", " prompt = f\"\"\"\n", " context: {context}\n", " query: {query}\n", " Answer the query using context. Do not justify the answer.\n", " \"\"\"\n", " answer = gpt3(prompt, model='gpt-3.5-turbo', service='azure')\n", " return answer\n", " else:\n", " return 'impossible to give an answer'\n", "\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='how much does a recommendation system cost?'\n", "# )\n", "# bot_answer" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### testing" ] }, { "cell_type": "code", "execution_count": 294, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['what does your company do?',\n", " 'how much does your company charge for a recommendation system?',\n", " 'how much does your company charge?',\n", " 'What does Goliath do?',\n", " 'How much does Goliath charge for a recommendation system?',\n", " 'How much does Goliath charge?',\n", " 'What do you do?',\n", " 'How much do you charge for a recommendation system?',\n", " 'What is your charge?',\n", " 'how much does a recommendation system cost?',\n", " 'what is the pricing structure?']" ] }, "execution_count": 294, "metadata": {}, "output_type": "execute_result" } ], "source": [ "testing_questions = {\n", " 'company; goliath; you' : #subject is the company\n", " [\n", " 'what does your company do?',\n", " 'how much does your company charge for a recommendation system?',\n", " 'how much does your company charge?'\n", " \n", " ],\n", " \"recommendation system\" : \n", " [\n", " 'how much does a recommendation system cost?'\n", " ],\n", " \"price\" : \n", " [\n", " \"what is the pricing structure?\"\n", " ]\n", "}\n", "\n", "list1 = list()\n", "for key in testing_questions:\n", " list2 = testing_questions[key]\n", " #we add the original questions\n", " if ';' in key:\n", " list1 += list2\n", " mainkey = key.split(';')[0]\n", " for subkey in key.split(';')[1:]:\n", " for question in list2:\n", " # print(mainkey, subkey.strip())\n", " prompt = f\"\"\"\n", " question: {question}\n", " instructions: replace {mainkey} with {subkey}. Correct the grammar.\n", " \"\"\"\n", " new_text = '_'\n", " new_text = gpt3(prompt, 'gpt-3.5-turbo', 'azure', max_tokens=400)\n", " new_text = new_text.replace('\\n', '')\n", " new_text = new_text.replace('\"', '')\n", " list1.append(new_text)\n", " else:\n", " list1 += list2\n", "list1" ] }, { "cell_type": "code", "execution_count": 341, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "what does your company do? -> Our company builds AI recommendaion systems\n", "how much does your company charge for a recommendation system? -> The price depends by its intended usage and complexity, contact us for a quotation.\n", "how much does your company charge? -> 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.\n", "What does Goliath do? -> Our company builds AI recommendaion systems\n", "How much does Goliath charge for a recommendation system? -> The price depends by its intended usage and complexity, contact us for a quotation.\n", "How much does Goliath charge? -> The price depends by its intended usage and complexity, contact us for a quotation.\n", "What do you do? -> Our company builds AI recommendaion systems\n", "How much do you charge for a recommendation system? -> The price depends by its intended usage and complexity, contact us for a quotation.\n", "What is your charge? -> The context provided is unrelated to the query.\n", "how much does a recommendation system cost? -> The price depends by its intended usage and complexity, contact us for a quotation.\n", "what is the pricing structure? -> The pricing of a recommendation system depends on the complexity of the required build and the volume of customers. Contact the company to receive a quotation.\n" ] } ], "source": [ "for question in list1:\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=question\n", " )\n", " print(question, '->', bot_answer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "qa(\n", " df_, \n", " df_qa_, \n", " min_qa_score=0.92, \n", " min_context_score=.75, \n", " verbose=False, \n", " query='How much for a recommender system?'\n", " )" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### gradio" ] }, { "cell_type": "code", "execution_count": 349, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7878\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": 349, "metadata": {}, "output_type": "execute_result" } ], "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", " 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)" ] } ], "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 }