אוטומציה של בדיקת הקוד באמצעות GenAI

1. סקירה כללית

בשיעור ה-Lab הזה תגדירו את צינור עיבוד הנתונים של CICD ותשלבו עם Gemini כדי לבצע באופן אוטומטי את השלבים לבדיקת קוד.

9dde56ad139b9553.png

מה תלמדו

בשיעור Lab זה תלמדו איך:

  • איך מוסיפים שלבים לאוטומציה של בדיקת הקוד של GenAI ב-GitHub, ב-GitLab וב-CircleCI
  • איך משתמשים בסוכני LangChain ReAct ובערכות הכלים שלהם כדי להפוך משימות לאוטומטיות, כמו הוספת תגובות לבעיות ב-GitLab ופתיחת כרטיסים ב-JIRA

דרישות מוקדמות

  • שיעור ה-Lab הזה מבוסס על היכרות עם הסביבות של Cloud Console ו-Cloud Shell.

2. הגדרה ודרישות

הגדרת פרויקט ב-Cloud

  1. נכנסים למסוף Google Cloud ויוצרים פרויקט חדש או עושים שימוש חוזר בפרויקט קיים. אם אין לכם עדיין חשבון Gmail או חשבון Google Workspace, עליכם ליצור חשבון.

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • שם הפרויקט הוא השם המוצג של המשתתפים בפרויקט. זוהי מחרוזת תווים שלא משמשת את Google APIs. תמיד אפשר לעדכן.
  • מזהה הפרויקט הוא ייחודי לכל הפרויקטים ב-Google Cloud ואי אפשר לשנות אותו אחרי שמגדירים אותו. מסוף Cloud יוצר מחרוזת ייחודית באופן אוטומטי; בדרך כלל לא מעניין אותך מה זה. ברוב ה-codelabs תצטרכו להפנות למזהה הפרויקט שלכם (בדרך כלל מזוהה כ-PROJECT_ID). אם המזהה שנוצר לא מוצא חן בעיניכם, אתם יכולים ליצור מזהה אקראי אחר. לחלופין, אפשר לנסות כתובת משלכם ולבדוק אם היא זמינה. לא ניתן לשנות אותו אחרי השלב הזה, והוא נשאר למשך הפרויקט.
  • לידיעתך, יש ערך שלישי, Project Number, שבו משתמשים בחלק מממשקי ה-API. מידע נוסף על כל שלושת הערכים האלה זמין במסמכי העזרה.
  1. בשלב הבא צריך להפעיל את החיוב במסוף Cloud כדי להשתמש במשאבים או בממשקי API של Cloud. מעבר ב-Codelab הזה לא יעלה הרבה כסף, אם בכלל. כדי להשבית את המשאבים ולמנוע חיובים אחרי סיום המדריך, אפשר למחוק את המשאבים שיצרתם או למחוק את הפרויקט. משתמשים חדשים ב-Google Cloud זכאים להשתתף בתוכנית תקופת ניסיון בחינם בשווי 1,200 ש"ח.

הגדרת הסביבה

פתיחת השיחה עם 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, ואתם צריכים להסביר את Cloud Run למפתח Kubernetes מוסמך ב-5 נקודות עיקריות קצרות.
  • אתם מנהלי מוצר של Google Cloud Run, ואתם צריכים להסביר למפתח בכיר מתי כדאי להשתמש ב-Cloud Run לעומת GKE, ב-5 נקודות מפתח קצרות.

במדריך לכתיבת הנחיות אפשר למצוא מידע נוסף על כתיבת הנחיות טובות יותר.

איך Gemini ל-Google Cloud משתמש בנתונים שלכם

המחויבות של Google לפרטיות

Google הייתה אחת מהחברות הראשונות בתחום שפרסמתה מחויבות לפרטיות ב-AI/ML, שבה אנו מבטאים את האמונה שלנו שללקוחות צריכה להיות רמה הגבוהה ביותר של אבטחה ושליטה על הנתונים שלהם שמאוחסנים בענן.

נתונים שאתם שולחים ומקבלים

השאלות ששואלים את Gemini, כולל כל קלט או קוד ששולחים ל-Gemini כדי לנתח או למלא, נקראות הנחיות. התשובות או השלמות הקוד שאתם מקבלים מ-Gemini נקראות תגובות. Gemini לא משתמש בהנחיות שלכם או בתשובות שלו כנתונים לאימון המודלים שלו.

