Code Review Automation with GenAI

Code Review Automation with GenAI

About this codelab

subjectLast updated Oct 7, 2024
account_circleWritten by Andrey Shakirov

1. Overview

In this lab, you will set up the CICD pipeline and integrate with Gemini to automate code review steps.

9dde56ad139b9553.png

What you will learn

In this lab, you will learn how to do the following:

  • How to add GenAI code review automation steps in GitHub, GitLab, and CircleCI
  • How to use LangChain ReAct agents and toolkits to automate tasks like commenting on GitLab issue and opening JIRA tickets

Prerequisites

  • This lab assumes familiarity with the Cloud Console and Cloud Shell environments.

2. Setup and requirements

Cloud Project setup

  1. Sign-in to the Google Cloud Console and create a new project or reuse an existing one. If you don't already have a Gmail or Google Workspace account, you must create one.

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • The Project name is the display name for this project's participants. It is a character string not used by Google APIs. You can always update it.
  • The Project ID is unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference your Project ID (typically identified as PROJECT_ID). If you don't like the generated ID, you might generate another random one. Alternatively, you can try your own, and see if it's available. It can't be changed after this step and remains for the duration of the project.
  • For your information, there is a third value, a Project Number, which some APIs use. Learn more about all three of these values in the documentation.
  1. Next, you'll need to enable billing in the Cloud Console to use Cloud resources/APIs. Running through this codelab won't cost much, if anything at all. To shut down resources to avoid incurring billing beyond this tutorial, you can delete the resources you created or delete the project. New Google Cloud users are eligible for the $300 USD Free Trial program.

Environment Setup

Open Gemini chat.

bc3c899ac8bcf488.png

Or type "Ask Gemini" in the search bar.

e1e9ad314691368a.png

Enable Cloud AI Companion API:

66cb6e561e384bbf.png

Click "Start chatting" and follow one of the sample questions or type your own prompt to try it out.

5482c153eef23126.png

Prompts to try:

  • Explain Cloud Run in 5 key points.
  • You are Google Cloud Run Product Manager, explain Cloud Run to a student in 5 short key points.
  • You are Google Cloud Run Product Manager, explain Cloud Run to a Certified Kubernetes Developer in 5 short key points.
  • You are Google Cloud Run Product Manager, explain when you would use Cloud Run versus GKE to a Senior Developer in 5 short key points.

Check out Prompt Guide to learn more about writing better prompts.

How Gemini for Google Cloud uses your data

Google's privacy commitment

Google was one of the first in the industry to publish an AI/ML privacy commitment, which outlines our belief that customers should have the highest level of security and control over their data that's stored in the cloud.

Data you submit and receive

The questions that you ask Gemini, including any input information or code that you submit to Gemini to analyze or complete, are called prompts. The answers or code completions that you receive from Gemini are called responses. Gemini doesn't use your prompts or its responses as data to train its models.

Encryption of prompts

When you submit prompts to Gemini, your data is encrypted in-transit as input to the underlying model in Gemini.

Program data generated from Gemini

Gemini is trained on first-party Google Cloud code as well as selected third-party code. You're responsible for the security, testing, and effectiveness of your code, including any code completion, generation, or analysis that Gemini offers you.

Learn more how Google handles your prompts.

3. Options to test prompts

If you would like to change/extend existing devai cli prompts, you have several options for that.

Vertex AI Studio is a part of Google Cloud's Vertex AI platform, specifically designed to simplify and accelerate the development and use of generative AI models.

Google AI Studio is a web-based tool for prototyping and experimenting with prompt engineering and the Gemini API. Sign-up for Gemini 1.5 Pro with 1M context window or learn more.

The Google Gemini web app (gemini.google.com) is a web-based tool designed to help you explore and utilize the power of Google's Gemini AI models.

4. Create Service Account

Activate Cloud Shell by clicking on the icon to the right of the search bar.

3e0c761ca41f315e.png

In the opened terminal, enable required services to use Vertex AI APIs and Gemini chat.

gcloud services enable \
    aiplatform
.googleapis.com \
    cloudaicompanion
.googleapis.com \
    cloudresourcemanager
.googleapis.com \
    secretmanager
.googleapis.com

If prompted to authorize, click "Authorize" to continue.

6356559df3eccdda.png

Run following commands to create a new service account and keys.

You will use this service account to make API calls to Vertex AI Gemini API from CICD pipelines.

