import requests os.system('pip install openpyxl') os.system('pip install sentence-transformers') def gpt3_question(prompt): api_key = "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" api_endpoint = "https://api.openai.com/v1/engines/text-davinci-003/completions" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } data = { "prompt": prompt, "max_tokens": 400, "temperature": 0.5 } print('sending request') response = requests.post(api_endpoint, headers=headers, json=data) print(response) generated_text = response.json()["choices"][0]["text"] return generated_text def chatgpt3_question(context, question): api_key = "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" url = "https://api.openai.com/v1/chat/completions" prompt = f""" based on this context: {context} answer this use question: {question} """ headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } data = { "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": prompt}] } response = requests.post(url, headers=headers, json=data) generated_text = response.json()['choices'][0]['message']['content'] return generated_text import os import requests import pandas as pd def split_paragraph(text, keyword): list1 = [x.strip() for x in text.split('.')] list2 = [] for sentence in list1: # Check if the sentence contains the phrase "chamber of commerce" if keyword in sentence.lower(): list2.append(1) else: list2.append(0) #in case first sentence has no keyword, we add it if list2[0] == 0: list1[0] = f'the {keyword}: ' + list1[0] list2[0] = 1 # print(list1) # print(list2) list3 = list() current_string = '' # Loop through each element of list1 and list2 for i in range(len(list1)): # If the corresponding element in list2 is 1, add the current string to list3 and reset the current string if list2[i] == 1: list3.append(current_string) current_string = "" #reset current_string += list1[i] # Otherwise, concatenate the current string with the current element of list1 if list2[i] == 0: current_string += '. '+list1[i] # Add the final concatenated string to list3 list3.append(current_string) return [x.strip() for x in list3[1:]] def context_dict2context_list(context_dict): list1 = list() for all_keys in context_dict: key = all_keys.split(';')[0] try: synonyms = all_keys.split(';')[1:] except: pass # print(key) str1 = context_dict[all_keys] split_list = [x.replace('\n', '').strip() for x in str1.split('\n\n')] split_list for sentence in split_list: for s in split_paragraph(sentence, key): #add synonyms for synonym in synonyms: #manual replacement causes a wrong grammar #gpt3 replacement print(s, key, synonym) prompt = f'in the following sentence: {s}. Replace {key} with {synonym} correcting the grammar' answer = gpt3_question(prompt).replace('\n', '') list1.append(answer) list1.append(s) return list1 def list2vec(list1): headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "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", } json_data = { 'input': list1, 'model': 'text-embedding-ada-002', } response = requests.post('https://api.openai.com/v1/embeddings', headers=headers, json=json_data) return [x['embedding'] for x in response.json()['data']] dict1 = dict() for index in range(len(json_data['input'])): dict1[json_data['input'][index]] = response.json()['data'][index]['embedding'] return dict1 def text2vec(query): headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "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", } json_data = { 'input': query, 'model': 'text-embedding-ada-002', } response = requests.post('https://api.openai.com/v1/embeddings', headers=headers, json=json_data) query = response.json()['data'][0]['embedding'] #len=1536 #pricing=0.0004 return query context_dict = { "company; goliath; we" : """ 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. """ , "price" : """ 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. """ , "recommendation system" : """ 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. """ , "a matching platform" : """ 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. """ } import pandas as pd from sentence_transformers import SentenceTransformer, util #prepare context context_list = context_dict2context_list(context_dict) #adding invidivual sentences context_list += [ 'We can also use GPT3, if requested', 'Our email is ma@goliath.jp', 'You can contact us at ma@goliath.jp' ] #create df df = pd.DataFrame([context_list, list2vec(context_list)]).T df.columns = ['description', 'text_vector_'] df['description'] = df['description'].apply(lambda x : x.strip()) df qa_list = { 'how long does it take to build a recommendation system?' : 'Usually, from a few weeks to one month', 'how long does it take to build one' : 'Usually, from a few weeks to one month', 'how many people are working for goliath?' : '5 people', 'how many people are working for you?' : '5 people', 'how much does it cost?' : 'The price depends by its intended usage and complexity, contact us for a quotation.', 'do you use GPT3 API?' : 'yes, we can', 'do you use GPT3?' : 'yes, we can', 'do you use GPT4?' : 'yes, we can', 'so you build chatbots' : 'yes, we built state-of-the art chatbots with GPT3 technology' } df_qa = pd.DataFrame([qa_list]).T.reset_index() df_qa.columns = ['question', 'answer'] df_qa['text_vector_'] = list2vec(df_qa['question'].values.tolist()) df_qa df_qa_ = df_qa.copy() df_ = df.copy() def qa(df_, df_qa_, min_qa_score, min_context_score, verbose, query): query_vec = text2vec(query) #first check if there is already a question in df_qa df_qa_['score'] = df_qa_['text_vector_'].apply(lambda x : float(util.cos_sim(x, query_vec))) df_qa_ = df_qa_.sort_values('score', ascending=False) df_qa_ = df_qa_[df_qa_['score']>=min_qa_score] #if we find at least one possible preset answer if len(df_qa_) > 0: if verbose : display(df_qa_) answer = df_qa_[0:1]['answer'].values.tolist()[0] return answer #then check if we can use the context to answer a question df_['score'] = df_['text_vector_'].apply(lambda x : float(util.cos_sim(x, query_vec))) df_ = df_.sort_values('score', ascending=False) df_ = df_[df_['score']>=min_context_score] #if we find at least one possible preset answer if len(df_) > 0: if verbose : display(df_) #in case we might decide to merge multiple context context = ' '.join(df_['description'][0:1].values.tolist()) answer = chatgpt3_question(context, query) return answer else: return 'impossible to give an answer' # print( # qa( # df_, # df_qa_, # min_qa_score=0.92, # min_context_score=.75, # verbose=False, # query='What is a recommender system?' # ) # ) import subprocess import random import gradio as gr import requests history = None history_prompt = None def predict(input, history): #WE CAN PLAY WITH user_input AND bot_answer, as well as history user_input = input global history_prompt global block_predict bot_answer = qa( df_, df_qa_, min_qa_score=0.92, min_context_score=.75, verbose=False, query=input ) response = list() response = [(input, bot_answer)] history.append(response[0]) response = history # print('#history', history) # print('#response', response) return response, history demo = gr.Blocks() with demo: gr.Markdown( """ Chatbot """ ) state = gr.Variable(value=[]) #beginning chatbot = gr.Chatbot() #color_map=("#00ff7f", "#00d5ff") text = gr.Textbox( label="Question", value="What is a recommendation system?", placeholder="", max_lines=1, ) text.submit(predict, [text, state], [chatbot, state]) text.submit(lambda x: "", text, text) # btn = gr.Button(value="submit") # btn.click(chatbot_foo, None, [chatbot, state]) demo.launch(share=False)