Tự động hoá quy trình xem xét mã bằng GenAI

Tự động hoá quy trình xem xét mã bằng GenAI

Thông tin về lớp học lập trình này

subjectLần cập nhật gần đây nhất: thg 10 7, 2024
account_circleTác giả: Andrey Shakirov

1. Tổng quan

Trong lớp học lập trình này, bạn sẽ thiết lập quy trình CICD và tích hợp với Gemini để tự động hoá các bước xem xét mã.

9dde56ad139b9553.png

Kiến thức bạn sẽ học được

Trong lớp học này, bạn sẽ tìm hiểu cách thực hiện những việc sau:

  • Cách thêm các bước tự động hoá quy trình xem xét mã GenAI trong GitHub, GitLab và CircleCI
  • Cách sử dụng các tác nhân và bộ công cụ LangChain ReAct để tự động hoá các tác vụ như bình luận về vấn đề trên GitLab và mở phiếu yêu cầu hỗ trợ trên JIRA

Điều kiện tiên quyết

  • Học phần này giả định rằng bạn đã quen thuộc với môi trường Cloud Console và Cloud Shell.

2. Cách thiết lập và yêu cầu

Thiết lập dự án trên Cloud

  1. Đăng nhập vào Google Cloud Console rồi tạo một dự án mới hoặc sử dụng lại một dự án hiện có. Nếu chưa có tài khoản Gmail hoặc Google Workspace, bạn phải tạo một tài khoản.

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • Tên dự án là tên hiển thị cho người tham gia dự án này. Đây là một chuỗi ký tự không được API của Google sử dụng. Bạn luôn có thể cập nhật thông tin này.
  • Mã dự án là duy nhất trên tất cả các dự án Google Cloud và không thể thay đổi (không thể thay đổi sau khi đặt). Cloud Console sẽ tự động tạo một chuỗi duy nhất; thường thì bạn không cần quan tâm đến chuỗi này. Trong hầu hết các lớp học lập trình, bạn sẽ cần tham chiếu đến Mã dự án (thường được xác định là PROJECT_ID). Nếu không thích mã được tạo, bạn có thể tạo một mã ngẫu nhiên khác. Ngoài ra, bạn có thể thử dùng email của riêng mình để xem có thể sử dụng hay không. Bạn không thể thay đổi thông tin này sau bước này và thông tin này sẽ được giữ nguyên trong suốt thời gian diễn ra dự án.
  • Xin lưu ý rằng có một giá trị thứ ba là Mã dự án mà một số API sử dụng. Tìm hiểu thêm về cả ba giá trị này trong tài liệu.
  1. Tiếp theo, bạn cần bật tính năng thanh toán trong Cloud Console để sử dụng các tài nguyên/API trên Cloud. Việc tham gia lớp học lập trình này sẽ không tốn kém nhiều chi phí, nếu có. Để tắt các tài nguyên nhằm tránh bị tính phí sau khi hoàn tất hướng dẫn này, bạn có thể xoá các tài nguyên đã tạo hoặc xoá dự án. Người dùng mới của Google Cloud đủ điều kiện tham gia chương trình Dùng thử miễn phí 300 USD.

Thiết lập môi trường

Mở cuộc trò chuyện trên Gemini.

bc3c899ac8bcf488.png

Hoặc nhập "Hỏi Gemini" vào thanh tìm kiếm.

e1e9ad314691368a.png

Bật Cloud AI Companion API:

66cb6e561e384bbf.png

Nhấp vào "Start chatting" rồi làm theo một trong các câu hỏi mẫu hoặc nhập câu lệnh của riêng bạn để thử.

5482c153eef23126.png

Các câu lệnh bạn có thể thử:

  • Giải thích Cloud Run trong 5 điểm chính.
  • Bạn là Nhà quản lý sản phẩm Google Cloud Run, hãy giải thích về Cloud Run cho học viên trong 5 điểm chính ngắn gọn.
  • Bạn là Nhà quản lý sản phẩm Cloud Run của Google, hãy giải thích về Cloud Run cho một Nhà phát triển Kubernetes được chứng nhận trong 5 điểm chính ngắn gọn.
  • Bạn là Nhà quản lý sản phẩm Google Cloud Run, hãy giải thích cho một Nhà phát triển cấp cao về thời điểm bạn sẽ sử dụng Cloud Run so với GKE trong 5 điểm chính ngắn gọn.

