Text Generation with Google Gemini

Nov 14 2024 · Python 3.12, Google Gemini, JupyterLab, Visual Studio Code

Lesson 02: Using Google Code Assist

Demo: Using Code Assist Features

Episode complete

Play next episode

Next
Transcript

Demo: Using Code Assist Features

In this demo, you’ll install Code Assist and use its features to complete, explain, and generate code, as well as create unit tests.

To get started, open Visual Studio Code. Then, click Extensions on the left, search for Gemini Code Assist + Google Cloud Code. Click Install. Allow the process to complete.

In the status bar, click Cloud Code - Sign In. Allow Cloud Code to open the external website, click Open. Sign into your Google Account.

Now that you’ve installed the Code Assist extension, the Gemini icon appears on the left. Click Gemini and then enter the following prompt:

Create Python code that contains a documented main function to demonstrate various features.

Run this prompt. You’ll get a text message Gemini Code Assist is working…. Wait for this process to complete. The AI model generates the code for you. Scroll down, and you’ll see it also explains the generated code to you!

Come back up and you’ll see an icon here to Open in a file. This opens the code in a new file on your right. Save this new file as MyFirstCodeAssist.py.

Delete the entire code except these two lines.

def main():

main()

Indent the main a little.

You declared an empty main function and called it. Now, inside the function, add:

name = "Alice"

You created a name string with “Alice” as its value. Press Enter, and on the next line, start typing print(f", and then wait. As soon as you type, Code Assist understands you want to write a print statement and suggests the rest of the line of code. Press Tab to accept the suggested code, and if you get any unwanted characters, you can delete them. Your code now looks like this print statement:

print(f"Hello, {name}!")

This code prints a formatted string with the name that you created.

Excellent! You just performed a basic code completion with Code Assist.

Next, below the print statement, add:

birthdate = datetime.date(1995, 5, 10)
age = calculate_age(birthdate)

Ignore the suggestions for now. Press Escape. With your cursor at the end of the calculate age line of code, press Command-I for Mac or Control-I for Windows or Linux. This brings the Code Assist window to the top. You’ll see an automated command /generate. Google also informs you to Use this code with caution. After this automated command, type a Space and then the prompt as:

Create the calculate_age function.

Press Enter. Once Gemini finishes its thinking process, it splits the screen into two windows and shows a diff of the old code on the left and the newly generated code on the right. At the top, you can choose to Accept or Decline the suggestion. Accept the suggestion, and it will add this newly generated code to your working file.

  print(f"You are {age} years old.")

def calculate_age(birthdate):
  today = datetime.date.today()
  age = today.year - birthdate.year
  if today.month < birthdate.month or (today.month == birthdate.month
    and today.day < birthdate.day):
    age -= 1
  return age

This function calculates the age of a person based on the birthdate parameter. Code Assist also added a print statement to print the calculated age with the right indentation. It also understood the context well and printed the variable with the variable name age that you created. How convenient!

Observe the newly added code closely. You’ll notice a couple of underlined wavy lines. These are warnings. Hover your mouse over the first warning on the birthdate line. Code Assist offers you View Problem and Quick Fix. The warning messages suggest that something is missing. At the top of this file, add:

import datetime

This imports Python’s datetime module. Code Assist gives you some more warnings. Hover over the remaining warnings, it’s actually informing you to Use code with caution, suggested code may be subject to licenses. Google gives you a source from which the model learned this code snippet. It’s warning you of any potential unknown license issues. These are some risks with AI-generated code. The good thing is that Google warns you upfront about this. This powerful feature sets Code Assist apart from other AI-assisted tools. You never want to use this code as to deploy in production. In the future, hopefully, Google may add a feature that doesn’t show code with unknown licenses. For now, since you’re only using this code for learning purposes, move on and click Run in the top-right. The messages are printed in the terminal.

Hello, Alice!

You are 29 years old.

Now, delete this AI-generated code. Delete all the code related to calculate_age and name. Also delete the import statement. At this point, your python file looks like this:

def main():

main()

So far, you’ve worked with strings. You’ll now work with integers. Inside main, using proper indentation, add:

numbers = generate_random_list(10)

Press Command-I or Control-I depending on the operating system you’re using. The Code Assist window comes on the top. After the generated automated message, type in the Space and then the prompt:

Create the generate_random_list function.

Press Enter. The AI model generates the function and a statement to print the list. Accept the suggestion:

def main():
    numbers = generate_random_list(10)
    print(numbers)

def generate_random_list(n):
    import random
    numbers = []
    for i in range(n):
        numbers.append(random.randint(1, 100))
    return numbers

main()

This code uses the random module to generate a list of 10 random numbers between 1 and 100 and prints it. Notice that you don’t get any warnings this time.

Above the print statement, add the following code to sort the list:

sorted_list = numbers.sort()

Select this line of code, and click the Gemini Code Assist extension on the left. Click Explain this.

It explains to you that numbers.sort modifies the list in place. It doesn’t return a value. Using it in this context is incorrect. It also provides two suggestions to fix this problem. Look at the second suggestion to sort the numbers in place. Replace this selected line of code with:

numbers.sort()

Now, based on Gemini’s suggestion, the code will sort the list in place. You avoided a potential issue that would otherwise go unnoticed. Now, after print(numbers) statement, add the following comment:

# Print sorted_numbers backwards

Press Control-Enter. Code Assist provides code suggestion using slicing to print the list backward. Using Control-Enter generates code suggestions inline. You can accept the suggestion by pressing tab, and it inserts them in the program. Press Esc to decline the suggestion for now.

Next, you’ll add error handling using Code Assist. Delete the print comment and add:

result = 10 / 0

Select this line of code and in the left panel click Explain this. Gemini recognizes that division by zero will raise a ZeroDivisionError in Python. It also explains to you that when the denominator in a mathematical division operation is 0, it raises a runtime exception, and you should avoid it. Next, type in the prompt:

Fix ZeroDivisionError.

Click Run. The AI-generated code shows try/ except blocks. While you’re here, also notice, the Context Sources. Code Assists uses the open files on the right as a context to work with.

Click the option to Diff with Open File. This new diff file opens on the right. Take this code and replace your result line with this newly generated code. Format it a little and your code is much cleaner now. You avoided a potential run time exception with Gemini’s help.

Lastly, you’ll use Code Assist to create something more sophisticated. In the chat panel, type the prompt:

Create unit test for generate_random_list function and then, click Run.

The AI generated unit tests to verify the total number of generated random numbers with assertEqual. It also wrote another unit test to verify the generated random numbers are between 1 and 100. Click Open in a File and Save this file as MyFirstCodeAssistUnitTests.py. Make sure you save this file in the same directory as your MyFirstCodeAssist.py.

Observe the unit tests are without any warnings. Click Run. You’ll see the successful result of the test in the terminal and a message that looks like this:

Ran 2 test in 0.000s

Well done!

You now have some hands-on experience with Gemini’s Code Assist in Visual Studio Code. You learned different ways of using the tool and avoided potential code issues. You invoked the AI-powered tool and utilized it to generate, explain, and refactor your code!

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion