תחילת העבודה עם Vector Embeddings ב-Cloud SQL ל-MySQL

1. מבוא

ב-Codelab הזה נסביר איך להשתמש בשילוב של AI עם Cloud SQL ל-MySQL כדי לבצע חיפוש סמנטי באמצעות הטמעות, ואיך לשפר את הביצועים באמצעות אינדקס של נתוני הווקטור.

8aa6ba3bc12a1593.png

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

  • הבנה בסיסית של Google Cloud ומסוף Google Cloud
  • ניסיון בסיסי עם ממשק שורת הפקודה ועם Cloud Shell

מה תלמדו

  • איך פורסים מכונה של Cloud SQL ל-MySQL
  • איך יוצרים מסד נתונים ומפעילים את השילוב של Cloud SQL עם AI
  • איך טוענים נתונים למסד הנתונים
  • איך משתמשים ב-Cloud SQL Studio
  • איך משתמשים במודל הטמעה של Vertex AI ב-Cloud SQL
  • איך משתמשים ב-Agent Platform Studio
  • איך משפרים את התוצאה באמצעות מודל של Gemini Enterprise Agent Platform
  • איך משפרים את הביצועים באמצעות אינדקס וקטורי

מה תצטרכו

  • חשבון Google Cloud ופרויקט Google Cloud
  • דפדפן אינטרנט כמו Chrome

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

הגדרת פרויקט

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

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

  1. יוצרים פרויקט חדש או משתמשים בפרויקט קיים. כדי ליצור פרויקט חדש במסוף Google Cloud, לוחצים על Select a project בסרגל הכלים.

295004821bab6a87.png

בחלון Select a project (בחירת פרויקט), לוחצים על הכפתור New Project (פרויקט חדש) כדי לפתוח תיבת דו-שיח לפרויקט החדש.

37d264871000675d.png

בתיבת הדו-שיח, מזינים שם פרויקט ובוחרים מיקום.

96d86d3d5655cdbe.png

  • שם הפרויקט הוא השם המוצג למשתתפים בפרויקט. השם של הפרויקט לא משמש את Google APIs, ואפשר לשנות אותו בכל שלב.
  • מזהה הפרויקט הוא ייחודי לכל הפרויקטים ב-Google Cloud, והוא קבוע (אי אפשר לשנות אותו אחרי שהוא מוגדר). מסוף Google Cloud יוצר באופן אוטומטי מזהה ייחודי, אבל אפשר להתאים אותו אישית. אם לא אהבתם את המזהה שנוצר, אתם יכולים ליצור מזהה אקראי אחר או לספק מזהה משלכם כדי לבדוק אם הוא זמין. ברוב סדנאות הקוד, אתם מפנים למזהה הפרויקט שלכם, שבדרך כלל מזוהה באמצעות placeholder‏ .
  • לידיעתכם, יש ערך שלישי, מספר פרויקט, שחלק מממשקי ה-API משתמשים בו. מידע נוסף על שלושת הערכים האלה זמין במאמר יצירה וניהול של פרויקטים.

הפעלת החיוב

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

מימוש קרדיטים ב-Google Cloud (אופציונלי)

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

הגדרה של חשבון לחיוב לשימוש אישי

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

כדי להגדיר חשבון לחיוב לשימוש אישי, מפעילים את החיוב במסוף חיוב ב-Cloud של Google.

הערות:

מפעילים את Cloud Shell

אפשר להפעיל את Google Cloud מרחוק מהמחשב, אבל בשיעור Codelab הזה משתמשים ב-Google Cloud Shell, סביבת שורת פקודה שפועלת בענן.

במסוף Google Cloud, לוחצים על סמל Cloud Shell בסרגל הכלים הימני העליון:

הפעלת Cloud Shell

לחלופין, אפשר להקיש על g ואז על s במסוף Google Cloud, או לפתוח את Cloud Shell.

הקצאת הסביבה והחיבור אליה אורכים רק כמה רגעים. בסיום התהליך, הטרמינל המחובר אמור להופיע:

