使用 GenAI 自動化程式碼審查

1. 總覽

在本實驗室中,您將設定 CICD 管道,並與 Gemini 整合,自動執行程式碼審查步驟。

9dde56ad139b9553.png

學習目標

在本實驗室中,您將瞭解如何執行下列操作:

  • 如何在 GitHub、GitLab 和 CircleCI 中新增 GenAI 程式碼審查自動化步驟
  • 如何使用 LangChain ReAct 代理程式和工具包,自動執行 GitLab 問題註解和開啟 JIRA 票證等工作

必要條件

  • 本實驗室假設您已熟悉 Cloud 控制台和 Cloud Shell 環境。

2. 設定和需求條件

設定 Cloud 專案

  1. 登入 Google Cloud 控制台,然後建立新專案或重複使用現有專案。如果沒有 Gmail 或 Google Workspace 帳戶,請先建立帳戶

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • 專案名稱是這個專案參與者的顯示名稱。這是 Google API 未使用的字元字串。你隨時可以更新。
  • 專案 ID 在所有 Google Cloud 專案中都是不重複的,而且設定後即無法變更。Cloud 控制台會自動產生專屬字串,通常您不需要在意該字串為何。在大多數程式碼研究室中,您需要參照專案 ID (通常標示為 PROJECT_ID)。如果您不喜歡產生的 ID,可以產生另一個隨機 ID。你也可以嘗試使用自己的名稱,看看是否可用。完成這個步驟後就無法變更,且專案期間會維持不變。
  • 請注意,有些 API 會使用第三個值,也就是「專案編號」。如要進一步瞭解這三種值,請參閱說明文件
  1. 接著,您需要在 Cloud 控制台中啟用帳單,才能使用 Cloud 資源/API。完成這個程式碼研究室的費用不高,甚至可能完全免費。如要關閉資源,避免在本教學課程結束後繼續產生費用,請刪除您建立的資源或專案。Google Cloud 新使用者可參加 $300 美元的免費試用計畫。

環境設定

開啟 Gemini 對話。

bc3c899ac8bcf488.png

或在搜尋列中輸入「問問 Gemini」。

e1e9ad314691368a.png

啟用 Cloud AI Companion API:

66cb6e561e384bbf.png

按一下「Start chatting」,然後按照其中一個範例問題操作,或自行輸入提示詞來試用。

5482c153eef23126.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 是網頁工具,可讓您製作提示工程和 Gemini API 的原型並進行實驗。註冊使用脈絡窗口達 100 萬個詞元的 Gemini 1.5 Pro,或進一步瞭解

Google Gemini 網頁應用程式 (gemini.google.com) 是一款網頁工具,可協助您探索及運用 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 存放區分支到個人 GitHub 存放區

前往 https://github.com/GoogleCloudPlatform/genai-for-developers/fork,然後選取您的 GitHub 使用者 ID 做為擁有者。

取消勾選只複製「主要」分支的選項。

請按一下 [Create fork]。

6. 啟用 GitHub Actions 工作流程

在瀏覽器中開啟已分叉的 GitHub 存放區,然後切換至「Actions」分頁,啟用工作流程。

1cd04db9b37af7cf.png

7. 新增存放區密鑰

在建立分支的 GitHub 存放區中,於「Settings / Secrets and variables / Actions」下方建立存放區密鑰。

新增名為「GOOGLE_API_CREDENTIALS」的存放區密鑰。

94cbe2778bef25eb.png

切換至 Google Cloud Shell 視窗/分頁,並在 Cloud Shell 終端機中執行下列指令。

cat ~/vertex-client-key.json

複製檔案內容,並貼上做為密鑰的值。

915579a97f8f2ced.png

新增 PROJECT_ID 密鑰,並將 Qwiklabs 專案 ID 設為值 4fa92833ce615a36.png

8. 執行 GitHub Actions 工作流程

在瀏覽器中前往 GitHub 存放區,然後執行工作流程。

工作流程已設為在程式碼推送或手動執行時執行。

在「所有工作流程」下方選取「GenAI For Developers」,然後使用「main」分支點按「Run workflow」。

da11273b4b54f7b6.png

查看結果:

cf49aa41980aacc5.png

測試涵蓋範圍指令的結果

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

3b21bd4639524763.png

程式碼審查指令的結果

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

4876dbc2e0042943.png

成效檢查指令的結果

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

98dd2472b2e819bf.png

安全審查指令的結果

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

7d180a763db92d56.png

檢視阻斷程式審查指令的結果

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

726175e874aefcf.png

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 顯示設定檔。

9e81e5a79d421eac.png

10. 啟用 Gemini Code Assist

按一下右下角的「Gemini」圖示 7c891e32c055c0e4.png

按一下「Login to Google Cloud」和「Select a Google Cloud Project」。

f5318f22c91ecaa8.png

6b7203ffdd8485fa.png

fb8d42a6bc8a260f.png

在彈出式視窗中,選取 Qwiklabs 專案。

f661047956a6d6f9.png

11. 使用 Gemini Code Assist 解釋程式碼

devai-review.yml 檔案的任意處按一下滑鼠右鍵,然後選取 Gemini Code Assist > Explain

41fb7da002bdf43.png

審查說明:

7724d52e54918c00.png

