Develop an app with Duet AI assistance

This tutorial shows you how to use Duet AI, an AI-powered collaborator in Google Cloud, to explore, create, modify, test, and deploy a sample app.

For the following example, consider that you're a developer who is part of a team that's developing an inventory app. You're in charge of prototyping a basic service that contains a few API methods to operate as part of the inventory app. You want to develop the app in your local VS Code environment and then deploy it to Google Cloud. However, you're unsure about which Google Cloud service best fits your use case.

In this tutorial, you use Duet AI along with Visual Studio Code as your IDE to build a sample inventory app that has two API methods.

This tutorial is intended for developers of any experience level who have contributed to building apps but might not be familiar with cloud technologies. It assumes that you have some experience using VS Code as your IDE and that you're familiar with Python and the Flask framework.

Objectives

  • Explore various Google services that you can use to deploy an app by asking Duet AI context-based questions.

  • Prompt Duet AI to provide templates that you can use to develop a basic app in Cloud Run.

  • Create, explore, and modify the app by using Duet AI to explain and generate the code.

  • Run and test the app locally, and then deploy it to Google Cloud by using Duet AI to generate the steps.

Google Cloud products used

This tutorial uses the following billable Google Cloud products. Use the Pricing Calculator to generate a cost estimate based on your projected usage.

  • Cloud Run. Cloud Run is a managed compute platform that lets you run containers directly on top of Google's scalable infrastructure. You can deploy code written in any programming language on Cloud Run if you can build a container image from it. For pricing information, see Cloud Run.

In addition to the previously mentioned product, this tutorial also uses the following products:

  • Duet AI. Duet AI is an always-on collaborator in Google Cloud that offers generative AI-powered assistance to a wide range of users, including developers and data scientists. To provide an integrated assistance experience, Duet AI is embedded in many Google Cloud products.

  • Cloud Code for VS Code extension. This extension is an IDE plugin that provides support for the development cycle of Kubernetes and Cloud Run applications. To learn more about the Cloud Code extension, see Cloud Code for VS Code features.

Before you begin

  1. Install a local copy of VS Code, if you have not already.

  2. Install the Cloud Code extension for VS Code.

    Follow the instructions in the installation guide to install Python, Git, and the Docker client. Also follow the steps to create a Google Cloud project.

  3. Ensure that Duet AI is set up for your Google Cloud user account and project.
  4. Enable Duet AI for your IDE.

    Follow the steps to connect to Google Cloud in your IDE and to select a project that's set up for Google Cloud.

Explore Google Cloud services

If you're new to Google Cloud, Duet AI can help you choose the Google Cloud services that meet the requirements of your application architecture.

In your IDE, you can chat with Duet AI to get help. Using the Duet AI pane, you enter prompts (questions or statements that describe the help you want), and Duet AI returns responses. 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 Duet AI.

To prompt Duet AI about Google Cloud services, follow these steps:

  1. In the activity bar of your IDE, click chat_spark Duet AI.

    To locate the activity bar of VS Code, see User Interface.

  2. In the Duet AI pane, enter 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 using containers.
    

    Duet AI responds with a list of Google Cloud services and descriptions.

    In this example, assume that Duet AI suggests both Cloud Run and Cloud Functions as two Google Cloud services that can help you build and deploy a sample app, but you need more information about those services.

    Duet AI doesn't use your prompts or its responses as data to train its model. For more information, see How Duet AI in Google Cloud uses your data.

  3. Enter a follow-up question such as the following:

    What is the difference between Cloud Run and Cloud Functions? Explain to me
    in simple terms as I am new to Google Cloud.
    

    Duet AI responds with the detailed differences between the two Google Cloud services.

  4. Optional: To reset your chat history, in the Duet AI pane, click delete Reset chat.

Create a Hello World Python app

Consider that you want to 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 section, you prompt Duet AI for help to build a Hello World Python app in Cloud Run.

  1. Launch your IDE, if you haven't already.

  2. In the activity bar of your IDE, click chat_spark Duet AI.

  3. In the Duet AI pane, enter the following prompt, and then click Send:

    How to create a new Cloud Run app in Cloud Code using the command palette?
    What languages are supported?
    

    The command palette in VS Code provides a list of all the commands, including the commands for Cloud Code.

    The output is similar to the following:

    To create a new Cloud Run app in Cloud Code using the command palette,
    follow these steps:
    1. Open the command palette (press Ctrl/Cmd+Shift+P or click View > Command Palette).
    2. Run the "Cloud Code: New Cloud Run App" command.
    ...
    

    Duet AI also displays the supported languages for the Cloud Run app.

    For this example, you choose to use a Python-based Cloud Run template to create the sample app.

  4. To learn how to create a Python app from a Cloud Run template, enter the following prompt:

    How do I create a Python app from a Cloud Run template using the
    command palette? I am using Cloud Code.
    

    The output is similar to the following:

    To create a Python app from a Cloud Run template using the command palette,
    follow these steps:
    
    1. Open Cloud Code.
    
    2. Click the Command Palette
       (press Ctrl/Cmd+Shift+P or click View > Command Palette).
    
    3. Run the "Cloud Code: New Application" command.
    
    ...
    

    Complete the steps that Duet AI provides in its response to create a basic Hello World Python app in Cloud Run. You can also refer to the following section to create the Hello World Python app.

