File size: 41,009 Bytes
8d12c87 a4ba306 08b8fbf a4ba306 08b8fbf a4ba306 08b8fbf a4ba306 99afee7 a4ba306 99afee7 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 788c658 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 8d12c87 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 8d12c87 a4ba306 9cc3953 a4ba306 8d12c87 a4ba306 8d12c87 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 9cc3953 a4ba306 8d12c87 a4ba306 |
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 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/towardsai/ai-tutor-rag-system/blob/main/notebooks/02-Basic_RAG.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4Tw3tvMs6R-Y"
},
"source": [
"# Install Packages and Setup Variables"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "HaB4G9zr0BYm",
"outputId": "2a76e676-6fae-44df-ae8c-e4869bfbbc2d"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m225.4/225.4 kB\u001b[0m \u001b[31m2.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m51.7/51.7 kB\u001b[0m \u001b[31m3.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.0/2.0 MB\u001b[0m \u001b[31m17.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.6/75.6 kB\u001b[0m \u001b[31m6.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.1/3.1 MB\u001b[0m \u001b[31m17.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m77.8/77.8 kB\u001b[0m \u001b[31m3.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 kB\u001b[0m \u001b[31m5.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25h"
]
}
],
"source": [
"!pip install -q openai==1.12.0 cohere==4.47 tiktoken==0.6.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MYvUA6CF2Le6"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Set the \"OPENAI_API_KEY\" in the Python environment. Will be used by OpenAI client later.\n",
"os.environ[\"OPENAI_API_KEY\"] = \"<YOUR_OPENAI_KEY>\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0ViVXXIqXBai"
},
"outputs": [],
"source": [
"# False: Generate the embedding for the dataset. (Associated cost with using OpenAI endpoint)\n",
"# True: Load the dataset that already has the embedding vectors.\n",
"load_embedding = False"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "D8Nzx-cN_bDz"
},
"source": [
"# Load Dataset"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5JpI7GiZ--Gw"
},
"source": [
"## Download Dataset (JSON)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NT68BDYt-GkG"
},
"source": [
"The dataset includes several articles from the TowardsAI blog, which provide an in-depth explanation of the LLaMA2 model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "p6NEJT9S2OoH",
"outputId": "fd3aa19c-a644-4635-9838-2c20526c4da2"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"--2024-03-20 16:18:39-- https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-llama-articles.csv\n",
"Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\n",
"Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 173646 (170K) [text/plain]\n",
"Saving to: ‘mini-llama-articles.csv’\n",
"\n",
"\rmini-llama-articles 0%[ ] 0 --.-KB/s \rmini-llama-articles 100%[===================>] 169.58K --.-KB/s in 0.02s \n",
"\n",
"2024-03-20 16:18:40 (6.91 MB/s) - ‘mini-llama-articles.csv’ saved [173646/173646]\n",
"\n",
"--2024-03-20 16:18:40-- https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-llama-articles-with_embeddings.csv\n",
"Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\n",
"Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 11868176 (11M) [text/plain]\n",
"Saving to: ‘mini-llama-articles-with_embeddings.csv’\n",
"\n",
"mini-llama-articles 100%[===================>] 11.32M --.-KB/s in 0.1s \n",
"\n",
"2024-03-20 16:18:40 (103 MB/s) - ‘mini-llama-articles-with_embeddings.csv’ saved [11868176/11868176]\n",
"\n"
]
}
],
"source": [
"!wget https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-llama-articles.csv\n",
"!wget https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-llama-articles-with_embeddings.csv"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oYDd03Qn_clh"
},
"source": [
"## Read File"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_bfhs5NMYr4N"
},
"outputs": [],
"source": [
"# Split the input text into chunks of specified size.\n",
"def split_into_chunks(text, chunk_size=1024):\n",
" chunks = []\n",
" for i in range(0, len(text), chunk_size):\n",
" chunks.append( text[i:i+chunk_size] )\n",
"\n",
" return chunks"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UcQ7Ge_XCuXa"
},
"outputs": [],
"source": [
"import csv\n",
"\n",
"chunks = []\n",
"\n",
"# Load the file as a CSV\n",
"with open(\"./mini-llama-articles.csv\", mode=\"r\", encoding=\"utf-8\") as file:\n",
" csv_reader = csv.reader(file)\n",
"\n",
" for idx, row in enumerate( csv_reader ):\n",
" if idx == 0: continue; # Skip header row\n",
" chunks.extend( split_into_chunks(row[1]) )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JKdFSOb0NXjx",
"outputId": "ce43c97f-2083-49b5-837d-62cc427fe848"
},
"outputs": [
{
"data": {
"text/plain": [
"Index(['chunk'], dtype='object')"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import pandas as pd\n",
"\n",
"# Convert the JSON list to a Pandas Dataframe\n",
"df = pd.DataFrame(chunks, columns=['chunk'])\n",
"\n",
"df.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "21pFDgNdW9rO"
},
"source": [
"# Generate Embedding"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AfS9w9eQAKyu"
},
"outputs": [],
"source": [
"from openai import OpenAI\n",
"\n",
"client = OpenAI()\n",
"\n",
"# Defining a function that converts a text to embedding vector using OpenAI's Ada model.\n",
"def get_embedding(text):\n",
" try:\n",
" # Remove newlines\n",
" text = text.replace(\"\\n\", \" \")\n",
" res = client.embeddings.create(input = [text], model=\"text-embedding-ada-002\")\n",
"\n",
" return res.data[0].embedding\n",
"\n",
" except:\n",
" return None"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 67,
"referenced_widgets": [
"46a91770024e4802acd3e64e9bc46f32",
"613898a418d64df3b18d35083f0bb36d",
"9f9427eb6a644166906bb321f13eaf48",
"a4a232c5b5e1493897e9acdd25b8efd4",
"b2e91819e1c94f28b7bbad66918cb797",
"010cbcb0f1364576b15f792f4d11f605",
"f51d5da0f39e4c1885357d3d4c9964d9",
"c4ceff5437e0470089c161e21488d2a7",
"6aafd52b0e3e4e0183b1666ad1e8a448",
"80137fc11d4b4e518d8c8957ca5461b1",
"c4236d507b354bff830620a8bde32191"
]
},
"id": "qC6aeFr3Rmi2",
"outputId": "7f54333f-fcb9-44ce-d4a0-94a9a8d822d5"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Generating embeddings...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "46a91770024e4802acd3e64e9bc46f32",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"0it [00:00, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from tqdm.notebook import tqdm\n",
"import numpy as np\n",
"\n",
"# Generate embedding\n",
"if not load_embedding:\n",
" print(\"Generating embeddings...\")\n",
" embeddings = []\n",
" for index, row in tqdm( df.iterrows() ):\n",
" # df.at[index, 'embedding'] = get_embedding( row['chunk'] )\n",
" embeddings.append( get_embedding( row['chunk'] ) )\n",
"\n",
" embeddings_values = pd.Series(embeddings)\n",
" df.insert(loc=1, column='embedding', value=embeddings_values)\n",
"\n",
"# Or, load the embedding from the file.\n",
"else:\n",
" print(\"Loaded the embedding file.\")\n",
" # Load the file as a CSV\n",
" df = pd.read_csv('mini-llama-articles-with_embeddings.csv')\n",
" # Convert embedding column to an array\n",
" df['embedding'] = df['embedding'].apply(lambda x: np.array(eval(x)), 0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jyX9M_n9o2ve"
},
"outputs": [],
"source": [
"# df.to_csv('mini-llama-articles-with_embeddings.csv')"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "E_qrXwImXrXJ"
},
"source": [
"# User Question"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "xGTa7cqCX97q",
"outputId": "6ae836e3-1a65-4447-b732-88758378e9dd"
},
"outputs": [
{
"data": {
"text/plain": [
"1536"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Define the user question, and convert it to embedding.\n",
"QUESTION = \"How many parameters LLaMA2 model has?\"\n",
"QUESTION_emb = get_embedding( QUESTION )\n",
"\n",
"len( QUESTION_emb )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BXNzNWrJYWhU"
},
"source": [
"# Test Cosine Similarity"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Vxaq-FgLIhIj"
},
"source": [
"Calculating the similarity of embedding representations can help us to find pieces of text that are close to each other. In the following sample you see how the Cosine Similarity metric can identify which sentence could be a possible answer for the given user question. Obviously, the unrelated answer will score lower."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LqDWcPd4b-ZI"
},
"outputs": [],
"source": [
"BAD_SOURCE_emb = get_embedding( \"The sky is blue.\" )\n",
"GOOD_SOURCE_emb = get_embedding( \"LLaMA2 model has a total of 2B parameters.\" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OI00eN86YZKB",
"outputId": "0d06c9ea-7de2-48a0-e6d8-3fc6e428914b"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"> Bad Response Score: [[0.69953438]]\n",
"> Good Response Score: [[0.93126147]]\n"
]
}
],
"source": [
"from sklearn.metrics.pairwise import cosine_similarity\n",
"\n",
"# A sample that how a good piece of text can achieve high similarity score compared\n",
"# to a completely unrelated text.\n",
"print(\"> Bad Response Score:\", cosine_similarity([QUESTION_emb], [BAD_SOURCE_emb]) )\n",
"print(\"> Good Response Score:\", cosine_similarity([QUESTION_emb], [GOOD_SOURCE_emb]) )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kdJlEtaaJC4I"
},
"source": [
"# Calculate Cosine Similarities"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "PNPN7OAXemmH",
"outputId": "54beed07-04de-4696-b513-f49a935d6820"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0.82047387 0.79858187 0.74135248 0.73226232 0.72406104 0.75608299\n",
" 0.76808965 0.77621683 0.80498431 0.71399955 0.69822549 0.67532971\n",
" 0.72473021 0.73449361 0.69998132 0.73749561 0.68490681 0.75076836\n",
" 0.72540663 0.70675593 0.76047822 0.73849418 0.78103858 0.75189435\n",
" 0.73619013 0.76962672 0.71289635 0.76996122 0.7827543 0.77959332\n",
" 0.82716952 0.77719335 0.80172766 0.76301732 0.78111546 0.75179235\n",
" 0.74741505 0.7576328 0.78998865 0.77283347 0.79180172 0.78170323\n",
" 0.80264132 0.79923073 0.76146584 0.75199024 0.8341403 0.74460259\n",
" 0.76259332 0.73693499 0.78469623 0.81698455 0.8254561 0.77921093\n",
" 0.75351863 0.79319721 0.73098248 0.71716001 0.73210099 0.74684248\n",
" 0.75760574 0.71070101 0.71507394 0.70847896 0.72395535 0.77801292\n",
" 0.75446732 0.75100258 0.7361131 0.78430831 0.74170516 0.71862961\n",
" 0.76792911 0.76471996 0.78551313 0.80846857 0.79231644 0.79505895\n",
" 0.76910825 0.78341548 0.74952152 0.7849115 0.80407507 0.82641741\n",
" 0.77074756 0.7356681 0.77452715 0.76224969 0.79906149 0.84520641\n",
" 0.82301383 0.8362749 0.81676624 0.8035085 0.80532594 0.81186134\n",
" 0.69082726 0.72587048 0.70070204 0.7155819 0.71758016 0.74945217\n",
" 0.72555195 0.7356198 0.73695714 0.75553407 0.77502366 0.71438692\n",
" 0.75846916 0.79831901 0.78600515 0.7601161 0.78696534 0.80404804\n",
" 0.85209549 0.77037783 0.76985195 0.75062239 0.69339426 0.7108229\n",
" 0.72051435 0.75137579 0.71168549 0.72276919 0.77669437 0.7726572\n",
" 0.74774188 0.73290677 0.70262553 0.72831247 0.7525444 0.7495277\n",
" 0.75188765 0.71491865 0.74460111 0.73599028 0.76314747 0.71318814\n",
" 0.70723754 0.73098562 0.72745902 0.76077793 0.72614335 0.72636887\n",
" 0.77770561 0.69882456 0.72396024 0.70349095 0.70541201 0.76424393\n",
" 0.72785191 0.74371405 0.67802651 0.7353597 0.69916559 0.70605271\n",
" 0.71477477 0.71021711 0.77423355 0.70897606 0.74946665 0.70971011\n",
" 0.72360056 0.72906996 0.76590153 0.74469991 0.73669136 0.71547661\n",
" 0.6958848 0.71459824 0.74863434 0.71430407 0.75165385 0.74221148]]\n"
]
}
],
"source": [
"# The similarity between the questions and each part of the essay.\n",
"cosine_similarities = cosine_similarity( [QUESTION_emb], df['embedding'].tolist() )\n",
"\n",
"print( cosine_similarities )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1-XI1_7mhlw4",
"outputId": "9598da10-ab61-45e9-e0bb-3e1d7046b657"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[114 89 91]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"number_of_chunks_to_retrieve = 3\n",
"\n",
"# Sort the scores\n",
"highest_index = np.argmax( cosine_similarities )\n",
"\n",
"# Pick the N highest scored chunks\n",
"indices = np.argsort(cosine_similarities[0])[::-1][:number_of_chunks_to_retrieve]\n",
"print( indices )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JPmhCb9kfB0w",
"outputId": "5089b207-a65a-4856-c065-56b3b9bbba72"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"> Chunk 1\n",
"by Meta that ventures into both the AI and academic spaces. The model aims to help researchers, scientists, and engineers advance their work in exploring AI applications. It will be released under a non-commercial license to prevent misuse, and access will be granted to academic researchers, individuals, and organizations affiliated with the government, civil society, academia, and industry research facilities on a selective case-by-case basis. The sharing of codes and weights allows other researchers to test new approaches in LLMs. The LLaMA models have a range of 7 billion to 65 billion parameters. LLaMA-65B can be compared to DeepMind's Chinchilla and Google's PaLM. Publicly available unlabeled data was used to train these models, and training smaller foundational models require less computing power and resources. LLaMA 65B and 33B have been trained on 1.4 trillion tokens in 20 different languages, and according to the Facebook Artificial Intelligence Research (FAIR) team, the model's performance varies ac\n",
"----\n",
"> Chunk 2\n",
"I. Llama 2: Revolutionizing Commercial Use Unlike its predecessor Llama 1, which was limited to research use, Llama 2 represents a major advancement as an open-source commercial model. Businesses can now integrate Llama 2 into products to create AI-powered applications. Availability on Azure and AWS facilitates fine-tuning and adoption. However, restrictions apply to prevent exploitation. Companies with over 700 million active daily users cannot use Llama 2. Additionally, its output cannot be used to improve other language models. II. Llama 2 Model Flavors Llama 2 is available in four different model sizes: 7 billion, 13 billion, 34 billion, and 70 billion parameters. While 7B, 13B, and 70B have already been released, the 34B model is still awaited. The pretrained variant, trained on a whopping 2 trillion tokens, boasts a context window of 4096 tokens, twice the size of its predecessor Llama 1. Meta also released a Llama 2 fine-tuned model for chat applications that was trained on over 1 million human annota\n",
"----\n",
"> Chunk 3\n",
"vely address a diverse range of questions. This limitation could hinder the model's practical applicability and user experience. Thus, achieving an optimum balance that allows the model to be both helpful and safe is of utmost importance. To strike the right balance between helpfulness and safety, Meta employed two reward models - one for helpfulness and another for safety - to optimize the model's responses. The 34B parameter model has reported higher safety violations than other variants, possibly contributing to the delay in its release. IV. Helpfulness Comparison: Llama 2 Outperforms Competitors Llama 2 emerges as a strong contender in the open-source language model arena, outperforming its competitors in most categories. The 70B parameter model outperforms all other open-source models, while the 7B and 34B models outshine Falcon in all categories and MPT in all categories except coding. Despite being smaller, Llam a2's performance rivals that of Chat GPT 3.5, a significantly larger closed-source model. \n",
"----\n"
]
}
],
"source": [
"# Look at the highest scored retrieved pieces of text\n",
"for idx, item in enumerate( df.chunk[indices] ):\n",
" print(f\"> Chunk {idx+1}\")\n",
" print(item)\n",
" print(\"----\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7uvQACqAkHg4"
},
"source": [
"# Augment the Prompt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "MXRdzta5kJ3V"
},
"outputs": [],
"source": [
"# Use the OpenAI API to answer the questions based on the retrieved pieces of text.\n",
"try:\n",
" # Formulating the system prompt and condition the model to answer only AI-related questions.\n",
" system_prompt = (\n",
" \"You are an assistant and expert in answering questions from a chunks of content. \"\n",
" \"Only answer AI-related question, else say that you cannot answer this question.\"\n",
" )\n",
"\n",
" # Create a user prompt with the user's question\n",
" prompt = (\n",
" \"Read the following informations that might contain the context you require to answer the question. You can use the informations starting from the <START_OF_CONTEXT> tag and end with the <END_OF_CONTEXT> tag. Here is the content:\\n\\n<START_OF_CONTEXT>\\n{}\\n<END_OF_CONTEXT>\\n\\n\"\n",
" \"Please provide an informative and accurate answer to the following question based on the avaiable context. Be concise and take your time. \\nQuestion: {}\\nAnswer:\"\n",
" )\n",
" # Add the retrieved pieces of text to the prompt.\n",
" prompt = prompt.format( \"\".join( df.chunk[indices] ), QUESTION )\n",
"\n",
" # Call the OpenAI API\n",
" response = client.chat.completions.create(\n",
" model='gpt-3.5-turbo',\n",
" temperature=0.0,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": system_prompt},\n",
" {\"role\": \"user\", \"content\": prompt}\n",
" ]\n",
" )\n",
"\n",
" # Return the AI's response\n",
" res = response.choices[0].message.content.strip()\n",
"\n",
"except Exception as e:\n",
" print( f\"An error occurred: {e}\" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "9tBvJ8oMucha",
"outputId": "418c0220-c2ee-43cf-a9bc-0ea755f7a04e"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The LLaMA2 model has four different sizes: 7 billion, 13 billion, 34 billion, and 70 billion parameters.\n"
]
}
],
"source": [
"print( res )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pW-BNCAC2JzE"
},
"source": [
"# Without Augmentation"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tr5zXEGIMwJu"
},
"source": [
"Test the OpenAI API to answer the same question without the addition of retrieved documents. Basically, the LLM will use its knowledge to answer the question."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RuyXjzZyuecE"
},
"outputs": [],
"source": [
"# Formulating the system prompt\n",
"system_prompt = (\n",
" \"You are an assistant and expert in answering questions.\"\n",
")\n",
"\n",
"# Combining the system prompt with the user's question\n",
"prompt = (\n",
" \"Be concise and take your time to answer the following question. \\nQuestion: {}\\nAnswer:\"\n",
")\n",
"prompt = prompt.format( QUESTION )\n",
"\n",
"# Call the OpenAI API\n",
"response = client.chat.completions.create(\n",
" model='gpt-3.5-turbo',\n",
" temperature=.9,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": system_prompt},\n",
" {\"role\": \"user\", \"content\": prompt}\n",
" ]\n",
")\n",
"\n",
"# Return the AI's response\n",
"res = response.choices[0].message.content.strip()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "YAy34tPTzGbh",
"outputId": "54041329-dd5f-4cdd-db38-f1440ae77181"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The LLaMA2 model has a total of [insert number] parameters.\n"
]
}
],
"source": [
"print( res )"
]
}
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyMiGemqWYAYHaqF1t8bElQ/",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"010cbcb0f1364576b15f792f4d11f605": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"46a91770024e4802acd3e64e9bc46f32": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HBoxModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_613898a418d64df3b18d35083f0bb36d",
"IPY_MODEL_9f9427eb6a644166906bb321f13eaf48",
"IPY_MODEL_a4a232c5b5e1493897e9acdd25b8efd4"
],
"layout": "IPY_MODEL_b2e91819e1c94f28b7bbad66918cb797"
}
},
"613898a418d64df3b18d35083f0bb36d": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HTMLModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_010cbcb0f1364576b15f792f4d11f605",
"placeholder": "",
"style": "IPY_MODEL_f51d5da0f39e4c1885357d3d4c9964d9",
"value": ""
}
},
"6aafd52b0e3e4e0183b1666ad1e8a448": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "ProgressStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"80137fc11d4b4e518d8c8957ca5461b1": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"9f9427eb6a644166906bb321f13eaf48": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "FloatProgressModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_c4ceff5437e0470089c161e21488d2a7",
"max": 1,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_6aafd52b0e3e4e0183b1666ad1e8a448",
"value": 1
}
},
"a4a232c5b5e1493897e9acdd25b8efd4": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "HTMLModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_80137fc11d4b4e518d8c8957ca5461b1",
"placeholder": "",
"style": "IPY_MODEL_c4236d507b354bff830620a8bde32191",
"value": " 174/? [00:31<00:00, 6.30it/s]"
}
},
"b2e91819e1c94f28b7bbad66918cb797": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"c4236d507b354bff830620a8bde32191": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "DescriptionStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"c4ceff5437e0470089c161e21488d2a7": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "1.2.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": "20px"
}
},
"f51d5da0f39e4c1885357d3d4c9964d9": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "1.5.0",
"model_name": "DescriptionStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
}
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
|