Using Duet AI Throughout the Software Development Lifecycle

1. Overview

A day in the life of a Google Cloud developer typically involves the use of multiple Google Cloud products and services. These products enable the developer to develop, test, deploy, and manage applications in the cloud. With assistance from Duet AI, a developer can become more productive when using Google Cloud's products by using Duet AI's interactive chat, code assistance, and embedded integrations.

This lab uses Duet AI assistance to deploy the "Cymbal Superstore" grocery web app. You'll then develop and deploy a new feature and build the front and backend of the app. You'll also get Duet's help in writing tests for your app and see how Duet can be integrated with other Google Cloud tools.

Objectives

You'll learn how to:

  • Enhance an existing web application with help from Duet AI.
  • Deploy the application to Cloud Run.
  • Prompt Duet AI to explain an error in the application and provide a fix.
  • Develop tests for the application with help from Duet AI.
  • View application logs with help from Duet AI.

Prerequisites

  • Google Cloud Platform account and a project with billing enabled
  • Basic Linux Experience

2. Setup

This section covers everything you need to do to get started with this lab.

Create a Project

To make cleanup easier, let's create a new google cloud project.

Enable Duet AI in the Google Cloud Project

We will now enable Duet AI API in our Google Cloud Project. Follow the steps given below:

  1. Go to the dashboard of your Visit https://console.cloud.google.com and ensure that you have selected the Google Cloud Project that you plan to work with for this lab. Click on the Duet AI icon that you see in the top right.

a4d8a7253b056abb.png

  1. Duet AI chat window will open up on the right side of the console. Click on the Enable button as shown below. If you do not see the Enable button and instead see a Chat interface, it is likely that you have already enabled Duet AI for the project and you can directly go to the next step.

58296b10f18b7a37.png

  1. Once it is enabled, you can test out Duet AI by asking it a query or two. A few sample queries are shown but you can try something like "What is Cloud Run?"

8953fb4afeeddb1a.png

Duet AI will respond with the answer to your question. You can click on the _ icon on the top right corner to close the Duet AI chat window.

Enable Duet AI in Cloud Shell IDE

We will be using Cloud Shell IDE for the rest of the codelab. We need to enable and configure Duet AI in the Cloud Shell IDE and the steps are given below:

  1. Launch Cloud Shell via the icon shown below. It may take a minute or two to start up the Cloud Shell instance.

3b59c357d06c5ab1.png

  1. Click on Editor or Open Editor button (as the case might be) and wait till the Cloud Shell IDE appears. You will use the "new" editor, not the legacy editor.

a54576c01be31a97.png

  1. Click on the Cloud Code - Sign in button in the bottom status bar as shown. Authorize the plugin as instructed. If you see "Cloud Code - no project" in the status bar, select that and then select the specific Google Cloud Project from the list of projects that you plan to work with.

9b77ab79e8c135e6.png

  1. Click on the Duet AI button in the bottom right corner as shown and select the correct Google Cloud project for which we had enabled the Cloud AI Companion API.

afa42f64a331ad70.png

  1. Once you select and authorize your Google Cloud project, ensure that you are able to see that in the Cloud Code status message in the status bar and that you also have Duet AI enabled on the right, in the status bar as shown below:

11656bd6a7ddfea4.png

Duet AI is ready to use!

3. Using Duet AI

You'll be creating a web app as part of this lab. The lab points out many places to try Duet. But if you're curious, you can also take time to ask Duet anywhere in the lab.

For example, you'll use Terraform to create and deploy the basic application. If you don't know what Terraform is, you can ask Duet. If you'd like to understand what each of the steps do, Duet can explain them. Want to actually open the code and ask about specific lines? Give Duet a try.

4. Build the web app

This lab uses the "Cymbal Superstore" grocery web app. In subsequent tasks of this lab, you use Duet AI to develop and deploy a new feature in this app. Before you can see how Duet AI helps you understand existing code, you'll need some existing code to work with, so you'll build the frontend and backend components of this app now.

You will move between the Cloud Shell and the Cloud Shell Editor as you work on this project. An easy way to do this is to use the buttons at the top of the screen:

750038c738f1f405.png

Configure the environment