צילום מסך של טרמינל Google Cloud Shell שבו מוצג שהסביבה מחוברת

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

3. לפני שמתחילים

הפעלת ה-API

כדי להשתמש ב-Cloud SQL, ב-Compute Engine, ב-Service Networking וב-Gemini Enterprise Agent Platform, צריך להפעיל את ממשקי ה-API שלהם בפרויקט Google Cloud.

בטרמינל של Cloud Shell, מוודאים שמזהה הפרויקט מוגדר:

gcloud config get project

אם הפונקציה מחזירה מחרוזת ריקה, מגדירים אותה באמצעות:

gcloud config set project [YOUR-PROJECT-ID]

מגדירים את משתנה הסביבה PROJECT_ID:

PROJECT_ID=$(gcloud config get-value project)

מפעילים את כל ממשקי ה-API הנדרשים:

gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com

הפלט הצפוי

student@cloudshell:~ (test-project-001-402417)$ gcloud config set project test-project-001-402417
Updated property [core/project].
student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project)
Your active configuration is: [cloudshell-14650]
student@cloudshell:~ (test-project-001-402417)$ 
student@cloudshell:~ (test-project-001-402417)$ gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.

במסמכי התיעוד אפשר לקרוא על כל API שמופעל.

4. יצירת מכונה של Cloud SQL

יוצרים מכונה של Cloud SQL עם שילוב של מסד נתונים של Gemini Enterprise Agent Platform.

יצירת סיסמה למסד נתונים

מגדירים סיסמה למשתמש ברירת המחדל במסד הנתונים. אפשר להגדיר סיסמה משלכם או להשתמש בפונקציה אקראית כדי ליצור סיסמה:

export CLOUDSQL_PASSWORD=`openssl rand -hex 16`

הצגת ערך הסיסמה שנוצר:

echo $CLOUDSQL_PASSWORD

שומרים את הסיסמה שנוצרה כדי להשתמש בה בהמשך.

יצירת מכונה של Cloud SQL ל-MySQL

אפשר ליצור מופעי Cloud SQL בכמה דרכים, כולל באמצעות מסוף Google Cloud,‏ Terraform או Google Cloud CLI ‏ (gcloud). במעבדת התכנות הזו משתמשים ב-gcloud. במאמר יצירת מופעים מוסבר איך ליצור מופע באמצעות כלים אחרים.

אפשר להפעיל את הדגל cloudsql_vector כשיוצרים מופע. תמיכה בווקטורים זמינה ב-MySQL 8.0 R20241208.01_00 ואילך

בסשן Cloud Shell, מריצים את הפקודה:

gcloud sql instances create my-cloudsql-instance \
--database-version=MYSQL_8_4 \
--tier=db-custom-2-8192 \
--region=us-central1 \
--enable-google-ml-integration \
--edition=ENTERPRISE \
--root-password=$CLOUDSQL_PASSWORD

מתחברים למופע באמצעות gcloud sql connect. כשמופיעה בקשה, מזינים את הסיסמה:

gcloud sql connect my-cloudsql-instance --user=root

הפלט הצפוי:

$gcloud sql connect my-cloudsql-instance --user=root
Allowlisting your IP for incoming connection for 5 minutes...done.                                                                                                                           
Connecting to database with SQL user [root].Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 71
Server version: 8.4.4-google (Google)

Copyright (c) 2000, 2025, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

כדי לצאת מהסשן של mysql, מקישים על Ctrl+D או מזינים exit:

exit

הפעלת השילוב של Gemini Enterprise Agent Platform

מקצים לחשבון השירות של Cloud SQL את תפקיד ה-IAM הנדרש כדי להפעיל את השילוב של Gemini Enterprise Agent Platform.

מאחזרים את כתובת האימייל של חשבון השירות ב-Cloud SQL ומייצאים אותה כמשתנה סביבה:

SERVICE_ACCOUNT_EMAIL=$(gcloud sql instances describe my-cloudsql-instance --format="value(serviceAccountEmailAddress)")
echo $SERVICE_ACCOUNT_EMAIL

