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

学习内容
在本实验中,您将学习如何完成以下操作:
- 如何在 GitHub、GitLab 和 CircleCI 中添加生成式 AI 代码审核自动化步骤
- 如何使用 LangChain ReAct 代理和工具包自动执行任务,例如在 GitLab 问题上添加评论和打开 JIRA 工单
前提条件
- 本实验假设您熟悉 Cloud 控制台和 Cloud Shell 环境。
2. 设置和要求
Cloud 项目设置
- 登录 Google Cloud 控制台,然后创建一个新项目或重复使用现有项目。如果您还没有 Gmail 或 Google Workspace 账号,则必须创建一个。



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

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

启用云 AI Companion API:

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

建议尝试的提示:
- 用 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 原型设计和实验。注册体验 Gemini 1.5 Pro(支持 100 万个 token 的上下文窗口),或详细了解。
- Gemini Web 应用 (gemini.google.com)
Google Gemini Web 应用 (gemini.google.com) 是一款基于 Web 的工具,旨在帮助您探索和利用 Google Gemini AI 模型的强大功能。
- 适用于 Android 的 Google Gemini 移动应用和 iOS 设备上的 Google 应用
4. 创建服务账号
点击搜索栏右侧的图标,激活 Cloud Shell。

在打开的终端中,启用使用 Vertex AI API 和 Gemini 对话所需的服务。
gcloud services enable \
aiplatform.googleapis.com \
cloudaicompanion.googleapis.com \
cloudresourcemanager.googleapis.com \
secretmanager.googleapis.com
如果系统提示您进行授权,请点击“授权”以继续。

运行以下命令以创建新的服务账号和密钥。
您将使用此服务账号从 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 代码库派生到您的个人 GitHub 代码库
前往 https://github.com/GoogleCloudPlatform/genai-for-developers/fork,然后选择您的 GitHub 用户 ID 作为所有者。
取消选中仅复制“主”分支的选项。
请点击“Create fork”。
6. 启用 GitHub Actions 工作流
在浏览器中打开已复刻的 GitHub 代码库,然后切换到“Actions”标签页以启用工作流。

7. 添加代码库 Secret
在已派生的 GitHub 代码库中的“Settings / Secrets and variables / Actions”下创建代码库密钥。
添加名称为“GOOGLE_API_CREDENTIALS”的仓库 Secret。

切换到 Google Cloud Shell 窗口/标签页,然后在 Cloud Shell 终端中运行以下命令。
cat ~/vertex-client-key.json
复制文件内容,并将其粘贴为 Secret 的值。

添加 PROJECT_ID,并将您的 Qwiklabs 项目 ID 作为值 
8. 运行 GitHub Actions 工作流
在浏览器中前往您的 GitHub 代码库,然后运行工作流。
工作流配置为在推送代码或手动执行时运行。
在“所有工作流”下选择“GenAI For Developers”,然后使用“main”分支点击“Run workflow”。

查看结果:

测试覆盖率命令的结果:
devai review testcoverage -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

代码审核命令的结果:
devai review code -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

效果评估命令的结果:
devai review performance -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

安全审核命令的结果:
devai review security -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

阻碍者查看命令的结果:
devai review blockers -c ${{ github.workspace }}/sample-app/pom.xml

9. 克隆代码库
返回到 Cloud Shell 终端并克隆代码库。
为 GitHub 代码库创建一个文件夹。
mkdir github
cd github
在运行命令之前,请将 YOUR-GITHUB-USERID 更改为您的 GitHub 用户 ID。
在终端中设置 Git 用户名和电子邮件地址。
请先更新值,然后再运行命令。
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
在 Cloud Shell 编辑器中更改文件夹并打开工作流文件。
cd genai-for-developers
cloudshell edit .github/workflows/devai-review.yml
等待,直到 IDE 中显示配置文件。

10. 启用 Gemini Code Assist
点击右下角的“Gemini”图标
,
点击“Login to Google Cloud”和“Select a Google Cloud Project”。



在弹出式窗口中,选择您的 Qwiklabs 项目。

11. 使用 Gemini Code Assist 解释代码
右键点击 devai-review.yml 文件中的任意位置,然后选择 Gemini Code Assist > Explain。

审核说明:

12. 在本地运行 DEVAI CLI
返回 Cloud Shell 编辑器,然后打开新的终端。

返回 Cloud Shell 终端,然后运行以下命令以在本地安装 devai。
pip3 install devai-cli
CLI 已安装,但不在 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.
运行以下命令以更新 PATH 环境变量。替换为用户的 home 文件夹名称。例如:student_00_478dfeb8df15
export PATH=$PATH:/home/YOUR-USER-HOME-FOLDER/.local/bin
运行 devai CLI 命令以在本地执行代码审核。查看 CLI 输出。
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
运行以下命令,打开审核脚本:
cloudshell edit devai-cli/src/devai/commands/review.py
右键点击 review.py 文件中的任意位置,然后选择 Gemini Code Assist > Explain。
查看说明。

