From ff788872f3584ee54917bffebb47754572279090 Mon Sep 17 00:00:00 2001 From: Shilpa Kancharla Date: Thu, 30 May 2024 13:12:11 -0700 Subject: [PATCH 1/7] Reformat notebook --- .../prompting/Basic_Code_Generation.ipynb | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/examples/prompting/Basic_Code_Generation.ipynb b/examples/prompting/Basic_Code_Generation.ipynb index 3f1021977..7205a1694 100644 --- a/examples/prompting/Basic_Code_Generation.ipynb +++ b/examples/prompting/Basic_Code_Generation.ipynb @@ -11,7 +11,11 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": null, +======= + "execution_count": 1, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "cellView": "form", "id": "vQoUR__bUlfj" @@ -66,7 +70,11 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 1, +======= + "execution_count": 2, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "id": "Ne-3gnXqR0hI" }, @@ -77,7 +85,11 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 2, +======= + "execution_count": 3, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "id": "EconMHePQHGw" }, @@ -101,7 +113,11 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 3, +======= + "execution_count": 4, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "id": "v-JZzORUpVR2" }, @@ -133,11 +149,16 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 4, +======= + "execution_count": 5, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "id": "kVF8ZQ38Vs1P" }, "outputs": [], +<<<<<<< HEAD "source": [ "error_handling_system_prompt =f\"\"\"\n", "Your task is to explain exactly why this error occurred and how to fix it.\n", @@ -177,6 +198,58 @@ "You've encountered the following error message:\n", "Error Message: {error_message}\"\"\"\n", "\n", +======= + "source": [ + "error_handling_system_prompt =f\"\"\"\n", + "You are a coding assistant tasked with error handling. Your task is to provide:\n", + "\n", + "Explanation:\n", + "Explain why this error occurred. Provide insights into common causes of the error.\n", + "For each common cause, provide a code example of how this error arose.\n", + "\n", + "Possible Solutions:\n", + "Offer a potential solution to resolve the error.\n", + "\n", + "Example Code:\n", + "Optionally, include example code snippets demonstrating correct usage or\n", + "implementation.\n", + "\"\"\"\n", + "error_handling_model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', generation_config={\"temperature\": 0},\n", + " system_instruction=error_handling_system_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "id": "CHTdAVE0pIFf" + }, + "outputs": [ + { + "data": { + "text/markdown": "## Explanation:\n\nThe error \"IndexError: list index out of range\" occurs when you try to access an element in a list using an index that is outside the valid range of indices for that list.\n\n**Common Causes:**\n\n1. **Incorrect Index:** You are trying to access an element at an index that doesn't exist in the list. \n * **Example:**\n ```python\n my_list = [1, 2, 3]\n print(my_list[3]) # Trying to access the 4th element (index 3), which doesn't exist.\n ```\n\n2. **Negative Index Out of Range:** You are using a negative index to access an element from the end of the list, but the index is too large (i.e., more negative than the length of the list).\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n print(my_list[-4]) # Trying to access the 4th element from the end, which doesn't exist.\n ```\n\n3. **List Modification During Iteration:** You are modifying the list while iterating over it, which can lead to unexpected index errors.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n for i in range(len(my_list)):\n if my_list[i] == 2:\n my_list.pop(i) # Removing an element while iterating can cause index errors.\n print(my_list[i])\n ```\n\n## Possible Solutions:\n\n1. **Check the Index:** Ensure that the index you are using to access the element is within the valid range of the list. You can use `len(my_list)` to get the length of the list and make sure your index is less than that.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n if 3 < len(my_list):\n print(my_list[3])\n else:\n print(\"Index out of range\")\n ```\n\n2. **Use Negative Indices Carefully:** When using negative indices, remember that `-1` refers to the last element, `-2` to the second-to-last, and so on. Make sure your negative index is within the valid range.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n if -1 >= -len(my_list):\n print(my_list[-1])\n else:\n print(\"Index out of range\")\n ```\n\n3. **Avoid Modifying Lists During Iteration:** If you need to modify a list while iterating over it, consider using a copy of the list or iterating over a range of indices instead of directly modifying the list during iteration.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n for i in range(len(my_list)):\n if my_list[i] == 2:\n my_list.pop(i) # Removing an element while iterating can cause index errors.\n print(my_list[i])\n ```\n\n **Solution:**\n ```python\n my_list = [1, 2, 3]\n for i in range(len(my_list)):\n if my_list[i] == 2:\n my_list.pop(i)\n break # Stop iterating after removing the element\n print(my_list[i])\n ```\n\nBy understanding the common causes of this error and implementing the appropriate solutions, you can avoid \"IndexError: list index out of range\" and ensure your code runs smoothly. \n", + "text/plain": [ + "" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "error_message = \"\"\"\n", + " 1 my_list = [1,2,3]\n", + "----> 2 print(my_list[3])\n", + "\n", + "IndexError: list index out of range\n", + "\"\"\"\n", + "\n", + "error_prompt = f\"\"\"\n", + "You've encountered the following error message:\n", + "Error Message: {error_message}\"\"\"\n", + "\n", +>>>>>>> 757cc02 (Update basic code generation) "Markdown(error_handling_model.generate_content(error_prompt).text)" ] }, @@ -191,7 +264,11 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 6, +======= + "execution_count": 7, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "id": "1T1QSzjVVvE_" }, @@ -210,7 +287,11 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 7, +======= + "execution_count": 8, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "id": "8KVpzExDqRj2" }, @@ -222,7 +303,11 @@ "" ] }, +<<<<<<< HEAD "execution_count": 7, +======= + "execution_count": 8, +>>>>>>> 757cc02 (Update basic code generation) "metadata": {}, "output_type": "execute_result" } @@ -244,7 +329,11 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 8, +======= + "execution_count": 9, +>>>>>>> 757cc02 (Update basic code generation) "metadata": { "id": "lOU_abTPSmZu" }, @@ -286,7 +375,11 @@ ], "metadata": { "colab": { +<<<<<<< HEAD "name": "Basic_code_generation.ipynb", +======= + "name": "Basic_Code_Generation.ipynb", +>>>>>>> 757cc02 (Update basic code generation) "toc_visible": true }, "kernelspec": { From 1979c184999be266c278e220e8032f46064cf741 Mon Sep 17 00:00:00 2001 From: Shilpa Kancharla Date: Thu, 30 May 2024 12:39:13 -0700 Subject: [PATCH 2/7] Update notebook with shorter prompt --- .../prompting/Basic_Code_Generation.ipynb | 59 ++++++++++++++----- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/examples/prompting/Basic_Code_Generation.ipynb b/examples/prompting/Basic_Code_Generation.ipynb index 7205a1694..216a03b3a 100644 --- a/examples/prompting/Basic_Code_Generation.ipynb +++ b/examples/prompting/Basic_Code_Generation.ipynb @@ -11,11 +11,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": null, ======= "execution_count": 1, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": null, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "cellView": "form", "id": "vQoUR__bUlfj" @@ -70,11 +74,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 1, ======= "execution_count": 2, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 1, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "id": "Ne-3gnXqR0hI" }, @@ -85,11 +93,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 2, ======= "execution_count": 3, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 2, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "id": "EconMHePQHGw" }, @@ -113,11 +125,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 3, ======= "execution_count": 4, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 3, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "id": "v-JZzORUpVR2" }, @@ -149,11 +165,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 4, ======= "execution_count": 5, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 4, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "id": "kVF8ZQ38Vs1P" }, @@ -201,18 +221,7 @@ ======= "source": [ "error_handling_system_prompt =f\"\"\"\n", - "You are a coding assistant tasked with error handling. Your task is to provide:\n", - "\n", - "Explanation:\n", - "Explain why this error occurred. Provide insights into common causes of the error.\n", - "For each common cause, provide a code example of how this error arose.\n", - "\n", - "Possible Solutions:\n", - "Offer a potential solution to resolve the error.\n", - "\n", - "Example Code:\n", - "Optionally, include example code snippets demonstrating correct usage or\n", - "implementation.\n", + "Your task is to explain exactly why this error occurred and how to fix it.\n", "\"\"\"\n", "error_handling_model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', generation_config={\"temperature\": 0},\n", " system_instruction=error_handling_system_prompt)" @@ -220,19 +229,19 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 5, "metadata": { "id": "CHTdAVE0pIFf" }, "outputs": [ { "data": { - "text/markdown": "## Explanation:\n\nThe error \"IndexError: list index out of range\" occurs when you try to access an element in a list using an index that is outside the valid range of indices for that list.\n\n**Common Causes:**\n\n1. **Incorrect Index:** You are trying to access an element at an index that doesn't exist in the list. \n * **Example:**\n ```python\n my_list = [1, 2, 3]\n print(my_list[3]) # Trying to access the 4th element (index 3), which doesn't exist.\n ```\n\n2. **Negative Index Out of Range:** You are using a negative index to access an element from the end of the list, but the index is too large (i.e., more negative than the length of the list).\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n print(my_list[-4]) # Trying to access the 4th element from the end, which doesn't exist.\n ```\n\n3. **List Modification During Iteration:** You are modifying the list while iterating over it, which can lead to unexpected index errors.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n for i in range(len(my_list)):\n if my_list[i] == 2:\n my_list.pop(i) # Removing an element while iterating can cause index errors.\n print(my_list[i])\n ```\n\n## Possible Solutions:\n\n1. **Check the Index:** Ensure that the index you are using to access the element is within the valid range of the list. You can use `len(my_list)` to get the length of the list and make sure your index is less than that.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n if 3 < len(my_list):\n print(my_list[3])\n else:\n print(\"Index out of range\")\n ```\n\n2. **Use Negative Indices Carefully:** When using negative indices, remember that `-1` refers to the last element, `-2` to the second-to-last, and so on. Make sure your negative index is within the valid range.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n if -1 >= -len(my_list):\n print(my_list[-1])\n else:\n print(\"Index out of range\")\n ```\n\n3. **Avoid Modifying Lists During Iteration:** If you need to modify a list while iterating over it, consider using a copy of the list or iterating over a range of indices instead of directly modifying the list during iteration.\n * **Example:**\n ```python\n my_list = [1, 2, 3]\n for i in range(len(my_list)):\n if my_list[i] == 2:\n my_list.pop(i) # Removing an element while iterating can cause index errors.\n print(my_list[i])\n ```\n\n **Solution:**\n ```python\n my_list = [1, 2, 3]\n for i in range(len(my_list)):\n if my_list[i] == 2:\n my_list.pop(i)\n break # Stop iterating after removing the element\n print(my_list[i])\n ```\n\nBy understanding the common causes of this error and implementing the appropriate solutions, you can avoid \"IndexError: list index out of range\" and ensure your code runs smoothly. \n", + "text/markdown": "The error message \"IndexError: list index out of range\" means you're trying to access an element in a list using an index that doesn't exist.\n\n**Explanation:**\n\n* **List Indexing:** In Python, lists are zero-indexed. This means the first element has an index of 0, the second element has an index of 1, and so on.\n* **Your Code:** In your code, `my_list = [1, 2, 3]` has three elements. The valid indices for this list are 0, 1, and 2.\n* **The Error:** You're trying to access `my_list[3]`. Since the list only has three elements, there is no element at index 3. This causes the \"IndexError: list index out of range\" error.\n\n**How to Fix It:**\n\n1. **Check the Index:** Ensure the index you're using is within the valid range of the list. In this case, you should use an index between 0 and 2.\n2. **Adjust the Code:** To access the last element of the list, use `my_list[2]`.\n\n**Corrected Code:**\n\n```python\nmy_list = [1, 2, 3]\nprint(my_list[2]) # This will print 3\n```\n\n**Important Note:** Always be mindful of the size of your lists and the indices you use to avoid this common error. \n", "text/plain": [ "" ] }, - "execution_count": 6, + "execution_count": 5, "metadata": {}, "output_type": "execute_result" } @@ -264,11 +273,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 6, ======= "execution_count": 7, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 6, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "id": "1T1QSzjVVvE_" }, @@ -287,11 +300,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 7, ======= "execution_count": 8, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 7, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "id": "8KVpzExDqRj2" }, @@ -303,11 +320,15 @@ "" ] }, +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 7, ======= "execution_count": 8, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 7, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": {}, "output_type": "execute_result" } @@ -329,11 +350,15 @@ }, { "cell_type": "code", +<<<<<<< HEAD <<<<<<< HEAD "execution_count": 8, ======= "execution_count": 9, >>>>>>> 757cc02 (Update basic code generation) +======= + "execution_count": 8, +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "id": "lOU_abTPSmZu" }, @@ -375,11 +400,15 @@ ], "metadata": { "colab": { +<<<<<<< HEAD <<<<<<< HEAD "name": "Basic_code_generation.ipynb", ======= "name": "Basic_Code_Generation.ipynb", >>>>>>> 757cc02 (Update basic code generation) +======= + "name": "Basic_code_generation.ipynb", +>>>>>>> 7c65d32 (Update notebook with shorter prompt) "toc_visible": true }, "kernelspec": { From 864da9a09f800fcfde6118a19b1043c43d7aa71e Mon Sep 17 00:00:00 2001 From: Shilpa Kancharla Date: Mon, 3 Jun 2024 13:42:18 -0700 Subject: [PATCH 3/7] Adding text classification JSON example --- .../Text_Classification.ipynb | 267 ++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 examples/json_capabilities/Text_Classification.ipynb diff --git a/examples/json_capabilities/Text_Classification.ipynb b/examples/json_capabilities/Text_Classification.ipynb new file mode 100644 index 000000000..c0671af9e --- /dev/null +++ b/examples/json_capabilities/Text_Classification.ipynb @@ -0,0 +1,267 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "KLHiTPXNTf2a" + }, + "source": [ + "##### Copyright 2024 Google LLC." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "id": "oTuT5CsaTigz" + }, + "outputs": [], + "source": [ + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# you may not use this file except in compliance with the License.\n", + "# You may obtain a copy of the License at\n", + "#\n", + "# https://www.apache.org/licenses/LICENSE-2.0\n", + "#\n", + "# Unless required by applicable law or agreed to in writing, software\n", + "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", + "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", + "# See the License for the specific language governing permissions and\n", + "# limitations under the License." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "sP8PQnz1QrcF" + }, + "source": [ + "# Gemini API: Text Classification" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "bxGr_x3MRA0z" + }, + "source": [ + "\n", + " \n", + "
\n", + " Run in Google Colab\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ysy--KfNRrCq" + }, + "source": [ + "You will use the Gemini API to classify what topics are relevant in the text." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "id": "Ne-3gnXqR0hI" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/158.8 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[32m133.1/158.8 kB\u001b[0m \u001b[31m3.7 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m158.8/158.8 kB\u001b[0m \u001b[31m2.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[?25h" + ] + } + ], + "source": [ + "!pip install -U -q google-generativeai" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "id": "EconMHePQHGw" + }, + "outputs": [], + "source": [ + "import google.generativeai as genai\n", + "\n", + "import json\n", + "from IPython.display import Markdown\n", + "from typing_extensions import TypedDict # in python 3.12 replace typing_extensions with typing" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "eomJzCa6lb90" + }, + "source": [ + "## Configure your API key\n", + "\n", + "To run the following cell, your API key must be stored it in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) for an example." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "id": "v-JZzORUpVR2" + }, + "outputs": [], + "source": [ + "from google.colab import userdata\n", + "GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')\n", + "\n", + "genai.configure(api_key=GOOGLE_API_KEY)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "kNE5XslpPpT0" + }, + "source": [ + "## Example" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "id": "d7vfQVmt9uUT" + }, + "outputs": [ + { + "data": { + "text/markdown": "## The Power of Sport: A Catalyst for Social Change\n\nSports have long been a source of entertainment and inspiration, captivating audiences worldwide with their thrilling competitions and captivating narratives. But beyond the cheers and the victories, sports hold a profound power to drive social change. From promoting gender equality to fostering cross-cultural understanding, the impact of sports extends far beyond the playing field.\n\nOne of the most significant ways sports can contribute to social change is by challenging societal norms and promoting inclusivity. The rise of female athletes in traditionally male-dominated sports has shattered stereotypes and empowered women to pursue their athletic dreams. Similarly, the increasing visibility of athletes from diverse backgrounds has helped to break down racial and cultural barriers, fostering a more inclusive and equitable society.\n\nFurthermore, sports can serve as a powerful tool for promoting peace and understanding. International sporting events, such as the Olympics, bring together athletes and spectators from all corners of the globe, fostering a sense of unity and shared humanity. These events can transcend political and cultural differences, creating a platform for dialogue and cooperation.\n\nHowever, the potential of sports to drive social change is not without its challenges. Issues such as discrimination, corruption, and the exploitation of athletes continue to plague the sporting world. It is crucial to address these issues head-on, ensuring that sports remain a force for good and a platform for positive change.\n\nIn conclusion, sports hold immense potential to drive social change, promoting inclusivity, fostering peace, and challenging societal norms. By embracing the power of sports and addressing its challenges, we can harness its transformative potential to create a more just and equitable world. As we celebrate the triumphs and the struggles of athletes on the field, let us also recognize the profound impact they have on society as a whole. \n", + "text/plain": [ + "" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', generation_config={\"temperature\": 0})\n", + "response = model.generate_content(\"Generate a 5 paragraph article about Sports, include one other topic\")\n", + "article = response.text\n", + "Markdown(article)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "id": "704lXZcS9uUT" + }, + "outputs": [], + "source": [ + "prompt = f\"\"\"\n", + "Generate list of topics in text, the topcis should be general e.g. Health:\n", + "\n", + "Follow this schema to generate JSON:\n", + "\n", + "class Topic(TypedDict):\n", + " topic: str # should be general\n", + " relevance: float\n", + "\n", + "class Topics(TypedDict):\n", + " topic: list[Topic]\n", + "\n", + "{article}\"\"\"\n", + "response = model.generate_content(prompt, generation_config={\"response_mime_type\": \"application/json\"})" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "id": "LMTjb4Gs9uUU" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{\n", + " \"topic\": [\n", + " {\n", + " \"topic\": \"Social Change\",\n", + " \"relevance\": 0.8\n", + " },\n", + " {\n", + " \"topic\": \"Sports\",\n", + " \"relevance\": 0.8\n", + " },\n", + " {\n", + " \"topic\": \"Gender Equality\",\n", + " \"relevance\": 0.6\n", + " },\n", + " {\n", + " \"topic\": \"Inclusivity\",\n", + " \"relevance\": 0.6\n", + " },\n", + " {\n", + " \"topic\": \"Peace\",\n", + " \"relevance\": 0.5\n", + " },\n", + " {\n", + " \"topic\": \"Cultural Understanding\",\n", + " \"relevance\": 0.5\n", + " },\n", + " {\n", + " \"topic\": \"Discrimination\",\n", + " \"relevance\": 0.4\n", + " },\n", + " {\n", + " \"topic\": \"Corruption\",\n", + " \"relevance\": 0.4\n", + " },\n", + " {\n", + " \"topic\": \"Exploitation\",\n", + " \"relevance\": 0.4\n", + " }\n", + " ]\n", + "}\n" + ] + } + ], + "source": [ + "print(json.dumps(json.loads(response.text), indent=4))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "l3XJbxtv1Htk" + }, + "source": [ + "## Summary\n", + "Now, you know how to classify text into different categories. Feel free to experiment with other texts, or provide a specific set of possible topics.\n", + "\n", + "Please see the other notebooks in this directory to learn more about how you can use the Gemini API for other JSON related tasks." + ] + } + ], + "metadata": { + "colab": { + "name": "Text_Classification.ipynb", + "toc_visible": true + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} From af4374079a598385983da931d9d1358a92063bda Mon Sep 17 00:00:00 2001 From: Shilpa Kancharla Date: Mon, 10 Jun 2024 14:55:06 -0700 Subject: [PATCH 4/7] Add chat SQL langchain example --- examples/Chat_with_SQL_using_langchain.ipynb | 563 +++++++++++++++++++ 1 file changed, 563 insertions(+) create mode 100644 examples/Chat_with_SQL_using_langchain.ipynb diff --git a/examples/Chat_with_SQL_using_langchain.ipynb b/examples/Chat_with_SQL_using_langchain.ipynb new file mode 100644 index 000000000..9d254d824 --- /dev/null +++ b/examples/Chat_with_SQL_using_langchain.ipynb @@ -0,0 +1,563 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "KLHiTPXNTf2a" + }, + "source": [ + "##### Copyright 2024 Google LLC." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellView": "form", + "id": "oTuT5CsaTigz" + }, + "outputs": [], + "source": [ + "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", + "# you may not use this file except in compliance with the License.\n", + "# You may obtain a copy of the License at\n", + "#\n", + "# https://www.apache.org/licenses/LICENSE-2.0\n", + "#\n", + "# Unless required by applicable law or agreed to in writing, software\n", + "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", + "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", + "# See the License for the specific language governing permissions and\n", + "# limitations under the License." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ZNM-D0pLXZeR" + }, + "source": [ + "# Gemini API: Chat with SQL using LangChain" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PRZo8H09Bs6u" + }, + "source": [ + "\n", + " \n", + "
\n", + " Run in Google Colab\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "mOGNjAZMwMIk" + }, + "source": [ + "Reading an SQL database can be challenging for humans. However, with accurate prompts, Gemini models can generate answers based on the data. Through the use of the Gemini API, you will be able retrieve necessary information by chatting with a SQL database." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "id": "CaSSapCIcoxy" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m158.8/158.8 kB\u001b[0m \u001b[31m1.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m974.0/974.0 kB\u001b[0m \u001b[31m11.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.2/2.2 MB\u001b[0m \u001b[31m27.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m314.7/314.7 kB\u001b[0m \u001b[31m6.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m124.9/124.9 kB\u001b[0m \u001b[31m3.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.2/49.2 kB\u001b[0m \u001b[31m906.2 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m53.0/53.0 kB\u001b[0m \u001b[31m2.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m142.7/142.7 kB\u001b[0m \u001b[31m3.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[?25h" + ] + } + ], + "source": [ + "!pip install -U -q google-generativeai langchain langchain-community langchain-google-genai" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "id": "bBoPE7f7cmKA" + }, + "outputs": [], + "source": [ + "import sqlite3\n", + "\n", + "from langchain.chains import create_sql_query_chain, LLMChain\n", + "from langchain.prompts import PromptTemplate\n", + "from langchain_google_genai import ChatGoogleGenerativeAI\n", + "from langchain_core.output_parsers import StrOutputParser\n", + "from langchain_community.utilities import SQLDatabase\n", + "from langchain_community.tools.sql_database.tool import QuerySQLDataBaseTool\n", + "from operator import itemgetter\n", + "from langchain_core.runnables import RunnablePassthrough\n", + "\n", + "import google.generativeai as genai\n", + "from IPython.display import Markdown" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "FQOGMejVu-6D" + }, + "source": [ + "## Configure your API key\n", + "\n", + "To run the following cell, your API key must be stored in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) for an example.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "id": "ysayz8skEfBW" + }, + "outputs": [], + "source": [ + "import os\n", + "from google.colab import userdata\n", + "GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')\n", + "\n", + "os.environ[\"GOOGLE_API_KEY\"] = GOOGLE_API_KEY" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "NzyyOcsUR0HO" + }, + "source": [ + "## Setting up the database\n", + "To query a database, you first need to set one up.\n", + "\n", + "1. **Load the California Housing Dataset:** Load the dataset from sklearn.datasets and extract it into a DataFrame.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "id": "lK85M4XGRzsM" + }, + "outputs": [], + "source": [ + "from sklearn.datasets import fetch_california_housing\n", + "\n", + "california_housing_bunch = fetch_california_housing(as_frame=True)\n", + "california_housing_df = california_housing_bunch.frame" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "GIjbnY4X_Kwd" + }, + "source": [ + "2. **Connect to the SQLite database:** The database will be stored in the specified file." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "id": "1Kbqtjo4V2qM" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "20640" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "conn = sqlite3.connect(\"mydatabase.db\")\n", + "\n", + "# Write the DataFrame to a SQL table named 'housing'.\n", + "california_housing_df.to_sql(\"housing\", conn, index=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "id": "D7ChiDUmXC3K" + }, + "outputs": [], + "source": [ + "# Create an SQLDatabase object\n", + "db = SQLDatabase.from_uri(\"sqlite:///mydatabase.db\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jHGQdREVYFxo" + }, + "source": [ + "## Question to query\n", + "With the database connection established, the `SQLDatabase` object now contains information about our database, which the model can access.\n", + "\n", + "You can now start asking the LLM to generate queries.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "id": "g0xP-OStxDW8" + }, + "outputs": [ + { + "data": { + "text/markdown": [ + "\n", + "CREATE TABLE housing (\n", + "\t\"MedInc\" REAL, \n", + "\t\"HouseAge\" REAL, \n", + "\t\"AveRooms\" REAL, \n", + "\t\"AveBedrms\" REAL, \n", + "\t\"Population\" REAL, \n", + "\t\"AveOccup\" REAL, \n", + "\t\"Latitude\" REAL, \n", + "\t\"Longitude\" REAL, \n", + "\t\"MedHouseVal\" REAL\n", + ")\n", + "\n", + "/*\n", + "3 rows from housing table:\n", + "MedInc\tHouseAge\tAveRooms\tAveBedrms\tPopulation\tAveOccup\tLatitude\tLongitude\tMedHouseVal\n", + "8.3252\t41.0\t6.984126984126984\t1.0238095238095237\t322.0\t2.5555555555555554\t37.88\t-122.23\t4.526\n", + "8.3014\t21.0\t6.238137082601054\t0.9718804920913884\t2401.0\t2.109841827768014\t37.86\t-122.22\t3.585\n", + "7.2574\t52.0\t8.288135593220339\t1.073446327683616\t496.0\t2.8022598870056497\t37.85\t-122.24\t3.521\n", + "*/" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# you can see what information is available\n", + "Markdown(db.get_table_info())" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "id": "MFnV5-dUaa77" + }, + "outputs": [], + "source": [ + "# Define query chain\n", + "llm = ChatGoogleGenerativeAI(model=\"gemini-1.5-flash-latest\", temperature=0)\n", + "write_query_chain = create_sql_query_chain(llm, db)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6EdrtzVX0zcm" + }, + "source": [ + "You use `create_sql_query_chain` that fits our database. It provides default prompts for various types of SQL including Oracle, Google SQL, MySQL and more.\n", + "\n", + "\n", + "In this case, default prompt is suitable for the task. However, feel free to experiment with writing this part of our chain yourself to suit your preferences." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "id": "r2TjWih70ro6" + }, + "outputs": [ + { + "data": { + "text/markdown": [ + "You are a SQLite expert. Given an input question, first create a syntactically correct SQLite query to run, then look at the results of the query and return the answer to the input question.\n", + "Unless the user specifies in the question a specific number of examples to obtain, query for at most {top_k} results using the LIMIT clause as per SQLite. You can order the results to return the most informative data in the database.\n", + "Never query for all columns from a table. You must query only the columns that are needed to answer the question. Wrap each column name in double quotes (\") to denote them as delimited identifiers.\n", + "Pay attention to use only the column names you can see in the tables below. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\n", + "Pay attention to use date('now') function to get the current date, if the question involves \"today\".\n", + "\n", + "Use the following format:\n", + "\n", + "Question: Question here\n", + "SQLQuery: SQL Query to run\n", + "SQLResult: Result of the SQLQuery\n", + "Answer: Final answer here\n", + "\n", + "Only use the following tables:\n", + "{table_info}\n", + "\n", + "Question: {input}" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Markdown(write_query_chain.get_prompts()[0].template)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "id": "dGONOILk0sr2" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "'Question: What is the total population?\\nSQLQuery: SELECT SUM(\"Population\") FROM housing'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "response = write_query_chain.invoke({\"question\": \"What is the total population?\"})\n", + "response" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "id": "1rwKuD6eYhzv" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "'[(29421840.0,)]'" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "db.run('SELECT SUM(\"Population\") FROM housing')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Fb_72hgXagco" + }, + "source": [ + "Great! The SQL query is correct, but it needs proper formatting before it can be executed directly by the database.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3ZOGsW9YcL-I" + }, + "source": [ + "## Validating the query\n", + "You will pass the output of the previous query to a model that will extract just the SQL query and ensure its validity." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "id": "ptuPPTordp6G" + }, + "outputs": [], + "source": [ + "validate_prompt = PromptTemplate(\n", + " input_variables=[\"not_formatted_query\"],\n", + " template=\"\"\"You are going to receive a text that contains a SQL query. Extract that query.\n", + " Make sure that it is a valid SQL command that can be passed directly to the Database.\n", + " Avoid using Markdown for this task.\n", + " Text: {not_formatted_query}\"\"\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "id": "5KP9yy1edRfJ" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "'SELECT SUM(\"Population\") FROM housing \\n'" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "validate_chain = write_query_chain | validate_prompt | llm | StrOutputParser()\n", + "validate_chain.invoke({\"question\": \"What is the total population?\"})" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "oskPmggygOJP" + }, + "source": [ + "## Automatic querying\n", + "Now, let's automate the process of querying the database using *QuerySQLDataBaseTool*. This tool can receive text from previous parts of the chain, execute the query, and return the answer.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "id": "mTfFkHVgcDuo" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "'[(29421840.0,)]'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "execute_query = QuerySQLDataBaseTool(db=db)\n", + "execute_chain = validate_chain | execute_query\n", + "execute_chain.invoke({\"question\": \"What is the total population?\"})" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "amQh9IvQlBH0" + }, + "source": [ + "## Generating answer\n", + "You are almost done!\n", + "\n", + "To enhance our output, you'll use LLM not only to get the number but to get properly formatted and natural language response." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "id": "658lkr4xlD6q" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "'The total population is 29,421,840. \\n'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "answer_prompt = PromptTemplate.from_template(\n", + " \"\"\"You are going to receive a original user question, generated SQL query, and result of said query. You should use this information to answer the original question. Use only information provided to you.\n", + "\n", + "Original Question: {question}\n", + "SQL Query: {query}\n", + "SQL Result: {result}\n", + "Answer: \"\"\"\n", + ")\n", + "\n", + "answer_chain = (\n", + " RunnablePassthrough.assign(query=validate_chain).assign(\n", + " result=itemgetter(\"query\") | execute_query\n", + " )\n", + " | answer_prompt | llm | StrOutputParser()\n", + ")\n", + "\n", + "answer_chain.invoke({\"question\": \"What is the total population?\"})" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "SJmceCo2Lebi" + }, + "source": [ + "## Next steps\n", + "\n", + "Congratulations! You've successfully created a functional chain to interact with SQL. Now, feel free to explore further by asking different questions." + ] + } + ], + "metadata": { + "colab": { + "name": "Chat_with_SQL_using_langchain.ipynb", + "toc_visible": true + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} From 3b8df927cd0dabe35dd370b3c8939c0c8990f5eb Mon Sep 17 00:00:00 2001 From: Shilpa Kancharla Date: Tue, 11 Jun 2024 11:36:16 -0700 Subject: [PATCH 5/7] moved to examples/langchain --- examples/{ => langchain}/Chat_with_SQL_using_langchain.ipynb | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename examples/{ => langchain}/Chat_with_SQL_using_langchain.ipynb (100%) diff --git a/examples/Chat_with_SQL_using_langchain.ipynb b/examples/langchain/Chat_with_SQL_using_langchain.ipynb similarity index 100% rename from examples/Chat_with_SQL_using_langchain.ipynb rename to examples/langchain/Chat_with_SQL_using_langchain.ipynb From d7cf0bb1231a63b5bca4690babdcc3be0ab49d14 Mon Sep 17 00:00:00 2001 From: Shilpa Kancharla Date: Tue, 11 Jun 2024 11:37:01 -0700 Subject: [PATCH 6/7] Update link and reformat --- examples/langchain/Chat_with_SQL_using_langchain.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/langchain/Chat_with_SQL_using_langchain.ipynb b/examples/langchain/Chat_with_SQL_using_langchain.ipynb index 9d254d824..5cbc2ed43 100644 --- a/examples/langchain/Chat_with_SQL_using_langchain.ipynb +++ b/examples/langchain/Chat_with_SQL_using_langchain.ipynb @@ -48,7 +48,7 @@ "source": [ "\n", " \n", "
\n", - " Run in Google Colab\n", + " Run in Google Colab\n", "
" ] From 2644cdd78896af763f7962eedf5c6043f4e72ef1 Mon Sep 17 00:00:00 2001 From: Shilpa Kancharla Date: Tue, 11 Jun 2024 12:21:23 -0700 Subject: [PATCH 7/7] Fix error in Basic Code Generation --- .../prompting/Basic_Code_Generation.ipynb | 138 +----------------- 1 file changed, 8 insertions(+), 130 deletions(-) diff --git a/examples/prompting/Basic_Code_Generation.ipynb b/examples/prompting/Basic_Code_Generation.ipynb index 216a03b3a..0762008fc 100644 --- a/examples/prompting/Basic_Code_Generation.ipynb +++ b/examples/prompting/Basic_Code_Generation.ipynb @@ -11,15 +11,7 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD "execution_count": null, -======= - "execution_count": 1, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": null, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": { "cellView": "form", "id": "vQoUR__bUlfj" @@ -74,15 +66,7 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 1, -======= - "execution_count": 2, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": 1, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) + "execution_count": null, "metadata": { "id": "Ne-3gnXqR0hI" }, @@ -93,15 +77,7 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 2, -======= - "execution_count": 3, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": 2, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) + "execution_count": null, "metadata": { "id": "EconMHePQHGw" }, @@ -125,15 +101,7 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 3, -======= - "execution_count": 4, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": 3, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) + "execution_count": null, "metadata": { "id": "v-JZzORUpVR2" }, @@ -165,60 +133,11 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 4, -======= - "execution_count": 5, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": 4, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) + "execution_count": null, "metadata": { "id": "kVF8ZQ38Vs1P" }, "outputs": [], -<<<<<<< HEAD - "source": [ - "error_handling_system_prompt =f\"\"\"\n", - "Your task is to explain exactly why this error occurred and how to fix it.\n", - "\"\"\"\n", - "error_handling_model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', generation_config={\"temperature\": 0},\n", - " system_instruction=error_handling_system_prompt)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "id": "CHTdAVE0pIFf" - }, - "outputs": [ - { - "data": { - "text/markdown": "The error message \"IndexError: list index out of range\" means you're trying to access an element in a list using an index that doesn't exist.\n\n**Explanation:**\n\n* **List Indexing:** In Python, lists are zero-indexed. This means the first element has an index of 0, the second element has an index of 1, and so on.\n* **Your Code:** In your code, `my_list = [1, 2, 3]` has three elements. The valid indices for this list are 0, 1, and 2.\n* **The Error:** You're trying to access `my_list[3]`. Since the list only has three elements, there is no element at index 3. This causes the \"IndexError: list index out of range\" error.\n\n**How to Fix It:**\n\n1. **Check the Index:** Ensure the index you're using is within the valid range of the list. In this case, you should use an index between 0 and 2.\n2. **Adjust the Code:** To access the last element of the list, use `my_list[2]`.\n\n**Corrected Code:**\n\n```python\nmy_list = [1, 2, 3]\nprint(my_list[2]) # This will print 3\n```\n\n**Important Note:** Always be mindful of the size of your lists and the indices you use to avoid this common error. \n", - "text/plain": [ - "" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "error_message = \"\"\"\n", - " 1 my_list = [1,2,3]\n", - "----> 2 print(my_list[3])\n", - "\n", - "IndexError: list index out of range\n", - "\"\"\"\n", - "\n", - "error_prompt = f\"\"\"\n", - "You've encountered the following error message:\n", - "Error Message: {error_message}\"\"\"\n", - "\n", -======= "source": [ "error_handling_system_prompt =f\"\"\"\n", "Your task is to explain exactly why this error occurred and how to fix it.\n", @@ -229,7 +148,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": null, "metadata": { "id": "CHTdAVE0pIFf" }, @@ -258,7 +177,6 @@ "You've encountered the following error message:\n", "Error Message: {error_message}\"\"\"\n", "\n", ->>>>>>> 757cc02 (Update basic code generation) "Markdown(error_handling_model.generate_content(error_prompt).text)" ] }, @@ -273,15 +191,7 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 6, -======= - "execution_count": 7, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": 6, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) + "execution_count": null, "metadata": { "id": "1T1QSzjVVvE_" }, @@ -300,15 +210,7 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 7, -======= - "execution_count": 8, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": 7, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) + "execution_count": null, "metadata": { "id": "8KVpzExDqRj2" }, @@ -320,15 +222,7 @@ "" ] }, -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 7, -======= - "execution_count": 8, ->>>>>>> 757cc02 (Update basic code generation) -======= "execution_count": 7, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) "metadata": {}, "output_type": "execute_result" } @@ -350,15 +244,7 @@ }, { "cell_type": "code", -<<<<<<< HEAD -<<<<<<< HEAD - "execution_count": 8, -======= - "execution_count": 9, ->>>>>>> 757cc02 (Update basic code generation) -======= - "execution_count": 8, ->>>>>>> 7c65d32 (Update notebook with shorter prompt) + "execution_count": null, "metadata": { "id": "lOU_abTPSmZu" }, @@ -400,15 +286,7 @@ ], "metadata": { "colab": { -<<<<<<< HEAD -<<<<<<< HEAD - "name": "Basic_code_generation.ipynb", -======= "name": "Basic_Code_Generation.ipynb", ->>>>>>> 757cc02 (Update basic code generation) -======= - "name": "Basic_code_generation.ipynb", ->>>>>>> 7c65d32 (Update notebook with shorter prompt) "toc_visible": true }, "kernelspec": {