Hãy xem Hướng dẫn về câu lệnh để tìm hiểu thêm về cách viết câu lệnh hiệu quả hơn.

Cách Gemini cho Google Cloud sử dụng dữ liệu của bạn

Cam kết của Google về quyền riêng tư

Google là một trong những công ty đầu tiên trong ngành công bố cam kết về quyền riêng tư liên quan đến AI/ML. Cam kết này nêu rõ quan điểm của chúng tôi rằng khách hàng phải có mức độ bảo mật và quyền kiểm soát cao nhất đối với dữ liệu của họ được lưu trữ trên đám mây.

Dữ liệu bạn gửi và nhận

Những câu hỏi mà bạn đặt cho Gemini, bao gồm mọi thông tin đầu vào hoặc mã mà bạn gửi cho Gemini để phân tích hoặc hoàn thành, được gọi là câu lệnh. Câu trả lời hoặc mã hoàn chỉnh mà bạn nhận được từ Gemini được gọi là phản hồi. Gemini không sử dụng câu lệnh của bạn hoặc câu trả lời của Gemini làm dữ liệu để huấn luyện các mô hình của mình.

Mã hoá lời nhắc

Khi bạn gửi câu lệnh cho Gemini, dữ liệu của bạn sẽ được mã hoá trong quá trình truyền dữ liệu dưới dạng dữ liệu đầu vào cho mô hình cơ bản trong Gemini.

Dữ liệu chương trình được tạo từ Gemini

Gemini được huấn luyện dựa trên mã Google Cloud của bên thứ nhất cũng như mã bên thứ ba đã chọn. Bạn chịu trách nhiệm về tính bảo mật, khả năng kiểm thử và hiệu quả của mã, bao gồm cả mọi tính năng hoàn tất, tạo hoặc phân tích mã mà Gemini cung cấp cho bạn.

Tìm hiểu thêm về cách Google xử lý lời nhắc của bạn.

3. Các lựa chọn để kiểm thử lời nhắc

Nếu muốn thay đổi/mở rộng lời nhắc devai cli hiện có, bạn có một số lựa chọn.

Vertex AI Studio là một phần của nền tảng Vertex AI của Google Cloud, được thiết kế riêng để đơn giản hoá và đẩy nhanh quá trình phát triển cũng như sử dụng các mô hình AI tạo sinh.

AI Studio của Google là một công cụ dựa trên web để tạo nguyên mẫu và thử nghiệm kỹ thuật câu lệnh cũng như API Gemini. Đăng ký Gemini 1.5 Pro với cửa sổ ngữ cảnh 1 triệu token hoặc tìm hiểu thêm.

Ứng dụng web Google Gemini (gemini.google.com) là một công cụ dựa trên web được thiết kế để giúp bạn khám phá và khai thác sức mạnh của các mô hình AI Gemini của Google.

4. Tạo tài khoản dịch vụ

Kích hoạt Cloud Shell bằng cách nhấp vào biểu tượng ở bên phải thanh tìm kiếm.

3e0c761ca41f315e.png

Trong thiết bị đầu cuối đã mở, hãy bật các dịch vụ bắt buộc để sử dụng API Vertex AI và tính năng trò chuyện trên Gemini.

gcloud services enable \
    aiplatform
.googleapis.com \
    cloudaicompanion
.googleapis.com \
    cloudresourcemanager
.googleapis.com \
    secretmanager
.googleapis.com

Nếu bạn được nhắc uỷ quyền, hãy nhấp vào "Uỷ quyền" để tiếp tục.

6356559df3eccdda.png

Chạy các lệnh sau để tạo tài khoản dịch vụ và khoá mới.

