GitLab - 利用生成式 AI 实现代码审核自动化

1. 概览

在本实验中,您将设置 GitLab CICD 流水线并将其与 Gemini 集成,以自动执行代码审核步骤。

e6923862de67e3f5.png

学习内容

在本实验中,您将学习如何完成以下操作:

  • 如何在 GitLab 中添加生成式 AI 代码审核自动化步骤
  • 如何在本地运行 devai CLI 以自动执行代码审核

前提条件

  • 本实验假设您熟悉 Cloud 控制台和 Cloud Shell 环境。

2. 设置和要求

Cloud 项目设置

  1. 登录 Google Cloud 控制台,然后创建一个新项目或重复使用现有项目。如果您还没有 Gmail 或 Google Workspace 账号,则必须创建一个。

fbef9caa1602edd0.pnga99b7ace416376c4.png5e3ff691252acf41.png

  • 项目名称是此项目参与者的显示名称。它是 Google API 尚未使用的字符串。您可以随时对其进行更新。
  • 项目 ID 在所有 Google Cloud 项目中是唯一的,并且是不可变的(一经设置便无法更改)。Cloud 控制台会自动生成一个唯一字符串;通常情况下,您无需关注该字符串。在大多数 Codelab 中,您都需要引用项目 ID(通常用 PROJECT_ID 标识)。如果您不喜欢生成的 ID,可以再随机生成一个 ID。或者,您也可以尝试自己的项目 ID,看看是否可用。完成此步骤后便无法更改该 ID,并且此 ID 在项目期间会一直保留。
  • 此外,还有第三个值,即部分 API 使用的项目编号,供您参考。如需详细了解所有这三个值,请参阅文档。
  1. 接下来,您需要在 Cloud 控制台中启用结算功能,以便使用 Cloud 资源/API。运行此 Codelab 应该不会产生太多的费用(如果有的话)。若要关闭资源以避免产生超出本教程范围的结算费用,您可以删除自己创建的资源或删除项目。Google Cloud 新用户符合参与 300 美元免费试用计划的条件。

环境设置

打开 Gemini 对话。

bc3c899ac8bcf488.png

或者在搜索栏中输入“问问 Gemini”。

e1e9ad314691368a.png

启用 Gemini for Google Cloud API:

990a0ceea7d05531.png

点击“Start chatting”,然后按照其中一个示例问题操作,或输入您自己的提示来试用该功能。

ed120d672468b412.png

建议尝试的提示:

  • 用 5 个要点说明 Cloud Run。
  • 您是 Google Cloud Run 产品经理,请用 5 个简短的要点向学生介绍 Cloud Run。
  • 您是 Google Cloud Run 产品经理,请用 5 个简短的关键点向一位经过认证的 Kubernetes 开发者介绍 Cloud Run。
  • 您是 Google Cloud Run 产品经理,请用 5 个简短的关键点向一位高级开发者说明何时应使用 Cloud Run 而不是 GKE。

如需详细了解如何撰写更好的提示,请参阅提示指南。

Gemini for Google Cloud 如何使用您的数据

Google 的隐私保护承诺

Google 是业界首家发布 AI/机器学习隐私权承诺的公司之一,该承诺概述了客户应拥有最高级别安全性并能够控制其在云中存储的数据的这一信念。

您提交和接收的数据

您向 Gemini 提出的问题(包括您提交给 Gemini 以进行分析或完成的任何输入信息或代码)称为“提示”。您从 Gemini 收到的答案或代码补全结果称为“回答”。Gemini 不会将您的提示或其回答用作训练模型的数据。

提示的加密

当您向 Gemini 提交提示时,您的数据会在传输过程中加密,然后作为输入数据传送到 Gemini 中的底层模型。

通过 Gemini 生成的节目数据

Gemini 使用第一方 Google Cloud 代码以及所选第三方代码进行训练。您需要对代码的安全性、测试和有效性负责,包括 Gemini 为您提供的任何代码补全、生成或分析。

详细了解 Google 如何处理您的提示。

3. 测试提示的选项

如果您想更改/扩展现有的 devai CLI 提示,有多种方法可供选择。

