Skip to content

Commit

Permalink
rebase
Browse files Browse the repository at this point in the history
  • Loading branch information
shilpakancharla committed May 30, 2024
1 parent 2632e49 commit a4e768e
Showing 1 changed file with 314 additions and 0 deletions.
314 changes: 314 additions & 0 deletions examples/prompting/Basic_Code_Generation.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"source": [
"##### Copyright 2024 Google LLC."
],
"metadata": {
"id": "LweKUTqZUn4z"
}
},
{
"cell_type": "code",
"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."
],
"metadata": {
"id": "vQoUR__bUlfj"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"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",
"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>"
],
"metadata": {
"id": "bxGr_x3MRA0z"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "ysy--KfNRrCq"
}
},
{
"cell_type": "code",
"source": [
"!pip install -U -q google-generativeai"
],
"metadata": {
"id": "Ne-3gnXqR0hI"
},
"execution_count": 1,
"outputs": []
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"id": "EconMHePQHGw"
},
"outputs": [],
"source": [
"import google.generativeai as genai\n",
"\n",
"from IPython.display import Markdown"
]
},
{
"cell_type": "markdown",
"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",
"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": 3,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Examples"
],
"metadata": {
"id": "yQnqEPjephXi"
}
},
{
"cell_type": "markdown",
"source": [
"### Error handling"
],
"metadata": {
"id": "bR-OOcC6pIm5"
}
},
{
"cell_type": "code",
"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)"
],
"metadata": {
"id": "kVF8ZQ38Vs1P"
},
"execution_count": 4,
"outputs": []
},
{
"cell_type": "code",
"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)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 313
},
"id": "CHTdAVE0pIFf",
"outputId": "fc459383-b51d-47b2-c315-d28736e0b733"
},
"execution_count": 5,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<IPython.core.display.Markdown object>"
],
"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"
},
"metadata": {},
"execution_count": 5
}
]
},
{
"cell_type": "markdown",
"source": [
"### Code generation"
],
"metadata": {
"id": "kTDi8WyDqQRf"
}
},
{
"cell_type": "code",
"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)"
],
"metadata": {
"id": "1T1QSzjVVvE_"
},
"execution_count": 6,
"outputs": []
},
{
"cell_type": "code",
"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)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 225
},
"id": "8KVpzExDqRj2",
"outputId": "8e45b5cb-3e8f-423c-d448-32903413977f"
},
"execution_count": 7,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<IPython.core.display.Markdown object>"
],
"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```"
},
"metadata": {},
"execution_count": 7
}
]
},
{
"cell_type": "markdown",
"source": [
"Let's check if generated code works."
],
"metadata": {
"id": "Z7X6pSdOMyvS"
}
},
{
"cell_type": "code",
"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!\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "lOU_abTPSmZu",
"outputId": "ee194082-f25d-4706-90d0-6d88346fa01d"
},
"execution_count": 8,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"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"
]
}
]
},
{
"cell_type": "markdown",
"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": {
"id": "AiGF8I290YzL"
}
}
]
}

0 comments on commit a4e768e

Please sign in to comment.