生成 AI によるコードレビューの自動化

1. 概要

このラボでは、CICD パイプラインを設定し、Gemini と統合してコードレビューの手順を自動化します。

9dde56ad139b9553.png

学習内容

このラボでは、次の方法について学びます。

  • GitHub、GitLab、CircleCI で GenAI コードレビューの自動化ステップを追加する方法
  • LangChain ReAct エージェントとツールキットを使用して、GitLab の問題へのコメントや JIRA チケットの作成などのタスクを自動化する方法

前提条件

  • このラボは、Cloud コンソールと Cloud Shell 環境に精通していることを前提としています。

2. 設定と要件

Cloud プロジェクトの設定

  1. Google Cloud Console にログインして、プロジェクトを新規作成するか、既存のプロジェクトを再利用します。Gmail アカウントも Google Workspace アカウントもまだお持ちでない場合は、アカウントを作成してください。

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • プロジェクト名は、このプロジェクトの参加者に表示される名称です。Google API では使用されない文字列です。いつでも更新できます。
  • プロジェクト ID は、すべての Google Cloud プロジェクトにおいて一意でなければならず、不変です(設定後は変更できません)。Cloud コンソールでは一意の文字列が自動生成されます。通常は、この内容を意識する必要はありません。ほとんどの Codelab では、プロジェクト ID(通常は PROJECT_ID と識別されます)を参照する必要があります。生成された ID が好みではない場合は、ランダムに別の ID を生成できます。または、ご自身で試して、利用可能かどうかを確認することもできます。このステップ以降は変更できず、プロジェクトを通して同じ ID になります。
  • なお、3 つ目の値として、一部の API が使用するプロジェクト番号があります。これら 3 つの値について詳しくは、こちらのドキュメントをご覧ください。
  1. 次に、Cloud のリソースや API を使用するために、Cloud コンソールで課金を有効にする必要があります。この Codelab の操作をすべて行って、費用が生じたとしても、少額です。このチュートリアルの終了後に請求が発生しないようにリソースをシャットダウンするには、作成したリソースを削除するか、プロジェクトを削除します。Google Cloud の新規ユーザーは、300 米ドル分の無料トライアル プログラムをご利用いただけます。

環境設定

Gemini チャットを開きます。

bc3c899ac8bcf488.png

または、検索バーに「Gemini に質問」と入力します。

e1e9ad314691368a.png

Cloud AI Companion API を有効にします。

66cb6e561e384bbf.png

[Start chatting] をクリックして、サンプルの質問のいずれかを使用するか、独自のプロンプトを入力して試します。

5482c153eef23126.png

プロンプトの例:

  • 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 に登録するか、詳細をご覧ください。

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. リポジトリ Secret を追加する

フォークされた GitHub リポジトリの「Settings / Secrets and variables / Actions」にリポジトリ シークレットを作成します。

名前が「GOOGLE_API_CREDENTIALS」のリポジトリ シークレットを追加します。

94cbe2778bef25eb.png

Google Cloud Shell ウィンドウ/タブに切り替えて、Cloud Shell ターミナルで次のコマンドを実行します。

cat ~/vertex-client-key.json

ファイルの内容をコピーして、シークレットの値として貼り付けます。

915579a97f8f2ced.png

4fa92833ce615a36.png として Qwiklabs プロジェクト ID を含む PROJECT_ID シークレットを追加します。

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 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」を選択します。

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 トークンなど)を追跡します。

ラボでは、さまざまなシステムでこれらのコマンドを使用するため、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 を有効にします。

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 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 ウェブサイトを開き、更新された問題を確認します。

9da39bf6070d9447.png

LangSmith で LLM トレースを調べます。

LLM トレースのサンプル。

f32eed34f3a3b040.png

20. 変更を GitLab リポジトリに push する

Google Cloud Shell エディタに戻ります。

[Source Control] タブに切り替えます。

変更をステージングして commit し、push して review.py ファイルを更新します。

b838a11f362454ce.png

21. GitLab CICD の構成

次に、変更がリポジトリに push されたときにコードレビューを実行するように 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 エディタに戻ります。コード 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 します。

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] タブに切り替えて、この変更をステージング、commit、push します。

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 All rights reserved. Google および Google のロゴは、Google LLC の商標です。その他すべての社名および製品名は、それぞれ該当する企業の商標である可能性があります。