{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMXMMAHStqNGMvJEAKWLtU7",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"5a7a3fb5cad44cedb743b29ae3d7642b": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"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_d00352e335b344adb4066268059420b5",
"IPY_MODEL_ffb90a464cb64dae9d6a1d323dfe4724",
"IPY_MODEL_56816b5e94c94591b1da8d8f36f496b3"
],
"layout": "IPY_MODEL_7251b3615601497581d998607d620fa9"
}
},
"d00352e335b344adb4066268059420b5": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"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_ec2a733c559e47f89380d62dd7c606bf",
"placeholder": "",
"style": "IPY_MODEL_7970407a245e43558e098c521935f5ba",
"value": ""
}
},
"ffb90a464cb64dae9d6a1d323dfe4724": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"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_6d9a5776d24d459bb76ea2f665f5663a",
"max": 1,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_7134f2d58a9a493bb5de794d275729a5",
"value": 1
}
},
"56816b5e94c94591b1da8d8f36f496b3": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"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_8f30969794454a3aa775f5f1fdcbf720",
"placeholder": "",
"style": "IPY_MODEL_a98e772e74464e0391399aedf6a18e7d",
"value": " 22/? [00:03<00:00, 7.20it/s]"
}
},
"7251b3615601497581d998607d620fa9": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"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
}
},
"ec2a733c559e47f89380d62dd7c606bf": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"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
}
},
"7970407a245e43558e098c521935f5ba": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"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": ""
}
},
"6d9a5776d24d459bb76ea2f665f5663a": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"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"
}
},
"7134f2d58a9a493bb5de794d275729a5": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"model_module_version": "1.5.0",
"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": ""
}
},
"8f30969794454a3aa775f5f1fdcbf720": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"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
}
},
"a98e772e74464e0391399aedf6a18e7d": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"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": ""
}
}
}
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
""
]
},
{
"cell_type": "markdown",
"source": [
"# Install Packages and Setup Variables"
],
"metadata": {
"id": "4Tw3tvMs6R-Y"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "HaB4G9zr0BYm",
"outputId": "30ab3a13-8e8f-467b-e6c7-362d466a0dd7"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m225.4/225.4 kB\u001b[0m \u001b[31m2.8 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[31m2.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[31m7.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.9/75.9 kB\u001b[0m \u001b[31m3.8 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[31m11.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m76.9/76.9 kB\u001b[0m \u001b[31m4.1 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[31m4.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25h\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
"tensorflow-probability 0.22.0 requires typing-extensions<4.6.0, but you have typing-extensions 4.9.0 which is incompatible.\u001b[0m\u001b[31m\n",
"\u001b[0m"
]
}
],
"source": [
"!pip install -q openai==1.6.0 cohere==4.39 tiktoken==0.5.2"
]
},
{
"cell_type": "code",
"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\"] = \"\""
],
"metadata": {
"id": "MYvUA6CF2Le6"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"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"
],
"metadata": {
"id": "0ViVXXIqXBai"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Load Dataset"
],
"metadata": {
"id": "D8Nzx-cN_bDz"
}
},
{
"cell_type": "markdown",
"source": [
"## Download Dataset (JSON)"
],
"metadata": {
"id": "5JpI7GiZ--Gw"
}
},
{
"cell_type": "markdown",
"source": [
"The dataset includes several articles from the TowardsAI blog, which provide an in-depth explanation of the LLaMA2 model."
],
"metadata": {
"id": "NT68BDYt-GkG"
}
},
{
"cell_type": "code",
"source": [
"!wget https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-dataset.json\n",
"!wget https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-dataset_with_embedding.json"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "p6NEJT9S2OoH",
"outputId": "47da0417-d8cb-4b2c-90a4-e6e0e08a8325"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"--2023-12-25 17:03:22-- https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-dataset.json\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: 25361 (25K) [text/plain]\n",
"Saving to: ‘mini-dataset.json’\n",
"\n",
"\rmini-dataset.json 0%[ ] 0 --.-KB/s \rmini-dataset.json 100%[===================>] 24.77K --.-KB/s in 0.002s \n",
"\n",
"2023-12-25 17:03:22 (15.1 MB/s) - ‘mini-dataset.json’ saved [25361/25361]\n",
"\n",
"--2023-12-25 17:03:22-- https://raw.githubusercontent.com/AlaFalaki/tutorial_notebooks/main/data/mini-dataset_with_embedding.json\n",
"Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.108.133, ...\n",
"Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 476803 (466K) [text/plain]\n",
"Saving to: ‘mini-dataset_with_embedding.json’\n",
"\n",
"mini-dataset_with_e 100%[===================>] 465.63K --.-KB/s in 0.02s \n",
"\n",
"2023-12-25 17:03:22 (19.9 MB/s) - ‘mini-dataset_with_embedding.json’ saved [476803/476803]\n",
"\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## Read File"
],
"metadata": {
"id": "oYDd03Qn_clh"
}
},
{
"cell_type": "code",
"source": [
"import json\n",
"\n",
"# Load the file as a JSON\n",
"with open('./mini-dataset.json', 'r') as file:\n",
" data = json.load(file)\n",
"\n",
"# The number of chunks in the essay dataset.\n",
"len( data['chunks'] )"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "UcQ7Ge_XCuXa",
"outputId": "19f545a3-835b-43ec-8183-0ecf7f291d24"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"22"
]
},
"metadata": {},
"execution_count": 54
}
]
},
{
"cell_type": "code",
"source": [
"import pandas as pd\n",
"\n",
"# Convert the JSON list to a Pandas Dataframe\n",
"df = pd.DataFrame(data['chunks'])\n",
"\n",
"df.keys()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JKdFSOb0NXjx",
"outputId": "a3196605-aade-4d69-e858-daf222e6c7ba"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Index(['text', 'embedding'], dtype='object')"
]
},
"metadata": {},
"execution_count": 56
}
]
},
{
"cell_type": "markdown",
"source": [
"# Generate Embedding"
],
"metadata": {
"id": "21pFDgNdW9rO"
}
},
{
"cell_type": "code",
"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"
],
"metadata": {
"id": "AfS9w9eQAKyu"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"from tqdm.notebook import tqdm\n",
"\n",
"# Generate embedding\n",
"if not load_embedding:\n",
" print(\"Generating embeddings...\")\n",
" for index, row in tqdm( df.iterrows() ):\n",
" row['embedding'] = get_embedding( row['text'] )\n",
"\n",
"# Or, load the embedding from the file.\n",
"else:\n",
" print(\"Loaded the embedding file.\")\n",
" with open('./mini-dataset_with_embedding.json', 'r') as file:\n",
" data = json.load(file)\n",
" df = pd.DataFrame(data)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 67,
"referenced_widgets": [
"5a7a3fb5cad44cedb743b29ae3d7642b",
"d00352e335b344adb4066268059420b5",
"ffb90a464cb64dae9d6a1d323dfe4724",
"56816b5e94c94591b1da8d8f36f496b3",
"7251b3615601497581d998607d620fa9",
"ec2a733c559e47f89380d62dd7c606bf",
"7970407a245e43558e098c521935f5ba",
"6d9a5776d24d459bb76ea2f665f5663a",
"7134f2d58a9a493bb5de794d275729a5",
"8f30969794454a3aa775f5f1fdcbf720",
"a98e772e74464e0391399aedf6a18e7d"
]
},
"id": "qC6aeFr3Rmi2",
"outputId": "02208934-78fe-4a77-e375-aed39da6b678"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Generating embeddings...\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"0it [00:00, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "5a7a3fb5cad44cedb743b29ae3d7642b"
}
},
"metadata": {}
}
]
},
{
"cell_type": "markdown",
"source": [
"# User Question"
],
"metadata": {
"id": "E_qrXwImXrXJ"
}
},
{
"cell_type": "code",
"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 )"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "xGTa7cqCX97q",
"outputId": "6935f145-1858-4959-833e-db2da1d49342"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"1536"
]
},
"metadata": {},
"execution_count": 34
}
]
},
{
"cell_type": "markdown",
"source": [
"# Test Cosine Similarity"
],
"metadata": {
"id": "BXNzNWrJYWhU"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "Vxaq-FgLIhIj"
}
},
{
"cell_type": "code",
"source": [
"BAD_SOURCE_emb = get_embedding( \"The sky is blue.\" )\n",
"GOOD_SOURCE_emb = get_embedding( \"LLaMA2 model has a total of 2B parameters.\" )"
],
"metadata": {
"id": "LqDWcPd4b-ZI"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"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]) )"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OI00eN86YZKB",
"outputId": "3c75fdaa-098e-467c-daa8-41e87dda0738"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"> Bad Response Score: [[0.7004201]]\n",
"> Good Response Score: [[0.93136087]]\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"# Calculate Cosine Similarities"
],
"metadata": {
"id": "kdJlEtaaJC4I"
}
},
{
"cell_type": "code",
"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 )"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "PNPN7OAXemmH",
"outputId": "5b76bf4f-bd0c-4023-9144-a9e251b843c9"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"array([[0.81753292, 0.86636556, 0.80883772, 0.7666163 , 0.8402256 ,\n",
" 0.79094611, 0.78480301, 0.80216887, 0.82483956, 0.82015252,\n",
" 0.84227555, 0.75434941, 0.82424112, 0.7045468 , 0.65628107,\n",
" 0.73970803, 0.76241388, 0.76344021, 0.79891075, 0.73932054,\n",
" 0.78295066, 0.75655412]])"
]
},
"metadata": {},
"execution_count": 38
}
]
},
{
"cell_type": "code",
"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 )"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1-XI1_7mhlw4",
"outputId": "c91bd5bc-c547-4760-d821-9f13fd564392"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"array([ 1, 10, 4])"
]
},
"metadata": {},
"execution_count": 41
}
]
},
{
"cell_type": "code",
"source": [
"# Look at the highest scored retrieved pieces of text\n",
"for idx, item in enumerate( df.text[indices] ):\n",
" print(f\"> Chunk {idx+1}\")\n",
" print(item)\n",
" print(\"----\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JPmhCb9kfB0w",
"outputId": "ee0f9bc2-3353-4ae8-b292-2356169b0d68"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"> Chunk 1\n",
"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 annotations. Such extensive training comes at a cost, with the 70B model taking a staggering 1720320 GPU hours to train. The context window’s length determines the amount of content the model can process at once, making Llama 2 a powerful language model in terms of scale and efficiency.\n",
"----\n",
"> Chunk 2\n",
"New Llama-2 model: In mid-July, Meta released its new family of pre-trained and finetuned models called Llama-2, with an open source and commercial character to facilitate its use and expansion. The base model was released with a chat version and sizes 7B, 13B, and 70B. Together with the models, the corresponding papers were published describing their characteristics and relevant points of the learning process, which provide very interesting information on the subject. An updated version of Llama 1, trained on a new mix of publicly available data. The pretraining corpus size was increased by 40%, the model’s context length was doubled, and grouped-query attention was adopted. Variants with 7B, 13B, and 70B parameters are released, along with 34B variants reported in the paper but not released.[1]\n",
"----\n",
"> Chunk 3\n",
"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. Source: Meta Llama 2 paper. Despite being smaller, Llam a2’s performance rivals that of Chat GPT 3.5, a significantly larger closed-source model. While GPT 4 and PalM-2-L, with their larger size, outperform Llama 2, this is expected due to their capacity for handling complex language tasks. Llama 2’s impressive ability to compete with larger models highlights its efficiency and potential in the market. Source: Meta Llama 2 paper. However, Llama 2 does face challenges in coding and math problems, where models like Chat GPT 4 excel, given their significantly larger size. Chat GPT 4 performed significantly better than Llama 2 for coding (HumanEval benchmark)and math problem tasks (GSM8k benchmark). Open-source AI technologies, like Llama 2, continue to advance, offering strong competition to closed-source models.\n",
"----\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"# Augment the Prompt"
],
"metadata": {
"id": "7uvQACqAkHg4"
}
},
{
"cell_type": "code",
"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 tag and end with the tag. Here is the content:\\n\\n\\n{}\\n\\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.text[indices] ), QUESTION )\n",
"\n",
" # Call the OpenAI API\n",
" response = client.chat.completions.create(\n",
" model='gpt-3.5-turbo-16k',\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}\" )"
],
"metadata": {
"id": "MXRdzta5kJ3V"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print( res )"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "9tBvJ8oMucha",
"outputId": "f473068b-0edc-424f-bb11-f7cfea76dc81"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"The Llama 2 model has four different model sizes: 7 billion, 13 billion, 34 billion, and 70 billion parameters.\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"# Without Augmentation"
],
"metadata": {
"id": "pW-BNCAC2JzE"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "tr5zXEGIMwJu"
}
},
{
"cell_type": "code",
"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-16k',\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()"
],
"metadata": {
"id": "RuyXjzZyuecE"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print( res )"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "YAy34tPTzGbh",
"outputId": "54041329-dd5f-4cdd-db38-f1440ae77181"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"The LLaMA2 model has a total of [insert number] parameters.\n"
]
}
]
}
]
}