PROJECT_ID=$(gcloud config get-value project)
SERVICE_ACCOUNT_NAME
='vertex-client'
DISPLAY_NAME
='Vertex Client'
KEY_FILE_NAME
='vertex-client-key'

gcloud iam service
-accounts create $SERVICE_ACCOUNT_NAME --display-name "$DISPLAY_NAME"

gcloud projects add
-iam-policy-binding $PROJECT_ID --member="serviceAccount:$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/aiplatform.admin" --condition None

gcloud projects add
-iam-policy-binding $PROJECT_ID --member="serviceAccount:$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/secretmanager.secretAccessor" --condition None

gcloud iam service
-accounts keys create $KEY_FILE_NAME.json --iam-account=$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com

5. Fork GitHub repo to your personal GitHub repo

Go to https://github.com/GoogleCloudPlatform/genai-for-developers/fork and select your GitHub userid as an owner.

Uncheck option to copy the "main" branch only.

Click "Create fork".

6. Enable GitHub Actions Workflows

Open the forked GitHub repo in the browser and switch to the "Actions" tab to enable workflows.

1cd04db9b37af7cf.png

7. Add Repository Secrets

Create a repository secret under "Settings / Secrets and variables / Actions" in the forked GitHub repository.

Add Repository secret with name "GOOGLE_API_CREDENTIALS".

94cbe2778bef25eb.png

Switch to Google Cloud Shell window/tab and run the command below in the Cloud Shell terminal.

cat ~/vertex-client-key.json

Copy the file content and paste it as a value for the secret.

915579a97f8f2ced.png

Add PROJECT_ID secret with your Qwiklabs project id as a valu 4fa92833ce615a36.png

8. Run GitHub Actions Workflow

Navigate to your GitHub repository in the browser and run the workflow.

The workflow is configured to run on code push or manual execution.

Select "GenAI For Developers" under All workflows and click "Run workflow" using "main" branch.

da11273b4b54f7b6.png

Review results:

cf49aa41980aacc5.png

Test coverage command's results:

devai review testcoverage -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

3b21bd4639524763.png

Code review command's results:

devai review code -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

4876dbc2e0042943.png

Performance review command's results:

devai review performance -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

98dd2472b2e819bf.png

Security review command's results:

devai review security -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

7d180a763db92d56.png

Blockers review command's results:

devai review blockers -c ${{ github.workspace }}/sample-app/pom.xml

726175e874aefcf.png

9. Clone the repository

Return to the Cloud Shell terminal and clone the repository.

Create a folder for the GitHub repository.

mkdir github
cd github

Change YOUR-GITHUB-USERID to your GitHub userid before running the commands.

Set Git user name and email in the terminal.

Update the values before running the commands.

git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"
git clone https://github.com/YOUR-GITHUB-USERID/genai-for-developers.git 

Change folder and open workflow file in the Cloud Shell Editor.

cd genai-for-developers

cloudshell edit
.github/workflows/devai-review.yml

Wait until the config file is displayed in the IDE.

9e81e5a79d421eac.png

10. Enable Gemini Code Assist

Click on the "Gemini" icon in the bottom right corner 7c891e32c055c0e4.png,

click "Login to Google Cloud" and "Select a Google Cloud Project".

f5318f22c91ecaa8.png

6b7203ffdd8485fa.png

fb8d42a6bc8a260f.png

From the popup window, select your Qwiklabs project.

f661047956a6d6f9.png

11. Explain code with Gemini Code Assist

Right click anywhere in the devai-review.yml file and select Gemini Code Assist > Explain this.

41fb7da002bdf43.png

Review explanation:

7724d52e54918c00.png

12. Run DEVAI CLI locally

Go back to Cloud Shell Editor and open a new Terminal.

149218baaf30865f.png

Go back to Cloud Shell terminal and run commands below to install devai locally.

pip3 install devai-cli

The cli was installed but it's not in the PATH.

WARNING: The script devai is installed in '/home/student_00_478dfeb8df15/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Run the command below to update the PATH environment variable. Replace with your user's home folder name. For example: student_00_478dfeb8df15

export PATH=$PATH:/home/YOUR-USER-HOME-FOLDER/.local/bin

Run devai cli command to perform code review locally. Review cli output.

export PROJECT_ID=$(gcloud config get-value project)
export LOCATION=us-central1

cd ~/github/genai-for-developers

devai review code -c ./sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

Open review script by running command below:

