Spaces:
Runtime error
Runtime error
File size: 36,415 Bytes
cf38d1a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 |
{
"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": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>question</th>\n",
" <th>answer</th>\n",
" <th>text_vector_</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>How much does it cost?</td>\n",
" <td>The price depends by its intended usage and co...</td>\n",
" <td>[0.028263725, -0.0101905335, 0.008142526, -0.0...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>Do you use GPT3 API?</td>\n",
" <td>yes, we can</td>\n",
" <td>[0.008896397, -0.0057652825, 0.00010452615, -0...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>Do you use GPT3?</td>\n",
" <td>yes, we can</td>\n",
" <td>[0.007887953, -0.0010633436, 6.204963e-05, -0....</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>Do you use GPT4?</td>\n",
" <td>yes, we can</td>\n",
" <td>[0.008745, -0.00041013403, -0.001318879, -0.04...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>What do you do?</td>\n",
" <td>Our company builds AI recommendation systems</td>\n",
" <td>[-0.00083139725, -0.017905554, 0.0027184868, -...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>5</th>\n",
" <td>What does goliath do?</td>\n",
" <td>Our company builds AI recommendation systems</td>\n",
" <td>[-0.02096649, -0.01710899, -0.00011881243, 0.0...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>6</th>\n",
" <td>What does your company do?</td>\n",
" <td>Our company builds AI recommendation systems</td>\n",
" <td>[0.0068105333, -0.010677755, -0.00048340266, -...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7</th>\n",
" <td>How much does Goliath charge?</td>\n",
" <td>The price depends by its intended usage and co...</td>\n",
" <td>[0.0018087317, -0.013888897, -0.00455645, -0.0...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>8</th>\n",
" <td>How much does Goliath charge for a recommendat...</td>\n",
" <td>The price depends by its intended usage and co...</td>\n",
" <td>[0.0006508778, -0.0021186466, -0.022374032, -0...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9</th>\n",
" <td>How much does Goliath charge for a chatbot?</td>\n",
" <td>The price depends by its intended usage and co...</td>\n",
" <td>[-0.009120062, -0.012517998, -0.0015486096, -0...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"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": [
"<div><iframe src=\"http://127.0.0.1:7878/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"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
}
|