AlaFalaki commited on
Commit
4db7cb2
Β·
1 Parent(s): fcc14cf

Created using Colaboratory

Browse files
Files changed (1) hide show
  1. notebooks/02-Basic_RAG.ipynb +85 -102
notebooks/02-Basic_RAG.ipynb CHANGED
@@ -4,7 +4,7 @@
4
  "metadata": {
5
  "colab": {
6
  "provenance": [],
7
- "authorship_tag": "ABX9TyMeAGO/FbVAX7iPUxTHf1EO",
8
  "include_colab_link": true
9
  },
10
  "kernelspec": {
@@ -372,9 +372,18 @@
372
  "<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>"
373
  ]
374
  },
 
 
 
 
 
 
 
 
 
375
  {
376
  "cell_type": "code",
377
- "execution_count": 1,
378
  "metadata": {
379
  "colab": {
380
  "base_uri": "https://localhost:8080/"
@@ -409,12 +418,13 @@
409
  "source": [
410
  "import os\n",
411
  "\n",
412
- "os.environ[\"OPENAI_API_KEY\"] = \"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\""
 
413
  ],
414
  "metadata": {
415
  "id": "MYvUA6CF2Le6"
416
  },
417
- "execution_count": 49,
418
  "outputs": []
419
  },
420
  {
@@ -427,7 +437,7 @@
427
  "metadata": {
428
  "id": "0ViVXXIqXBai"
429
  },
430
- "execution_count": 50,
431
  "outputs": []
432
  },
433
  {
@@ -442,7 +452,7 @@
442
  {
443
  "cell_type": "markdown",
444
  "source": [
445
- "### Download Paul Graham Essay (JSON)"
446
  ],
447
  "metadata": {
448
  "id": "5JpI7GiZ--Gw"
@@ -461,7 +471,7 @@
461
  "id": "p6NEJT9S2OoH",
462
  "outputId": "47da0417-d8cb-4b2c-90a4-e6e0e08a8325"
463
  },
464
- "execution_count": 52,
465
  "outputs": [
466
  {
467
  "output_type": "stream",
@@ -496,7 +506,7 @@
496
  {
497
  "cell_type": "markdown",
498
  "source": [
499
- "### Read JSON"
500
  ],
501
  "metadata": {
502
  "id": "oYDd03Qn_clh"
@@ -507,18 +517,11 @@
507
  "source": [
508
  "import json\n",
509
  "\n",
 
510
  "with open('./mini-dataset.json', 'r') as file:\n",
511
- " data = json.load(file)"
512
- ],
513
- "metadata": {
514
- "id": "XjW10Cnz_DVZ"
515
- },
516
- "execution_count": 53,
517
- "outputs": []
518
- },
519
- {
520
- "cell_type": "code",
521
- "source": [
522
  "len( data['chunks'] )"
523
  ],
524
  "metadata": {
@@ -528,7 +531,7 @@
528
  "id": "UcQ7Ge_XCuXa",
529
  "outputId": "19f545a3-835b-43ec-8183-0ecf7f291d24"
530
  },
531
- "execution_count": 54,
532
  "outputs": [
533
  {
534
  "output_type": "execute_result",
@@ -547,17 +550,9 @@
547
  "source": [
548
  "import pandas as pd\n",
549
  "\n",
550
- "df = pd.DataFrame(data['chunks'])"
551
- ],
552
- "metadata": {
553
- "id": "YNk1hxGVDqTu"
554
- },
555
- "execution_count": 55,
556
- "outputs": []
557
- },
558
- {
559
- "cell_type": "code",
560
- "source": [
561
  "df.keys()"
562
  ],
563
  "metadata": {
@@ -567,7 +562,7 @@
567
  "id": "JKdFSOb0NXjx",
568
  "outputId": "a3196605-aade-4d69-e858-daf222e6c7ba"
569
  },
570
- "execution_count": 56,
571
  "outputs": [
572
  {
573
  "output_type": "execute_result",
@@ -584,7 +579,7 @@
584
  {
585
  "cell_type": "markdown",
586
  "source": [
587
- "### Apply Embedding"
588
  ],
589
  "metadata": {
590
  "id": "21pFDgNdW9rO"
@@ -597,6 +592,7 @@
597
  "\n",
598
  "client = OpenAI()\n",
599
  "\n",
 
600
  "def get_embedding(text):\n",
601
  " try:\n",
602
  " # Remove newlines\n",
@@ -611,7 +607,7 @@
611
  "metadata": {
612
  "id": "AfS9w9eQAKyu"
613
  },
614
- "execution_count": 57,
615
  "outputs": []
616
  },
617
  {
@@ -619,11 +615,13 @@
619
  "source": [
620
  "from tqdm.notebook import tqdm\n",
621
  "\n",
 
622
  "if not load_embedding:\n",
623
  " print(\"Generating embeddings...\")\n",
624
  " for index, row in tqdm( df.iterrows() ):\n",
625
  " row['embedding'] = get_embedding( row['text'] )\n",
626
  "\n",
 
627
  "else:\n",
628
  " print(\"Loaded the embedding file.\")\n",
629
  " with open('./mini-dataset_with_embedding.json', 'r') as file:\n",
@@ -651,7 +649,7 @@
651
  "id": "qC6aeFr3Rmi2",
652
  "outputId": "02208934-78fe-4a77-e375-aed39da6b678"
653
  },
654
- "execution_count": 59,
655
  "outputs": [
656
  {
657
  "output_type": "stream",
@@ -688,28 +686,10 @@
688
  {
689
  "cell_type": "code",
690
  "source": [
691
- "QUESTION = \"How many parameters LLaMA2 model has?\""
692
- ],
693
- "metadata": {
694
- "id": "mHt4bZjYRaiY"
695
- },
696
- "execution_count": 30,
697
- "outputs": []
698
- },
699
- {
700
- "cell_type": "code",
701
- "source": [
702
- "QUESTION_emb = get_embedding( QUESTION )"
703
- ],
704
- "metadata": {
705
- "id": "OMQG6DtaVKGl"
706
- },
707
- "execution_count": 33,
708
- "outputs": []
709
- },
710
- {
711
- "cell_type": "code",
712
- "source": [
713
  "len( QUESTION_emb )"
714
  ],
715
  "metadata": {
@@ -719,7 +699,7 @@
719
  "id": "xGTa7cqCX97q",
720
  "outputId": "6935f145-1858-4959-833e-db2da1d49342"
721
  },
722
- "execution_count": 34,
723
  "outputs": [
724
  {
725
  "output_type": "execute_result",
@@ -736,12 +716,21 @@
736
  {
737
  "cell_type": "markdown",
738
  "source": [
739
- "# Calculate Cosine Similarities"
740
  ],
741
  "metadata": {
742
  "id": "BXNzNWrJYWhU"
743
  }
744
  },
 
 
 
 
 
 
 
 
 
745
  {
746
  "cell_type": "code",
747
  "source": [
@@ -751,7 +740,7 @@
751
  "metadata": {
752
  "id": "LqDWcPd4b-ZI"
753
  },
754
- "execution_count": 35,
755
  "outputs": []
756
  },
757
  {
@@ -771,7 +760,7 @@
771
  "id": "OI00eN86YZKB",
772
  "outputId": "3c75fdaa-098e-467c-daa8-41e87dda0738"
773
  },
774
- "execution_count": 36,
775
  "outputs": [
776
  {
777
  "output_type": "stream",
@@ -784,20 +773,21 @@
784
  ]
785
  },
786
  {
787
- "cell_type": "code",
788
  "source": [
789
- "cosine_similarities = cosine_similarity( [QUESTION_emb], df['embedding'].tolist() )"
790
  ],
791
  "metadata": {
792
- "id": "iYzyEU6-bwSz"
793
- },
794
- "execution_count": 37,
795
- "outputs": []
796
  },
797
  {
798
  "cell_type": "code",
799
  "source": [
800
- "cosine_similarities"
 
 
 
801
  ],
802
  "metadata": {
803
  "colab": {
@@ -806,7 +796,7 @@
806
  "id": "PNPN7OAXemmH",
807
  "outputId": "5b76bf4f-bd0c-4023-9144-a9e251b843c9"
808
  },
809
- "execution_count": 38,
810
  "outputs": [
811
  {
812
  "output_type": "execute_result",
@@ -829,32 +819,14 @@
829
  "source": [
830
  "import numpy as np\n",
831
  "\n",
832
- "# Sort the scores\n",
833
- "highest_index = np.argmax( cosine_similarities )"
834
- ],
835
- "metadata": {
836
- "id": "g0cBfePFaayw"
837
- },
838
- "execution_count": 39,
839
- "outputs": []
840
- },
841
- {
842
- "cell_type": "code",
843
- "source": [
844
  "number_of_chunks_to_retrieve = 3\n",
845
  "\n",
846
- "indices = np.argsort(cosine_similarities[0])[::-1][:number_of_chunks_to_retrieve]"
847
- ],
848
- "metadata": {
849
- "id": "vBbHJ7uihfKO"
850
- },
851
- "execution_count": 40,
852
- "outputs": []
853
- },
854
- {
855
- "cell_type": "code",
856
- "source": [
857
- "indices"
858
  ],
859
  "metadata": {
860
  "colab": {
@@ -863,7 +835,7 @@
863
  "id": "1-XI1_7mhlw4",
864
  "outputId": "c91bd5bc-c547-4760-d821-9f13fd564392"
865
  },
866
- "execution_count": 41,
867
  "outputs": [
868
  {
869
  "output_type": "execute_result",
@@ -880,7 +852,7 @@
880
  {
881
  "cell_type": "code",
882
  "source": [
883
- "# Get the highest scored pieces of text\n",
884
  "for idx, item in enumerate( df.text[indices] ):\n",
885
  " print(f\"> Chunk {idx+1}\")\n",
886
  " print(item)\n",
@@ -893,7 +865,7 @@
893
  "id": "JPmhCb9kfB0w",
894
  "outputId": "ee0f9bc2-3353-4ae8-b292-2356169b0d68"
895
  },
896
- "execution_count": 42,
897
  "outputs": [
898
  {
899
  "output_type": "stream",
@@ -924,18 +896,20 @@
924
  {
925
  "cell_type": "code",
926
  "source": [
 
927
  "try:\n",
928
- " # Formulating the system prompt\n",
929
  " system_prompt = (\n",
930
  " \"You are an assistant and expert in answering questions from a chunks of content. \"\n",
931
  " \"Only answer AI-related question, else say that you cannot answer this question.\"\n",
932
  " )\n",
933
  "\n",
934
- " # Combining the system prompt with the user's question\n",
935
  " prompt = (\n",
936
  " \"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",
937
  " \"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",
938
  " )\n",
 
939
  " prompt = prompt.format( \"\".join( df.text[indices] ), QUESTION )\n",
940
  "\n",
941
  " # Call the OpenAI API\n",
@@ -957,7 +931,7 @@
957
  "metadata": {
958
  "id": "MXRdzta5kJ3V"
959
  },
960
- "execution_count": 43,
961
  "outputs": []
962
  },
963
  {
@@ -972,7 +946,7 @@
972
  "id": "9tBvJ8oMucha",
973
  "outputId": "f473068b-0edc-424f-bb11-f7cfea76dc81"
974
  },
975
- "execution_count": 44,
976
  "outputs": [
977
  {
978
  "output_type": "stream",
@@ -992,6 +966,15 @@
992
  "id": "pW-BNCAC2JzE"
993
  }
994
  },
 
 
 
 
 
 
 
 
 
995
  {
996
  "cell_type": "code",
997
  "source": [
@@ -1022,7 +1005,7 @@
1022
  "metadata": {
1023
  "id": "RuyXjzZyuecE"
1024
  },
1025
- "execution_count": 31,
1026
  "outputs": []
1027
  },
1028
  {
@@ -1037,7 +1020,7 @@
1037
  "id": "YAy34tPTzGbh",
1038
  "outputId": "54041329-dd5f-4cdd-db38-f1440ae77181"
1039
  },
1040
- "execution_count": 32,
1041
  "outputs": [
1042
  {
1043
  "output_type": "stream",
 
4
  "metadata": {
5
  "colab": {
6
  "provenance": [],
7
+ "authorship_tag": "ABX9TyP70PdVay2ty6up4u2jHr1P",
8
  "include_colab_link": true
9
  },
10
  "kernelspec": {
 
372
  "<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>"
373
  ]
374
  },
375
+ {
376
+ "cell_type": "markdown",
377
+ "source": [
378
+ "# Install Packages and Setup Variables"
379
+ ],
380
+ "metadata": {
381
+ "id": "4Tw3tvMs6R-Y"
382
+ }
383
+ },
384
  {
385
  "cell_type": "code",
386
+ "execution_count": null,
387
  "metadata": {
388
  "colab": {
389
  "base_uri": "https://localhost:8080/"
 
418
  "source": [
419
  "import os\n",
420
  "\n",
421
+ "# Set the \"OPENAI_API_KEY\" in the Python environment. Will be used by OpenAI client later.\n",
422
+ "os.environ[\"OPENAI_API_KEY\"] = \"<YOUR_OPENAI_KEY>\""
423
  ],
424
  "metadata": {
425
  "id": "MYvUA6CF2Le6"
426
  },
427
+ "execution_count": null,
428
  "outputs": []
429
  },
430
  {
 
437
  "metadata": {
438
  "id": "0ViVXXIqXBai"
439
  },
440
+ "execution_count": null,
441
  "outputs": []
442
  },
443
  {
 
452
  {
453
  "cell_type": "markdown",
454
  "source": [
455
+ "## Download Paul Graham Essay (JSON)"
456
  ],
457
  "metadata": {
458
  "id": "5JpI7GiZ--Gw"
 
471
  "id": "p6NEJT9S2OoH",
472
  "outputId": "47da0417-d8cb-4b2c-90a4-e6e0e08a8325"
473
  },
474
+ "execution_count": null,
475
  "outputs": [
476
  {
477
  "output_type": "stream",
 
506
  {
507
  "cell_type": "markdown",
508
  "source": [
509
+ "## Read File"
510
  ],
511
  "metadata": {
512
  "id": "oYDd03Qn_clh"
 
517
  "source": [
518
  "import json\n",
519
  "\n",
520
+ "# Load the file as a JSON\n",
521
  "with open('./mini-dataset.json', 'r') as file:\n",
522
+ " data = json.load(file)\n",
523
+ "\n",
524
+ "# The number of chunks in the essay dataset.\n",
 
 
 
 
 
 
 
 
525
  "len( data['chunks'] )"
526
  ],
527
  "metadata": {
 
531
  "id": "UcQ7Ge_XCuXa",
532
  "outputId": "19f545a3-835b-43ec-8183-0ecf7f291d24"
533
  },
534
+ "execution_count": null,
535
  "outputs": [
536
  {
537
  "output_type": "execute_result",
 
550
  "source": [
551
  "import pandas as pd\n",
552
  "\n",
553
+ "# Convert the JSON list to a Pandas Dataframe\n",
554
+ "df = pd.DataFrame(data['chunks'])\n",
555
+ "\n",
 
 
 
 
 
 
 
 
556
  "df.keys()"
557
  ],
558
  "metadata": {
 
562
  "id": "JKdFSOb0NXjx",
563
  "outputId": "a3196605-aade-4d69-e858-daf222e6c7ba"
564
  },
565
+ "execution_count": null,
566
  "outputs": [
567
  {
568
  "output_type": "execute_result",
 
579
  {
580
  "cell_type": "markdown",
581
  "source": [
582
+ "# Generate Embedding"
583
  ],
584
  "metadata": {
585
  "id": "21pFDgNdW9rO"
 
592
  "\n",
593
  "client = OpenAI()\n",
594
  "\n",
595
+ "# Defining a function that converts a text to embedding vector using OpenAI's Ada model.\n",
596
  "def get_embedding(text):\n",
597
  " try:\n",
598
  " # Remove newlines\n",
 
607
  "metadata": {
608
  "id": "AfS9w9eQAKyu"
609
  },
610
+ "execution_count": null,
611
  "outputs": []
612
  },
613
  {
 
615
  "source": [
616
  "from tqdm.notebook import tqdm\n",
617
  "\n",
618
+ "# Generate embedding\n",
619
  "if not load_embedding:\n",
620
  " print(\"Generating embeddings...\")\n",
621
  " for index, row in tqdm( df.iterrows() ):\n",
622
  " row['embedding'] = get_embedding( row['text'] )\n",
623
  "\n",
624
+ "# Or, load the embedding from the file.\n",
625
  "else:\n",
626
  " print(\"Loaded the embedding file.\")\n",
627
  " with open('./mini-dataset_with_embedding.json', 'r') as file:\n",
 
649
  "id": "qC6aeFr3Rmi2",
650
  "outputId": "02208934-78fe-4a77-e375-aed39da6b678"
651
  },
652
+ "execution_count": null,
653
  "outputs": [
654
  {
655
  "output_type": "stream",
 
686
  {
687
  "cell_type": "code",
688
  "source": [
689
+ "# Define the user question, and convert it to embedding.\n",
690
+ "QUESTION = \"How many parameters LLaMA2 model has?\"\n",
691
+ "QUESTION_emb = get_embedding( QUESTION )\n",
692
+ "\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
693
  "len( QUESTION_emb )"
694
  ],
695
  "metadata": {
 
699
  "id": "xGTa7cqCX97q",
700
  "outputId": "6935f145-1858-4959-833e-db2da1d49342"
701
  },
702
+ "execution_count": null,
703
  "outputs": [
704
  {
705
  "output_type": "execute_result",
 
716
  {
717
  "cell_type": "markdown",
718
  "source": [
719
+ "# Test Cosine Similarity"
720
  ],
721
  "metadata": {
722
  "id": "BXNzNWrJYWhU"
723
  }
724
  },
725
+ {
726
+ "cell_type": "markdown",
727
+ "source": [
728
+ "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."
729
+ ],
730
+ "metadata": {
731
+ "id": "Vxaq-FgLIhIj"
732
+ }
733
+ },
734
  {
735
  "cell_type": "code",
736
  "source": [
 
740
  "metadata": {
741
  "id": "LqDWcPd4b-ZI"
742
  },
743
+ "execution_count": null,
744
  "outputs": []
745
  },
746
  {
 
760
  "id": "OI00eN86YZKB",
761
  "outputId": "3c75fdaa-098e-467c-daa8-41e87dda0738"
762
  },
763
+ "execution_count": null,
764
  "outputs": [
765
  {
766
  "output_type": "stream",
 
773
  ]
774
  },
775
  {
776
+ "cell_type": "markdown",
777
  "source": [
778
+ "# Calculate Cosine Similarities"
779
  ],
780
  "metadata": {
781
+ "id": "kdJlEtaaJC4I"
782
+ }
 
 
783
  },
784
  {
785
  "cell_type": "code",
786
  "source": [
787
+ "# The similarity between the questions and each part of the essay.\n",
788
+ "cosine_similarities = cosine_similarity( [QUESTION_emb], df['embedding'].tolist() )\n",
789
+ "\n",
790
+ "print( cosine_similarities )"
791
  ],
792
  "metadata": {
793
  "colab": {
 
796
  "id": "PNPN7OAXemmH",
797
  "outputId": "5b76bf4f-bd0c-4023-9144-a9e251b843c9"
798
  },
799
+ "execution_count": null,
800
  "outputs": [
801
  {
802
  "output_type": "execute_result",
 
819
  "source": [
820
  "import numpy as np\n",
821
  "\n",
 
 
 
 
 
 
 
 
 
 
 
 
822
  "number_of_chunks_to_retrieve = 3\n",
823
  "\n",
824
+ "# Sort the scores\n",
825
+ "highest_index = np.argmax( cosine_similarities )\n",
826
+ "\n",
827
+ "# Pick the N highest scored chunks\n",
828
+ "indices = np.argsort(cosine_similarities[0])[::-1][:number_of_chunks_to_retrieve]\n",
829
+ "print( indices )"
 
 
 
 
 
 
830
  ],
831
  "metadata": {
832
  "colab": {
 
835
  "id": "1-XI1_7mhlw4",
836
  "outputId": "c91bd5bc-c547-4760-d821-9f13fd564392"
837
  },
838
+ "execution_count": null,
839
  "outputs": [
840
  {
841
  "output_type": "execute_result",
 
852
  {
853
  "cell_type": "code",
854
  "source": [
855
+ "# Look at the highest scored retrieved pieces of text\n",
856
  "for idx, item in enumerate( df.text[indices] ):\n",
857
  " print(f\"> Chunk {idx+1}\")\n",
858
  " print(item)\n",
 
865
  "id": "JPmhCb9kfB0w",
866
  "outputId": "ee0f9bc2-3353-4ae8-b292-2356169b0d68"
867
  },
868
+ "execution_count": null,
869
  "outputs": [
870
  {
871
  "output_type": "stream",
 
896
  {
897
  "cell_type": "code",
898
  "source": [
899
+ "# Use the OpenAI API to answer the questions based on the retrieved pieces of text.\n",
900
  "try:\n",
901
+ " # Formulating the system prompt and condition the model to answer only AI-related questions.\n",
902
  " system_prompt = (\n",
903
  " \"You are an assistant and expert in answering questions from a chunks of content. \"\n",
904
  " \"Only answer AI-related question, else say that you cannot answer this question.\"\n",
905
  " )\n",
906
  "\n",
907
+ " # Create a user prompt with the user's question\n",
908
  " prompt = (\n",
909
  " \"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",
910
  " \"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",
911
  " )\n",
912
+ " # Add the retrieved pieces of text to the prompt.\n",
913
  " prompt = prompt.format( \"\".join( df.text[indices] ), QUESTION )\n",
914
  "\n",
915
  " # Call the OpenAI API\n",
 
931
  "metadata": {
932
  "id": "MXRdzta5kJ3V"
933
  },
934
+ "execution_count": null,
935
  "outputs": []
936
  },
937
  {
 
946
  "id": "9tBvJ8oMucha",
947
  "outputId": "f473068b-0edc-424f-bb11-f7cfea76dc81"
948
  },
949
+ "execution_count": null,
950
  "outputs": [
951
  {
952
  "output_type": "stream",
 
966
  "id": "pW-BNCAC2JzE"
967
  }
968
  },
969
+ {
970
+ "cell_type": "markdown",
971
+ "source": [
972
+ "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."
973
+ ],
974
+ "metadata": {
975
+ "id": "tr5zXEGIMwJu"
976
+ }
977
+ },
978
  {
979
  "cell_type": "code",
980
  "source": [
 
1005
  "metadata": {
1006
  "id": "RuyXjzZyuecE"
1007
  },
1008
+ "execution_count": null,
1009
  "outputs": []
1010
  },
1011
  {
 
1020
  "id": "YAy34tPTzGbh",
1021
  "outputId": "54041329-dd5f-4cdd-db38-f1440ae77181"
1022
  },
1023
+ "execution_count": null,
1024
  "outputs": [
1025
  {
1026
  "output_type": "stream",