מקצים לחשבון השירות של Cloud SQL את התפקיד roles/aiplatform.user:

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
  --role="roles/aiplatform.user"

מידע נוסף על יצירה והגדרה של מכונות זמין במסמכי התיעוד של Cloud SQL כאן.

5. הכנת מסד הנתונים

יצירת מסד נתונים והפעלת תמיכה בווקטורים.

יצירת מסד נתונים

יוצרים מסד נתונים בשם quickstart_db. אפשר ליצור מסדי נתונים באמצעות לקוחות של מסדי נתונים (כמו mysql), Google Cloud CLI או Cloud SQL Studio. בשלב הזה, משתמשים ב-gcloud.

ב-Cloud Shell, מריצים את הפקודה הבאה כדי ליצור את מסד הנתונים:

gcloud sql databases create quickstart_db --instance=my-cloudsql-instance

6. טען נתונים

ליצור טבלאות במסד הנתונים ולטעון נתונים באמצעות קבצים של מערך הנתונים הפיקטיבי Cymbal Store שמאוחסנים בקטגוריה ציבורית של Cloud Storage בפורמט CSV.

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

מוסיפים את כתובת ה-IP הציבורית של Cloud Shell לרשימת הרשתות המורשות של מכונת Cloud SQL.

ב-Cloud Shell, מריצים את הפקודה:

gcloud sql instances patch my-cloudsql-instance --authorized-networks=$(curl ifconfig.me)

אם הסשן אבד, צריך לאפס אותו או לעבוד מכלי אחר ואז לייצא שוב את המשתנה CLOUDSQL_PASSWORD:

export CLOUDSQL_PASSWORD=...your password defined for the instance...

יוצרים את אובייקטי מסד הנתונים הנדרשים. משתמשים ב-mysql יחד עם curl כדי להוריד ולהחיל את הסכימה מהמקור הציבורי.

ב-Cloud Shell, מריצים את הפקודה:

export INSTANCE_IP=$(gcloud sql instances describe my-cloudsql-instance --format="value(ipAddresses.ipAddress)")
curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_mysql_schema.sql | mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db

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

לאחר מכן, מאכלסים את מסד הנתונים בנתוני cymbal_products על ידי הרצת הפקודות curl ו-mysql:

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_products.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_products FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

להמשיך עם cymbal_stores.

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_stores.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_stores FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

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

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_inventory.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_inventory FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

אופציונלי: אם יש לכם מערך נתונים לדוגמה משלכם, אתם יכולים לייבא קובצי CSV תואמים באמצעות כלי הייבוא במסוף Google Cloud.

7. יצירת הטמעות

יוצרים הטבעות לתיאורי המוצרים באמצעות מודל text-embedding-005 מ-Gemini Enterprise Agent Platform ומאחסנים אותן כנתוני וקטור.

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

מריצים את הפקודה ב-Cloud Shell:

gcloud sql instances patch my-cloudsql-instance \
--database-flags=cloudsql_vector=on

מתחברים למסד הנתונים:

mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db

יוצרים עמודה חדשה embedding בטבלה cymbal_products באמצעות פונקציית ההטמעה. העמודה החדשה הזו תכיל את הטמעות הווקטורים על סמך הטקסט בעמודה product_description:

ALTER TABLE cymbal_products ADD COLUMN embedding vector(768) using varbinary;
UPDATE cymbal_products SET embedding = mysql.ml_embedding('text-embedding-005', product_description);

הערה: בדרך כלל, יצירת הטמעה ל-2,000 שורות מסתיימת תוך פחות מ-5 דקות.

יציאה מהסשן של mysql:

exit

8. הרצת חיפוש דמיון

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

אפשר להריץ שאילתות SQL משורת הפקודה או מ-Cloud SQL Studio. ‫Cloud SQL Studio מספק דרך נוחה יותר לערוך ולהריץ הצהרות SQL ארוכות עם כמה שורות בפלט.

