1. 概览
在本实验中,您将设置 CICD 流水线并与 Gemini 集成,以自动执行代码审核步骤。
学习内容
在本实验中,您将学习如何完成以下操作:
- 如何在 GitHub、GitLab 和 CircleCI 中添加 GenAI 代码审核自动化步骤
- 如何使用 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 Chat。
或者,在搜索栏中输入“询问 Gemini”。
启用 Cloud AI Companion API:
点击“Start chatting
”,然后按照其中一个示例问题操作,或输入您自己的问题进行试用。
建议尝试的提示:
- 通过 5 个要点介绍 Cloud Run。
- 您是 Google Cloud Run 产品经理,需要用 5 个关键要点向学生简要介绍 Cloud Run。
- 您是 Google Cloud Run 产品经理,需要向一名经过认证的 Kubernetes 开发者简要说明 5 个 Cloud Run 要点。
- 您是 Google Cloud Run 产品经理,需要向一名高级开发者解释在什么情况下应使用 Cloud Run 而非 GKE,并用 5 个要点简要说明。
如需详细了解如何撰写更优质的提示,请参阅提示指南。
Google Cloud 专用 Gemini 如何使用您的数据
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 是一款基于网络的工具,可用于对问题工程和 Gemini API 进行原型设计和实验。注册 Gemini 1.5 Pro(支持 100 万个词元的上下文窗口),或了解详情。
- 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 作为所有者。
取消选中相应选项,以仅复制“main”分支。
请点击“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 Editor 中更改文件夹并打开工作流文件。
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 Editor,然后打开一个新终端。
返回 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 环境变量。请将其替换为用户的主文件夹名称。例如: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 virtualenv、安装所需组件并运行示例命令。
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 账号,然后在“设置”部分生成 Service API 密钥。https://docs.smith.langchain.com/
设置 LangSmith 集成所需的环境变量。请先替换 Service 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 账号。
为您的项目创建 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(
Entering new AgentExecutor chain... 思考:题目中已提供说明,因此无需思考
{
"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
如果您之前未启用 Gemini
,请在 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 网站,然后在项目中创建标题为“CICD AI Insights
”的新 GitLab 问题。
另一种方法是使用以下 curl 命令。您需要一个 GitLab 项目 ID,可以在“Settings
/ General
”部分下查找。
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 virtualenv、安装所需软件包并运行示例命令。
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 CICD 流水线
在 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 中添加了 GenAI 代码审核自动化步骤。
- LangChain ReAct 代理,用于自动执行 GitLab 问题评论和打开 JIRA 工单等任务。
后续步骤:
- 我们将推出更多实操课程,敬请期待!
清理
为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。
删除项目
若要避免产生费用,最简单的方法是删除您为本教程创建的项目。
©2024 Google LLC 保留所有权利。Google 和 Google 徽标是 Google LLC 的商标。其他所有公司名称和产品名称可能是其各自相关公司的商标。