Alternative steps to create a Hello World Python app

  1. Launch your IDE if you haven't already.

  2. Open the command palette: press Command+Shift+P (for MacOS) or Control+Shift+P (For Windows and Linux).

  3. In the command palette field, enter Cloud Code: New Application, and then click the result.

  4. From the list of available samples, select Cloud Run application.

  5. From the list of available templates, select Python (Flask): Cloud Run.

  6. Save the new app in your preferred location.

A notification confirms that your app was created. A preview of the README file for your selected service opens in your IDE, as shown in figure 1:

screenshot
Figure 1 README file displayed for a Hello World Python app created in Cloud Run.

Explore the Hello World Python app

Now that you've created your Hello World app in Cloud Run, you can use Duet AI to explain the files and code snippets that are deployed in your IDE. To explore the code of the sample app that you created, follow these steps:

  1. Launch your IDE.

  2. Open Explorer: press Command+Shift+E (for MacOS) or Control+Shift+E (For Windows and Linux).

    You can see the files related to your sample app.

  3. In the list of files, click Dockerfile to display its contents.

  4. Select the entire contents of Dockerfile, click on the bulb icon, and then click Explain this, as shown in figure 2:

    screenshot of dockerfile
    Figure 2. The code explanation feature is available when you select code.

    Duet AI generates an explanation in natural language about the contents and function of Dockerfile. If you're unsure about some points within the response, you can ask follow-up questions.

  5. To learn more about the app.py file that's mentioned in Dockerfile, in the Duet AI pane, enter the following prompt:

    What is the function of the app.py file in Dockerfile?
    

    Duet AI generates a response similar to the following:

    The app.py file is the entrypoint for the container. It is the file that
    will be executed when the container is launched. In this case, the app.py
    file will run the Python code that is contained within it.
    

    Alternatively, you can also select the text app.py in Dockerfile, click on the bulb icon, and then click Explain this.

  6. Open Explorer: press Command+Shift+E (for MacOS) or Control+Shift+E (for Windows and Linux).

  7. Open the app.py file. You see two variables, K_SERVICE and K_REVISION.

  8. To learn more about the variables in the app.py file, in the Duet AI pane, enter the following prompt:

    What is the function of `K_SERVICE` and `K_REVISION` in the `app.py` file?
    

    Alternatively, you can also select the following text in Dockerfile, click on the bulb icon, and then click Explain this:

    service = os.environ.get('K_SERVICE', 'Unknown service')
    revision = os.environ.get('K_REVISION', 'Unknown revision')
    

    The response is similar to the following:

    The code above is using the os.environ module to get the values of the
    K_SERVICE and K_REVISION environment variables. These variables are set by
    Cloud Run when it deploys the service, and they contain the name of the
    service and the revision number, respectively.
    ...
    

Generate sample data for the app

You have a basic Flask app created in Cloud Run. Before you can add functionality to build the inventory app, you need a file that contains a list of sample inventory items. To use Duet AI to generate the relevant sample data, follow these steps:

  1. To display the files related to your sample app, in your IDE, click the Explorer icon.

  2. Click the New file icon and create a file called inventory.py.

  3. To let Duet AI generate the sample data, in the Duet AI pane, enter the following prompt:

    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.
    

    Duet AI generates sample code for three JSON objects.

  4. In the response, click addInsert in current file to insert the code sample in the inventory.py file, as shown in figure 3:

    insert code
    Figure 3. You can insert code from a Duet AI response.

    The inventory.py file looks similar to the following:

    inventory = [
       {
          "productid": "12345",
          "onhandqty": "10"
       },
       {
          "productid": "23456",
          "onhandqty": "20"
       },
       {
          "productid": "34567",
          "onhandqty": "30"
       }
    ]
    

    You have successfully created the inventory.py file, which includes a list of inventory items.

Modify the Hello World Python app