יצירת משתמש MySQL ל-Cloud SQL Studio

צריך משתמש חדש במסד הנתונים שיוכל להשתמש ב-Cloud SQL Studio. יוצרים משתמש מובנה student עם אותה סיסמה שבה השתמשתם עבור משתמש Root.

ב-Cloud Shell, מריצים את הפקודה:

gcloud sql users create student  --instance=my-cloudsql-instance --password=$CLOUDSQL_PASSWORD --host=%

הפעלת Cloud SQL Studio

  1. במסוף Google Cloud, עוברים אל Cloud SQL instances ולוחצים על my-cloudsql-instance.

רשימת מכונות Cloud SQL במסוף Google Cloud

  1. בתפריט הניווט, לוחצים על Cloud SQL Studio.

פריט התפריט Cloud SQL Studio

  1. בתיבת הדו-שיח לאימות, מזינים את שם מסד הנתונים ואת פרטי הכניסה:
    • מסד נתונים: quickstart_db
    • משתמש: student
    • סיסמה:
  2. לוחצים על אימות.

תיבת דו-שיח לאימות ב-Cloud SQL Studio

  1. לוחצים על הכרטיסייה Untitled query כדי לפתוח את עורך ה-SQL.

הכרטיסייה של עורך SQL ב-Cloud SQL Studio

הרצת השאילתה

מריצים שאילתה כדי לאחזר את 5 המוצרים שהכי רלוונטיים לשאילתת הלקוח: "What kind of fruit trees grow well here?" (אילו עצי פרי גדלים טוב באזור הזה?)

זו השאילתה שאפשר להריץ כדי לבחור את 5 הפריטים הראשונים שהכי מתאימים לבקשה שלנו באמצעות הפונקציה cosine_distance:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cosine_distance(cp.embedding ,@query_vector) as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

ב-Cloud SQL Studio, מזינים את השאילתה ולוחצים על Run (או מריצים את השאילתה בסשן sql):

הרצת שאילתת SQL ב-Cloud SQL Studio

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

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set (0.13 sec)

זמן ההפעלה של השאילתה הוא בערך 0.13 שניות עם הפונקציה cosine_distance.

מריצים את אותה שאילתה אבל משתמשים בחיפוש KNN באמצעות הפונקציה approx_distance. אם אין לכם אינדקס ANN להטמעות, המערכת חוזרת אוטומטית לחיפוש מדויק מאחורי הקלעים:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

זו רשימת המוצרים שהוחזרו על ידי השאילתה.

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set, 1 warning (0.12 sec)

ביצוע השאילתה נמשך רק 0.12 שניות. קיבלנו את אותן תוצאות כמו בפונקציה המדויקת של KNN cosine_distance.

מידע נוסף על הפונקציה זמין במאמר בנושא Cloud SQL ל-MySQL

9. שיפור התשובה של LLM באמצעות נתונים שאוחזרו

כדי לשפר את התשובה של ה-AI הגנרטיבי לאפליקציית לקוח, אפשר להעביר את תוצאות השאילתה כהקשר מעוגן בנתונים בהנחיה למודל שפה בסיסי של Gemini Enterprise Agent Platform.

לשם כך:

  1. יצירת מטען ייעודי (payload) בפורמט JSON מתוצאת החיפוש הווקטורי ב-Cloud SQL.
  2. בודקים את ההנחיה ב-Agent Platform Studio.
  3. מריצים את ההנחיה מקצה לקצה ישירות מ-SQL באמצעות השילוב של google_ml.

יצירת פלט בפורמט JSON

משנים את השאילתה כדי לעצב את התוצאה כ-JSON ולהחזיר שורה אחת:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine')) ASC
LIMIT 1)
SELECT json_arrayagg(json_object('product_name',product_name,'description',description,'sale_price',sale_price,'zip_code',zip_code,'product_id',product_id)) FROM trees;

פלט JSON צפוי:

[{"zip_code": 93230, "product_id": "23e41a71d63d8bbc9bdfa1d118cfddc5", "sale_price": 100.00, "description": "Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo", "product_name": "Malus Domestica"}]