Execute the commands in the Cloud Shell.

  1. Set the project ID:
gcloud config set project <Google Cloud Project ID>
  1. To run the Docker credential helper, run the following command:
gcloud auth configure-docker
  1. If asked if you want to continue, type Y.
  2. To download the "Cymbal Superstore" application code, run the following command from your root directory in Cloud Shell. It will get the Cymbal Superstore code from Github.
git clone https://github.com/GoogleCloudPlatform/cymbal-superstore
  1. You'll need to enable several APIs for this code to run properly. In the Cloud Shell, enter the command below:
gcloud services enable cloudresourcemanager.googleapis.com compute.googleapis.com artifactregistry.googleapis.com serviceusage.googleapis.com run.googleapis.com bigquery.googleapis.com 
  1. Change to the Terraform directory in the code you downloaded:
cd cymbal-superstore/terraform
  1. Since this lab will not use Spanner, we'll use a version of the Terraform instructions that does not install Spanner. In the Cloud Shell, enter the command below:
mv main.tf.nospanner main.tf
  1. To save having to enter your project name and number each time you run a Terraform command, create a file named terraform.tfvars in this terraform directory. Add two lines to this file with the information below and save the file. You can find this information in the project dashboard.
project_id="Your project id"
project_number=Your project number
  1. Initialize Terraform with the line:
terraform init
  1. Finally, deploy the Terraform resources to your project using the command below. You may be prompted to type "yes" during this deployment. This may take up to 10 minutes, so you may want to take the time to examine the architecture diagram at https://github.com/GoogleCloudPlatform/cymbal-superstore/blob/main/assets/architecture.png. You could also take a look at the existing code and use Duet to help us understand it.
terraform apply

Once this command is finished successfully, you should see output similar to the following:

9c9d2378167312eb.png

  1. Update your frontend to talk to the backend inventory_cr_endpoint in your output. To do this, copy the value of your inventory_cr_endpoint, open cymbal-superstore/frontend/.env.production, and replace the value of REACT_APP_INVENTORY_URL.
  2. Re-run terraform apply. This should only take a minute, as it will redeploy your frontend React app to Cloud Storage using the updated backend URL.
  3. Open your frontend_ip in a browser. You should see the Cymbal Superstore frontend. The changes may take a few minutes to propagate, so you may need to check more than once.

b864d3efe9a26eaa.png

  1. Click New Arrivals on the left side of the Cymbal homepage. You should see a mock frontend page with placeholder products. This is expected, as you will implement the backend Inventory API code to serve the new products page in the next task of this lab.

f4d7579f73ee8ed2.png

5. Modify the web app backend

Let's now use Duet AI to add functionality to our web app backend.

In this task, you prompt Duet AI for code completion to implement the /newproducts endpoint in the app. You'll create an endpoint in the backend to retrieve the new products from Firestore and test this endpoint before deploying the change.

Develop the /newproducts endpoint

  1. Open the file cymbal-superstore/backend/index.ts in the Cloud Shell editor.
  2. In the index.ts file, scroll to the comment for DEMO TASK START, around line 95, where you see a group of lines commented out for this task. Remove all the commented lines and replace them with the following Duet AI prompt:
// Get new products from Firestore (added < 7 days ago) and quantity > 0 (in stock)
  1. To prompt Duet AI to generate the function code, select the entire comment, and then click the bulb ( Code OSS Duet AI bulb).
  2. In the More Actions menu, select Generate code.
  3. Hover over the generated code, and in the Duet AI toolbar, click Accept. Duet AI populates the function code for the /newproducts endpoint.

Note: Duet AI might generate multiple versions of the code for your prompt. You can choose a specific version by scrolling through the list in the toolbar.

  1. The generated code should be similar to the following:
app.get("/newproducts", async (req: Request, res: Response) => {
  const products = await firestore
    .collection("inventory")
    .where("timestamp", ">", new Date(Date.now() - 604800000))
    .where("quantity", ">", 0)
    .get();
  const productsArray: any[] = [];
  products.forEach((product) => {
    const p: Product = {
      id: product.id,
      name: product.data().name,
      price: product.data().price,
      quantity: product.data().quantity,
      imgfile: product.data().imgfile,
      timestamp: product.data().timestamp,
      actualdateadded: product.data().actualdateadded,
    };
    productsArray.push(p);
  });
  res.send(productsArray);
});