Bạn sẽ sử dụng tài khoản dịch vụ này để thực hiện các lệnh gọi API đến API Gemini của Vertex AI từ quy trình CICD.

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. Phát triển nhánh kho lưu trữ GitHub sang kho lưu trữ GitHub cá nhân của bạn

Truy cập vào https://github.com/GoogleCloudPlatform/genai-for-developers/fork và chọn tên người dùng GitHub của bạn làm chủ sở hữu.

Bỏ chọn tuỳ chọn chỉ sao chép nhánh "chính".

Nhấp vào "Create fork".

6. Bật quy trình công việc GitHub Actions

Mở kho lưu trữ GitHub đã phân nhánh trong trình duyệt và chuyển sang thẻ "Actions" để bật quy trình làm việc.

1cd04db9b37af7cf.png

7. Thêm Kho lưu trữ bí mật

Tạo một khoá bí mật của kho lưu trữ trong "Settings / Secrets and variables / Actions" trong kho lưu trữ GitHub được phân nhánh.

Thêm khoá bí mật của Kho lưu trữ có tên "GOOGLE_API_CREDENTIALS".

94cbe2778bef25eb.png

Chuyển sang cửa sổ/thẻ Google Cloud Shell rồi chạy lệnh bên dưới trong dòng lệnh Cloud Shell.

cat ~/vertex-client-key.json

Sao chép nội dung tệp rồi dán nội dung đó dưới dạng giá trị cho khoá bí mật.

915579a97f8f2ced.png

Thêm khoá PROJECT_ID bằng mã dự án Qwiklabs làm giá trị 4fa92833ce615a36.png

8. Chạy quy trình công việc GitHub Actions

Chuyển đến kho lưu trữ GitHub trong trình duyệt và chạy quy trình công việc.

Quy trình công việc được định cấu hình để chạy trên tính năng đẩy mã hoặc thực thi theo cách thủ công.

Chọn "GenAI For Developers" trong phần Tất cả quy trình công việc rồi nhấp vào "Run workflow" bằng nhánh "main".

da11273b4b54f7b6.png

Xem xét kết quả:

cf49aa41980aacc5.png

Kết quả của lệnh kiểm thử mức độ sử dụng:

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

3b21bd4639524763.png

Kết quả của lệnh xem xét mã:

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

4876dbc2e0042943.png

Kết quả của lệnh xem xét hiệu suất:

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

98dd2472b2e819bf.png

Kết quả của lệnh đánh giá bảo mật:

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

7d180a763db92d56.png

Kết quả của lệnh xem xét trình chặn:

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

726175e874aefcf.png

9. Sao chép kho lưu trữ

Quay lại cửa sổ dòng lệnh Cloud Shell và sao chép kho lưu trữ.

Tạo thư mục cho kho lưu trữ GitHub.

mkdir github
cd github

Thay đổi YOUR-GITHUB-USERID thành tên người dùng GitHub của bạn trước khi chạy các lệnh.

Đặt tên người dùng và email Git trong thiết bị đầu cuối.

Cập nhật các giá trị trước khi chạy các lệnh.

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 

Thay đổi thư mục và mở tệp quy trình công việc trong Trình chỉnh sửa Cloud Shell.

cd genai-for-developers

cloudshell edit
.github/workflows/devai-review.yml

Chờ cho đến khi tệp cấu hình xuất hiện trong IDE.

9e81e5a79d421eac.png

10. Bật tính năng Gemini Code Assist

Nhấp vào biểu tượng "Gemini" ở góc dưới cùng bên phải 7c891e32c055c0e4.png,

nhấp vào "Login to Google Cloud" và "Select a Google Cloud Project".

f5318f22c91ecaa8.png

6b7203ffdd8485fa.png

fb8d42a6bc8a260f.png

Trong cửa sổ bật lên, hãy chọn dự án Qwiklabs của bạn.

f661047956a6d6f9.png

11. Giải thích đoạn mã bằng tính năng Gemini Code Assist