cloudshell edit devai-cli/src/devai/commands/review.py

Right click anywhere in the review.py file and select Gemini Code Assist > Explain this.

Review explanation.

30e3baf4c272c8ab.png

13. DevAI CLI Development

In this section you will be making changes to devai cli.

To start, set up python virtualenv, install requirements and run the sample command.

cd ~/github/genai-for-developers/devai-cli
python3
-m venv venv
. venv/bin/activate
pip3 install
-r src/requirements.txt
pip3 install
--editable ./src
devai echo

Run test coverage review command to check that everything is working fine:

devai review testcoverage -c ~/github/genai-for-developers/sample-app/src

Review results using Markdown preview in Cloud Shell Editor.

Create a new file and paste the Gemini's response.

Then use Command Palette and select "Markdown: Open Preview".

ec6fedf4b6d3fb73.png

9999e7fbb20cf251.png

76858be03d73abd0.png

14. Explore devai cli commands

Code review command

devai review code -c ~/github/genai-for-developers/sample-app/src/main/java

Performance review command

devai review performance -c ~/github/genai-for-developers/sample-app/src/main/java

Security review command

devai review security -c ~/github/genai-for-developers/sample-app/src/main/java

Test coverage review command

devai review testcoverage -c ~/github/genai-for-developers/sample-app/src

Blockers review commands

devai review blockers -c ~/github/genai-for-developers/sample-app/pom.xml
devai review blockers -c ~/github/genai-for-developers/sample-app/setup.md

Image/Diagram review and summarization:

Input diagram[~/github/genai-for-developers/images/extension-diagram.png]:

4b109a74e1aa3fb6.png

Review command:

devai review image \
 
-f ~/github/genai-for-developers/images/extension-diagram.png \
 
-p "Review and summarize this diagram"

Output:

The diagram outlines a process for conducting local code reviews using a VS Code extension or CLI, leveraging Google Cloud's Vertex AI (Gemini Pro) for generating review prompts. 

**Process Flow:**

1. **Code Style Check:** Developers initiate the process by checking their code for adherence to pre-defined style guidelines.
2. **Prompt Generation:** The VS Code extension/CLI sends the code to Vertex AI (Gemini Pro) on Google Cloud. 
3. **Vertex AI Review:** Vertex AI analyzes the code and generates relevant review prompts.
4. **Local Review:** The prompts are sent back to the developer's IDE for their consideration.
5. **Optional Actions:** Developers can optionally: 
    - Create new JIRA issues directly from the IDE based on the review prompts.
    - Generate new issues in a GitLab repository.

**Key Components:**

* **VS Code Extension/CLI:** Tools facilitating the interaction with Vertex AI and potential integrations with JIRA and GitLab.
* **Vertex AI (Gemini Pro):** Google Cloud's generative AI service responsible for understanding the code and generating meaningful review prompts.
* **Google Cloud Secret Manager:** Securely stores API keys and access tokens required to authenticate and interact with Google Cloud services.
* **JIRA/GitLab (Optional):** Issue tracking and project management tools that can be integrated for a streamlined workflow.

**Benefits:**

* **Automated Review Assistance:** Leveraging AI to generate review prompts saves time and improves the consistency and quality of code reviews. 
* **Local Development:** The process empowers developers to conduct reviews locally within their familiar IDE.
* **Integration Options:** The flexibility to integrate with project management tools like JIRA and GitLab streamlines workflow and issue tracking.

Image diff analysis:

devai review imgdiff \
 
-c ~/github/genai-for-developers/images/devai-api.png \
 
-t ~/github/genai-for-developers/images/devai-api-slack.png

Output:

The following UI elements are missing in the "AFTER UPGRADE STATE" image compared to the "BEFORE UPGRADE STATE" image:

1. **Slack:** The entire Slack element, including the icon, "Team channel" label, and the arrow indicating interaction, is absent in the AFTER UPGRADE image. 
2. **Storage Bucket:** The "Storage Bucket" element with its icon and "PDFs" label is missing in the AFTER UPGRADE image. 
3. **"GenAI Agents" label in Vertex AI block:** The BEFORE UPGRADE image has "Vertex AI Agents" and "GenAI Agent" labels within the Vertex AI block, while the AFTER UPGRADE image only has "Vertex AI."
4. **"Open JIRA Issue" and "Team Project" labels:** In the BEFORE UPGRADE image, these labels are connected to the JIRA block with an arrow. These are missing in the AFTER UPGRADE image.

