{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "metadata": { "id": "4Tw3tvMs6R-Y" }, "source": [ "# Install Packages and Setup Variables\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "HaB4G9zr0BYm", "outputId": "335ec94d-1982-4396-a8d0-34387d1abe1c", "collapsed": true }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/337.0 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m41.0/337.0 kB\u001b[0m \u001b[31m956.6 kB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m122.9/337.0 kB\u001b[0m \u001b[31m2.1 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m\u001b[90m━\u001b[0m \u001b[32m327.7/337.0 kB\u001b[0m \u001b[31m3.3 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m337.0/337.0 kB\u001b[0m \u001b[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m177.4/177.4 kB\u001b[0m \u001b[31m9.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.1/1.1 MB\u001b[0m \u001b[31m13.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m139.2/139.2 kB\u001b[0m \u001b[31m7.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[31m30.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m76.4/76.4 kB\u001b[0m \u001b[31m3.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m77.9/77.9 kB\u001b[0m \u001b[31m4.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m12.5/12.5 MB\u001b[0m \u001b[31m52.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m82.7/82.7 kB\u001b[0m \u001b[31m3.2 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[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25h" ] } ], "source": [ "!pip install -q openai==1.37.0 cohere==5.6.2 tiktoken==0.7.0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "MYvUA6CF2Le6" }, "outputs": [], "source": [ "import os\n", "from google.colab import userdata\n", "\n", "# Set the \"OPENAI_API_KEY\" in the Python environment. Will be used by OpenAI client later.\n", "os.environ[\"OPENAI_API_KEY\"] = userdata.get('openai_api_key')\n", "os.environ[\"GOOGLE_API_KEY\"] = userdata.get('Google_api_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\n" ] }, { "cell_type": "markdown", "metadata": { "id": "5JpI7GiZ--Gw" }, "source": [ "## Download Dataset (JSON)\n" ] }, { "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.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "p6NEJT9S2OoH", "outputId": "3fbc938a-cc52-4721-b5a9-683bc4cc8e80" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "--2024-09-07 09:46:21-- 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.03s \n", "\n", "2024-09-07 09:46:21 (4.95 MB/s) - ‘mini-llama-articles.csv’ saved [173646/173646]\n", "\n", "--2024-09-07 09:46:21-- 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: 6157740 (5.9M) [text/plain]\n", "Saving to: ‘mini-llama-articles-with_embeddings.csv’\n", "\n", "mini-llama-articles 100%[===================>] 5.87M --.-KB/s in 0.09s \n", "\n", "2024-09-07 09:46:21 (67.8 MB/s) - ‘mini-llama-articles-with_embeddings.csv’ saved [6157740/6157740]\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\n" ] }, { "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:\n", " continue\n", " # 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": "dad093a6-66a6-4493-84a3-2fb2eaa2bd7c" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "Index(['chunk'], dtype='object')" ] }, "metadata": {}, "execution_count": 8 } ], "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\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "AfS9w9eQAKyu" }, "outputs": [], "source": [ "from openai import OpenAI\n", "\n", "client = OpenAI()\n", "\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-3-small\")\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": 66, "referenced_widgets": [ "32a9876eaa924600b2d32c72c0bfc7b4", "1963b6ad45ff4b7697112b0c19b2cab5", "5fec0ec4e3c84208bd10a8afe6983596", "f35bfdba42db4f3a83aff86b607cd138", "73beec53e1ac41d986c6e8ec585f1c80", "5a62b428fb92498bb799849fe3a91775", "50240902b2a7405d8046f01c870a4533", "7651f8c1645c4df1a14fcd4efde2aeab", "d3227f1f0d0342bcac40686439fb2acf", "4fdeae40b54c45c0a27d90103b3fc422", "e650511151ac4e55a51f001367b48dc8" ] }, "id": "qC6aeFr3Rmi2", "outputId": "745bc089-5009-42fc-b60d-e9cacf77b0e2" }, "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": "32a9876eaa924600b2d32c72c0bfc7b4" } }, "metadata": {} } ], "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\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "xGTa7cqCX97q", "outputId": "1fcf2321-5fd6-42a5-92f5-1bf1db2e88ff" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "1536" ] }, "metadata": {}, "execution_count": 12 } ], "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\n" ] }, { "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.\n" ] }, { "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": "08524c6e-1400-420c-bd80-217e50982823" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "> Bad Response Score: [[0.0257948]]\n", "> Good Response Score: [[0.8319631]]\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\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PNPN7OAXemmH", "outputId": "6165e564-8e19-4a4a-c4d7-b064c489cb1b" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[[0.46773341 0.4691859 0.25978152 0.2938158 0.31967458 0.40164521\n", " 0.41504525 0.45272455 0.45929084 0.12604131 0.11753091 0.01344322\n", " 0.2260097 0.2142525 0.10143629 0.33072012 0.10745194 0.34694871\n", " 0.16313157 0.08741076 0.34824215 0.22843791 0.19205032 0.26476001\n", " 0.24955816 0.34893839 0.24834228 0.32762574 0.41444235 0.41335705\n", " 0.46364893 0.38345735 0.46855645 0.35642136 0.35398538 0.30147809\n", " 0.2994191 0.29257011 0.40031753 0.46468319 0.3947144 0.41046847\n", " 0.44707962 0.43177834 0.35912069 0.33981274 0.51355581 0.2092876\n", " 0.40203406 0.32830316 0.42850513 0.48267992 0.45033212 0.3425906\n", " 0.32084533 0.42600947 0.24604548 0.18087562 0.2366496 0.34272949\n", " 0.34381983 0.20473187 0.1976715 0.22442031 0.21108372 0.42298466\n", " 0.26383981 0.30427213 0.33608375 0.38302947 0.23529731 0.24347982\n", " 0.37074994 0.28020178 0.49052503 0.53047743 0.3782057 0.43774654\n", " 0.37767354 0.39259992 0.30086669 0.41712126 0.46747369 0.45419194\n", " 0.35156058 0.21228866 0.42623473 0.31603508 0.44058488 0.52727785\n", " 0.50599529 0.49751443 0.44284556 0.35114649 0.39483491 0.44134527\n", " 0.20328705 0.2791654 0.15405437 0.19228087 0.15912351 0.2410772\n", " 0.22523022 0.19943632 0.26240676 0.35060261 0.3621904 0.15316608\n", " 0.27645759 0.45343372 0.33425713 0.29444112 0.38160578 0.4172119\n", " 0.61953101 0.38690114 0.34437145 0.28275648 0.20158952 0.14611004\n", " 0.19514904 0.28226726 0.15624049 0.18058744 0.30279851 0.28139205\n", " 0.30261309 0.23775109 0.14549918 0.19745894 0.39240474 0.33000759\n", " 0.23545656 0.1570537 0.26887607 0.26478377 0.37819151 0.18126983\n", " 0.13047551 0.18455338 0.26054357 0.35592299 0.33277615 0.23504426\n", " 0.37103824 0.19002948 0.18963116 0.20083951 0.16392139 0.3500949\n", " 0.2524212 0.33872521 0.18281637 0.30645896 0.24204104 0.13083708\n", " 0.18218162 0.19086746 0.41316022 0.16360567 0.26365129 0.20633043\n", " 0.30182374 0.24800064 0.41007405 0.21778566 0.22249178 0.27770754\n", " 0.14573012 0.19763099 0.35371152 0.15400485 0.32276182 0.30300924]]\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": "6dc968f3-380f-48f7-83dc-9a9ba19d1ef3" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[114 75 89]\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": "bbd172df-9851-4dd4-9ec8-3da775a99a7a" }, "outputs": [ { "output_type": "stream", "name": "stdout", "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", "LLaMA: Meta's new AI tool According to the official release, LLaMA is a foundational language model developed to assist 'researchers and academics' in their work (as opposed to the average web user) to understand and study these NLP models. Leveraging AI in such a way could give researchers an edge in terms of time spent. You may not know this, but this would be Meta's third LLM after Blender Bot 3 and Galactica. However, the two LLMs were shut down soon, and Meta stopped their further development, as it produced erroneous results. Before moving further, it is important to emphasize that LLaMA is NOT a chatbot like ChatGPT. As I mentioned before, it is a 'research tool' for researchers. We can expect the initial versions of LLaMA to be a bit more technical and indirect to use as opposed to the case with ChatGPT, which was very direct, interactive, and a lot easy to use. \"Smaller, more performant models such as LLaMA enable ... research community who don't have access to large amounts of infrastructure to stud\n", "----\n", "> Chunk 3\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" ] } ], "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\n" ] }, { "cell_type": "code", "source": [ "import google.generativeai as genai\n", "# Use the Gemini 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.chunk[indices]), QUESTION)\n", "\n", " model = genai.GenerativeModel(model_name= \"gemini-1.5-flash\", system_instruction=system_prompt)\n", "\n", " result = model.generate_content(prompt,request_options={\"timeout\": 1000},)\n", " res = result.text\n", "\n", "except Exception as e:\n", " print(f\"An error occurred: {e}\")" ], "metadata": { "id": "sw1lb0dJ6vP7" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9tBvJ8oMucha", "outputId": "0706aef2-a8f8-4905-d5aa-001d2f8194e6" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "LLaMA 2 comes in four different model sizes: 7 billion, 13 billion, 34 billion, and 70 billion parameters. \n", "\n" ] } ], "source": [ "print(res)" ] }, { "cell_type": "markdown", "source": [ "## How Augmenting the Prompt can address knowledge cutoff limitations and hallucinations" ], "metadata": { "id": "Aamim8n6RZHO" } }, { "cell_type": "code", "source": [ "# Consider this as a retrieved chunk\n", "# https://ai.meta.com/blog/meta-llama-3-1/\n", "Example_chunk = \"\"\"\n", "Introducing Llama 3.1 Llama 3.1 405B is the first openly available model that rivals the top AI models when it comes to state-of-the-art capabilities in general knowledge, steerability, math, tool use, and multilingual translation. With the release of the 405B model, we’re poised to supercharge innovation—with unprecedented opportunities for growth and exploration. We believe the latest generation of Llama will ignite new applications and modeling paradigms, including synthetic data generation to enable the improvement and training of smaller models, as well as model distillation—a capability that has never been achieved at this scale in open source.\n", "As part of this latest release, we’re introducing upgraded versions of the 8B and 70B models. These are multilingual and have a significantly longer context length of 128K, state-of-the-art tool use, and overall stronger reasoning capabilities. This enables our latest models to support advanced use cases, such as long-form text summarization, multilingual conversational agents, and coding assistants. We’ve also made changes to our license, allowing developers to use the outputs from Llama models—including the 405B—to improve other models. True to our commitment to open source, starting today, we’re making these models available to the community for download on llama.meta.com and Hugging Face and available for immediate development on our broad ecosystem of partner platforms. Model evaluations\n", "For this release, we evaluated performance on over 150 benchmark datasets that span a wide range of languages. In addition, we performed extensive human evaluations that compare Llama 3.1 with competing models in real-world scenarios. Our experimental evaluation suggests that our flagship model is competitive with leading foundation models across a range of tasks, including GPT-4, GPT-4o, and Claude 3.5 Sonnet. Additionally, our smaller models are competitive with closed and open models that have a similar number of parameters.\n", "Model Architecture As our largest model yet, training Llama 3.1 405B on over 15 trillion tokens was a major challenge. To enable training runs at this scale and achieve the results we have in a reasonable amount of time, we significantly optimized our full training stack and pushed our model training to over 16 thousand H100 GPUs, making the 405B the first Llama model trained at this scale.\n", "To address this, we made design choices that focus on keeping the model development process scalable and straightforward. We opted for a standard decoder-only transformer model architecture with minor adaptations rather than a mixture-of-experts model to maximize training stability.\n", "We adopted an iterative post-training procedure, where each round uses supervised fine-tuning and direct preference optimization. This enabled us to create the highest quality synthetic data for each round and improve each capability’s performance.\n", "Compared to previous versions of Llama, we improved both the quantity and quality of the data we use for pre- and post-training. These improvements include the development of more careful pre-processing and curation pipelines for pre-training data, the development of more rigorous quality assurance, and filtering approaches for post-training data.\n", "\"\"\"" ], "metadata": { "id": "jAPOfX9fSKai" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "QUESTION = \"How many parameters LLaMA 3.1 model has?\"\n", "\n", "# Formulating the system prompt\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", "# Combining the system 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", "prompt = prompt.format(Example_chunk, QUESTION)\n", "\n", "model = genai.GenerativeModel(model_name= \"gemini-1.5-flash\", system_instruction=system_prompt)\n", "\n", "#Gemini API call\n", "result = model.generate_content(prompt,request_options={\"timeout\": 1000},)\n", "res = result.text\n", "print(res)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "E28JMT8mSKUf", "outputId": "2afca017-7093-42f9-a477-a2a732f29017" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The LLaMA 3.1 model has **405 billion parameters**. \n", "\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "pW-BNCAC2JzE" }, "source": [ "# Without Augmentation\n" ] }, { "cell_type": "markdown", "metadata": { "id": "tr5zXEGIMwJu" }, "source": [ "Test the Gemini API to answer the same question without the addition of retrieved documents. Basically, the LLM will use its knowledge to answer the question.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "RuyXjzZyuecE" }, "outputs": [], "source": [ "QUESTION = \"How many parameters LLaMA 3 model has?\"\n", "\n", "# Formulating the system prompt\n", "system_prompt = \"You are an assistant and expert in answering questions.\"\n", "\n", "# Combining the system prompt with the user's question\n", "prompt = \"Be concise and take your time to answer the following question. \\nQuestion: {}\\nAnswer:\"\n", "prompt = prompt.format(QUESTION)\n", "\n", "model = genai.GenerativeModel(model_name= \"gemini-1.5-flash\", system_instruction=system_prompt)\n", "\n", "#Gemini API call\n", "result = model.generate_content(prompt,request_options={\"timeout\": 1000},)\n", "res = result.text" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "YAy34tPTzGbh", "outputId": "134022f6-5067-45a4-bdb7-c6513aded50c" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "LLaMA 3 has **34 billion parameters**. \n", "\n" ] } ], "source": [ "print(res)" ] }, { "cell_type": "code", "source": [], "metadata": { "id": "jCEapX5C83m2" }, "execution_count": null, "outputs": [] } ], "metadata": { "colab": { "provenance": [], "include_colab_link": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python", "version": "3.12.4" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "32a9876eaa924600b2d32c72c0bfc7b4": { "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_1963b6ad45ff4b7697112b0c19b2cab5", "IPY_MODEL_5fec0ec4e3c84208bd10a8afe6983596", "IPY_MODEL_f35bfdba42db4f3a83aff86b607cd138" ], "layout": "IPY_MODEL_73beec53e1ac41d986c6e8ec585f1c80" } }, "1963b6ad45ff4b7697112b0c19b2cab5": { "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_5a62b428fb92498bb799849fe3a91775", "placeholder": "​", "style": "IPY_MODEL_50240902b2a7405d8046f01c870a4533", "value": "" } }, "5fec0ec4e3c84208bd10a8afe6983596": { "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_7651f8c1645c4df1a14fcd4efde2aeab", "max": 1, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_d3227f1f0d0342bcac40686439fb2acf", "value": 1 } }, "f35bfdba42db4f3a83aff86b607cd138": { "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_4fdeae40b54c45c0a27d90103b3fc422", "placeholder": "​", "style": "IPY_MODEL_e650511151ac4e55a51f001367b48dc8", "value": " 174/? [00:34<00:00,  6.48it/s]" } }, "73beec53e1ac41d986c6e8ec585f1c80": { "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 } }, "5a62b428fb92498bb799849fe3a91775": { "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 } }, "50240902b2a7405d8046f01c870a4533": { "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": "" } }, "7651f8c1645c4df1a14fcd4efde2aeab": { "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" } }, "d3227f1f0d0342bcac40686439fb2acf": { "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": "" } }, "4fdeae40b54c45c0a27d90103b3fc422": { "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 } }, "e650511151ac4e55a51f001367b48dc8": { "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": "" } } } } }, "nbformat": 4, "nbformat_minor": 0 }