{ "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", " | question | \n", "answer | \n", "text_vector_ | \n", "
---|---|---|---|
0 | \n", "How much does it cost? | \n", "The price depends by its intended usage and co... | \n", "[0.028263725, -0.0101905335, 0.008142526, -0.0... | \n", "
1 | \n", "Do you use GPT3 API? | \n", "yes, we can | \n", "[0.008896397, -0.0057652825, 0.00010452615, -0... | \n", "
2 | \n", "Do you use GPT3? | \n", "yes, we can | \n", "[0.007887953, -0.0010633436, 6.204963e-05, -0.... | \n", "
3 | \n", "Do you use GPT4? | \n", "yes, we can | \n", "[0.008745, -0.00041013403, -0.001318879, -0.04... | \n", "
4 | \n", "What do you do? | \n", "Our company builds AI recommendation systems | \n", "[-0.00083139725, -0.017905554, 0.0027184868, -... | \n", "
5 | \n", "What does goliath do? | \n", "Our company builds AI recommendation systems | \n", "[-0.02096649, -0.01710899, -0.00011881243, 0.0... | \n", "
6 | \n", "What does your company do? | \n", "Our company builds AI recommendation systems | \n", "[0.0068105333, -0.010677755, -0.00048340266, -... | \n", "
7 | \n", "How much does Goliath charge? | \n", "The price depends by its intended usage and co... | \n", "[0.0018087317, -0.013888897, -0.00455645, -0.0... | \n", "
8 | \n", "How much does Goliath charge for a recommendat... | \n", "The price depends by its intended usage and co... | \n", "[0.0006508778, -0.0021186466, -0.022374032, -0... | \n", "
9 | \n", "How much does Goliath charge for a chatbot? | \n", "The price depends by its intended usage and co... | \n", "[-0.009120062, -0.012517998, -0.0015486096, -0... | \n", "