13. DevAI CLI 开发
在本部分中,您将对 devai CLI 进行更改。
首先,设置 Python 虚拟环境,安装所需项并运行示例命令。
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
运行测试覆盖率检查命令,以检查一切是否正常运行:
devai review testcoverage -c ~/github/genai-for-developers/sample-app/src
使用 Cloud Shell 编辑器中的 Markdown 预览功能查看结果。
创建一个新文件,然后粘贴 Gemini 的回答。
然后使用 Command Palette 并选择“Markdown: Open Preview”。



14. 探索 devai CLI 命令
代码审核命令
devai review code -c ~/github/genai-for-developers/sample-app/src/main/java
效果回顾命令
devai review performance -c ~/github/genai-for-developers/sample-app/src/main/java
安全审核命令
devai review security -c ~/github/genai-for-developers/sample-app/src/main/java
测试覆盖率审核命令
devai review testcoverage -c ~/github/genai-for-developers/sample-app/src
阻碍因素审核命令
devai review blockers -c ~/github/genai-for-developers/sample-app/pom.xml
devai review blockers -c ~/github/genai-for-developers/sample-app/setup.md
图片/图表审核和总结:
输入图表 [~/github/genai-for-developers/images/extension-diagram.png]:

查看命令:
devai review image \
-f ~/github/genai-for-developers/images/extension-diagram.png \
-p "Review and summarize this diagram"
输出:
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 ~/github/genai-for-developers/images/devai-api.png \
-t ~/github/genai-for-developers/images/devai-api-slack.png
输出:
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 document readme -c ~/github/genai-for-developers/sample-app/src/main/
输出:
# 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)
在 Cloud Shell 编辑器中查看可用的 devai CLI 命令:
cloudshell edit ~/github/genai-for-developers/devai-cli/README.md
或者查看 GitHub 代码库中的 README.md。
15. 在一个文件中跟踪所有环境变量
新建一个文件,用于跟踪您将创建的所有环境变量(例如 API 密钥、API 令牌等)。
在完成本实验的过程中,您将多次在不同系统中使用这些凭据,因此最好将它们集中在一处,以便于参考。
16. LangSmith LLM 跟踪配置
创建 LangSmith 账号,并在“设置”部分中生成服务 API 密钥。https://docs.smith.langchain.com/
设置 LangSmith 集成所需的环境变量。在运行命令之前,请替换服务 API 密钥。
export LANGCHAIN_API_KEY=langsmith-service-api-key
export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
为避免在终端中泄露敏感信息,最佳实践是使用 read -s,这是一种安全设置环境变量的方式,不会在控制台的命令历史记录中显示值。运行后,您必须粘贴该值并按 Enter 键。
17. JIRA 命令配置
创建 JIRA 账号(如果您还没有账号)。
为您的项目创建 JIRA API 令牌。https://id.atlassian.com/manage-profile/security/api-tokens
设置 JIRA 集成所需的这些环境变量(在运行命令之前替换相应值)。
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
打开 review.py 文件:
cloudshell edit ~/github/genai-for-developers/devai-cli/src/devai/commands/review.py
查看 review.py 文件:
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)
找到并取消对下面这行的注释:
# Uncomment after configuring JIRA and GitLab env variables - see README.md for details
在文件顶部导入 JIRA 命令
# from devai.commands.jira import create_jira_issue
在 code 方法中创建 JIRA 问题的方法
#create_jira_issue("Code Review Results", response.text)
重新运行代码审核命令,并检查代理的输出:
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
示例输出:
(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: 函数 __call__ 已在 LangChain 0.1.0 中弃用,将在 0.2.0 中移除。请改用 invoke。warn_deprecated(
进入新的 AgentExecutor 链... 思路:问题中已提供说明,因此无需考虑操作:
{
"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."
}
}
已创建新问题,问题 ID 为:CYMEATS-117
观察:创建了新问题,键为 CYMEATS-117。想法:最终答案:CYMEATS-117
已完成链。
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
更改目录并打开 .gitlab-ci.yml 文件。
cd genai-for-developers
cloudshell edit .gitlab-ci.yml
如果您之前未执行此操作,请在 Cloud Shell 编辑器中启用 Gemini。

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

18. GitLab 命令配置
打开 GitLab,然后在上一步中创建的 GitLab 代码库中的“Settings / Access Tokens”下创建项目访问令牌。
复制并存储访问令牌值,以便在后续步骤中使用。
使用以下详细信息:
- 令牌名称:
devai-cli-qwiklabs - 角色:
Maintainer - 范围:
api

设置 GitLab 集成所需的环境变量。
此命令要求您更新 GitLab 访问令牌。
export GITLAB_PERSONAL_ACCESS_TOKEN=gitlab-access-token
此命令需要您更新 GitLab 用户 ID 和代码库名称。
export GITLAB_REPOSITORY="USERID/REPOSITORY"
设置其余环境变量:
export GITLAB_URL="https://gitlab.com"
export GITLAB_BRANCH="devai"
export GITLAB_BASE_BRANCH="main"
打开 GitLab 网站,然后在您的项目中创建一个新的 GitLab 问题,并将标题设为“CICD AI Insights”。

另一种方法是使用以下 curl 命令。您需要一个 GitLab 项目 ID,您可以在“Settings / General”部分下查找该 ID。
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
返回 Cloud Shell 并打开 review.py 文件:
cloudshell edit ~/gitlab/genai-for-developers/devai-cli/src/devai/commands/review.py
找到并取消注释以下代码
用于导入 GitLab 命令的行
# from devai.commands.gitlab import create_gitlab_issue_comment
在 GitLab 问题上添加评论的方法
# create_gitlab_issue_comment(response.text)
19. DevAI CLI 开发
由于您已切换到 GitLab 代码库/目录。您需要重新运行以下设置步骤。
在终端中,设置 Python 虚拟环境、安装要求并运行示例命令。
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
您可以确认 CLI 的位置 - 这次它应该位于 GitLab 文件夹下。
which devai
在终端中重新运行代码审核命令:
devai review code -c ~/gitlab/genai-for-developers/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
示例输出 - 部分内容已缩短:
(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.
打开 GitLab 网站,然后查看更新后的问题。

在 LangSmith 中查看 LLM 轨迹。
LLM 轨迹示例。

20. 将更改推送到 GitLab 代码库
返回 Google Cloud Shell 编辑器。
切换到“Source Control”标签页。
暂存、提交并推送您为更新 review.py 文件所做的更改。

21. GitLab CICD 配置
接下来,您将启用 GitLab CICD 流水线,以便在将更改推送到代码库时运行代码审核。
打开 GitLab 网站,然后前往“Settings / CICD"”部分。
展开 Variables 部分,然后点击“Add variable”。
添加变量时,请务必取消选中所有复选框。示例:

根据您记录所有环境变量的笔记,为 JIRA、GitLab 和 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"
对于 GOOGLE_CLOUD_CREDENTIALS 变量值,请使用上文中创建的服务账号密钥。
cat ~/vertex-client-key.json
CI/CD 变量视图:

22. 运行 GitLab CI/CD 流水线
在 GitLab 界面中打开“Build / Pipelines”,然后点击“Run Pipeline”。

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

打开 GitLab 网站,查看“CICD Insights”问题中更新的评论。
停用 GitLab 工作流程执行
返回 Google Cloud Shell 编辑器。取消注释相应行,以在代码推送事件发生时停用 GitLab 工作流执行。您仍然可以根据需要从界面执行工作流。
# workflow: # rules: # - if: $CI_PIPELINE_SOURCE == "web"
打开项目根目录中的 .gitlab-ci.yml,然后取消注释以下行:
cloudshell edit ~/gitlab/genai-for-developers/.gitlab-ci.yml
切换到“Source Control”标签页 - 暂存、提交并推送此更改。

24. CircleCI 集成
什么是 CircleCI?
CircleCI 是一个基于云的 CI/CD 平台,可让团队自动执行软件开发和部署流程。它与 GitHub、Bitbucket 和 GitLab 等版本控制系统集成,让团队可以通过运行自动化测试和构建来实时验证代码更改。对于持续交付,CircleCI 可以自动将软件部署到各种云环境,例如 AWS、Google Cloud 和 Azure。
设置
打开 CircleCI 网站并创建新项目。为代码库选择“GitLab”/“Cloud”。
向 CircleCI 授予对您的 GitLab 账号的访问权限。
在“最快”选项下,选择 main 分支。CircleCI 可能会检测到现有配置文件并跳过此步骤。

创建项目后,点击“Project Settings”/“Environment Variables”部分。

添加您目前使用的所有环境变量。

以下是要添加的环境变量的示例列表。
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. 启用 JIRA 和 GitLab 方法
打开 Google Cloud Shell Editor,然后对 review.py 文件进行更改。
找到并取消注释以下代码行。
# 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)
切换到“Source Control”标签页 - 暂存、提交并推送此更改。
打开 GitLab 网站,然后前往“Build”/“Pipelines”。

点击链接前往 CircleCI,查看工作流。

查看代码库中 GitLab 问题上的评论。


查看在您的 JIRA 项目中创建的新问题。

26. 恭喜!
恭喜,您已完成本实验!
所学内容:
- 在 GitHub、GitLab 和 CircleCI 中添加了生成式 AI 代码审核自动化步骤。
- LangChain ReAct 代理,用于自动执行在 GitLab 问题上添加评论和打开 JIRA 工单等任务。
后续步骤:
- 我们即将推出更多实操课程!
清理
为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。
删除项目
若要避免产生费用,最简单的方法是删除您为本教程创建的项目。
©2024 Google LLC 保留所有权利。Google 和 Google 徽标是 Google LLC 的商标。其他所有公司名称和产品名称可能是其各自相关公司的商标。