Many of the lines may be underlined to warn you of potential licensing problems. For this lab, you can apply a Quick Fix, but in the future, check these warnings!

  1. If your generated code does not look equivalent to the example in the previous step, you may want to replace it now or see how Duet can help debug later. There is also a version of the code with the expected error in the file scripts/solutioncode-with-bug.ts .
  2. Save the index.ts file.

Testing and debugging the /``newproducts endpoint

  1. In the Cloud Shell, move to the cymbal-superstore/backend directory. Enter the command:
npm run start

This will start the endpoint.

  1. To see the results of the endpoint, open another terminal using the + in the menu bar of the Cloud Shell and execute the command:
curl localhost:8000/newproducts

You may see the error curl: (52) Empty reply from server in the new terminal and a long error message with the details 'Cannot have inequality filters on multiple properties: [quantity, timestamp]' in the terminal running the endpoint.

  1. Let's fix that error. But first we need to understand what the error message means. To do this, we'll ask Duet. Open the Duet AI Chat from the menu on the left side of the Cloud Shell Editor and ask the following:
I'm querying Cloud Firestore and getting this error: 'Cannot have inequality filters on multiple properties: [quantity, timestamp]' What does it mean?

Duet should give you some options to fix it, including removing one of the inequality filters. To resolve, delete the line .where("quantity", ">", 0) from index.ts so that we only have one filter in our query.

  1. Repeat the first two steps above to restart the server and get the list of products. It should be successful now, but if not, use Duet to figure out the problem (or use the corrected solution in scripts/solutioncode-bug-fixed.ts to move on).

Deploying the Change

To deploy the changed application, just rerun terraform apply from the terraform directory in Cloud Shell. You can then view the app at the ip address Terraform provides.

6. Writing Tests

An important task that is often not prioritized is creating tests for the code in a project. As you might have figured out, Duet can help create these tests.

Let's create tests for the newproducts code we just created.

  1. Open backend/index.test.ts. Use Duet AI chat to generate a test for the newproducts() function with the prompt:
Help me write an Express.js test using Jest, in typescript, for the GET /newproducts handler in index.ts. Should check if the response code is 200 and the list of new products is length 8.

You'll notice it provides import lines which are already in the file. Copy just the describe() test into the file at the lines indicated. Save the file.

Alternatively, you could improve the prompt and tell Duet to not include any import statements, so you should get just the code you need.

  1. To see the results of the test, go the Cloud Shell and change the directory to the backend folder and run the command:
npm run test

7. Logging

Duet AI can help your project even after it's deployed. In this section, we'll look at logs with the help of Duet AI.

Return to the Cloud Console and make sure Duet is running. Ask Duet where to find logs. Feel free to try your own prompt, but if it doesn't give a suitable answer, the following prompt should work.

How can I view the Cloud Run logs for the service called 'inventory'?

Duet AI should suggest going to the Cloud Run page, selecting the inventory service and then examining that service's logs. You should see something like:

b7c50b67e49ee71a.png

Select one of the items and ask Duet AI to explain it. You should get a description of the entry in natural language.

You can also view Log Entries in the Logs Explorer, which you can open from the Logging option in the main menu. An advantage of viewing log entries from the Logs Explorer is that the option to explain entries is built in, as shown below:

2574adab06524ad4.png

8. Congratulations!

Congratulations - you've successfully used Duet AI to help you understand code you may never have seen before. You've enhanced this code, created tests for it, and used Duet to help understand log entries.

Cleanup

Delete Project

To cleanup, we simply delete our project.

  • In the navigation menu select IAM & Admin
  • Then click on settings in the submenu
  • Click on the trashcan icon with the text "Delete Project"
  • Follow the prompts instructions

In this lab, we've seen how to:

  • Enhance an existing web application with help from Duet AI.
  • Deploy the application to Cloud Run.
  • Prompt Duet AI to explain an error in the application and provide a fix.
  • Develop tests for the application with help from Duet AI.
  • View application logs with help from Duet AI.