הצפנה של הנחיות

כששולחים הנחיות ל-Gemini, הנתונים מוצפנים במעבר כקלט למודל הבסיסי ב-Gemini.

נתוני התוכנית נוצרו מ-Gemini

Gemini מאומן על קוד Google Cloud של צד ראשון ועל קוד של צד שלישי שנבחר. אתם אחראים לאבטחה, לבדיקה וליעילות של הקוד, כולל כל השלמה, יצירה או ניתוח של הקוד ש-Gemini מציע לכם.

למידע נוסף על האופן שבו Google מטפלת בהודעות שלך.

3. אפשרויות לבדיקה של הנחיות

אם אתם רוצים לשנות או להרחיב הנחיות קיימות של CLI של devai, יש כמה אפשרויות לעשות זאת.

Vertex AI Studio הוא חלק מפלטפורמת Vertex AI של Google Cloud, שמיועדת במיוחד לפשט ולהאיץ את הפיתוח והשימוש במודלים של AI גנרטיבי.

Google AI Studio הוא כלי מבוסס-אינטרנט ליצירת אב טיפוס ולהתנסות בהנדסת הנחיות וב-Gemini API. נרשמים ל-Gemini 1.5 Pro עם חלון הקשר של מיליון או מידע נוסף.

אתר Google Gemini (gemini.google.com) הוא כלי מבוסס-אינטרנט שמטרתו לעזור לכם להתנסות ביכולות של המודלים ב-Gemini AI מבית Google ולהשתמש בהם.

4. יצירת חשבון שירות

לוחצים על הסמל שמופיע מימין לסרגל החיפוש כדי להפעיל את Cloud Shell.

3e0c761ca41f315e.png

בטרמינל שנפתח, מפעילים את השירותים הנדרשים כדי להשתמש בממשקי ה-API של Vertex AI וב-Gemini Chat.

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

אם מתבקשים לאשר, לוחצים על 'הרשאה' כדי להמשיך.

6356559df3eccdda.png

מריצים את הפקודות הבאות כדי ליצור חשבון שירות ומפתחות חדשים.

חשבון השירות הזה ישמש לביצוע קריאות ל-API ל-Vertex AI Gemini API מצינורות עיבוד נתונים של 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. איחוד מאגר GitHub למאגר האישי שלך ב-GitHub

עוברים אל https://github.com/GoogleCloudPlatform/genai-for-developers/fork ובוחרים את מזהה המשתמש ב-GitHub בתור הבעלים.

מבטלים את הסימון של האפשרות להעתקת ההסתעפות 'main' בלבד.

לוחצים על 'Create fork'.

6. הפעלת תהליכי עבודה של פעולות GitHub

פותחים את המאגר המחובר ב-GitHub בדפדפן ומעברים לכרטיסייה Actions כדי להפעיל את תהליכי העבודה.

1cd04db9b37af7cf.png

7. הוספת סודות של מאגרים

יוצרים סוד במאגר בקטע 'Settings / Secrets and variables / Actions' במאגר המחובר ב-GitHub.

מוסיפים סוד למאגר בשם GOOGLE_API_CREDENTIALS.

94cbe2778bef25eb.png

עוברים לחלון או לכרטיסייה של Google Cloud Shell ומריצים את הפקודה הבאה בטרמינל של Cloud Shell.

cat ~/vertex-client-key.json

מעתיקים את תוכן הקובץ ומדביקים אותו כערך של הסוד.

915579a97f8f2ced.png

מוסיפים את הסוד PROJECT_ID עם מזהה הפרויקט ב-Qwiklabs כערך 4fa92833ce615a36.png

8. הפעלת תהליך עבודה של GitHub Actions

עוברים למאגר ב-GitHub בדפדפן ומפעילים את תהליך העבודה.

תהליך העבודה מוגדר לפעול בהעברת קוד או בהפעלה ידנית.

בוחרים באפשרות GenAI For Developers בקטע All workflows (כל תהליכי העבודה) ולוחצים על Run workflow באמצעות ההסתעפות main.

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.