הרצת הפרומפט ב-Agent Platform Studio

מספקים את ה-JSON שנוצר כהקשר בפרומפט למודל גנרטיבי ב-Agent Platform Studio.

  1. במסוף Google Cloud, פותחים את Agent Platform Studio.

ניווט ב-Agent Platform Studio

  1. מזינים את הפרומפט הבא ב-Agent Platform Studio:

הזנת פרומפט ב-Agent Platform Studio

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "produt_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
<JSON_OUTPUT>
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

מחליפים את בתגובת ה-JSON מהשאילתה:

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "produt_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
{"zip_code": 93230, "product_id": "23e41a71d63d8bbc9bdfa1d118cfddc5", "sale_price": 100.00, "description": "Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo", "product_name": "Malus Domestica"}
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

ההנחיה ב-Agent Platform Studio

  1. מריצים את הפרומפט.

תוצאת ההנחיה ב-Agent Platform Studio

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

הפעלת הפרומפט ב-SQL

אפשר גם להשתמש בשילוב של Cloud SQL AI עם Gemini Enterprise Agent Platform כדי לקבל תשובות ממודל גנרטיבי ישירות ב-SQL.

קודם כול, רושמים את המודל.

  1. רושמים את מודל gemini-3.5-flash ליצירת תשובות (מחליפים את במזהה הפרויקט):
CALL
  mysql.ml_create_model_registration(
  'gemini-3.5-flash',
  'https://aiplatform.googleapis.com/v1/projects/<PROJECT_ID>/locations/global/publishers/google/models/gemini-3.5-flash:generateContent',
  'google',
  'GENERIC',
  NULL,
  'auth_type_cloudsql_service_agent_iam',
  NULL, NULL, NULL, NULL);

אפשר גם להשתמש בשילוב של Cloud SQL עם AI ו-Gemini Enterprise Agent Platform כדי לקבל תשובה דומה ממודל גנרטיבי באמצעות SQL ישירות במסד הנתונים.

עכשיו אפשר להשתמש בתוצאה שנוצרה בשאילתת משנה עם תוצאות JSON כדי לספק אותה כחלק מההנחיה למודל טקסט של AI גנרטיבי באמצעות SQL.