Nhấp chuột phải vào vị trí bất kỳ trong tệp devai-review.yml rồi chọn Gemini Code Assist > Explain này.

41fb7da002bdf43.png

Giải thích về bài đánh giá:

7724d52e54918c00.png

12. Chạy DEVAI CLI cục bộ

Quay lại Trình chỉnh sửa Cloud Shell và mở một Cửa sổ dòng lệnh mới.

149218baaf30865f.png

Quay lại cửa sổ dòng lệnh Cloud Shell và chạy các lệnh bên dưới để cài đặt devai trên máy.

pip3 install devai-cli

Bạn đã cài đặt cli nhưng cli không có trong 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.

Chạy lệnh dưới đây để cập nhật biến môi trường PATH. Thay thế bằng tên thư mục gốc của người dùng. Ví dụ: student_00_478dfeb8df15

export PATH=$PATH:/home/YOUR-USER-HOME-FOLDER/.local/bin

Chạy lệnh devai cli để xem xét mã cục bộ. Xem lại kết quả đầu ra của 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

Mở tập lệnh đánh giá bằng cách chạy lệnh dưới đây:

cloudshell edit devai-cli/src/devai/commands/review.py

Nhấp chuột phải vào vị trí bất kỳ trong tệp review.py rồi chọn Gemini Code Assist > Explain này.

Giải thích về bài đánh giá.

30e3baf4c272c8ab.png

13. Phát triển DevAI CLI

Trong phần này, bạn sẽ thực hiện các thay đổi đối với devai cli.

Để bắt đầu, hãy thiết lập python virtualenv, cài đặt các yêu cầu và chạy lệnh mẫu.

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

Chạy lệnh xem xét mức độ sử dụng kiểm thử để kiểm tra xem mọi thứ có hoạt động tốt không:

devai review testcoverage -c ~/github/genai-for-developers/sample-app/src

Xem lại kết quả bằng tính năng xem trước Markdown trong Trình chỉnh sửa Cloud Shell.

Tạo một tệp mới và dán nội dung phản hồi của Gemini.

Sau đó, sử dụng Bảng điều khiển lệnh và chọn "Markdown: Open Preview".

ec6fedf4b6d3fb73.png

9999e7fbb20cf251.png

76858be03d73abd0.png

14. Khám phá các lệnh devai cli

Lệnh xem xét mã

devai review code -c ~/github/genai-for-developers/sample-app/src/main/java

Lệnh đánh giá hiệu suất

devai review performance -c ~/github/genai-for-developers/sample-app/src/main/java

Lệnh xem xét bảo mật

devai review security -c ~/github/genai-for-developers/sample-app/src/main/java

Lệnh xem xét mức độ bao phủ kiểm thử

devai review testcoverage -c ~/github/genai-for-developers/sample-app/src

Lệnh xem xét trình chặn

devai review blockers -c ~/github/genai-for-developers/sample-app/pom.xml
devai review blockers
-c ~/github/genai-for-developers/sample-app/setup.md

Xem xét và tóm tắt hình ảnh/biểu đồ:

Sơ đồ đầu vào[~/github/genai-for-developers/images/extension-diagram.png]:

4b109a74e1aa3fb6.png

Lệnh xem xét:

devai review image \
 
-f ~/github/genai-for-developers/images/extension-diagram.png \
 
-p "Review and summarize this diagram"

Kết quả:

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.

Phân tích sự khác biệt về hình ảnh:

devai review imgdiff \
 
-c ~/github/genai-for-developers/images/devai-api.png \
 
-t ~/github/genai-for-developers/images/devai-api-slack.png

Kết quả:

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.

Lệnh tạo tài liệu:

devai document readme -c ~/github/genai-for-developers/sample-app/src/main/

Kết quả:

# 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)

Xem lại các lệnh devai cli hiện có trong Trình chỉnh sửa Cloud Shell:

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

Hoặc xem lại README.md trong kho lưu trữ GitHub.

15. Theo dõi tất cả biến môi trường trong một tệp