במסוף, מגדירים את שם המשתמש והאימייל ב-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 Editor.

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 Editor ופותחים טרמינל חדש.

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. פיתוח CLI של DevAI

בקטע הזה תבצעו שינויים ב-devai cli.

כדי להתחיל, צריך להגדיר pythonVirtualenv, להתקין את הדרישות ולהריץ את הפקודה לדוגמה.

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

בודקים את התוצאות באמצעות תצוגה מקדימה של Markdown ב-Cloud Shell Editor.

יוצרים קובץ חדש ומדביקים את התשובה של Gemini.

לאחר מכן משתמשים בלוח הפקודות ובוחרים באפשרות Markdown: Open Preview.

ec6fedf4b6d3fb73.png

9999e7fbb20cf251.png

76858be03d73abd0.png

14. פקודות CLI של devai

הפקודה לבדיקת קוד

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)

עיון בפקודות devai cli הזמינות ב-Cloud Shell Editor:

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

לחלופין, אפשר לעיין בקובץ README.md במאגר ב-GitHub.

15. מעקב אחרי כל משתני הסביבה בקובץ

יוצרים קובץ חדש כדי לעקוב אחרי כל משתני הסביבה (למשל, מפתחות API, אסימוני API וכו') שתיצרו.

במהלך השיעור תשתמשו בהם במערכות שונות, ולכן קל יותר להפנות אליהן במקום אחד.

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, אם אין לכם חשבון כזה.

יוצרים אסימון API של JIRA לפרויקט. 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

שיטה ליצירת בעיה ב-JIRA בשיטה code

#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: The function __call__ was deprecated in LangChain 0.1.0 and will be removed in 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 שמשויכים:Final Answer: 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

חתול ~/.ssh/id_ed25519.pub

Add a public key to your GitLab account.

Open  [https://gitlab.com/-/profile/keys](https://gitlab.com/-/profile/keys) and click "Add new key".

For the key value copy/paste the output of the last command.

Go back to the terminal and clone the repository. 

cd ~ mkdir gitlab cd gitlab

Replace with your GitLab userid and repository url that was just created.

```console
git clone git@gitlab.com:YOUR_GITLAB_USERID/genai-for-developers.git

שינוי הספרייה ופתיחת הקובץ .gitlab-ci.yml.

cd genai-for-developers

cloudshell edit .gitlab-ci.yml

אם לא עשיתם זאת בעבר, צריך להפעיל את Gemini ב-Cloud Shell Editor.

4a7f4640f66037f.png

לוחצים לחיצה ימנית במקום כלשהו בקובץ .gitlab-ci.yml ובוחרים באפשרות Gemini Code Assist > Explain this".

154838a0100389a9.png

18. הגדרת הפקודה של GitLab

פותחים את GitLab ויוצרים אסימון גישה לפרויקט בקטע Settings / Access Tokens במאגר GitLab שנוצר בשלבים הקודמים.

מעתיקים ומאחסנים את הערך של אסימון הגישה לשימוש בשלבים הבאים.

משתמשים בפרטים הבאים:

  • שם הטוקן: devai-cli-qwiklabs
  • תפקיד: Maintainer
  • היקף: api

1865de233277f11c.png

מגדירים את משתני הסביבה הנדרשים לשילוב עם GitLab.

הפקודה הזו מחייבת לעדכן את אסימון הגישה של GitLab.

export GITLAB_PERSONAL_ACCESS_TOKEN=gitlab-access-token

כדי להשתמש בפקודה הזו, צריך לעדכן את מזהה המשתמש ואת שם המאגר ב-GitLab.

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. אפשר למצוא אותו בקטע 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. פיתוח CLI של DevAI

כי עברת למאגר/לספרייה של GitLab. תצטרכו להריץ מחדש את שלבי ההגדרה שמפורטים בהמשך.

בטרמינל, מגדירים את ה-Virtualenv של python, מתקינים את הדרישות ומריצים את הפקודה לדוגמה.

export PROJECT_ID=$(gcloud config get-value project)
export LOCATION=us-central1

cd ~/gitlab/genai-for-developers/devai-cli
python3 -m venv venv
. venv/bin/activate
pip3 install -r src/requirements.txt
pip3 install --editable ./src
devai echo

אפשר לאמת את המיקום של cli – הפעם הוא אמור להיות בתיקיית GitLab.

 which devai

מריצים מחדש את הפקודה לבדיקה של הקוד במסוף:

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

פלט לדוגמה – עם חלק מהקטעים מקוצרים:

(venv) student_00_19a997c157f8@cloudshell:~/genai-for-developers/devai-cli (qwiklabs-gcp-02-71a9948ae110)$ devai review code -c ../sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
.
.
Response from Model: **Class: Transaction**

**Method: toString**

**Maintainability:**

* The formatting of the string representation could be more clear and concise. Consider using a dedicated method for formatting the amount, e.g., `formatAmount()`.
.
.

> Entering new AgentExecutor chain...
Thought: I need to first get the issue ID using the Get Issues tool, then I can comment on the issue using the Comment on Issue tool.
Action: Get Issues
Action Input: 
Observation: Found 1 issues:
[{'title': 'CICD AI Insights', 'number': 1}]
Thought:Thought: I found the issue ID, so now I can add the comment to the issue.
Action: Comment on Issue
Action Input: 1


Action: Get Issue
Action Input: 1
Observation: {"title": "CICD AI Insights", "body": "", "comments": "[{'body': '**Transaction.java**\\n\\n\\n**Class:** Transaction\\n\\n\\n* **Security:** Consider using a custom date format like \\\\\"yyyy-MM-dd HH:mm:ss.SSS\\\\\" to handle timestamps more robustly.\\n\\n\\n**JWTVerifierGenerator.java**\\n\\n\\n* .
.
Thought:Now I can use the Comment on Issue tool to add the comment to the issue.

Action: Comment on Issue
Action Input: 
1

**Class: Transaction**

**Method: toString**

**Maintainability:**
.
.
.
Observation: Commented on issue 1
Thought:I have now completed the necessary actions and added the comment to the issue 'CICD AI Insights'.

Final Answer: Comment added to issue 'CICD AI Insights'

> Finished chain.

פותחים את האתר של GitLab ובודקים את הבעיה המעודכנת.

9da39bf6070d9447.png

אפשר לבדוק מעקב אחר מודל שפה גדול (LLM) ב-LangSmith.

דוגמה למעקב אחר LLM.

f32eed34f3a3b040.png

20. דחיפת שינויים למאגר GitLab

חוזרים ל-Google Cloud Shell Editor.

עוברים לכרטיסייה Source Control.

מעבירים את השינויים שבוצעו לשלב ההמתנה, שומרים אותם ומעבירים אותם (push) כדי לעדכן את הקובץ review.py.

b838a11f362454ce.png

21. הגדרת GitLab CICD

בשלב הבא תפעילו את צינור עיבוד הנתונים של GitLab CICD כדי להריץ בדיקת קוד כשדוחפים שינויים למאגר.

פותחים את האתר של GitLab ועוברים לקטע Settings / CICD".

מרחיבים את הקטע Variables ולוחצים על 'Add variable'.

חשוב לבטל את הסימון של כל התיבות כשמוסיפים את המשתנים. דוגמה:

68b3ed732b6a8fe9.png

באמצעות ההערות, שבו שומרים את כל משתני הסביבה, מוסיפים משתני סביבה של JIRA, GitLab ו-LangSmith.

PROJECT_ID=qwiklabs-project-id
LOCATION=us-central1
GOOGLE_CLOUD_CREDENTIALS - cat ~/vertex-client-key.json

LANGCHAIN_TRACING_V2=true
LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
LANGCHAIN_API_KEY=your-service-api-key

JIRA_API_TOKEN=your-token
JIRA_USERNAME="email that you used to register with JIRA"
JIRA_INSTANCE_URL="https://YOUR-PROJECT.atlassian.net"
JIRA_PROJECT_KEY="JIRA project key"
JIRA_CLOUD=true

GITLAB_PERSONAL_ACCESS_TOKEN=your-gitlab-token
GITLAB_URL="https://gitlab.com"
GITLAB_REPOSITORY="USERID/REPOSITORY"
GITLAB_BRANCH="devai"
GITLAB_BASE_BRANCH="main"

לערך המשתנה GOOGLE_CLOUD_CREDENTIALS, צריך להשתמש במפתח של חשבון השירות שנוצר בקטע שלמעלה.

cat ~/vertex-client-key.json

תצוגת משתני CI/CD:

2f4594ce72be4834.png

22. הפעלת צינור עיבוד נתונים CICD של GitLab

פותחים את Build / Pipelines בממשק המשתמש של GitLab ולוחצים על Run Pipeline.

a7518e37dde42366.png

23. בדיקת הפלט של צינור עיבוד הנתונים של GitLab

פתיחת 'Build / Jobs' בממשק המשתמש של GitLab ולבדוק את פלט צינור עיבוד הנתונים.

985e4b322fb73b1c.png

פותחים את האתר של GitLab ובודקים את התגובות המעודכנות ב-CICD Insights בעיה.

השבתת ביצוע תהליך העבודה ב-GitLab

חוזרים ל-Google Cloud Shell Editor. מסירים את ההערות מהשורות כדי להשבית את ההפעלה של תהליך העבודה ב-GitLab באירועי דחיפת קוד. עדיין אפשר להריץ את תהליך העבודה מהממשק המשתמש על פי דרישה.

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

פותחים את .gitlab-ci.yml ברמה הבסיסית (root) של הפרויקט ומבטלים את הוספת התגובה לשורות:

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

עוברים לכרטיסייה Source Control – מעבירים את השינוי לשלב, מבצעים השמה ומעבירים אותו.

a9d52beb8c642982.png

24. שילוב של CircleCI

מהו CircleCI?

CircleCI היא פלטפורמת CI/CD מבוססת-ענן שמאפשרת לצוותים להפוך את תהליכי הפיתוח והפריסה שלהם לאוטומטיים. הוא משתלב עם מערכות לניהול גרסאות כמו GitHub , Bitbucket ו-GitLab וכך מאפשר לצוותים לאמת שינויי קוד בזמן אמת על ידי הרצה של בדיקות וגרסאות build אוטומטיות. לצורך פיתוח רציף, CircleCI יכול להפוך את פריסת התוכנה לאוטומטית לסביבות ענן שונות כמו AWS, Google Cloud ו-Azure.

הגדרה

פותחים את האתר של CircleCI ויוצרים פרויקט חדש. בחירה של 'GitLab' / 'Cloud' של המאגר.

מעניקים גישה ל-CircleCI לחשבון GitLab.

בקטע Fastest (המהירה ביותר), בוחרים את ההסתעפות 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 Editor ועורכים את הקובץ 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" Tab - שלב, שמירה ודחיפה של השינוי הזה.

פותחים את האתר של GitLab ועוברים אל Build / 'Pipelines'.

d196ad631be17b88.png

אפשר ללחוץ על הקישור ל-CircleCI כדי לעיין בתהליך העבודה.

d4ff287694b82445.png

בודקים את התגובות בבעיה ב-GitLab במאגר שלכם.

e77ee826488d5299.png

9a51daa2960994e3.png

לבדוק את הבעיות החדשות שנוצרו בפרויקט JIRA.

1e6305a32aaef6a2.png

26. מעולה!

כל הכבוד, סיימת את שיעור ה-Lab!

הנושאים שעסקנו בהם:

  • הוספת שלבים לאוטומציה של בדיקת הקוד של GenAI ב-GitHub, ב-GitLab וב-CircleCI.
  • סוכני LangChain ReAct להפיכת משימות לאוטומטיות, כמו פרסום תגובות בבעיה ב-GitLab ופתיחת כרטיסים ב-JIRA.

השלב הבא:

  • בקרוב נוסיף עוד סשנים מעשיים.

הסרת המשאבים

כדי להימנע מצבירת חיובים בחשבון Google Cloud על המשאבים שנעשה בהם שימוש במדריך הזה, צריך למחוק את הפרויקט שמכיל את המשאבים או לשמור את הפרויקט ולמחוק את המשאבים הספציפיים.

מחיקת הפרויקט

הדרך הקלה ביותר לבטל את החיוב היא למחוק את הפרויקט שיצרתם בשביל המדריך הזה.

. ©2024 Google LLC כל הזכויות שמורות. Google והלוגו של Google הם סימנים מסחריים רשומים של Google LLC. שמות של חברות ומוצרים אחרים עשויים להיות סימנים מסחריים של החברות, בהתאמה, שאליהן הם משויכים.