diff --git a/examples/prompting/Basic_Code_Generation.ipynb b/examples/prompting/Basic_Code_Generation.ipynb
index 3526fd18c..bfdceeb8a 100644
--- a/examples/prompting/Basic_Code_Generation.ipynb
+++ b/examples/prompting/Basic_Code_Generation.ipynb
@@ -1,66 +1,83 @@
{
- "nbformat": 4,
- "nbformat_minor": 0,
- "metadata": {
- "colab": {
- "provenance": []
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "LweKUTqZUn4z"
+ },
+ "source": [
+ "##### Copyright 2024 Google LLC."
+ ]
},
- "kernelspec": {
- "name": "python3",
- "display_name": "Python 3"
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "cellView": "form",
+ "id": "vQoUR__bUlfj"
+ },
+ "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."
+ ]
},
- "language_info": {
- "name": "python"
- }
- },
- "cells": [
{
"cell_type": "markdown",
+ "metadata": {
+ "id": "sP8PQnz1QrcF"
+ },
"source": [
"# Gemini API: Basic code generation\n",
"\n",
"This notebook demonstrates how to use prompting to perform basic code generation using the Gemini API's Python SDK. Two use cases are explored: error handling and code generation."
- ],
- "metadata": {
- "id": "sP8PQnz1QrcF"
- }
+ ]
},
{
"cell_type": "markdown",
+ "metadata": {
+ "id": "bxGr_x3MRA0z"
+ },
"source": [
"
"
- ],
- "metadata": {
- "id": "bxGr_x3MRA0z"
- }
+ ]
},
{
"cell_type": "markdown",
- "source": [
- "Gemini can be a great tool to save you time during the development process. Tasks such as code generation, debugging, or optimization can be done with the assistance of the Gemini model."
- ],
"metadata": {
"id": "ysy--KfNRrCq"
- }
+ },
+ "source": [
+ "The Gemini API can be a great tool to save you time during the development process. Tasks such as code generation, debugging, or optimization can be done with the assistance of the Gemini model."
+ ]
},
{
"cell_type": "code",
- "source": [
- "!pip install -U -q google-generativeai"
- ],
+ "execution_count": 2,
"metadata": {
"id": "Ne-3gnXqR0hI"
},
- "execution_count": null,
- "outputs": []
+ "outputs": [],
+ "source": [
+ "!pip install -U -q google-generativeai"
+ ]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 3,
"metadata": {
"id": "EconMHePQHGw"
},
@@ -73,76 +90,61 @@
},
{
"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."
- ],
- "metadata": {
- "id": "eomJzCa6lb90"
- }
+ ]
},
{
"cell_type": "code",
+ "execution_count": 4,
+ "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)"
- ],
- "metadata": {
- "id": "v-JZzORUpVR2"
- },
- "execution_count": null,
- "outputs": []
+ ]
},
{
"cell_type": "markdown",
- "source": [
- "## Examples"
- ],
"metadata": {
"id": "yQnqEPjephXi"
- }
- },
- {
- "cell_type": "code",
- "source": [
- "model = genai.GenerativeModel(model_name='gemini-pro', generation_config={\"temperature\": 0})"
- ],
- "metadata": {
- "id": "VvMhQfbYpNXN"
},
- "execution_count": null,
- "outputs": []
+ "source": [
+ "## Examples"
+ ]
},
{
"cell_type": "markdown",
- "source": [
- "### Error handling"
- ],
"metadata": {
"id": "bR-OOcC6pIm5"
- }
+ },
+ "source": [
+ "### Error handling"
+ ]
},
{
"cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "id": "kVF8ZQ38Vs1P"
+ },
+ "outputs": [],
"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_handling =f\"\"\"\n",
- "You are a coding assistant tasked with error handling.\n",
- "\n",
- "You've encountered the following error message:\n",
- "Error Message: {error_message}\n",
+ "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",
@@ -151,89 +153,158 @@
"Optionally, include example code snippets demonstrating correct usage or\n",
"implementation.\n",
"\"\"\"\n",
- "\n",
- "Markdown(model.generate_content(error_handling).text)"
- ],
+ "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": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 383
- },
- "id": "CHTdAVE0pIFf",
- "outputId": "63cc0397-d0c7-4f59-cbf4-3190bd552761"
+ "id": "CHTdAVE0pIFf"
},
- "execution_count": null,
"outputs": [
{
- "output_type": "execute_result",
"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": [
""
- ],
- "text/markdown": "**Explanation:**\n\nThe error occurs because you are trying to access an element at index 3 in the list `my_list`, which has only three elements. List indices start from 0, so the valid indices for this list are 0, 1, and 2. Attempting to access an element at an index outside this range results in an `IndexError`.\n\n**Common Causes:**\n\n* **Off-by-one errors:** It's easy to make a mistake when counting the elements in a list, leading to an off-by-one error where you try to access an element at an index that is one greater than the actual number of elements.\n* **Negative indices:** Negative indices are not allowed in Python lists. Using a negative index will result in an `IndexError`.\n* **Accessing elements beyond the end of the list:** If you try to access an element at an index that is greater than or equal to the length of the list, you will get an `IndexError`.\n\n**Possible Solution:**\n\nTo resolve the error, you can check the length of the list before accessing its elements. For example:\n\n```python\nmy_list = [1, 2, 3]\nif len(my_list) > 3:\n print(my_list[3])\nelse:\n print(\"Index out of range\")\n```\n\nThis code checks if the list has more than three elements before trying to access the element at index 3. If the list has fewer than three elements, it prints an error message instead."
+ ]
},
+ "execution_count": 6,
"metadata": {},
- "execution_count": 5
+ "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",
+ "Markdown(error_handling_model.generate_content(error_prompt).text)"
]
},
{
"cell_type": "markdown",
- "source": [
- "### Code generation"
- ],
"metadata": {
"id": "kTDi8WyDqQRf"
- }
+ },
+ "source": [
+ "### Code generation"
+ ]
},
{
"cell_type": "code",
+ "execution_count": 7,
+ "metadata": {
+ "id": "1T1QSzjVVvE_"
+ },
+ "outputs": [],
"source": [
- "coding_goal = \"\"\"Create a countdown timer that ticks down every second and prints \"Time is up!\" after 20 seconds\"\"\"\n",
- "\n",
- "code_generation = f\"\"\"\n",
- "You are a coding assistant. Your task is to generate a code snippet that accomplishes a specific goal: {coding_goal}.\n",
+ "code_generation_system_prompt = f\"\"\"\n",
+ "You are a coding assistant. Your task is to generate a code snippet that accomplishes a specific goal.\n",
"The code snippet must be concise, efficient, and well-commented for clarity.\n",
"Consider any constraints or requirements provided for the task.\n",
"\n",
"If the task does not specify a programming language, default to Python.\n",
"\"\"\"\n",
- "\n",
- "Markdown(model.generate_content(code_generation).text)"
- ],
+ "code_generation_model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', generation_config={\"temperature\": 0},\n",
+ " system_instruction=code_generation_system_prompt)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
"metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 329
- },
- "id": "8KVpzExDqRj2",
- "outputId": "51b6c365-ae28-4243-f74d-1e9a88ce4de7"
+ "id": "8KVpzExDqRj2"
},
- "execution_count": null,
"outputs": [
{
- "output_type": "execute_result",
"data": {
+ "text/markdown": "```python\nimport time\n\n# Set the countdown duration in seconds\ncountdown_duration = 20\n\n# Start the countdown\nfor i in range(countdown_duration, 0, -1):\n print(i, end=\" \")\n time.sleep(1) # Wait for 1 second\n\n# Print \"Time is up!\" after the countdown\nprint(\"Time is up!\")\n```",
"text/plain": [
""
- ],
- "text/markdown": "```python\nimport time\n\n# Set the initial time remaining (in seconds)\ntime_remaining = 20\n\n# Create a loop that decrements the time remaining every second\nwhile time_remaining > 0:\n # Decrement the time remaining by 1 second\n time_remaining -= 1\n\n # Print the remaining time\n print(f\"Time remaining: {time_remaining} seconds\")\n\n # Sleep for 1 second\n time.sleep(1)\n\n# Print \"Time is up!\" when the time remaining reaches 0\nprint(\"Time is up!\")\n```"
+ ]
},
+ "execution_count": 8,
"metadata": {},
- "execution_count": 6
+ "output_type": "execute_result"
}
+ ],
+ "source": [
+ "code_generation_prompt = 'Create a countdown timer that ticks down every second and prints \"Time is up!\" after 20 seconds'\n",
+ "\n",
+ "Markdown(code_generation_model.generate_content(code_generation_prompt).text)"
]
},
{
"cell_type": "markdown",
+ "metadata": {
+ "id": "Z7X6pSdOMyvS"
+ },
"source": [
- "## Next steps\n",
- "\n",
- "Be sure to explore other examples of prompting in the repository. Try writing prompts around your own code as well using the examples in this notebook."
+ "Let's check if generated code works."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "id": "lOU_abTPSmZu"
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Time is up!\n"
+ ]
+ }
],
+ "source": [
+ "import time\n",
+ "\n",
+ "# Set the countdown duration in seconds\n",
+ "countdown_duration = 20\n",
+ "\n",
+ "# Start the countdown\n",
+ "for i in range(countdown_duration, 0, -1):\n",
+ " print(i, end=\" \")\n",
+ " time.sleep(1) # Wait for 1 second\n",
+ "\n",
+ "# Print \"Time is up!\" after the countdown\n",
+ "print(\"Time is up!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
"metadata": {
"id": "AiGF8I290YzL"
- }
+ },
+ "source": [
+ "## Next steps\n",
+ "\n",
+ "Be sure to explore other examples of prompting in the repository. Try writing prompts around your own code as well using the examples in this notebook."
+ ]
+ }
+ ],
+ "metadata": {
+ "colab": {
+ "name": "Basic_Code_Generation.ipynb",
+ "toc_visible": true
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "name": "python3"
}
- ]
-}
\ No newline at end of file
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}