1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "LweKUTqZUn4z"
},
"source": [
"##### Copyright 2025 Google LLC."
]
},
{
"cell_type": "code",
"execution_count": 7,
"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": [
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/prompting/Basic_Code_Generation.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
]
},
{
"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": 8,
"metadata": {
"id": "Ne-3gnXqR0hI"
},
"outputs": [],
"source": [
"%pip install -U -q \"google-genai>=1.0.0\""
]
},
{
"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": 9,
"metadata": {
"id": "v-JZzORUpVR2"
},
"outputs": [],
"source": [
"from google import genai\n",
"from google.colab import userdata\n",
"\n",
"GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')\n",
"client = genai.Client(api_key=GOOGLE_API_KEY)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UsKJpRiFzrfu"
},
"source": [
"Additionally, select the model you want to use from the available options below:\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"id": "rpsJhVPezrKs"
},
"outputs": [],
"source": [
"MODEL_ID = \"gemini-3-flash-preview\" # @param [\"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-pro\", \"gemini-2.5-flash-preview\", \"gemini-3-pro-preview\"] {\"allow-input\":true, isTemplate: true}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yQnqEPjephXi"
},
"source": [
"## Examples"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bR-OOcC6pIm5"
},
"source": [
"### Error handling"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "l4ywOwlb54vw"
},
"source": [
"For code generation, you should prioritize accuracy over creativity.\n",
"A temperature of 0 ensures that the generated content is deterministic,\n",
"producing the most sensible output every time."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"id": "kVF8ZQ38Vs1P"
},
"outputs": [],
"source": [
"from google.genai import types\n",
"\n",
"error_handling_system_prompt =f\"\"\"\n",
" Your task is to explain exactly why this error occurred and how to fix it.\n",
"\"\"\"\n",
"\n",
"error_handling_model_config = types.GenerateContentConfig(\n",
" temperature=0,\n",
" system_instruction=error_handling_system_prompt\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"id": "CHTdAVE0pIFf"
},
"outputs": [
{
"data": {
"text/markdown": [
"Okay, let's break down this `IndexError: list index out of range` error.\n",
"\n",
"**What the Error Means**\n",
"\n",
"The error `IndexError: list index out of range` specifically tells you that you're trying to access an element in a list using an index (a number representing its position) that doesn't exist within that list. Think of it like trying to find a page number in a book that's beyond the total number of pages.\n",
"\n",
"**Why the Error Occurred in this Code**\n",
"\n",
"1. **`my_list = [1, 2, 3]`**: This line creates a list named `my_list` containing the numbers 1, 2, and 3.\n",
"\n",
"2. **`print(my_list[3])`**: This line attempts to print the element at index 3 of `my_list`. **Crucially, in Python (and most programming languages), list indices start at 0.**\n",
"\n",
" * Index 0 refers to the first element (which is 1).\n",
" * Index 1 refers to the second element (which is 2).\n",
" * Index 2 refers to the third element (which is 3).\n",
"\n",
" Since `my_list` only has three elements (at indices 0, 1, and 2), there is no element at index 3. Trying to access `my_list[3]` goes \"out of range\" of the valid indices, hence the error.\n",
"\n",
"**How to Fix the Error**\n",
"\n",
"The fix depends on what you *intended* to do. Here are a few possibilities and their solutions:\n",
"\n",
"1. **If you wanted to access the last element:**\n",
"\n",
" * You could use index 2 (because the list has 3 elements, and the last element is at index 2):\n",
"\n",
" ```python\n",
" my_list = [1, 2, 3]\n",
" print(my_list[2]) # Output: 3\n",
" ```\n",
"\n",
" * Alternatively, you can use negative indexing. `-1` refers to the last element, `-2` to the second-to-last, and so on:\n",
"\n",
" ```python\n",
" my_list = [1, 2, 3]\n",
" print(my_list[-1]) # Output: 3\n",
" ```\n",
"\n",
"2. **If you wanted to access an element at a specific position (e.g., the fourth element if you *thought* there were four elements):**\n",
"\n",
" * You need to make sure your list actually *has* that many elements. You would need to add more elements to the list:\n",
"\n",
" ```python\n",
" my_list = [1, 2, 3, 4] # Now the list has four elements\n",
" print(my_list[3]) # Output: 4\n",
" ```\n",
"\n",
"3. **If you're unsure how many elements are in the list:**\n",
"\n",
" * Use the `len()` function to find the number of elements and then adjust your index accordingly:\n",
"\n",
" ```python\n",
" my_list = [1, 2, 3]\n",
" list_length = len(my_list) # list_length will be 3\n",
" if list_length > 3: # Check if index 3 is valid\n",
" print(my_list[3])\n",
" else:\n",
" print(\"Index 3 is out of range for this list.\")\n",
" ```\n",
"\n",
"**In summary:** The core problem is that you're trying to access an element at an index that doesn't exist in your list. Carefully examine your code to determine the correct index you want to use or to ensure your list has the necessary number of elements. Remember that list indices start at 0.\n"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import Markdown\n",
"\n",
"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",
"\n",
"response = client.models.generate_content(\n",
" model=MODEL_ID,\n",
" contents=error_prompt,\n",
" config=error_handling_model_config\n",
")\n",
"\n",
"Markdown(response.text)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kTDi8WyDqQRf"
},
"source": [
"### Code generation"
]
},
{
"cell_type": "code",
"execution_count": 13,
"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\n",
" accomplishes a specific goal. The code snippet must be concise, efficient,\n",
" and well-commented for clarity. Consider any constraints or requirements\n",
" provided for the task.\n",
"\n",
" If the task does not specify a programming language, default to Python.\n",
"\"\"\"\n",
"\n",
"code_generation_model_config = types.GenerateContentConfig(\n",
" temperature= 0,\n",
" system_instruction=code_generation_system_prompt\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"id": "8KVpzExDqRj2"
},
"outputs": [
{
"data": {
"text/markdown": [
"```python\n",
"import time\n",
"\n",
"def countdown_timer(seconds):\n",
" \"\"\"\n",
" Counts down from a specified number of seconds and prints \"Time is up!\" when finished.\n",
"\n",
" Args:\n",
" seconds (int): The number of seconds to count down from.\n",
" \"\"\"\n",
" for i in range(seconds, 0, -1): # Iterate from seconds down to 1\n",
" print(f\"{i} seconds remaining...\")\n",
" time.sleep(1) # Pause for 1 second\n",
" print(\"Time is up!\")\n",
"\n",
"if __name__ == \"__main__\":\n",
" countdown_timer(20) # Start a 20-second countdown\n",
"```"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"code_generation_prompt = \"\"\"\n",
" Create a countdown timer that ticks down every second and prints\n",
" \"Time is up!\" after 20 seconds\n",
"\"\"\"\n",
"\n",
"response = client.models.generate_content(\n",
" model=MODEL_ID,\n",
" contents=code_generation_prompt,\n",
" config=code_generation_model_config\n",
")\n",
"Markdown(response.text)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Z7X6pSdOMyvS"
},
"source": [
"Let's check if generated code works."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"id": "lOU_abTPSmZu"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"20 seconds remaining...\n",
"19 seconds remaining...\n",
"18 seconds remaining...\n",
"17 seconds remaining...\n",
"16 seconds remaining...\n",
"15 seconds remaining...\n",
"14 seconds remaining...\n",
"13 seconds remaining...\n",
"12 seconds remaining...\n",
"11 seconds remaining...\n",
"10 seconds remaining...\n",
"9 seconds remaining...\n",
"8 seconds remaining...\n",
"7 seconds remaining...\n",
"6 seconds remaining...\n",
"5 seconds remaining...\n",
"4 seconds remaining...\n",
"3 seconds remaining...\n",
"2 seconds remaining...\n",
"1 seconds remaining...\n",
"Time is up!\n"
]
}
],
"source": [
"import re\n",
"matchFound = re.search(r\"python\\n(.*?)```\", response.text, re.DOTALL)\n",
"if matchFound:\n",
" code = matchFound.group(1)\n",
" exec(code)"
]
},
{
"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
}