Skip to content

Commit

Permalink
Add basic code generation prompting notebook (#148)
Browse files Browse the repository at this point in the history
* Add basic code generation prompting notebook

* Update basic code generation
  • Loading branch information
shilpakancharla authored May 30, 2024
1 parent cae597c commit b67bf46
Showing 1 changed file with 310 additions and 0 deletions.
310 changes: 310 additions & 0 deletions examples/prompting/Basic_Code_Generation.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "LweKUTqZUn4z"
},
"source": [
"##### Copyright 2024 Google LLC."
]
},
{
"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."
]
},
{
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bxGr_x3MRA0z"
},
"source": [
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/prompting/Basic_Code_Generation.ipynb\"><img src = \"https://www.tensorflow.org/images/colab_logo_32px.png\"/>Run in Google Colab</a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"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",
"execution_count": 2,
"metadata": {
"id": "Ne-3gnXqR0hI"
},
"outputs": [],
"source": [
"!pip install -U -q google-generativeai"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "EconMHePQHGw"
},
"outputs": [],
"source": [
"import google.generativeai as genai\n",
"\n",
"from IPython.display import Markdown"
]
},
{
"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": 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)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yQnqEPjephXi"
},
"source": [
"## Examples"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bR-OOcC6pIm5"
},
"source": [
"### Error handling"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"id": "kVF8ZQ38Vs1P"
},
"outputs": [],
"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": [
"<IPython.core.display.Markdown object>"
]
},
"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",
"Markdown(error_handling_model.generate_content(error_prompt).text)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kTDi8WyDqQRf"
},
"source": [
"### Code generation"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"id": "1T1QSzjVVvE_"
},
"outputs": [],
"source": [
"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",
"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": {
"id": "8KVpzExDqRj2"
},
"outputs": [
{
"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": [
"<IPython.core.display.Markdown object>"
]
},
"execution_count": 8,
"metadata": {},
"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": [
"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"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

0 comments on commit b67bf46

Please sign in to comment.