בסשן של mysql או Cloud SQL Studio למסד הנתונים, מריצים את השאילתה

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
WITH trees AS (
SELECT
        cp.product_name,
        cp.product_description AS description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id AS product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci ON
        ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON
        cs.store_id = ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
         (approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine')) ASC
LIMIT 1),
prompt AS (
SELECT
       CONCAT( 'You are a friendly advisor helping to find a product based on the customer''s needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","product_description":"some description","sale_price":10}
Here is the list of products:', json_arrayagg(json_object('product_name',trees.product_name,'description',trees.description,'sale_price',trees.sale_price,'zip_code',trees.zip_code,'product_id',trees.product_id)) , 'The customer asked "What kind of fruit trees grow well here?"
You should give information about the product, price and some supplemental information') AS prompt_text
FROM
        trees),
response AS (
SELECT
       mysql.ML_PREDICT_ROW('gemini-3.5-flash',
        json_object('contents',
        json_object('role',
        'user',
        'parts',
        json_array(
        json_object('text',
        prompt_text))))) AS resp
FROM
        prompt)
SELECT
JSON_EXTRACT(resp, '$.candidates[0].content.parts[0].text')
FROM
        response;

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

"Hello there! I'd be happy to help you find the perfect fruit tree for your space. \n\nBased on your area, a wonderful option we currently have in stock is the **Malus Domestica** (the classic Apple Tree)!\n\nHere are the key details:\n\n* **Product Name:** Malus Domestica (Classic Apple Tree)\n* **Price:** $100.00\n\n### Why it's a great choice:\n* **Beautiful Seasonal Foliage:** It features vibrant green leaves during the summer that turn into gorgeous shades of red, orange, and yellow in the autumn. \n* **Shade & Size:** It grows to approximately 30 feet tall, making it a strong, durable tree that offers excellent shade for your yard alongside delicious fresh fruit.\n* **Growing Conditions:** It thrives best in cool, moist climates with well-draining, loamy soil and is ideal for USDA Hardiness Zones 4–8.\n\n### Supplemental Care Tips:\n* **Planting Location:** Choose a spot that gets full sunlight (at least 6 hours a day) to ensure maximum fruit production.\n* **Soil:** Make sure the soil is rich and loamy with good drainage so the roots stay healthy.\n* **Cross-Pollination:** Apple trees often produce a higher yield when planted near another compatible apple tree variety, so if you have extra space, adding a companion tree in the future can boost your harvest!\n\nLet me know if you have any questions about planting or care, or if you'd like help adding this to your cart!"

הפלט מסופק בפורמט Markdown.

10. יצירת אינדקס של השכן הקרוב ביותר

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

יצירת אינדקס ScaNN

ננסה את סוג האינדקס ScaNN לבדיקה שלנו.

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

CREATE VECTOR INDEX cymbal_products_embedding_idx ON cymbal_products(embedding) USING SCANN DISTANCE_MEASURE=COSINE;

השוואת תשובות

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

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

הפלט אמור להיראות כך:

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set (0.08 sec)

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

בודקים את תוכנית הביצוע באמצעות הפקודה EXPLAIN:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
EXPLAIN ANALYZE SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

תוכנית הרצה (קטע):

...
-> Nested loop inner join  (cost=443 rows=5) (actual time=1.14..1.18 rows=5 loops=1)
                                -> Vector index scan on cp  (cost=441 rows=5) (actual time=1.1..1.1 rows=5 loops=1)
                                -> Single-row index lookup on cp using PRIMARY (uniq_id=cp.uniq_id)  (cost=0.25 rows=1) (actual time=0.0152..0.0152 rows=1 loops=5)

...

הוא מציג סריקה של אינדקס וקטור בטבלה cp(כינוי לטבלה cymbal_products).

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

11. ניקוי הסביבה

מחיקת המכונה של Cloud SQL

השמדת המכונה של Cloud SQL בסיום שיעור ה-Lab

אם התנתקתם וכל ההגדרות הקודמות אבדו, מגדירים את משתני הפרויקט והסביבה ב-Cloud Shell:

export INSTANCE_NAME=my-cloudsql-instance
export PROJECT_ID=$(gcloud config get-value project)

מוחקים את המכונה:

gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID

הפלט הצפוי בקונסולה:

student@cloudshell:~$ gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID
All of the instance data will be lost when the instance is deleted.

Do you want to continue (Y/n)?  y

Deleting Cloud SQL instance...done.                                                                                                                
Deleted [https://sandbox.googleapis.com/v1beta4/projects/test-project-001-402417/instances/my-cloudsql-instance].

12. מזל טוב

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

תוכנית הלימודים של Google Cloud

שיעור ה-Lab הזה הוא חלק מתוכנית הלימודים Production-Ready AI with Google Cloud (שימוש ב-AI מוכן לייצור באמצעות Google Cloud).

מה למדתם

  • איך פורסים מכונה של Cloud SQL ל-MySQL
  • איך יוצרים מסד נתונים ומפעילים את השילוב של Cloud SQL עם AI
  • איך טוענים נתונים למסד הנתונים
  • איך משתמשים ב-Cloud SQL Studio
  • איך משתמשים במודל הטמעה של Vertex AI ב-Cloud SQL
  • איך משתמשים ב-Agent Platform Studio
  • איך משפרים את התוצאה באמצעות מודל של Gemini Enterprise Agent Platform
  • איך משפרים את הביצועים באמצעות אינדקס וקטורי

אפשר לנסות Codelab דומה ל-AlloyDB או Codelab ל-Cloud SQL ל-Postgres

סקר

פלט:

איך תשתמשו במדריך הזה?

רק לקרוא את המידע לקרוא את המידע ולהשלים את התרגילים