程式碼研究室簡介
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 控制台會自動產生一個不重複的字串。但通常是在乎它何在在大部分的程式碼研究室中,您必須參照專案 ID (通常為
PROJECT_ID
)。如果您對產生的 ID 不滿意,可以隨機產生一個 ID。或者,您也可以自行嘗試,看看是否可用。在這個步驟後,這個名稱即無法變更,而且在專案期間內仍會保持有效。 - 資訊中的第三個值是專案編號,部分 API 會使用這個編號。如要進一步瞭解這三個值,請參閱說明文件。
- 接下來,您需要在 Cloud 控制台中啟用計費功能,才能使用 Cloud 資源/API。執行本程式碼研究室不會產生任何費用 (如果有的話)。如要關閉資源,避免在本教學課程結束後繼續產生費用,您可以刪除已建立的資源或專案。新使用者符合 $300 美元免費試用計畫的資格。
環境設定
開啟 Gemini 對話。
或輸入「詢問 Gemini」。
啟用 Cloud AI Companion API:
按一下「Start chatting
」然後按照其中一個範例問題輸入,或自行輸入提示來試試看。
建議提示:
- 以 5 個重點說明 Cloud Run。
- 您是 Google Cloud Run 產品經理,請向學生解釋 Cloud Run 的 5 個重點。
- 您是 Google Cloud Run 產品經理,請透過 5 個簡短重點向認證的 Kubernetes 開發人員說明 Cloud Run。
- 您是 Google Cloud Run 產品經理,想要瞭解何時適合向資深開發人員使用 Cloud Run,而非 GKE。
請參閱提示指南,進一步瞭解如何撰寫更優質的提示。
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 網頁應用程式 (gemini.google.com)
Google Gemini 網頁應用程式 (gemini.google.com) 是一項網頁式工具,旨在探索及運用 Google Gemini AI 模型的強大功能。
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
]。
7. 新增存放區密鑰
在分支的 GitHub 存放區中,在「Settings / Secrets and variables / Actions
」下方建立存放區密鑰。
新增名為「GOOGLE_API_CREDENTIALS
」的存放區密鑰。
請切換至 Google Cloud Shell 視窗/分頁,然後在 Cloud Shell 終端機中執行下列指令。
cat ~/vertex-client-key.json
複製檔案內容並將其貼上為密鑰的值。
透過 Qwiklabs 專案 ID 新增 PROJECT_ID
密鑰做為 valu
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
Blockers 檢查指令的結果:
devai review blockers -c ${{ github.workspace }}/sample-app/pom.xml
9. 複製存放區
返回 Cloud Shell 終端機,複製存放區。
為 GitHub 存放區建立資料夾。
mkdir github
cd github
先將 YOUR-GITHUB-USERID
變更為 GitHub userid,再執行指令。
在終端機中設定 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 環境變數。替換為使用者的主資料夾名稱。例如: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 的回應。
然後使用「指令面板」並選取「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。
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 中移除。請改用叫用。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."
}
}
使用鍵建立的新問題: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 網站,並在專案中建立名為「CICD AI Insights
」的新 GitLab 問題。
另一種做法是使用下方的 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 變數」檢視畫面:
23. 查看 GitLab 管道輸出內容
開啟「Build / Jobs
」並檢查管道輸出內容。
開啟 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
」分頁,將此變更提交及推送。
24. CircleCI 整合
什麼是 CircleCI?
CircleCI 是一個雲端式 CI/CD 平台,可讓團隊自動化軟體開發和部署程序。這項服務與 GitHub、Bitbucket 和 GitLab 等版本管控系統整合,讓團隊能夠執行自動化測試和建構作業,即時驗證程式碼變更。為了持續推送軟體更新,CircleCI 可將軟體自動部署至 AWS、Google Cloud 和 Azure 等多種雲端環境。
設定
開啟 CircleCI 網站,然後建立新專案。選取「GitLab
」/「Cloud
」做為您的存放區。
將 GitLab 帳戶存取權授予 CircleCI。
選取「最快」選項下方的 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 編輯器,然後變更 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 的商標,其他公司和產品名稱則有可能是其關聯公司的商標。