**Decision Explanation:**

The analysis is based on a direct visual comparison of the two provided images, noting the presence and absence of specific UI elements and their associated labels. The elements listed above are present in the BEFORE UPGRADE image but absent in the AFTER UPGRADE image.

Documentation generation command:

devai document readme -c ~/github/genai-for-developers/sample-app/src/main/

Output:

# Bank of Anthos - Balance Reader Service

## Table of Contents
- [Description](#description)
- [Features](#features)
- [Technologies Used](#technologies-used)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [Health Checks](#health-checks)
- [Metrics and Tracing](#metrics-and-tracing)
- [Contributing](#contributing)
- [License](#license)

## Description

The Balance Reader service is a component of the Bank of Anthos sample application. It provides a REST endpoint for retrieving the current balance of a user account. This service demonstrates key concepts for building microservices with Spring Boot and deploying them to a Kubernetes cluster.

## Features

- Securely retrieves account balances using JWT authentication.
- Leverages a local cache for fast balance retrieval.
- Asynchronously processes transactions from a central ledger.
- Provides health check endpoints for Kubernetes liveness and readiness probes.
- Exposes metrics to Stackdriver for monitoring and observability.
- Supports distributed tracing with Zipkin.

## Technologies Used

- Java
- Spring Boot
- Spring Data JPA
- Hibernate
- Google Cloud SQL (PostgreSQL)
- JWT (JSON Web Token)
- Guava Cache
- Micrometer
- Stackdriver
- Zipkin

## Installation

1. **Prerequisites:**
   - Java 17 or later
   - Maven 3.5 or later
   - Docker (for containerization)
   - Kubernetes cluster (for deployment)
   - Google Cloud account (for Stackdriver and other GCP services)

Review available devai cli commands in the Cloud Shell Editor:

cloudshell edit ~/github/genai-for-developers/devai-cli/README.md

Or review README.md in the GitHub repository.

15. Keep track of all environment variables in a file

Start a new file to keep track of all environment variables (e.g. API keys, API tokens, etc.) you will be creating.

You will use them for different systems many times as you go through the lab, so it will be easier to reference them in one place.

16. LangSmith LLM tracing configuration

Create a LangSmith account and generate a Service API key in the Settings section. https://docs.smith.langchain.com/

Set environment variables required for LangSmith integration. Replace Service API key before running the commands.

export LANGCHAIN_API_KEY=langsmith-service-api-key

export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"

To avoid exposing sensitive information in the terminal, the best practice is to use read -s this is a secure way to set environment variables without value showing up in the console's command history. After running it, you have to paste the value and hit enter.

17. JIRA command configuration

Create a JIRA account, if you do not have one.

Create a JIRA API token for your project. https://id.atlassian.com/manage-profile/security/api-tokens

Set these environment variables required for JIRA integration (replace the values before running the commands).

export JIRA_API_TOKEN=your-token-value
export JIRA_USERNAME="email that you used to register with JIRA"
export JIRA_INSTANCE_URL="https://YOUR-PROJECT.atlassian.net"
export JIRA_PROJECT_KEY="JIRA project key"
export JIRA_CLOUD=true

Open review.py file:

cloudshell edit ~/github/genai-for-developers/devai-cli/src/devai/commands/review.py

Review review.py file:

    source=source.format(format_files_as_string(context))

    code_chat_model = GenerativeModel(model_name)
    code_chat = code_chat_model.start_chat()
    code_chat.send_message(qry)
    response = code_chat.send_message(source)
    ...
    else:
        click.echo(response.text) 

Find and uncomment line below this one:

# Uncomment after configuring JIRA and GitLab env variables - see README.md for details

Import JIRA command at the top of the file

# from devai.commands.jira import create_jira_issue

Method to create JIRA issue in the code method

#create_jira_issue("Code Review Results", response.text)

Re-run code review command and check agent's output:

export PROJECT_ID=$(gcloud config get-value project)
export LOCATION=us-central1

devai review code -c ~/github/genai-for-developers/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

Sample output:

(venv) student_00_19a997c157f8@cloudshell:~/genai-for-developers/devai-cli (qwiklabs-gcp-02-71a9948ae110)$ devai review code -c ../sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
/home/student_00_19a997c157f8/genai-for-developers/devai-cli/venv/lib/python3.9/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `initialize_agent` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. instead.
  warn_deprecated(
Response from Model: ```java
// Class: TransactionRepository
// Method: findBalance

// Efficiency
- Consider using a native SQL query to improve performance for complex database operations.
- Use prepared statements to avoid SQL injection vulnerabilities.

// Best Practices
- Return a Optional<Long> instead of null to handle the case when no balance is found for the given account.

/home/student_00_19a997c157f8/genai-for-developers/devai-cli/venv/lib/python3.9/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function __call__ was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead. warn_deprecated(

Entering new AgentExecutor chain... Thought: The description is provided in the question so there is nothing to think about Action:

{
 
"action": "create_issue",
 
"action_input": {
   
"description": "Class: TransactionRepository\nMethod: findBalance\n\nEfficiency\n- Consider using a native SQL query to improve performance for complex database operations.\n- Use prepared statements to avoid SQL injection vulnerabilities.\n\nBest Practices\n- Return a Optional<Long> instead of null to handle the case when no balance is found for the given account."
 
}
}

New issue created with key: CYMEATS-117

Observation: New issue created with key: CYMEATS-117 Thought:Final Answer: CYMEATS-117

Finished chain.

Open your JIRA project in the browser and review the created issue.

Sample JIRA issue view.

<img src="img/9a93a958c30f0b51.png" alt="9a93a958c30f0b51.png"  width="624.00" />

Open  [LangSmith portal](https://smith.langchain.com/) and review LLM trace for JIRA issue creation call.

Sample LangSmith LLM trace.

<img src="img/6222ee1653a5ea54.png" alt="6222ee1653a5ea54.png"  width="624.00" />


## Import GitHub repo to GitLab repo



Go to  [https://gitlab.com/projects/new](https://gitlab.com/projects/new) and select "`Import project`" / "`Repository by URL`" option:

Git repository url:

https://github.com/GoogleCloudPlatform/genai-for-developers.git

Or

Your personal GitHub project that you created earlier in this lab.

Under Project URL - select your GitLab userid

Set Visibility to `Public`.

Click - "`Create Project`" to start the import process.

If you see an error about invalid GitHub Repository URL,  [create a new GitHub token](https://github.com/settings/tokens)(fine-grained) with Public repositories read-only access, and retry import again providing your GitHub userid and token.


## Clone GitLab repo and setup SSH key



Return to Google Cloud Shell terminal and set up a new SSH key.

Update your email before running the commands. Hit enter multiple times to accept defaults.

ssh-keygen -t ed25519 -C "your-email-address"

eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519

cat ~/.ssh/id_ed25519.pub

Add a public key to your GitLab account.

Open  [https://gitlab.com/-/profile/keys](https://gitlab.com/-/profile/keys) and click "Add new key".

For the key value copy/paste the output of the last command.

Go back to the terminal and clone the repository.

cd ~ mkdir gitlab cd gitlab

Replace with your GitLab userid and repository url that was just created.

```console
git clone git@gitlab.com:YOUR_GITLAB_USERID/genai-for-developers.git

Change directory and open .gitlab-ci.yml file.

cd genai-for-developers

cloudshell edit
.gitlab-ci.yml

In case you didn't do it previously, enable Gemini in the Cloud Shell Editor.

4a7f4640f66037f.png

Right click anywhere in the .gitlab-ci.yml file and select "Gemini Code Assist > Explain this".

154838a0100389a9.png

18. GitLab command configuration

Open GitLab and create a Project Access Token under "Settings / Access Tokens" in the GitLab repository that was created in the previous steps.

Copy and store the Access Token value to be used in the next steps.

Use following details:

  • Token name: devai-cli-qwiklabs
  • Role: Maintainer
  • Scope: api

1865de233277f11c.png

Set environment variables required for GitLab integration.

This command requires you to update your GitLab Access Token.

export GITLAB_PERSONAL_ACCESS_TOKEN=gitlab-access-token

This command requires you to update your GitLab userid and repository name.

export GITLAB_REPOSITORY="USERID/REPOSITORY"

Set rest of the environment variables:

export GITLAB_URL="https://gitlab.com"
export GITLAB_BRANCH="devai"
export GITLAB_BASE_BRANCH="main"

Open the GitLab website and create a new GitLab issue in your project with the title "CICD AI Insights".

63a13948f6864074.png

Another option is to use the curl command below. You will need a GitLab project id - you can look it up under the "Settings / General" section.

export GITLAB_PROJECT_ID=56390153 # replace

curl --request POST \
  --header "PRIVATE-TOKEN: $GITLAB_PERSONAL_ACCESS_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{"title":"CICD AI Insights"}' \
  https://gitlab.com/api/v4/projects/$GITLAB_PROJECT_ID/issues

Go back to Cloud Shell and open review.py file:

cloudshell edit ~/gitlab/genai-for-developers/devai-cli/src/devai/commands/review.py

Find and uncomment code below

Line to import GitLab command

# from devai.commands.gitlab import create_gitlab_issue_comment

Method to comment on GitLab issue

# create_gitlab_issue_comment(response.text)

19. DevAI CLI development

Since you switched to the GitLab repo/directory. You will need to re-run the setup steps below.

In the terminal, set up your python virtualenv, install requirements and run the sample command.

export PROJECT_ID=$(gcloud config get-value project)
export LOCATION=us-central1

cd ~/gitlab/genai-for-developers/devai-cli
python3 -m venv venv
. venv/bin/activate
pip3 install -r src/requirements.txt
pip3 install --editable ./src
devai echo

You can confirm the location of cli - this time it should be located under the GitLab folder.

 which devai

Re-run code review command in the terminal:

devai review code -c ~/gitlab/genai-for-developers/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

Sample output - with some sections shortened:

(venv) student_00_19a997c157f8@cloudshell:~/genai-for-developers/devai-cli (qwiklabs-gcp-02-71a9948ae110)$ devai review code -c ../sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
.
.
Response from Model: **Class: Transaction**

**Method: toString**

**Maintainability:**

* The formatting of the string representation could be more clear and concise. Consider using a dedicated method for formatting the amount, e.g., `formatAmount()`.
.
.

> Entering new AgentExecutor chain...
Thought: I need to first get the issue ID using the Get Issues tool, then I can comment on the issue using the Comment on Issue tool.
Action: Get Issues
Action Input: 
Observation: Found 1 issues:
[{'title': 'CICD AI Insights', 'number': 1}]
Thought:Thought: I found the issue ID, so now I can add the comment to the issue.
Action: Comment on Issue
Action Input: 1


Action: Get Issue
Action Input: 1
Observation: {"title": "CICD AI Insights", "body": "", "comments": "[{'body': '**Transaction.java**\\n\\n\\n**Class:** Transaction\\n\\n\\n* **Security:** Consider using a custom date format like \\\\\"yyyy-MM-dd HH:mm:ss.SSS\\\\\" to handle timestamps more robustly.\\n\\n\\n**JWTVerifierGenerator.java**\\n\\n\\n* .
.
Thought:Now I can use the Comment on Issue tool to add the comment to the issue.

Action: Comment on Issue
Action Input: 
1

**Class: Transaction**

**Method: toString**

**Maintainability:**
.
.
.
Observation: Commented on issue 1
Thought:I have now completed the necessary actions and added the comment to the issue 'CICD AI Insights'.

Final Answer: Comment added to issue 'CICD AI Insights'

> Finished chain.

Open the GitLab website and review the updated issue.

9da39bf6070d9447.png

Review LLM trace in LangSmith.

Sample LLM trace.

f32eed34f3a3b040.png

20. Push changes to GitLab repository

Go back to Google Cloud Shell Editor.

Switch to the "Source Control" tab.

Stage, commit and push the changes you made to update the review.py file.

b838a11f362454ce.png

21. GitLab CICD configuration

Next you are going to enable the GitLab CICD pipeline to run code review when changes are pushed to the repository.

Open the GitLab website and navigate to the "Settings / CICD" section.

Expand the Variables section and click "Add variable".

Make sure to uncheck all the checkboxes when you add the variables. Example:

68b3ed732b6a8fe9.png

Using your notes, where you are keeping all environment variables, add environment variables for JIRA, GitLab and LangSmith.

PROJECT_ID=qwiklabs-project-id
LOCATION=us-central1
GOOGLE_CLOUD_CREDENTIALS - cat ~/vertex-client-key.json

LANGCHAIN_TRACING_V2=true
LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
LANGCHAIN_API_KEY=your-service-api-key

JIRA_API_TOKEN=your-token
JIRA_USERNAME="email that you used to register with JIRA"
JIRA_INSTANCE_URL="https://YOUR-PROJECT.atlassian.net"
JIRA_PROJECT_KEY="JIRA project key"
JIRA_CLOUD=true

GITLAB_PERSONAL_ACCESS_TOKEN=your-gitlab-token
GITLAB_URL="https://gitlab.com"
GITLAB_REPOSITORY="USERID/REPOSITORY"
GITLAB_BRANCH="devai"
GITLAB_BASE_BRANCH="main"

For GOOGLE_CLOUD_CREDENTIALS variable value, use the service account key created in section above.

cat ~/vertex-client-key.json

CI/CD Variables view:

2f4594ce72be4834.png

22. Run GitLab CICD pipeline

Open "Build / Pipelines" in the GitLab UI and click "Run Pipeline".

a7518e37dde42366.png

23. Review GitLab pipeline output

Open "Build / Jobs" in the GitLab UI and review the pipeline output.

985e4b322fb73b1c.png

Open the GitLab website and review the updated comments on the "CICD Insights" issue.

Disable GitLab workflow execution

Go back to Google Cloud Shell Editor. Uncomment the lines to disable GitLab workflow execution on code push events. You can still execute the workflow from UI on demand.

# workflow:
#   rules:
#     - if: $CI_PIPELINE_SOURCE == "web"

Open .gitlab-ci.yml in the root of the project and uncomment the lines:

cloudshell edit ~/gitlab/genai-for-developers/.gitlab-ci.yml

Switch to the "Source Control" tab - stage, commit and push this change.

a9d52beb8c642982.png

24. CircleCI integration

What is CircleCI?

CircleCI is a cloud-based CI/CD platform that allows teams to automate their software development and deployment processes. It integrates with version control systems like GitHub, Bitbucket, and GitLab, allowing teams to validate code changes in real-time by running automated tests and builds. For continuous delivery, CircleCI can automate the deployment of software to various cloud environments like AWS, Google Cloud, and Azure.

Setup

Open CircleCI website and create a new Project. Select "GitLab" / "Cloud" for your repo.

Grant CircleCI access to your GitLab account.

Under the Fastest option, select the main branch. CircleCI might detect an existing config file and skip this step.

4e9b7cef458d5fba.png

After the project is created, click on the "Project Settings" / "Environment Variables" section.

1499b5f96ac0fe5e.png

Add all the environment variables that you used so far.

f15b7a3e02c649e8.png

Here's a sample list of env vars to add.

PROJECT_ID=qwiklabs-project-id
LOCATION=us-central1
GOOGLE_CLOUD_CREDENTIALS - cat ~/vertex-client-key.json

LANGCHAIN_TRACING_V2=true
LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
LANGCHAIN_API_KEY=your-service-api-key

JIRA_API_TOKEN=your-token
JIRA_USERNAME="email that you used to register with JIRA"
JIRA_INSTANCE_URL="https://YOUR-PROJECT.atlassian.net"
JIRA_PROJECT_KEY="JIRA project key"
JIRA_CLOUD=true

GITLAB_PERSONAL_ACCESS_TOKEN=your-gitlab-token
GITLAB_URL="https://gitlab.com"
GITLAB_REPOSITORY="USERID/REPOSITORY"
GITLAB_BRANCH="devai"
GITLAB_BASE_BRANCH="main"

25. Enable JIRA and GitLab methods

Open Google Cloud Shell Editor and make a change to review.py file.

Find and uncomment lines below.

# from devai.commands.jira import create_jira_issue
create_jira_issue("Performance Review Results", response.text)
create_gitlab_issue_comment(response.text)
.
.
.
create_jira_issue("Security Review Results", response.text)
create_gitlab_issue_comment(response.text)

Switch to the "Source Control" tab - stage, commit and push this change.

Open the GitLab website and go to "Build" / "Pipelines".

d196ad631be17b88.png

Follow the link to CircleCI to review the workflow.

d4ff287694b82445.png

Review comments on the GitLab issue in your repository.

e77ee826488d5299.png

9a51daa2960994e3.png

Review new issues created in your JIRA project.

1e6305a32aaef6a2.png

26. Congratulations!

Congratulations, you finished the lab!

What we've covered:

  • Adding GenAI code review automation steps in GitHub, GitLab, and CircleCI.
  • LangChain ReAct agents to automate tasks like commenting on GitLab issue and opening JIRA tickets.

What's next:

  • More hands-on sessions are coming!

Clean up

To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.

Deleting the project

The easiest way to eliminate billing is to delete the project that you created for the tutorial.

©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.