Points de contrôle
Enable relevant APIs and set IAM roles.
/ 20
Create and start a Cloud Workstation.
/ 20
Deploy your app to Cloud Run.
/ 60
Develop an app with Gemini
- Overview
- Objectives
- Setup
- Task 1. Configure your environment and account
- Task 2. Create a Cloud Workstation
- Task 3. Update the Cloud Code extension to enable Gemini
- Task 4. Chat with Gemini
- Task 5. Develop a Python app
- Task 6. Enhance the Python app
- Task 7. Deploy the app to Cloud Run
- End your lab
- Congratulations!
Overview
In this lab, you use Gemini, an AI-powered collaborator in Google Cloud, to explore, create, modify, test, and deploy a sample app.
You use Cloud Workstations to create a development environment that uses Code OSS as the IDE. You use Gemini Code Assist in Cloud Code to understand code and build a sample inventory app that has two API methods. You also use Gemini to generate the steps for deploying your app to Cloud Run.
This lab is intended for developers of any experience level who contribute to building apps but might not be familiar with cloud application development. It helps to have some experience using VS Code or Code OSS as your IDE and to be familiar with Python and the Flask framework.
Objectives
In this lab, you learn how to perform the following tasks:
- Create a cloud-based application development environment by using Cloud Workstations.
- Explore various Google services that you can use to deploy an app by asking Gemini context-based questions.
- Prompt Gemini to provide templates that you can use to develop a basic app in Cloud Run.
- Create, explore, and modify the app by using Gemini to explain and generate the code.
- Run and test the app locally, and then deploy it to Google Cloud by using Gemini to generate the steps.
Setup
For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.
-
Sign in to Qwiklabs using an incognito window.
-
Note the lab's access time (for example,
1:15:00
), and make sure you can finish within that time.
There is no pause feature. You can restart if needed, but you have to start at the beginning. -
When ready, click Start lab.
-
Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.
-
Click Open Google Console.
-
Click Use another account and copy/paste credentials for this lab into the prompts.
If you use other credentials, you'll receive errors or incur charges. -
Accept the terms and skip the recovery resource page.
Activate Cloud Shell
Cloud Shell is a virtual machine that contains development tools. It offers a persistent 5-GB home directory and runs on Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources. gcloud
is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab completion.
-
Click the Activate Cloud Shell button () at the top right of the console.
-
Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are also authenticated, and the project is set to your PROJECT_ID.
Sample commands
- List the active account name:
(Output)
(Example output)
- List the project ID:
(Output)
(Example output)
Task 1. Configure your environment and account
-
Sign in to the Google Cloud console with your lab credentials, and open the Cloud Shell terminal window.
-
To set your project ID and region environment variables, in Cloud Shell, run the following commands:
PROJECT_ID=$(gcloud config get-value project) REGION={{{project_0.default_region|set at lab start}}} echo "PROJECT_ID=${PROJECT_ID}" echo "REGION=${REGION}" -
To store the signed-in Google user account in an environment variable, run the following command:
USER=$(gcloud config get-value account 2> /dev/null) echo "USER=${USER}" -
Enable the Cloud AI Companion API for Gemini:
gcloud services enable cloudaicompanion.googleapis.com --project ${PROJECT_ID} -
To use Gemini, grant the necessary IAM roles to your Google Cloud Qwiklabs user account:
gcloud projects add-iam-policy-binding ${PROJECT_ID} --member user:${USER} --role=roles/cloudaicompanion.user gcloud projects add-iam-policy-binding ${PROJECT_ID} --member user:${USER} --role=roles/serviceusage.serviceUsageViewer Adding these roles lets the user use Gemini assistance.
To verify the objective, click Check my progress.
Task 2. Create a Cloud Workstation
This lab uses Gemini assistance to develop an app with the Cloud Code plugin for Cloud Workstations IDE. Cloud Workstations is a fully managed integrated development environment that includes native integration with Gemini.
In this task, you configure and provision your Cloud Workstation environment, and you enable the Cloud Code plugin for Gemini.
View the workstation cluster
A workstation cluster named my-cluster
has been pre-created for this lab. This cluster is used to configure and create a workstation.
-
In the Google Cloud console, select the Navigation menu (), and then select View All Products > Tools > Cloud Workstations.
-
In the Navigation pane, click Cluster management.
-
Check the Status of the cluster. If the status of the cluster is
Reconciling
orUpdating
, periodically refresh and wait until it becomesReady
before moving to the next step.
Create a workstation configuration
Before creating a workstation, you must create a workstation configuration in Cloud Workstations.
-
In the Navigation pane, click Workstation configurations, and then click Create Workstation Configuration.
-
Specify the following values:
Property Value Name my-config Workstation cluster select my-cluster -
Click Create.
-
Click Refresh.
-
Check the Status of the configuration being created. If the status of the configuration is
Reconciling
orUpdating
, periodically refresh and wait until the status becomesReady
before moving to the next step.
Create a workstation
-
In the Navigation pane, click Workstations, and then click Create Workstation.
-
Specify the following values:
Property Value Name my-workstation Configuration select my-config -
Click Create.
After the workstation is created, it is listed under My workstations with a status of
Stopped
. -
To start the workstation, click Start.
As the workstation starts up, the status changes to
Starting
. Wait for the status to change toRunning
which indicates that it is ready to be used. It might take several minutes for the workstation to fully start up.
Launch the IDE
To function properly, some extensions need third-party cookies to be enabled in your browser.
-
To enable third-party cookies in Chrome, in the Chrome menu, click Settings.
-
In the search bar, type Third-party cookies.
-
Click the Third-party cookies setting, and select Allow third-party cookies.
Note: If you want to restore your browser to its current settings after the lab, note the original setting for third-party cookies.
-
To launch the Code OSS IDE on the workstation, from the Workstations page in the Google Cloud console, click Launch.
The IDE opens in a separate browser tab.
To verify the objective, click Check my progress.
Task 3. Update the Cloud Code extension to enable Gemini
In this task, you enable Gemini in Cloud Code for your Workstation IDE.
Connect to Google Cloud
To connect to Google Cloud in your workstation, perform these steps:
-
At the bottom of the window, on the status bar, click Cloud Code - Sign In.
-
When you're prompted to sign in, click Proceed to sign in.
A link is displayed in the terminal.
-
To launch the Cloud Cloud sign-in flow, press Control (for Windows and Linux) or Command (for MacOS) and click the link in the terminal.
-
If you are asked to confirm the opening of the external website, click Open.
-
Click the student email address.
-
When you're prompted to continue, click Continue.
-
To let the Google Cloud SDK access your Google Account and agree to the terms, click Allow.
Your verification code is displayed in the browser tab.
Note: You may see a warning that you ran a gcloud auth login command. This process is normal. The IDE ran this command on your behalf. -
Click Copy.
-
Back in the IDE, in the terminal, where it says Enter authorization code, paste the code.
-
If asked to approve copying from the clipboard, click Allow.
-
Click Enter, and then wait for the status bar to show Cloud Code - No Project.
You're now connected to Google Cloud.
Enable Gemini in Cloud Code
To enable Gemini in Cloud Code for your workstation IDE, perform these steps:
-
In your workstation IDE, click the menu (), and then navigate to File > Preferences > Settings.
-
On the User tab of the Settings dialog, select Extensions > Gemini Code Assist + Google Cloud Code.
-
In Search settings, enter
Gemini
. -
On the Qwiklabs lab credentials panel, to copy the Project ID, click Copy.
-
On the Cloud Code settings page, for Cloudcode > Duet AI: Project, paste the Google Cloud project ID.
Note: This setting may be specified as Cloudcode > Gemini: Project. -
Confirm that Cloud Code > Duet AI: Enable is enabled.
Note: This setting may be specified as Cloudcode > Gemini: Enable. -
In the IDE status bar, click Cloud Code - No Project.
-
Click Select a Google Cloud Project, and then click your project ID.
The project ID is now shown in the status bar. Gemini is now ready to use.
Task 4. Chat with Gemini
Gemini can help you choose the Google Cloud services that meet the requirements of your application architecture. If you want to develop and test your app in your local IDE, and then deploy it to Google Cloud, you can chat with Gemini to get help.
In this task, you use the Gemini Code Assist pane to enter prompts and view the responses from Gemini.
Prompts are questions or statements that describe the help that you need. Prompts can include context from existing code that Google Cloud analyzes to provide more useful or complete responses. For more information on writing prompts to generate good responses, see Write better prompts for Gemini in Google Cloud.
Prompt Gemini
To prompt Gemini about Google Cloud services, perform these steps:
-
To open the Gemini chat pane, in the IDE activity bar, click Gemini Code Assist ().
-
If an error occurs when trying to open the Gemini chat pane, refresh the browser window.
-
In the Gemini Code Assist pane, type the following prompt, and then click Send ():
I am new to Google Cloud and I want to use the Cloud Code extension. Give me some examples of Google services that I can use to build and deploy a sample app. Gemini responds with a list of Google Cloud services and descriptions.
In this example, assume that Gemini suggests both Cloud Run and Cloud Functions as two Google Cloud services that can help you build and deploy a sample app. You can ask for more information about those services.
-
To provide a follow-up question or prompt, in the Gemini Code Assist pane, type the text below, and then click Send:
What is the difference between Cloud Run and Cloud Functions? Gemini responds with key differences between the two Google Cloud services.
-
To reset your chat history, in the Gemini Code Assist pane, click Reset Chat ().
Note: Chat history state is kept in memory only, and doesn't persist when you switch to another workspace or when you close your IDE. Gemini doesn't use your prompts or its responses as data to train its model. For more information, see How Gemini for Google Cloud uses your data.
Task 5. Develop a Python app
Let's now use Cloud Run to create and deploy a basic Python app. Because you're new to Cloud Run and Cloud Code, you need help with the steps for creating the app.
In this task, you prompt Gemini for help to build a Hello World Python app in Cloud Run.
Get help from Gemini
-
In the Gemini Code Assist pane, to learn how to create a Cloud Run app with Cloud Code, type the following prompt, and then click Send ():
How do I create a new Cloud Run app in Cloud Code using the command palette? What languages are supported? -
In the response from Gemini, view the set of steps to create an app. Gemini also displays the supported languages for the Cloud Run app.
Note: The command palette in VS Code provides a list of all the commands, including the commands for Cloud Code.
Create a Python app by using the steps from Gemini
-
Click the menu (), and then navigate to View > Command Palette.
-
Type
Cloud Code New
, and then select Cloud Code: New Application. -
Select Cloud Run application.
-
Select Python (Flask): Cloud Run.
-
Update the name of the app and top-level folder to
/home/user/hello-world
, and then click Ok.Cloud Code downloads the template and creates the application files in the folder in your IDE.
Explore the app with Gemini
Now that you've created your Hello World
app in Cloud Run, you can use Gemini to explain the files and code snippets that are deployed in your IDE.
-
If the files are not visible, in the IDE activity bar, click Explorer ().
-
In the Explorer pane, select Dockerfile.
-
Select the entire contents of the Dockerfile, click the bulb (), and from the More Actions menu, click Gemini: Explain this.
Gemini generates a natural-language explanation about the contents and function of the
Dockerfile
. You can also select portions of the file contents, click the bulb (), and then click Gemini: Explain this. -
Select the line that begins with ENTRYPOINT, click the bulb (), and then click Gemini: Explain this.
Gemini responds with details about the ENTRYPOINT instruction. You learn that, with this instruction, Docker will run the app.py file when the container launches.
-
To view the contents of the
app.py
file, in the activity bar, click Explorer (), and then clickapp.py
. -
In the
hello()
function definition, select the lines that contain theK_SERVICE
, andK_REVISION
environment variables. Click the bulb (), then click Gemini: Explain this.Gemini responds with a detailed explanation of these two Cloud Run environment variables and how they are used in the application code.
Run the app locally
You can run your app locally from your IDE by using the Cloud Run emulator. In this case, locally means on the workstation machine.
-
In the activity bar of your IDE, click Cloud Code (), and then click Cloud Run.
Note: You will first run the app using the Cloud Run Emulator, so you won't need to enable the Cloud Run API yet. -
In the Cloud Run activity bar, click Run App on Local Cloud Run Emulator (), and then click Run.
The Output tab in the IDE displays the progress of the build.
-
When prompted at the top of the screen to Enable minikube gcp-auth addon to access Google APIs, select Yes.
When you're prompted to sign in, click Proceed to sign in.
A link is displayed in the terminal.
-
To launch the Cloud Cloud sign-in flow, press Control (for Windows and Linux) or Command (for MacOS) and click the link in the terminal.
-
If you are asked to confirm the opening of the external website, click Open.
-
Click the student email address.
-
When you're prompted to continue, click Continue.
-
To let the Google Cloud SDK access your Google Account and agree to the terms, click Allow.
Your verification code is displayed in the browser tab.
-
Click Copy.
-
Back in the IDE, in the terminal, where it says Enter authorization code, paste the code and click Enter.
Wait for the build and deploy to complete.
-
Hold the pointer over the link to the hello-world service at the localhost URL, and click Follow link.
A new tab is opened in the browser that displays a page indicating that the service is running.
Task 6. Enhance the Python app
Let's now add data and functionality to the app so that it can be used for management of inventory data.
In this task, you first add inventory data for the app.
Generate sample data using Gemini
-
In the activity bar of your IDE, click Explorer ().
-
Click New file (), and create a file named
inventory.py
. -
To let Gemini generate the sample data, open the Gemini Code Assist pane, type the following prompt, and then click Send:
Create a variable called inventory which is a list of 3 JSON objects. Each JSON object has 2 attributes: productid and onhandqty. Both attributes are strings. Gemini generates the
inventory
JSON array that contains 3 JSON objects. -
To insert the sample JSON data in the inventory.py file, in the Gemini response, click Insert in current file (). The contents of the file is similar to:
inventory = [ {"productid": "12345", "onhandqty": "100"}, {"productid": "67890", "onhandqty": "50"}, {"productid": "11122", "onhandqty": "25"} ] -
To save the
inventory.py
file in thehome/user/hello-world
folder, in the IDE menu (), click File > Save.You use this sample inventory data in the next subtask.
Add the GET /inventory list API method to the app
You now introduce API methods in the app.py
file that can operate on the inventory data. To complete this subtask, you use the code generation feature in Gemini.
-
In Explorer, open the file
app.py
. -
Modify the flask import statement to include the
inventory
file and thejsonify
library:from flask import Flask, render_template, jsonify from inventory import inventory -
In the
app.py
file, position your cursor below the app assignment statement:app = Flask(__name__) -
To let Gemini Code Assist generate the code for the first API method, in the
app.py
file, enter the following comment:# Generate an app route to display a list of inventory items in the JSON format from the inventory.py file. # Use the GET method. -
Select the comment lines, including the blank line below the comment.
-
Click the bulb (), and then select Gemini: Generate code.
Gemini generates a function for the GET operation that returns a list of items from the
inventory.py
file. The function generally looks similar to this:@app.route('/inventory', methods=['GET']) def inventory_list(): """Return a list of inventory items in JSON format.""" return jsonify(inventory) Note: To learn more about the jsonify(inventory)
function, highlight the term and prompt Gemini to explain the code to you. -
To accept the generated code, hold the pointer over any part of the generate code response, then click Accept.
Important: Gemini can generate more than one code snippet, and these snippets might differ from the snippet that is displayed above. -
If the app.route and return statements in your generated code is different from the code shown above, replace the generated code snippet with the snippet displayed above. This should ensure that the lab works as intended.
Add the GET /inventory/{productID} method to the app
Let's add another API method to return data about a specific inventory item, given its product ID. If the product ID is not found, the API returns the standard HTTP status code of 404.
-
Add a few blank lines following the `/inventory' route.
-
To let Gemini generate the code for this second API method, in the
app.py
file, enter the following comment:# Generate an App route to get a product from the list of inventory items given the productID. # Use the GET method. # If there is an invalid productID, return a 404 error with an error message in the JSON. -
Select the 3 comment lines and the blank line that follows the comment, click the bulb (), and then select Gemini: Generate code.
Gemini generates a function for the GET operation that returns the item from the inventory file whose productID is provided in the request, or the 404 status code if the product does not exist.
@app.route('/inventory/<productid>', methods=['GET']) def inventory_item(productid): """Return a single inventory item in JSON format.""" for item in inventory: if item['productid'] == productid: return jsonify(item) return jsonify({'error': 'Product not found'}), 404 -
Hold the pointer over any part of the generate code response. To accept the generated code, in the toolbar, click Accept.
-
If the generated code is different from the code shown above, replace the generated code snippet with the snippet displayed above.
Your
app.py
file should now look similar to this:""" A sample Hello World server. """ import os from flask import Flask, render_template, jsonify from inventory import inventory # pylint: disable=C0103 app = Flask(__name__) # Generate an app route to display a list of inventory items in the JSON format from the inventory.py file. # Use the GET method. @app.route('/inventory', methods=['GET']) def inventory_list(): """Return a list of inventory items in JSON format.""" return jsonify(inventory) # Generate an App route to get a product from the list of inventory items given the productID. # Use the GET method. # If there is an invalid productID, return a 404 error with an error message in the JSON. @app.route('/inventory/', methods=['GET']) def inventory_item(productid): """Return a single inventory item in JSON format.""" for item in inventory: if item['productid'] == productid: return jsonify(item) return jsonify({'error': 'Product not found'}), 404 @app.route('/') def hello(): """Return a friendly HTTP greeting.""" message = "It's running!" """Get Cloud Run environment variables.""" service = os.environ.get('K_SERVICE', 'Unknown service') revision = os.environ.get('K_REVISION', 'Unknown revision') return render_template('index.html', message=message, Service=service, Revision=revision) if __name__ == '__main__': server_port = os.environ.get('PORT', '8080') app.run(debug=False, port=server_port, host='0.0.0.0')
Rebuild and redeploy the app locally
You can run your app locally from your IDE using the Cloud Run emulator. In this case, locally means on the workstation machine.
-
In the activity bar of your IDE, click Cloud Code ().
-
In the Cloud Run activity bar, click Run App on Local Cloud Run Emulator ().
-
When prompted at the top of the screen to Enable minikube gcp-auth addon to access Google APIs, select Yes.
Wait for the build and deploy to complete.
-
Hold the pointer over the link to the hello-world service at the localhost URL, and click Follow link.
A new tab is opened in the browser that displays a page indicating that the service is running.
Test the API methods
-
Follow the steps in the earlier task to run the app locally.
-
After following the localhost URL link to view the running app in a separate browser tab, add
/inventory
to the end of the URL in the same tab and press Enter.The API returns a JSON response that contains the list of products from the
inventory.py
file. The JSON response should resemble this:[{"onhandqty":"100","productid":"12345"},{"onhandqty":"50","productid":"67890"},{"onhandqty":"25","productid":"11122"}] -
Append
/{productID}
to the URL that ends with/inventory
, where{productID}
is a product ID in your inventory.For the example above, the end of a valid URL would be
/inventory/12345
. -
Note this product ID, as it will be used in later steps.
-
Type Enter.
The API returns a JSON response that contains data about the specific product.
-
In the URL, replace the product ID with
XXXXX
and type Enter.The URL should now end with
/inventory/XXXXX
.XXXXX is not a valid product ID, so the API returns a JSON error response indicating that the product is not found.
Task 7. Deploy the app to Cloud Run
You can now deploy the app to Cloud Run on Google Cloud.
-
In the activity bar main menu (), click View > Command Palette.
-
In the command palette field, type Cloud Code Deploy, and then select Cloud Code: Deploy to Cloud Run from the list.
-
To enable the Cloud Run API for your project, click Enable API.
-
On the Service Settings page, for Region, select
. -
Leave the remaining settings as their defaults, and then click Deploy.
Cloud Code builds your image, pushes it to the registry, and deploys your service to Cloud Run. This may take a few minutes.
Note: To see the detailed logs for the deployment, click Show Detailed Logs. -
To view your running service, open the URL that is displayed in the Deploy to Cloud Run dialog.
-
Test your service by appending the
/inventory
, and/inventory/{productID}
paths to the URL, and verify the response.Note: For the product URL, use the same product ID you used before. The end of the URL should resemble /inventory/12345. To get the URL for the Cloud Run service inventory page, in Cloud Shell, run the following command:
export SVC_URL=$(gcloud run services describe hello-world \ --project {{{project_0.project_id|set at lab start}}} \ --region {{{project_0.default_region|set at lab start}}} \ --platform managed \ --format='value(status.url)') echo ${SVC_URL}/inventory
To verify the objective, click Check my progress.
End your lab
When you have completed your lab, click End Lab. Qwiklabs removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
- 1 star = Very dissatisfied
- 2 stars = Dissatisfied
- 3 stars = Neutral
- 4 stars = Satisfied
- 5 stars = Very satisfied
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Congratulations!
In this lab you learned how to:
- Explore various Google services that you can use to deploy an app by asking Gemini context-based questions.
- Prompt Gemini to provide templates that you can use to develop a basic app in Cloud Run.
- Create, explore, and modify the app by using Gemini to explain and generate the code.
- Run and test the app locally, and then deploy it to Google Cloud by using Gemini to generate the steps.
Next Steps/Learn More
- Gemini for Google Cloud overview
- Develop a Python app with Gemini for Google Cloud assistance
- Develop a Node.js app with Gemini for Google Cloud assistance
Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.