Skip to content

Commit

Permalink
Add basic code generation prompting notebook
Browse files Browse the repository at this point in the history
shilpakancharla committed May 17, 2024
1 parent 02c1720 commit 414415b
Showing 1 changed file with 239 additions and 0 deletions.
239 changes: 239 additions & 0 deletions examples/prompting/Basic_Code_Generation.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"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/quickstarts/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": [
"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"
}
},
{
"cell_type": "code",
"source": [
"!pip install -U -q google-generativeai"
],
"metadata": {
"id": "Ne-3gnXqR0hI"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"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": 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": []
},
{
"cell_type": "markdown",
"source": [
"### Error handling"
],
"metadata": {
"id": "bR-OOcC6pIm5"
}
},
{
"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_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",
"\n",
"Explanation:\n",
"Explain why this error occurred. Provide insights into common causes of the error.\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",
"\n",
"Markdown(model.generate_content(error_handling).text)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 383
},
"id": "CHTdAVE0pIFf",
"outputId": "63cc0397-d0c7-4f59-cbf4-3190bd552761"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<IPython.core.display.Markdown object>"
],
"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."
},
"metadata": {},
"execution_count": 5
}
]
},
{
"cell_type": "markdown",
"source": [
"### Code generation"
],
"metadata": {
"id": "kTDi8WyDqQRf"
}
},
{
"cell_type": "code",
"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",
"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)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 329
},
"id": "8KVpzExDqRj2",
"outputId": "51b6c365-ae28-4243-f74d-1e9a88ce4de7"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<IPython.core.display.Markdown object>"
],
"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```"
},
"metadata": {},
"execution_count": 6
}
]
},
{
"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 414415b

Please sign in to comment.