Bắt đầu một tệp mới để theo dõi tất cả các biến môi trường (ví dụ: khoá API, mã thông báo API, v.v.) mà bạn sẽ tạo.

Bạn sẽ sử dụng các biến này cho nhiều hệ thống trong quá trình tham gia lớp học này, vì vậy, việc tham chiếu các biến này ở cùng một nơi sẽ dễ dàng hơn.

16. Cấu hình theo dõi LLM LangSmith

Tạo tài khoản LangSmith và tạo khoá API dịch vụ trong mục Cài đặt. https://docs.smith.langchain.com/

Thiết lập các biến môi trường cần thiết để tích hợp LangSmith. Thay thế khoá API dịch vụ trước khi chạy các lệnh.

export LANGCHAIN_API_KEY=langsmith-service-api-key

export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"

Để tránh tiết lộ thông tin nhạy cảm trong thiết bị đầu cuối, tốt nhất bạn nên sử dụng read -s. Đây là cách an toàn để đặt các biến môi trường mà không cần giá trị xuất hiện trong nhật ký lệnh của bảng điều khiển. Sau khi chạy, bạn phải dán giá trị và nhấn enter.

17. Cấu hình lệnh JIRA

Tạo tài khoản JIRA nếu bạn chưa có.

Tạo mã thông báo API JIRA cho dự án của bạn. https://id.atlassian.com/manage-profile/security/api-tokens

Đặt các biến môi trường này cần thiết để tích hợp JIRA (thay thế các giá trị trước khi chạy các lệnh).

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

Mở tệp review.py:

cloudshell edit ~/github/genai-for-developers/devai-cli/src/devai/commands/review.py

Xem xét tệp 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) 

Tìm và bỏ ghi chú dòng bên dưới dòng này:

# Uncomment after configuring JIRA and GitLab env variables - see README.md for details

Lệnh nhập JIRA ở đầu tệp

# from devai.commands.jira import create_jira_issue

Phương thức tạo vấn đề JIRA trong phương thức code

#create_jira_issue("Code Review Results", response.text)

Chạy lại lệnh xem xét mã và kiểm tra kết quả của tác nhân:

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

Kết quả mẫu:

(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: Hàm __call__ không còn được dùng nữa trong LangChain 0.1.0 và sẽ bị xoá trong 0.2.0. Thay vào đó, hãy sử dụng lệnh gọi. warn_deprecated(

Đang nhập chuỗi AgentExecutor mới... Suy nghĩ: Nội dung mô tả được cung cấp trong câu hỏi nên bạn không cần phải suy nghĩ về Hành động:

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

Tạo vấn đề mới bằng khoá: CYMEATS-117

Quan sát: Vấn đề mới được tạo bằng khoá: CYMEATS-117 Ý kiến:Đáp án cuối cùng: CYMEATS-117

Chuỗi đã hoàn tất.

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

Thay đổi thư mục và mở tệp .gitlab-ci.yml.

cd genai-for-developers

cloudshell edit
.gitlab-ci.yml

Trong trường hợp bạn chưa bật, hãy bật Gemini trong Trình chỉnh sửa Cloud Shell.

4a7f4640f66037f.png

Nhấp chuột phải vào vị trí bất kỳ trong tệp .gitlab-ci.yml rồi chọn "Gemini Code Assist > Explain this".

154838a0100389a9.png

18. Cấu hình lệnh GitLab

Mở GitLab và tạo Mã truy cập dự án trong "Settings / Access Tokens" trong kho lưu trữ GitLab đã tạo ở các bước trước.

Sao chép và lưu trữ giá trị Mã thông báo truy cập để sử dụng trong các bước tiếp theo.

Sử dụng các thông tin sau:

  • Tên mã thông báo: devai-cli-qwiklabs
  • Vai trò: Maintainer
  • Phạm vi: api

1865de233277f11c.png

Đặt các biến môi trường cần thiết để tích hợp GitLab.

Lệnh này yêu cầu bạn cập nhật Mã truy cập GitLab.

export GITLAB_PERSONAL_ACCESS_TOKEN=gitlab-access-token

Lệnh này yêu cầu bạn cập nhật tên người dùng và tên kho lưu trữ GitLab.

export GITLAB_REPOSITORY="USERID/REPOSITORY"

Thiết lập phần còn lại của các biến môi trường:

export GITLAB_URL="https://gitlab.com"
export GITLAB_BRANCH="devai"
export GITLAB_BASE_BRANCH="main"

Mở trang web GitLab và tạo một vấn đề GitLab mới trong dự án của bạn có tiêu đề "CICD AI Insights".

63a13948f6864074.png

Một lựa chọn khác là sử dụng lệnh curl bên dưới. Bạn sẽ cần mã dự án GitLab – bạn có thể tra cứu mã này trong phần "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

Quay lại Cloud Shell và mở tệp review.py:

cloudshell edit ~/gitlab/genai-for-developers/devai-cli/src/devai/commands/review.py

Tìm và bỏ ghi chú mã bên dưới

Dòng để nhập lệnh GitLab

# from devai.commands.gitlab import create_gitlab_issue_comment

Phương thức để bình luận về vấn đề trên GitLab

# create_gitlab_issue_comment(response.text)

19. Phát triển CLI DevAI

Kể từ khi bạn chuyển sang kho lưu trữ/thư mục GitLab. Bạn sẽ cần chạy lại các bước thiết lập bên dưới.

Trong cửa sổ dòng lệnh, hãy thiết lập virtualenv python, cài đặt các yêu cầu và chạy lệnh mẫu.

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

Bạn có thể xác nhận vị trí của cli – lần này, cli sẽ nằm trong thư mục GitLab.

 which devai

Chạy lại lệnh xem xét mã trong dòng lệnh:

devai review code -c ~/gitlab/genai-for-developers/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader

Kết quả mẫu – với một số phần được rút ngắn:

(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.

Mở trang web GitLab và xem lại vấn đề đã cập nhật.

9da39bf6070d9447.png

Xem lại dấu vết LLM trong LangSmith.

Dấu vết LLM mẫu.

f32eed34f3a3b040.png

20. Đẩy các thay đổi vào kho lưu trữ GitLab

Quay lại Trình chỉnh sửa Google Cloud Shell.

Chuyển sang thẻ "Source Control".

Phân đoạn, xác nhận và đẩy các thay đổi bạn đã thực hiện để cập nhật tệp review.py.

b838a11f362454ce.png

21. Cấu hình GitLab CICD

Tiếp theo, bạn sẽ bật quy trình CICD của GitLab để chạy quy trình xem xét mã khi các thay đổi được đẩy vào kho lưu trữ.

Mở trang web GitLab rồi chuyển đến phần "Settings / CICD"".

Mở rộng phần Variables rồi nhấp vào "Add variable".

Hãy nhớ bỏ chọn tất cả các hộp đánh dấu khi bạn thêm biến. Ví dụ:

68b3ed732b6a8fe9.png

Sử dụng ghi chú của bạn, nơi bạn lưu giữ tất cả các biến môi trường, hãy thêm biến môi trường cho JIRA, GitLab và 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"

Đối với giá trị biến GOOGLE_CLOUD_CREDENTIALS, hãy sử dụng khoá tài khoản dịch vụ được tạo trong phần trên.

cat ~/vertex-client-key.json

Chế độ xem Biến CI/CD:

2f4594ce72be4834.png

22. Chạy quy trình CICD của GitLab

Mở "Build / Pipelines" trong giao diện người dùng GitLab rồi nhấp vào "Run Pipeline".

a7518e37dde42366.png

23. Xem xét đầu ra của quy trình GitLab

Mở "Build / Jobs" trong giao diện người dùng GitLab và xem lại đầu ra của quy trình.

985e4b322fb73b1c.png

Mở trang web GitLab và xem lại các nhận xét đã cập nhật về vấn đề "CICD Insights".

Tắt tính năng thực thi quy trình công việc GitLab

Quay lại Trình chỉnh sửa Google Cloud Shell. Huỷ ghi chú các dòng để tắt tính năng thực thi quy trình công việc GitLab trên các sự kiện đẩy mã. Bạn vẫn có thể thực thi quy trình công việc từ giao diện người dùng theo yêu cầu.

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

Mở .gitlab-ci.yml trong thư mục gốc của dự án và bỏ ghi chú các dòng:

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

Chuyển sang thẻ "Source Control" – giai đoạn, cam kết và đẩy thay đổi này.

a9d52beb8c642982.png

24. Tích hợp CircleCI

CircleCI là gì?

CircleCI là một nền tảng CI/CD dựa trên đám mây, cho phép các nhóm tự động hoá quy trình phát triển và triển khai phần mềm. Công cụ này tích hợp với các hệ thống quản lý phiên bản như GitHub, Bitbucket và GitLab, cho phép các nhóm xác thực các thay đổi về mã theo thời gian thực bằng cách chạy các bản kiểm thử và bản dựng tự động. Đối với phương thức phân phối liên tục, CircleCI có thể tự động triển khai phần mềm cho nhiều môi trường đám mây như AWS, Google Cloud và Azure.

Thiết lập

Mở trang web CircleCI và tạo một Dự án mới. Chọn "GitLab" / "Cloud" cho kho lưu trữ của bạn.

Cấp cho CircleCI quyền truy cập vào tài khoản GitLab của bạn.

Trong tuỳ chọn Nhanh nhất, hãy chọn nhánh main. CircleCI có thể phát hiện một tệp cấu hình hiện có và bỏ qua bước này.

4e9b7cef458d5fba.png

Sau khi tạo dự án, hãy nhấp vào phần "Project Settings" / "Environment Variables".

1499b5f96ac0fe5e.png

Thêm tất cả biến môi trường mà bạn đã sử dụng cho đến thời điểm này.

f15b7a3e02c649e8.png

Dưới đây là danh sách mẫu các biến môi trường cần thêm.

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. Bật phương thức JIRA và GitLab

Mở Trình chỉnh sửa Google Cloud Shell và thực hiện thay đổi đối với tệp review.py.

Tìm và bỏ ghi chú các dòng bên dưới.

# 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)

Chuyển sang thẻ "Source Control" – giai đoạn, cam kết và đẩy thay đổi này.

Mở trang web GitLab rồi chuyển đến "Build" / "Pipelines".

d196ad631be17b88.png

Hãy truy cập vào đường liên kết đến CircleCI để xem quy trình làm việc.

d4ff287694b82445.png

Xem lại các nhận xét về vấn đề trên GitLab trong kho lưu trữ của bạn.

e77ee826488d5299.png

9a51daa2960994e3.png

Xem xét các vấn đề mới được tạo trong dự án JIRA.

1e6305a32aaef6a2.png

26. Xin chúc mừng!

Xin chúc mừng, bạn đã hoàn thành lớp học lập trình!

Nội dung chúng ta đã đề cập:

  • Thêm các bước tự động hoá quy trình xem xét mã GenAI trong GitHub, GitLab và CircleCI.
  • Các tác nhân LangChain ReAct để tự động hoá các tác vụ như bình luận về vấn đề trên GitLab và mở phiếu yêu cầu hỗ trợ trên JIRA.

Bước tiếp theo:

  • Chúng tôi sẽ tổ chức thêm nhiều buổi thực hành khác!

Dọn dẹp

Để tránh bị tính phí cho tài khoản Google Cloud của bạn đối với các tài nguyên được sử dụng trong hướng dẫn này, hãy xoá dự án chứa các tài nguyên đó hoặc giữ lại dự án và xoá từng tài nguyên.

Xoá dự án

Cách dễ nhất để loại bỏ tính năng thanh toán là xoá dự án mà bạn đã tạo cho hướng dẫn này.

©2024 Google LLC Mọi quyền được bảo lưu. Google và biểu trưng Google là các nhãn hiệu của Google LLC. Tất cả các tên công ty và sản phẩm khác có thể là nhãn hiệu của công ty liên quan tương ứng.