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

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

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

9dde56ad139b9553.png

מה תלמדו

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

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

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

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

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

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

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

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

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

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

נתוני תוכניות שנוצרו על ידי Gemini

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

מידע נוסף על אופן הטיפול של Google בהנחיות שלכם

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

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

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

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

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

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

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

3e0c761ca41f315e.png

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

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

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

6356559df3eccdda.png

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

תשתמשו בחשבון השירות הזה כדי לבצע קריאות ל-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 כבעלים.

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

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

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

פותחים בדפדפן את מאגר הנתונים של 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 בקטע 'כל תהליכי העבודה' ולוחצים על 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 

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

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 הותקן אבל הוא לא נמצא בנתיב.

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

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

יוצרים קובץ חדש ומדביקים בו את התשובה של 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)

כדי לעיין בפקודות ה-CLI של devai שזמינות ב-Cloud Shell Editor:

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

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

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

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

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

16. הגדרת מעקב אחרי LLM ב-LangSmith

יוצרים חשבון LangSmith ומפיקים מפתח Service API בקטע Settings (הגדרות). https://docs.smith.langchain.com/

מגדירים את משתני הסביבה שנדרשים לשילוב עם LangSmith. לפני שמריצים את הפקודות, מחליפים את מפתח ה-API של השירות.

export LANGCHAIN_API_KEY=langsmith-service-api-key

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

כדי להימנע מחשיפת מידע רגיש במסוף, מומלץ להשתמש בread -s זו דרך מאובטחת להגדיר משתני סביבה בלי שהערך יופיע בהיסטוריית הפקודות של המסוף. אחרי שמריצים את הפקודה, צריך להדביק את הערך וללחוץ על Enter.

17. הגדרת פקודות ב-JIRA

אם אין לכם חשבון JIRA, אתם צריכים ליצור חשבון.

יוצרים אסימון JIRA API לפרויקט. https://id.atlassian.com/manage-profile/security/api-tokens

מגדירים את משתני הסביבה האלה שנדרשים לשילוב עם JIRA (צריך להחליף את הערכים לפני שמריצים את הפקודות).

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

פתיחת קובץ review.py:

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

בדיקת הקובץ review.py:

    source=source.format(format_files_as_string(context))

    code_chat_model = GenerativeModel(model_name)
    code_chat = code_chat_model.start_chat()
    code_chat.send_message(qry)
    response = code_chat.send_message(source)
    ...
    else:
        click.echo(response.text) 

מחפשים את השורה הבאה ומבטלים את הסימון שלה כהערה:

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

ייבוא פקודת JIRA בחלק העליון של הקובץ

# from devai.commands.jira import create_jira_issue

השיטה ליצירת קריאה ב-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. במקום זאת, צריך להשתמש ב-invoke. warn_deprecated(

הזנה של שרשרת AgentExecutor חדשה... מחשבה: התיאור מופיע בשאלה, אז אין מה לחשוב. פעולה:

{
  "action": "create_issue",
  "action_input": {
    "description": "Class: TransactionRepository\nMethod: findBalance\n\nEfficiency\n- Consider using a native SQL query to improve performance for complex database operations.\n- Use prepared statements to avoid SQL injection vulnerabilities.\n\nBest Practices\n- Return a Optional<Long> instead of null to handle the case when no balance is found for the given account."
  }
}

נוצרה בעיה חדשה עם המפתח: CYMEATS-117

תצפית: נוצרה בעיה חדשה עם המפתח: CYMEATS-117 מחשבה:תשובה סופית: CYMEATS-117

השרשרת הסתיימה.

Open your JIRA project in the browser and review the created issue.

Sample JIRA issue view.

<img src="img/9a93a958c30f0b51.png" alt="9a93a958c30f0b51.png"  width="624.00" />

Open  [LangSmith portal](https://smith.langchain.com/) and review LLM trace for JIRA issue creation call.

Sample LangSmith LLM trace.

<img src="img/6222ee1653a5ea54.png" alt="6222ee1653a5ea54.png"  width="624.00" />


## Import GitHub repo to GitLab repo



Go to  [https://gitlab.com/projects/new](https://gitlab.com/projects/new) and select "`Import project`" / "`Repository by URL`" option:

Git repository url:

https://github.com/GoogleCloudPlatform/genai-for-developers.git

Or

Your personal GitHub project that you created earlier in this lab.

Under Project URL - select your GitLab userid

Set Visibility to `Public`.

Click - "`Create Project`" to start the import process.

If you see an error about invalid GitHub Repository URL,  [create a new GitHub token](https://github.com/settings/tokens)(fine-grained) with Public repositories read-only access, and retry import again providing your GitHub userid and token.


## Clone GitLab repo and setup SSH key



Return to Google Cloud Shell terminal and set up a new SSH key. 

Update your email before running the commands. Hit enter multiple times to accept defaults.

ssh-keygen -t ed25519 -C "your-email-address"

eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519

cat ~/.ssh/id_ed25519.pub

Add a public key to your GitLab account.

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

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

Go back to the terminal and clone the repository. 

cd ~ mkdir gitlab cd gitlab

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

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

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

cd genai-for-developers

cloudshell edit .gitlab-ci.yml

אם לא עשיתם את זה קודם, מפעילים את Gemini בעורך Cloud Shell.

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

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

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

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

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

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

 which devai

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

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

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

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

**Method: toString**

**Maintainability:**

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

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


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

Action: Comment on Issue
Action Input: 
1

**Class: Transaction**

**Method: toString**

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

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

> Finished chain.

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

9da39bf6070d9447.png

בדיקת תיעוד העקבות של LLM ב-LangSmith.

דוגמה לתיעוד LLM.

f32eed34f3a3b040.png

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

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

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

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

b838a11f362454ce.png

21. הגדרת GitLab CICD

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

פותחים את האתר 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

פותחים את 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) של הפרויקט ומבטלים את הסימון כהערה (uncomment) בשורות:

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

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

a9d52beb8c642982.png

24. שילוב עם CircleCI

מה זה CircleCI?

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

הגדרה

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

נותנים ל-CircleCI גישה לחשבון GitLab.

בקטע Fastest option, בוחרים בסניף 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, מבצעים staging, שומרים את השינוי ושולחים אותו.

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

d196ad631be17b88.png

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

d4ff287694b82445.png

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

e77ee826488d5299.png

9a51daa2960994e3.png

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

1e6305a32aaef6a2.png

26. מעולה!

כל הכבוד, סיימתם את ה-Lab.

הנושאים שדיברנו עליהם:

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

השלב הבא:

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

הסרת המשאבים

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

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

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

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