Vertex AI Studio 是 Google Cloud 的 Vertex AI 平台的一部分,专门用于简化和加速生成式 AI 模型的开发和使用。

Google AI Studio 是一款基于 Web 的工具,可用于进行提示工程和 Gemini API 原型设计和实验。

Google Gemini Web 应用 (gemini.google.com) 是一款基于 Web 的工具,旨在帮助您探索和利用 Google Gemini AI 模型的强大功能。

4. 创建服务账号

点击搜索栏右侧的图标,激活 Cloud Shell。

3e0c761ca41f315e.png

在打开的终端中,启用使用 Vertex AI API 和 Gemini Chat 所需的服务。

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

如果系统提示您进行授权,请点击“授权”继续。

6356559df3eccdda.png

运行以下命令以创建新的服务账号和密钥。

您将使用此服务账号从 CICD 流水线向 Vertex AI Gemini API 发出 API 调用。

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. 将 GitHub 代码库导入到 GitLab 代码库

前往 https://gitlab.com/projects/new,然后选择“Import project”/“Repository by URL”选项:

Git 代码库网址:

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

在“项目网址”下,选择您的 GitLab 用户 ID

将公开范围设置为 Public。

点击“Create Project”即可开始导入流程。

如果您看到有关 GitHub 代码库网址无效的错误,请创建新的 GitHub 令牌(精细),并授予对公共代码库的只读访问权限,然后再次尝试导入,并提供您的 GitHub 用户 ID 和令牌。

6. 添加 GitLab CICD 流水线变量

接下来,您将启用 GitLab CICD 流水线,以便在将更改推送到代码库时运行代码审核。

在浏览器中打开 GitLab 代码库,然后前往“Settings / CICD"”部分。

展开 Variables 部分,然后点击“Add variable”。

添加新变量时,请务必取消选中所有复选框。

示例:

5644cec84e7303c3.png

添加 3 个变量:

  • PROJECT_ID - 您的 Qwiklabs 项目 ID
  • LOCATION - us-central1
  • GOOGLE_CLOUD_CREDENTIALS

对于 GOOGLE_CLOUD_CREDENTIALS 变量值,请使用上文中创建的服务账号密钥。在 Google Cloud Shell 中运行此命令,然后复制/粘贴相应值。

cat ~/vertex-client-key.json

CI/CD 变量视图:

2f4594ce72be4834.png

7. 运行 GitLab CI/CD 流水线

在 GitLab 界面中打开“Build / Pipelines”,然后点击“Run Pipeline”。

a7518e37dde42366.png

8. 查看 GitLab 流水线输出

在 GitLab 界面中打开“Build / Jobs”,然后查看流水线输出。

985e4b322fb73b1c.png

流水线命令概览

GitLab 流水线配置:.gitlab-ci.yml

测试覆盖率命令:

devai review testcoverage -c ./sample-app/src

此 devai review testcoverage 命令使用生成式 AI 模型 Gemini 分析代码及其关联的测试套件(如果有)。它会评估所提供代码的测试覆盖率,识别有和没有单元测试的文件和方法。然后,该命令会利用模型提供覆盖率摘要,包括覆盖的行数和分支/条件数等指标。根据分析结果,它会提供有关如何提高测试覆盖率的建议,包括建议添加哪些具体测试,以及提供有关测试最佳实践的一般建议。最后,它会通过命令行向用户输出 Gemini 模型的回答,其中包括缺少覆盖率的文件等详细信息,以及有关如何改进现有测试的建议。

代码审核命令:

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

devai review code 命令使用生成式 AI 模型对提供的代码段进行全面的代码审核。它将待审核的代码作为输入(上下文),并将输出格式偏好作为输出。它利用大语言模型分析代码的正确性、效率、可维护性、安全性以及是否遵循最佳实践。该命令会构建一个详细的提示,指示 Gemini 如何进行审核,然后将其发送给模型以评估所提供的代码。最后,它会处理 Gemini 的回答,根据用户的偏好将其格式设置为 Markdown、JSON 或表格,并输出审核结果。

合规性审核命令:

devai review compliance --context ./sample-app/k8s --config ./devai-cli/gemini/styleguide.md

devai review compliance 命令会根据一组最佳实践(通常是针对 Kubernetes 配置)分析代码。它利用 Gemini 模型来检查所提供的代码 (context),并将其与单独的配置文件 (config) 中定义的指定标准进行比较。该命令利用提示来指示 Gemini 模型充当专业的 Kubernetes 工程师并提供合规性报告。然后,它会将发现的问题格式化为简要说明,重点介绍演示如何解决任何已发现问题的代码示例。最后,该命令会将 Gemini 的合规性审核输出内容打印到控制台。这样,用户就可以轻松审核代码是否符合相关规定。

9. 克隆 GitLab 代码库

返回 Google Cloud Shell 终端并克隆代码库。

cd ~
mkdir gitlab
cd gitlab

替换为您刚刚创建的 GitLab 用户 ID 和代码库网址。

git clone https://gitlab.com:YOUR_GITLAB_USERID/genai-for-developers.git

更改目录并打开 .gitlab-ci.yml 文件。如果您在导入期间更改了代码库名称,请先更新文件夹名称,然后再运行以下命令。

cd genai-for-developers

cloudshell edit .gitlab-ci.yml

10. 使用 Gemini Code Assist 解释代码

右键点击 .gitlab-ci.yml 文件中的任意位置,然后选择 Gemini Code Assist > Explain。

f112229bcb52f48a.png

查看说明:

b07fb4cdf803c141.png

11. DevAI CLI 开发

在本部分中,您将对 devai cli 进行更改。

首先,设置 Python 虚拟环境,安装所需项并运行示例命令。

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

设置所需的环境变量。

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

运行代码审核命令,检查一切是否正常运行:

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

cloudshell edit code-review.md

使用 Cloud Shell 编辑器中的 Markdown 预览功能查看结果。

使用命令面板,然后选择“Markdown: Open Preview”。

9587123b62f12a55.png9999e7fbb20cf251.png9a12ba6ee8b3eedd.png

12. 探索 devai CLI 命令

测试覆盖率审核命令

devai review testcoverage -c ~/genai-for-developers/sample-app/src > testcoverage.md

cloudshell edit testcoverage.md

合规性审核命令

devai review compliance --context ~/genai-for-developers/sample-app/k8s --config ~/genai-for-developers/devai-cli/.gemini/styleguide.md > k8s-review.md

cloudshell edit k8s-review.md

效果回顾命令

devai review performance -c ~/genai-for-developers/sample-app/src/main/java > performance-review.md

cloudshell edit performance-review.md

安全审核命令

devai review security -c ~/genai-for-developers/sample-app/src/main/java > security-review.md

cloudshell edit security-review.md

阻碍因素审核命令

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

图片/图表审核和总结

输入图表 [~/genai-for-developers/images/extension-diagram.png]:

4b109a74e1aa3fb6.png

查看命令:

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

cloudshell edit image-review.md

输出:

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.

图片差异分析:

devai review imgdiff \
  -c ~/genai-for-developers/images/devai-api.png \
  -t ~/genai-for-developers/images/devai-api-slack.png > image-diff-review.md

 cloudshell edit image-diff-review.md

输出:

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.

视频文件分析:

devai review video \
  -f "/tmp/video.mp4" \
  -p "Review user journey video and create unit tests using jest framework"

文档生成命令

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

输出:

# Bank of Anthos - Balance Reader Service

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

在 Cloud Shell 编辑器中查看可用的 devai CLI 命令:

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

或者查看 GitHub 代码库中的 README.md。

13. 恭喜!

恭喜,您已完成此 Codelab!

所学内容:

  • 在 GitLab 中添加生成式 AI 代码审核自动化步骤
  • 在本地运行 devai CLI

后续步骤:

  • 我们即将推出更多实操课程!

清理

为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。

删除项目

若要避免产生费用,最简单的方法是删除您为本教程创建的项目。

©2024 Google LLC 保留所有权利。Google 和 Google 徽标是 Google LLC 的商标。其他所有公司名称和产品名称可能是其各自相关公司的商标。