1. 概要
このラボでは、CICD パイプラインを設定し、Gemini と統合してコードレビューの手順を自動化します。
学習内容
このラボでは、次の方法について学びます。
- GitHub、GitLab、CircleCI で GenAI コードレビューの自動化ステップを追加する方法
- LangChain ReAct エージェントとツールキットを使用して、GitLab の問題へのコメントや JIRA チケットの作成などのタスクを自動化する方法
前提条件
- このラボは、Cloud コンソールと Cloud Shell 環境に精通していることを前提としています。
2. 設定と要件
Cloud プロジェクトの設定
- Google Cloud Console にログインして、プロジェクトを新規作成するか、既存のプロジェクトを再利用します。Gmail アカウントも Google Workspace アカウントもまだお持ちでない場合は、アカウントを作成してください。
- プロジェクト名は、このプロジェクトの参加者に表示される名称です。Google API では使用されない文字列です。いつでも更新できます。
- プロジェクト ID は、すべての Google Cloud プロジェクトにおいて一意でなければならず、不変です(設定後は変更できません)。Cloud コンソールでは一意の文字列が自動生成されます。通常は、この内容を意識する必要はありません。ほとんどの Codelab では、プロジェクト ID(通常は
PROJECT_ID
と識別されます)を参照する必要があります。生成された ID が好みではない場合は、ランダムに別の ID を生成できます。または、ご自身で試して、利用可能かどうかを確認することもできます。このステップ以降は変更できず、プロジェクトを通して同じ ID になります。 - なお、3 つ目の値として、一部の API が使用するプロジェクト番号があります。これら 3 つの値について詳しくは、こちらのドキュメントをご覧ください。
- 次に、Cloud のリソースや API を使用するために、Cloud コンソールで課金を有効にする必要があります。この Codelab の操作をすべて行って、費用が生じたとしても、少額です。このチュートリアルの終了後に請求が発生しないようにリソースをシャットダウンするには、作成したリソースを削除するか、プロジェクトを削除します。Google Cloud の新規ユーザーは、300 米ドル分の無料トライアル プログラムをご利用いただけます。
環境設定
Gemini チャットを開きます。
または、検索バーに「Gemini に質問」と入力します。
Cloud AI Companion API を有効にします。
[Start chatting
] をクリックして、サンプルの質問のいずれかを使用するか、独自のプロンプトを入力して試します。
プロンプトの例:
- Cloud Run の 5 つの主なポイントについて説明します。
- 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/ML プライバシー コミットメントを業界で最初に発表した企業の 1 つです。これは、お客様がクラウドに保存されている自社のデータについて最高レベルのセキュリティとコントロールを得るべきという、Google の信念を概説したものです。
送信および受信するデータ
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 に登録するか、詳細をご覧ください。
- Gemini ウェブアプリ(gemini.google.com)
Google Gemini ウェブアプリ(gemini.google.com)は、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
」のリポジトリ シークレットを追加します。
Google Cloud Shell ウィンドウ/タブに切り替えて、Cloud Shell ターミナルで次のコマンドを実行します。
cat ~/vertex-client-key.json
ファイルの内容をコピーして、シークレットの値として貼り付けます。
値 として Qwiklabs プロジェクト ID を含む
PROJECT_ID
シークレットを追加します。
8. GitHub Actions ワークフローを実行する
ブラウザで GitHub リポジトリに移動し、ワークフローを実行します。
ワークフローは、コードプッシュまたは手動実行で実行されるように構成されています。
[すべてのワークフロー] で [GenAI For Developers
] を選択し、[main
] ブランチを使用して [Run workflow
] をクリックします。
結果を確認する:
テストカバレッジ コマンドの結果:
devai review testcoverage -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
コードレビュー コマンドの結果:
devai review code -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
パフォーマンス レビュー コマンドの出力:
devai review performance -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
セキュリティ レビュー コマンドの結果:
devai review security -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
ブロックツールがコマンドの結果を確認する:
devai review blockers -c ${{ github.workspace }}/sample-app/pom.xml
9. リポジトリのクローンを作成する
Cloud Shell ターミナルに戻り、リポジトリのクローンを作成します。
GitHub リポジトリのフォルダを作成します。
mkdir github
cd github
コマンドを実行する前に、YOUR-GITHUB-USERID
を GitHub のユーザー ID に変更します。
ターミナルで Git のユーザー名とメールを設定します。
コマンドを実行する前に値を更新します。
git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"
git clone https://github.com/YOUR-GITHUB-USERID/genai-for-developers.git
フォルダを変更し、Cloud Shell エディタでワークフロー ファイルを開きます。
cd genai-for-developers
cloudshell edit .github/workflows/devai-review.yml
IDE に構成ファイルが表示されるまで待ちます。
10. Gemini Code Assist を有効にする
右下にある [Gemini
] アイコン をクリックします。
[Login to Google Cloud
] と [Select a Google Cloud Project
] をクリックします。
ポップアップ ウィンドウで、Qwiklabs プロジェクトを選択します。
11. Gemini Code Assist でコードを説明する
devai-review.yml
ファイルを右クリックして、Gemini Code Assist > Explain
を選択します。
審査の説明:
12. DEVAI CLI をローカルで実行する
Cloud Shell エディタに戻り、新しいターミナルを開きます。
Cloud Shell ターミナルに戻り、次のコマンドを実行して devai
をローカルにインストールします。
pip3 install devai-cli
CLI はインストールされているが、PATH にない。
WARNING: The script devai is installed in '/home/student_00_478dfeb8df15/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
次のコマンドを実行して、PATH 環境変数を更新します。ユーザーのホームフォルダ名に置き換えます。例: 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 をご覧ください。
15. すべての環境変数をファイルに記録する
新しいファイルを作成して、作成するすべての環境変数(API キー、API トークンなど)を追跡します。
ラボでは、さまざまなシステムでこれらのコマンドを使用するため、1 か所で参照できるようにしておくと便利です。
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 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."
}
}
キー: CYMEATS-117 で新しい問題を作成しました
観察: キー: CYMEATS-117 で新しい問題が作成されました。考えられる原因:最終的な回答: CYMEATS-117
チェーンが終了しました。
Open your JIRA project in the browser and review the created issue.
Sample JIRA issue view.
<img src="img/9a93a958c30f0b51.png" alt="9a93a958c30f0b51.png" width="624.00" />
Open [LangSmith portal](https://smith.langchain.com/) and review LLM trace for JIRA issue creation call.
Sample LangSmith LLM trace.
<img src="img/6222ee1653a5ea54.png" alt="6222ee1653a5ea54.png" width="624.00" />
## Import GitHub repo to GitLab repo
Go to [https://gitlab.com/projects/new](https://gitlab.com/projects/new) and select "`Import project`" / "`Repository by URL`" option:
Git repository url:
https://github.com/GoogleCloudPlatform/genai-for-developers.git
Or
Your personal GitHub project that you created earlier in this lab.
Under Project URL - select your GitLab userid
Set Visibility to `Public`.
Click - "`Create Project`" to start the import process.
If you see an error about invalid GitHub Repository URL, [create a new GitHub token](https://github.com/settings/tokens)(fine-grained) with Public repositories read-only access, and retry import again providing your GitHub userid and token.
## Clone GitLab repo and setup SSH key
Return to Google Cloud Shell terminal and set up a new SSH key.
Update your email before running the commands. Hit enter multiple times to accept defaults.
ssh-keygen -t ed25519 -C "your-email-address"
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519
cat ~/.ssh/id_ed25519.pub
Add a public key to your GitLab account.
Open [https://gitlab.com/-/profile/keys](https://gitlab.com/-/profile/keys) and click "Add new key".
For the key value copy/paste the output of the last command.
Go back to the terminal and clone the repository.
cd ~ mkdir gitlab cd gitlab
Replace with your GitLab userid and repository url that was just created.
```console
git clone git@gitlab.com:YOUR_GITLAB_USERID/genai-for-developers.git
ディレクトリを変更して .gitlab-ci.yml
ファイルを開きます。
cd genai-for-developers
cloudshell edit .gitlab-ci.yml
まだ有効にしていない場合は、Cloud Shell エディタで Gemini
を有効にします。
.gitlab-ci.yml
ファイルの任意の場所を右クリックし、[Gemini Code Assist > Explain
this"
] を選択します。
18. GitLab コマンドの構成
GitLab を開き、前の手順で作成した GitLab リポジトリの「Settings / Access Tokens
」にプロジェクト アクセス トークンを作成します。
次の手順で使用するアクセス トークンの値をコピーして保存します。
次の情報を使用します。
- トークン名:
devai-cli-qwiklabs
- ロール:
Maintainer
- スコープ:
api
GitLab の統合に必要な環境変数を設定します。
このコマンドを使用するには、GitLab アクセス トークンを更新する必要があります。
export GITLAB_PERSONAL_ACCESS_TOKEN=gitlab-access-token
このコマンドでは、GitLab のユーザー ID とリポジトリ名を更新する必要があります。
export GITLAB_REPOSITORY="USERID/REPOSITORY"
残りの環境変数を設定します。
export GITLAB_URL="https://gitlab.com"
export GITLAB_BRANCH="devai"
export GITLAB_BASE_BRANCH="main"
GitLab ウェブサイトを開き、プロジェクトに新しい GitLab の問題を作成してタイトルを「CICD AI Insights
」にします。
別の方法として、次の curl コマンドを使用することもできます。GitLab プロジェクト ID が必要です。これは [Settings
/ General
] セクションで確認できます。
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 リポジトリに push する
Google Cloud Shell エディタに戻ります。
[Source Control
] タブに切り替えます。
変更をステージングして commit し、push して review.py
ファイルを更新します。
21. GitLab CICD の構成
次に、変更がリポジトリに push されたときにコードレビューを実行するように 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 UI で [Build / Pipelines
] を開き、[Run Pipeline
] をクリックします。
23. GitLab パイプラインの出力を確認する
GitLab UI で [Build / Jobs
] を開き、パイプラインの出力を確認します。
GitLab ウェブサイトを開き、「CICD Insights
」の問題に関する最新のコメントを確認します。
GitLab ワークフローの実行を無効にする
Google Cloud Shell エディタに戻ります。コード push イベントでの GitLab ワークフローの実行を無効にするには、行のコメント化を解除します。ワークフローは、UI からオンデマンドで実行できます。
# workflow: # rules: # - if: $CI_PIPELINE_SOURCE == "web"
プロジェクトのルートで .gitlab-ci.yml
を開き、次の行のコメント化を解除します。
cloudshell edit ~/gitlab/genai-for-developers/.gitlab-ci.yml
[Source Control
] タブに切り替えて、この変更をステージング、commit、push します。
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 エディタを開き、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
] タブに切り替えて、この変更をステージング、commit、push します。
GitLab ウェブサイトを開き、「Build
」/「Pipelines
」に移動します。
CircleCI へのリンクからワークフローをご確認ください。
リポジトリの GitLab の問題に関するコメントを確認します。
JIRA プロジェクトで作成された新しい問題を確認します。
26. 完了
お疲れさまでした。ラボはこれで完了です。
学習した内容
- GitHub、GitLab、CircleCI に GenAI コードレビュー自動化の手順を追加。
- LangChain ReAct エージェント。GitLab の問題へのコメントや JIRA チケットの作成などのタスクを自動化します。
次のステップ:
- 今後もハンズオン セッションを開催する予定です。
クリーンアップ
このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。
プロジェクトの削除
課金を停止する最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。
©2024 Google LLC All rights reserved. Google および Google のロゴは、Google LLC の商標です。その他すべての社名および製品名は、それぞれ該当する企業の商標である可能性があります。