After you create the inventory.py file, you now introduce some API methods in the app.py file that can operate on the inventory data. To complete this objective, you can use the code generation feature in Duet AI.

  1. To display the files that are related to your sample app, in your IDE, click the Explorer icon.

  2. To display the contents, click the app.py file.

  3. Edit the import statements so that the app.py file includes the inventory.py file:

    import os
    from flask import Flask, render_template
    from inventory import inventory
    
  4. To let Duet AI generate the code for the first API method, in the app.py file, enter the following comment, and press Control+Enter:

     # Generate an app route to display a list of inventory
     # items in the JSON format from the
     # inventory.py file. Use the GET method.
    
    

    Duet AI generates a response in the app.py file.

    Depending on the system configuration, the keyboard shortcut for generating code using Duet AI might be different from the Control+Enter combination that this tutorial uses.

  5. Hold the pointer over any part of the response.

    A Duet AI toolbar is displayed.

    Duet AI might generate more than one response. In the toolbar, you can cycle through each response using the < and > keys. In the following example, Duet AI generates only one response, as shown in figure 4:

    accept code
    Figure 4. You can accept a code suggestion from Duet AI.
  6. To accept the suggested code sample, in the toolbar, click Accept.

    The output looks similar to the following:

    # 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 get_inventory():
        """Return a list of inventory items."""
        return jsonify(inventory)
    
  7. Optional: To know more about the jsonify(inventory) function, highlight the term and prompt Duet AI to explain the code to you.

  8. Edit the import statements so that the app.py file includes the jsonify function:

    import os
    from flask import Flask, render_template, jsonify
    from inventory import inventory
    
  9. To add another API method, in the app.py file, enter the following prompt, and then press Control+Enter:

    # Generate an App route to get an inventory item
    # given the productid. Use the GET method.
    # If there is an invalid productid,
    # display a 404 error.
    

    Duet AI generates a response in the app.py file.

  10. Hold the pointer over any part of the response.

    A Duet AI toolbar is displayed.

  11. To accept one of the suggested code samples, in the toolbar, click Accept.

    The output looks similar to the following:

    # Generate an App route to get an inventory item
    # given the productid. Use the GET method.
    # If there is an invalid productid,
    # display a 404 error.
    @app.route('/inventory/<productid>', methods=['GET'])
    def get_inventory_item(productid):
        """Return an inventory item given the productid."""
        for item in inventory:
            if item["productid"] == productid:
               return jsonify(item)
        return jsonify({"error": "Item not found"}), 404
    

    You have successfully added two API methods to create your inventory app.

Run the app locally from your IDE

You are ready to deploy the app locally from VS Code. To deploy the app, follow these steps:

  1. Launch your IDE, if you haven't already.

  2. In the activity bar of your IDE, click chat_spark Duet AI.

  3. In the Duet AI pane, enter the following prompt, and then click Send:

    How do I run a Cloud Run app locally within Cloud Code?
    Is there an emulator?
    

    Follow the steps in the Duet AI response to run the app locally from VS Code. You can also refer to the following section to deploy a sample Cloud Run app locally from within VS Code.

Alternative steps to run the app locally from your IDE

If you didn't follow the steps in the Duet AI response in the preceding section, you can follow these steps to deploy your sample app:

  1. Launch your IDE.

  2. Open the command palette: press Command+Shift+P (for MacOS) or Control+Shift+P (for Windows and Linux).

  3. In the command palette field, enter Run on Cloud Run Emulator, and then click the result.

  4. In the Build environment file, retain the default values and click Run.

    This tutorial uses Docker as the builder option.

    In the Output pane of your IDE, you can view the build progress. The actual deployment process might take some time to complete.

    Starting to run the app using configuration 'Cloud Run:
    Run/Debug Locally' from .vscode/launch.json...
    To view more detailed logs, go to Output channel : "Cloud Run: Run/Debug Locally - Detailed"
    Dependency check started
    Dependency check succeeded
    Starting minikube, this may take a while......
    ...
    

To view your live app, after the deployment is complete, click the URL in the Output pane. For a local copy of VS Code, if you specified localhost 8080, your sample app is live at the URL http://localhost:8080.

Test the two API methods

If your sample app is live, you can also check if your two app routes work. In this example, assume the app URL is http://localhost:8080.

  1. To view the sample landing page for your app, go to http://localhost:8080.

  2. To get a list of all the inventory items, go to http://localhost:8080/inventory.

    In the app.py file, to list all the inventory items, the function @app.route('/inventory', methods=['GET']) is used.

  3. To display a specific inventory item filtered by the productid attribute, click http://localhost:8080/inventory/productid.

    For example, http://localhost:8080/inventory/1, where productid equals 1.

    In the app.py file, to display a specific inventory item by the productid attribute, the function @app.route('/inventory/<productid>', methods=['GET']) is used.

Deploy a Cloud Run app to Google Cloud

You can now deploy the Cloud Run app to Google Cloud. You can prompt Duet AI to provide you the steps, or you can follow these steps:

  1. Open the command palette: press Command+Shift+P (for MacOS) or Control+Shift+P (for Windows and Linux).

  2. In the command palette field, enter Cloud Code: Deploy to Cloud Run, and then click the result.

  3. In the Service settings pane, set your Google Cloud project.

  4. Accept the remaining default settings, and then click Deploy.

  5. Cloud Code builds your image, pushes it to the registry, and deploys your service to Cloud Run.

  6. To view your running service, open the URL displayed in the Deploy to Cloud Run dialog.

    You can also use the same steps found in Test the two API methods to view the sample app in Google Cloud. Adjust your URLs accordingly.

Clean up

To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, you can delete the Google Cloud project that you created for this tutorial. Alternatively, you can delete the individual resources.

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

What's next