使用 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

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

環境設定

開啟 Gemini 對話。

bc3c899ac8bcf488.png

或者,在搜尋列中輸入「Ask Gemini」。

e1e9ad314691368a.png

啟用 Cloud AI Companion API:

66cb6e561e384bbf.png

按一下「Start chatting」,然後按照其中一個範例問題操作,或自行輸入提示,即可試用這項功能。

5482c153eef23126.png

建議提示:

  • 以 5 個重點說明 Cloud Run。
  • 您是 Google Cloud Run 產品經理,請向學生解釋 Cloud Run 的 5 個重點。
  • 您是 Google Cloud Run 產品經理,向 Kubernetes 認證開發人員解釋 Cloud Run 的 5 大重點。
  • 您是 Google Cloud Run 產品經理,請向資深開發人員說明在哪些情況下應使用 Cloud Run 而非 GKE,並以 5 個重點說明。

請參閱提示指南,進一步瞭解如何撰寫優質提示。

Gemini for Google Cloud 如何使用您的資料

Google 的隱私權承諾

Google 是第一間發表 AI/機器學習隱私權承諾的公司,該文中也提到我們的信念:除了極致的安全性之外,客戶也應該對儲存在雲端的自家資料保有最大的掌控權。

您提交及收到的資料

您向 Gemini 提出的問題,包括您提交給 Gemini 以便分析或完成的任何輸入資訊或程式碼,都稱為提示。您從 Gemini 收到的答案或程式碼完成作業稱為回覆。Gemini 不會將您的提示或回覆內容做為模型訓練資料

提示訊息加密

向 Gemini 提交提示時,您的資料會在傳輸過程中經過加密,並做為輸入內容傳送至 Gemini 中的基礎模型。

由 Gemini 產生的節目資料

Gemini 是根據第一方 Google Cloud 程式碼和精選第三方程式碼進行訓練。您必須負責程式碼的安全性、測試和效能,包括 Gemini 提供的任何程式碼完成、產生或分析功能。

進一步瞭解 Google 如何處理提示。

3. 測試提示的選項

如果您想變更/擴充現有的 devai 指令列提示,可以使用以下幾種做法。

Vertex AI Studio 是 Google Cloud Vertex AI 平台的一部分,專門用於簡化及加速生成式 AI 模型的開發與使用。

Google AI Studio 是網頁式工具,可用於設計原型,並透過提示設計和 Gemini API 進行實驗。訂閱 Gemini 1.5 Pro 以便使用 100 萬個詞元的脈絡窗口,或進一步瞭解

Google Gemini 網頁應用程式 (gemini.google.com) 是一項網頁式工具,可協助您探索並運用 Google Gemini AI 模型的強大功能。

4. 建立服務帳戶

按一下搜尋列右側的圖示,即可啟用 Cloud Shell。

3e0c761ca41f315e.png

在開啟的終端機中,啟用必要服務,以便使用 Vertex AI API 和 Gemini 聊天機器人。

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 做為擁有者。

取消勾選該選項,只複製「main」分支。

請按一下 [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

Blockers review 指令的結果

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. 在本機執行 DEV AI 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 cli 指令:

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

或者,您也可以查看 GitHub 存放區中的 README.md

15. 追蹤檔案中的所有環境變數

開始建立新檔案,以便追蹤您要建立的所有環境變數 (例如 API 金鑰、API 權杖等)。

您在實驗室中會多次使用這些值來測試不同的系統,因此將這些值放在同一個地方會比較方便。

16. LangSmith LLM 追蹤設定

建立 LangSmith 帳戶,並在「Settings」(設定) 部分產生 Service 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。

進入新的 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."
  }
}

使用鍵建立的新問題: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 編輯器中啟用。

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 變數檢視畫面:

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」做為您的存放區。

將 GitLab 帳戶存取權授予 CircleCI。

在「最快」選項下方,選取 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 的商標,其他公司和產品名稱則有可能是其關聯公司的商標。