12. 在本機執行 DEVAI CLI

返回 Cloud Shell 編輯器,然後開啟新的終端機。

149218baaf30865f.png

返回 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

查看說明。

30e3baf4c272c8ab.png

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 的回覆。

然後使用指令區塊面板,選取「Markdown: Open Preview」。

ec6fedf4b6d3fb73.png

9999e7fbb20cf251.png

76858be03d73abd0.png

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]:

4b109a74e1aa3fb6.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 指令列指令:

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: 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... 想法:問題中已提供說明,因此無需思考。動作:

{
  "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."
  }
}

已建立新問題,金鑰為:CYMEATS-117

Observation: New issue created with key: CYMEATS-117 Thought:Final Answer: 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 編輯器中啟用。

4a7f4640f66037f.png

.gitlab-ci.yml 檔案的任意位置按一下滑鼠右鍵,然後選取「Gemini Code Assist > Explain this"」。

154838a0100389a9.png

18. GitLab 指令設定

開啟 GitLab,並在先前步驟建立的 GitLab 存放區中,於「Settings / Access Tokens」下方建立專案存取權杖。

複製並儲存存取權杖值,以供後續步驟使用。

使用下列詳細資料:

  • 權杖名稱:devai-cli-qwiklabs
  • 角色:Maintainer
  • 範圍:api

1865de233277f11c.png

設定 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」。

63a13948f6864074.png

您也可以使用下列 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 虛擬環境、安裝必要條件,然後執行範例指令。

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 網站,查看更新後的問題。

9da39bf6070d9447.png

LangSmith 中查看 LLM 追蹤記錄。

LLM 追蹤記錄範例。

f32eed34f3a3b040.png

20. 將變更推送至 GitLab 存放區

返回 Google Cloud Shell 編輯器。

切換至「Source Control」分頁。

暫存、提交並推送所做的變更,以更新 review.py 檔案。

b838a11f362454ce.png

21. GitLab CICD 設定

接下來,您要啟用 GitLab CICD 管道,以便在變更推送至存放區時執行程式碼審查。

開啟 GitLab 網站,然後前往「Settings / CICD"」部分。

展開 Variables 部分,然後按一下「Add variable」。

新增變數時,請務必取消勾選所有核取方塊。範例:

68b3ed732b6a8fe9.png

使用筆記 (您在其中保留所有環境變數),為 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 Variables」檢視畫面:

2f4594ce72be4834.png

22. 執行 GitLab CICD 管道

在 GitLab UI 中開啟「Build / Pipelines」,然後按一下「Run Pipeline」。

a7518e37dde42366.png

23. 查看 GitLab 管道輸出內容

在 GitLab UI 中開啟「Build / Jobs」,並檢查管道輸出內容。

985e4b322fb73b1c.png

開啟 GitLab 網站,查看「CICD Insights」問題的更新註解。

停用 GitLab 工作流程執行作業

返回 Google Cloud Shell 編輯器。取消註解這些行,即可在程式碼推送事件中停用 GitLab 工作流程執行作業。您仍可透過 UI 視需要執行工作流程。

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

開啟專案根目錄中的 .gitlab-ci.yml,並取消註解下列幾行:

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

切換至「Source Control」分頁,暫存、提交並推送這項變更。

a9d52beb8c642982.png

24. CircleCI 整合

什麼是 CircleCI?

CircleCI 是雲端式 CI/CD 平台,可讓團隊自動執行軟體開發和部署程序。這項服務可與 GitHub、Bitbucket 和 GitLab 等版本管控系統整合,讓團隊執行自動化測試和建構作業,即時驗證程式碼變更。在持續推送軟體更新方面,CircleCI 可自動將軟體部署至各種雲端環境,例如 AWS、Google Cloud 和 Azure。

設定

開啟 CircleCI 網站並建立新專案。為存放區選取「GitLab」/「Cloud」。

授予 CircleCI 存取 GitLab 帳戶的權限。

在「最快」選項下方,選取 main 分支版本。CircleCI 可能會偵測到現有的設定檔,並略過這個步驟。

4e9b7cef458d5fba.png

建立專案後,按一下「Project Settings」/「Environment Variables」部分。

1499b5f96ac0fe5e.png

新增目前為止使用的所有環境變數。

f15b7a3e02c649e8.png

以下是新增環境變數的範例清單。

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 編輯器,然後變更 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」。

d196ad631be17b88.png

點選 CircleCI 的連結,即可查看工作流程。

d4ff287694b82445.png

查看存放區中 GitLab 問題的留言。

e77ee826488d5299.png

9a51daa2960994e3.png

查看在 JIRA 專案中建立的新問題。

1e6305a32aaef6a2.png

26. 恭喜!

恭喜,您已完成本實驗室!

涵蓋內容:

  • 在 GitHub、GitLab 和 CircleCI 中新增 GenAI 程式碼審查自動化步驟。
  • LangChain ReAct 代理程式可自動執行工作,例如在 GitLab 問題中加上註解,以及開啟 JIRA 票證。

後續步驟:

  • 更多實務課程即將推出!

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程所用資源的費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

©2024 Google LLC 保留所有權利。Google 和 Google 標誌是 Google LLC 的商標,所有其他公司和產品名稱可能是其關聯公司的商標。