بدء استخدام تضمينات المتجهات في Cloud SQL for PostgreSQL

1. مقدمة

في هذا الدرس التطبيقي حول الترميز، ستتعرّف على كيفية استخدام ميزة دمج الذكاء الاصطناعي في Cloud SQL for PostgreSQL من خلال الجمع بين البحث المتّجه وتضمينات "منصة وكيل Gemini Enterprise".

مخطّط بياني معماري يوضّح عملية دمج Cloud SQL مع Gemini Enterprise Agent Platform

المتطلبات الأساسية

  • فهم أساسي لـ Google Cloud وGoogle Cloud Console
  • خبرة أساسية في استخدام واجهة سطر الأوامر وCloud Shell

الإجراءات التي ستنفذّها

  • نشر مثيل Cloud SQL for PostgreSQL
  • إنشاء قاعدة بيانات وتفعيل عملية دمج Cloud SQL AI
  • تحميل البيانات إلى قاعدة البيانات
  • استخدام Cloud SQL Studio
  • إنشاء تضمينات باستخدام Gemini Enterprise Agent Platform في Cloud SQL
  • استخدام Agent Platform Studio
  • إثراء نتائج طلب البحث باستخدام نموذج توليدي من Gemini Enterprise Agent Platform
  • تحسين أداء طلبات البحث باستخدام فهرس متّجه HNSW

المتطلبات

  • حساب Google Cloud ومشروع على السحابة الإلكترونية
  • متصفّح ويب، مثل Chrome

2. الإعداد والمتطلبات

إعداد المشروع

  1. سجِّل الدخول إلى Google Cloud Console. إذا لم يكن لديك حساب على Google (Gmail أو Google Workspace)، عليك إنشاء حساب على Google.

استخدام حساب شخصي بدلاً من حساب تديره المؤسسة التعليمية أو حساب تابع للعمل.

  1. أنشئ مشروعًا جديدًا أو أعِد استخدام مشروع حالي. لإنشاء مشروع جديد في Google Cloud Console، انقر على اختيار مشروع في شريط الأدوات.

مربّع حوار اختيار مشروع في Google Cloud Console

في مربّع الحوار اختيار مشروع، انقر على مشروع جديد.

37d264871000675d.png

في مربّع الحوار، أدخِل اسم مشروع واختَر الموقع الجغرافي.

96d86d3d5655cdbe.png

  • اسم المشروع هو الاسم المعروض للمشاركين في هذا المشروع. لا تستخدم Google APIs اسم المشروع، ويمكن تغييره في أي وقت.
  • رقم تعريف المشروع هو معرّف فريد في جميع مشاريع Google Cloud ولا يمكن تغييره (لا يمكن تغييره بعد ضبطه). تنشئ وحدة تحكّم Google Cloud تلقائيًا معرّفًا فريدًا، ولكن يمكنك تخصيصه. إذا لم يعجبك المعرّف الذي تم إنشاؤه، يمكنك إنشاء معرّف عشوائي آخر أو تقديم معرّفك الخاص للتحقّق من توفّره. في معظم دروس Codelab، يمكنك الرجوع إلى رقم تعريف مشروعك، والذي يتم تحديده عادةً باستخدام العنصر النائب .
  • تستخدم بعض واجهات برمجة التطبيقات قيمة ثالثة، وهي رقم المشروع. يمكنك الاطّلاع على مزيد من المعلومات عن هذه القيم الثلاث في مستندات إنشاء المشاريع وإدارتها.

تفعيل الفوترة

إعداد حساب فوترة شخصي

إذا أعددت الفوترة باستخدام أرصدة Google Cloud، يمكنك تخطّي هذه الخطوة.

لإعداد حساب فوترة شخصي، فعِّل الفوترة في وحدة تحكّم الفوترة في Google Cloud.

ملاحظات:

  • لا تتجاوز تكلفة إكمال هذا الدرس التطبيقي 5 دولارات أمريكية من موارد Google Cloud.
  • اتّبِع الخطوات الواردة في نهاية هذا الدرس التطبيقي لحذف الموارد وتجنُّب تحمّل رسوم إضافية.
  • يمكن للمستخدمين الجدد الاستفادة من الفترة التجريبية المجانية بقيمة 300 دولار أمريكي.

بدء Cloud Shell

على الرغم من إمكانية تشغيل Google Cloud عن بُعد من جهاز الكمبيوتر، ستستخدم في هذا الدرس التطبيقي حول الترميز Google Cloud Shell، وهي بيئة سطر أوامر تعمل في السحابة الإلكترونية.

في شريط أدوات Google Cloud Console، انقر على تفعيل Cloud Shell:

تفعيل Cloud Shell

بدلاً من ذلك، اضغط على g ثم s في Google Cloud Console، أو افتح Cloud Shell.

لا يستغرق توفير البيئة والاتصال بها سوى بضع لحظات. عند الانتهاء، من المفترض أن يظهر لك الجهاز الطرفي المرتبط:

لقطة شاشة لواجهة سطر الأوامر في Google Cloud Shell توضّح أنّه تم ربط البيئة

يتم تحميل هذا الجهاز الظاهري بجميع أدوات التطوير التي تحتاج إليها. توفّر هذه الخدمة دليلًا منزليًا دائمًا بسعة 5 غيغابايت وتعمل على Google Cloud، ما يحسّن أداء الشبكة والمصادقة. يمكن إكمال جميع المهام في هذا الدرس البرمجي بدون استخدام أي رمز برمجي داخل المتصفّح.

3- تفعيل واجهات برمجة التطبيقات

لاستخدام Cloud SQL وCompute Engine وService Networking ومنصة وكيل Gemini Enterprise، فعِّل واجهات برمجة التطبيقات الخاصة بها في مشروعك على Google Cloud.

في نافذة Cloud Shell، تأكَّد من ضبط رقم تعريف مشروعك:

gcloud config set project <PROJECT_ID>

اضبط متغيّر البيئة PROJECT_ID:

PROJECT_ID=$(gcloud config get-value project)

فعِّل جميع الخدمات المطلوبة:

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.

يمكنك الاطّلاع على معلومات حول كل واجهة برمجة تطبيقات مفعّلة في المستندات.

4. إنشاء مثيل Cloud SQL

أنشئ مثيلاً من Cloud SQL مع دمج قاعدة بيانات Gemini Enterprise Agent Platform.

إنشاء كلمة مرور لقاعدة البيانات

حدِّد كلمة مرور لمستخدم قاعدة البيانات التلقائي. يمكنك تحديد كلمة المرور الخاصة بك أو استخدام دالة عشوائية لإنشاء كلمة مرور:

export CLOUDSQL_PASSWORD=$(openssl rand -hex 16)

اعرض قيمة كلمة المرور التي تم إنشاؤها:

echo $CLOUDSQL_PASSWORD

دوِّن كلمة المرور التي تم إنشاؤها لاستخدامها لاحقًا.

إنشاء مثيل Cloud SQL for PostgreSQL

يمكن إنشاء مثيلات Cloud SQL باستخدام عدة طرق، بما في ذلك Google Cloud Console أو Terraform أو Google Cloud CLI (gcloud). في هذا الدرس التطبيقي حول الترميز، ستستخدم gcloud. للتعرّف على كيفية إنشاء آلة افتراضية باستخدام أدوات أخرى، راجِع مستند إنشاء آلات افتراضية.

في Cloud Shell، نفِّذ الأمر التالي لإنشاء الجهاز الظاهري:

gcloud sql instances create my-cloudsql-instance \
--database-version=POSTGRES_18 \
--tier=db-custom-1-3840 \
--region=us-central1 \
--edition=ENTERPRISE \
--enable-google-ml-integration \
--database-flags cloudsql.enable_google_ml_integration=on

بعد إنشاء الجهاز الافتراضي، اضبط كلمة مرور للمستخدم التلقائي (postgres) وتأكَّد من إمكانية الاتصال:

gcloud sql users set-password postgres \
    --instance=my-cloudsql-instance \
    --password=$CLOUDSQL_PASSWORD

اربط بنسخة Looker باستخدام gcloud sql connect. عندما يُطلب منك ذلك، أدخِل كلمة المرور:

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

يمكنك الخروج من جلسة psql من خلال الضغط على Ctrl+D أو إدخال exit:

exit

تفعيل ميزة دمج Gemini Enterprise Agent Platform

امنح دور IAM اللازم لحساب خدمة Cloud SQL لتفعيل عملية الربط بمنصة "وكيل Gemini Enterprise".

استرداد البريد الإلكتروني لحساب خدمة Cloud SQL وتصديره كمتغيّر بيئة:

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

امنح دور roles/aiplatform.user لحساب خدمة Cloud SQL:

PROJECT_ID=$(gcloud config get-value project)
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
  --role="roles/aiplatform.user"

لمزيد من المعلومات حول إنشاء مثيل وإعداده، يُرجى الاطّلاع على مقالة دمج Cloud SQL مع Gemini Enterprise Agent Platform.

5- إعداد قاعدة البيانات

إنشاء قاعدة بيانات وتفعيل إمكانية البحث المتّجه

إنشاء قاعدة بيانات

أنشئ قاعدة بيانات باسم quickstart_db. يمكنك إنشاء قواعد بيانات باستخدام برامج قواعد البيانات (مثل psql) أو واجهة سطر الأوامر (CLI) في Google Cloud أو Cloud SQL Studio. في هذه الخطوة، استخدِم gcloud.

في Cloud Shell، نفِّذ الأمر التالي لإنشاء قاعدة البيانات:

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

تفعيل الإضافات

للعمل مع Gemini Enterprise Agent Platform والمتجهات، فعِّل إضافتَين في قاعدة بيانات quickstart_db: google_ml_integration وvector.

في Cloud Shell، اتّصِل بقاعدة البيانات:

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

أدخِل كلمة مرور قاعدة البيانات عندما يُطلب منك ذلك.

في جلسة SQL، نفِّذ الأوامر التالية:

CREATE EXTENSION IF NOT EXISTS google_ml_integration CASCADE;
CREATE EXTENSION IF NOT EXISTS vector CASCADE;

اخرج من جلسة SQL:

exit;

6. تحميل البيانات

إنشاء جداول في قاعدة البيانات وتحميل البيانات باستخدام ملفات مجموعة بيانات Cymbal Store الوهمية المخزَّنة في حزمة Cloud Storage عامة بتنسيق CSV

أولاً، أنشئ عناصر المخطط المطلوبة. نفِّذ الأمرَين gcloud sql connect وgcloud storage لتنزيل المخطط واستيراده:

في Cloud Shell، نفِّذ الأمر التالي (عندما يُطلب منك ذلك، أدخِل كلمة المرور التي تم إنشاؤها للمثيل):

gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql | gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

يربط هذا الأمر بقاعدة البيانات وينفّذ رمز SQL الذي تم تنزيله لإنشاء الجداول والفهارس والتسلسلات.

بعد ذلك، نزِّل ملفات بيانات CSV من Cloud Storage:

gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv .

الربط بقاعدة البيانات:

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

استيراد البيانات من ملفات CSV:

\copy cymbal_products from 'cymbal_products.csv' csv header
\copy cymbal_inventory from 'cymbal_inventory.csv' csv header
\copy cymbal_stores from 'cymbal_stores.csv' csv header

إذا كنت تستخدم بياناتك الخاصة وكانت ملفات CSV متوافقة مع أداة الاستيراد في Cloud SQL ضمن وحدة تحكّم Google Cloud، يمكنك استخدام وحدة التحكّم بدلاً من سطر الأوامر.

7. إنشاء تضمينات

إنشاء تضمينات لأوصاف المنتجات باستخدام نموذج text-embedding-005 من Gemini Enterprise Agent Platform وتخزينها كبيانات متجهة

إذا تم قطع اتصال جلستك، عليك الاتصال بقاعدة البيانات:

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

أنشئ عمودًا تم إنشاؤه باسم embedding في الجدول cymbal_products باستخدام الدالة embedding. ينشئ هذا الأمر عمودًا مخزّنًا تم إنشاؤه يحتوي على تضمينات المتجهات التي تم إنشاؤها من العمود product_description لجميع الصفوف في الجدول. يتم تحديد النموذج كالمَعلمة الأولى وعمود النص المصدر كالمَعلمة الثانية:

ALTER TABLE cymbal_products ADD COLUMN embedding vector(768) GENERATED ALWAYS AS (google_ml.embedding('text-embedding-005', product_description)) STORED;

بالنسبة إلى 900 إلى 1, 000 صف، تستغرق هذه العملية عادةً من دقيقة واحدة إلى 5 دقائق.

عند إدراج صف جديد في الجدول أو تعديل product_description في صف حالي، يتم تعديل العمود embedding تلقائيًا.

8. إجراء بحث عن التشابه

يمكنك إجراء بحث عن منتجات مشابهة من خلال مقارنة عمليات تضمين المتجهات المحسوبة لأوصاف المنتجات بعملية التضمين لطلب بحث.

يمكنك تنفيذ طلبات بحث SQL من سطر الأوامر باستخدام gcloud sql connect أو من Cloud SQL Studio. توفّر أداة Cloud SQL Studio طريقة أكثر ملاءمة لتعديل عبارات SQL الطويلة وتنفيذها مع صفوف متعددة في الناتج.

بدء Cloud SQL Studio

  1. في Google Cloud Console، انتقِل إلى مثيلات Cloud SQL وانقر على my-cloudsql-instance.

قائمة مثيلات Cloud SQL في Google Cloud Console

  1. في قائمة التنقّل، انقر على Cloud SQL Studio.

عنصر قائمة Cloud SQL Studio

  1. في مربّع حوار المصادقة، أدخِل اسم قاعدة البيانات وبيانات الاعتماد:
    • قاعدة البيانات: quickstart_db
    • المستخدم: postgres
    • كلمة المرور:
  2. انقر على مصادقة.

مربّع حوار مصادقة Cloud SQL Studio

  1. انقر على علامة التبويب المحرّر لفتح "محرّر SQL".

علامة التبويب &quot;محرّر SQL&quot; في Cloud SQL Studio

تشغيل طلب البحث

نفِّذ طلب بحث لاسترداد أفضل 10 منتجات ذات صلة بطلب بحث العميل: "ما هي أنواع أشجار الفاكهة التي تنمو جيدًا هنا؟"

SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::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 10;

في Cloud SQL Studio، أدخِل طلب البحث وانقر على تنفيذ (أو نفِّذ طلب البحث في جلسة psql):

تنفيذ طلب بحث SQL في Cloud SQL Studio

يعرض طلب البحث المنتجات المطابقة مرتّبة حسب مسافة جيب التمام:

product_name       |                                   description                                    | sale_price | zip_code |      distance       
-------------------------+----------------------------------------------------------------------------------+------------+----------+---------------------
 Cherry Tree             | This is a beautiful cherry tree that will produce delicious cherries. It is an d |      75.00 |    93230 | 0.43922018972266397
 Meyer Lemon Tree        | Meyer Lemon trees are California's favorite lemon tree! Grow your own lemons by  |         34 |    93230 |  0.4685112926118228
 Toyon                   | This is a beautiful toyon tree that can grow to be over 20 feet tall. It is an e |      10.00 |    93230 |  0.4835677149651668
 California Lilac        | This is a beautiful lilac tree that can grow to be over 10 feet tall. It is an d |       5.00 |    93230 |  0.4947204525907498
 California Peppertree   | This is a beautiful peppertree that can grow to be over 30 feet tall. It is an e |      25.00 |    93230 |  0.5054166905547247
 California Black Walnut | This is a beautiful walnut tree that can grow to be over 80 feet tall. It is a d |     100.00 |    93230 |  0.5084219510932597
 California Sycamore     | This is a beautiful sycamore tree that can grow to be over 100 feet tall. It is  |     300.00 |    93230 |  0.5140519790508755
 Coast Live Oak          | This is a beautiful oak tree that can grow to be over 100 feet tall. It is an ev |     500.00 |    93230 |  0.5143126438081371
 Fremont Cottonwood      | This is a beautiful cottonwood tree that can grow to be over 100 feet tall. It i |     200.00 |    93230 |  0.5174774727252058
 Madrone                 | This is a beautiful madrona tree that can grow to be over 80 feet tall. It is an |      50.00 |    93230 |  0.5227400803389093
(10 rows)

9. تحسين ردّ النموذج اللغوي الكبير باستخدام البيانات المسترجَعة

تحسين ردّ الذكاء الاصطناعي التوليدي على تطبيق العميل من خلال تمرير نتائج طلب البحث كسياق مستند إلى بيانات واقعية في طلب إلى نموذج لغوي أساسي في Agent Platform من Gemini Enterprise

ولإجراء ذلك:

  1. إنشاء حمولة JSON من نتيجة البحث المتّجه في Cloud SQL
  2. اختبِر الطلب في Agent Platform Studio.
  3. تنفيذ الطلب الشامل مباشرةً من SQL باستخدام عملية الدمج google_ml

إنشاء ناتج بتنسيق JSON

عدِّل الاستعلام لتنسيق النتيجة كملف JSON وعرض صف واحد:

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
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

الردّ المتوقّع بتنسيق JSON:

[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]

تشغيل الطلب في Agent Platform Studio

قدِّم ملف JSON الذي تم إنشاؤه كسياق في طلب إلى نموذج توليدي في Agent Platform Studio.

  1. في Google Cloud Console، افتح 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, "product_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, "product_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]
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

تتضمّن الإجابة السعر والوصف والمعلومات التكميلية التي يحصل عليها النموذج من مصادر خارجية استنادًا إلى معلومات حول الشجرة والموقع الجغرافي.

تنفيذ الطلب في psql

يمكنك أيضًا استخدام عملية دمج الذكاء الاصطناعي في Cloud SQL مع "منصة وكيل Gemini Enterprise" للحصول على ردود من نموذج توليدي مباشرةً في SQL. أولاً، سجِّل النموذج.

  1. يمكنك ترقية الإضافة إلى الإصدار 1.4.3 أو إصدار أحدث إذا لزم الأمر. اتّصِل بجهاز quickstart_db ونفِّذ ما يلي:
SELECT extversion from pg_extension where extname='google_ml_integration';

إذا كان الإصدار الذي تم إرجاعه أقل من 1.4.3، نفِّذ ما يلي:

ALTER EXTENSION google_ml_integration UPDATE TO '1.4.3';
  1. تحقَّق من علامة قاعدة بيانات google_ml_integration.enable_model_support:
SHOW google_ml_integration.enable_model_support;

إذا كانت العلامة off، عدِّل علامة قاعدة البيانات في Cloud Shell:

gcloud sql instances patch my-cloudsql-instance \
--database-flags google_ml_integration.enable_model_support=on,cloudsql.enable_google_ml_integration=on

تستغرق هذه العملية من دقيقة واحدة إلى 3 دقائق. تحقَّق من الإعداد مرة أخرى:

SHOW google_ml_integration.enable_model_support;
  1. سجِّل نموذج gemini-3.5-flash لإنشاء الردود (استبدِل برقم تعريف مشروعك):
CALL
  google_ml.create_model(
    model_id => 'gemini-3.5-flash',
    model_request_url => 'https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3.6-flash:generateContent',
    model_provider => 'google',
    model_auth_type => 'cloudsql_service_agent_iam');

تحقَّق من الطُرز المسجَّلة:

SELECT model_id, model_type FROM google_ml.model_info_view WHERE model_id='gemini-3.5-flash';
  1. نفِّذ طلب بحث SQL الكامل لاسترداد نتائج البحث المتّجه ومرِّرها مباشرةً إلى gemini-3.5-flash:
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
        (cp.embedding <=> embedding('text-embedding-005',
        'What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1),
prompt AS (
SELECT
        '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_agg(trees) || '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
        google_ml.predict_row( model_id =>'gemini-3.5-flash',
        request_body => json_build_object('contents',
        json_build_object('role',
        'user',
        'parts',
        json_build_object('text',
        prompt_text))))->'candidates'->0->'content'->'parts'->0->'text' AS resp
FROM
        prompt)
SELECT
REPLACE(resp::text, '\n', CHR(10))
FROM
        response;

الناتج المتوقّع:

"Hello there! If you're looking for a wonderful fruit tree to plant, I have a fantastic option for you: ### **Cherry Tree** * **Price:** $75.00 * **Product ID:** `d536e9e823296a2eba198e52dd23e712` --- ### **Why it's a great choice:** * **Fruit & Shade:** Not only will it produce delicious, sweet cherries, but it also grows into a beautiful 15-foot deciduous tree that provides excellent shade and privacy for your yard. * **Seasonal Beauty:** Its leaves are a lovely dark green throughout the summer and transition into a striking red during the fall. * **Ideal Growing Conditions:** Cherry trees thrive best in cool, moist climates with sandy soil and are suitable for **USDA hardiness zones 4–9**. If your local climate matches these conditions, this Cherry Tree would make a beautiful and tasty addition to your garden! Let me know if you'd like more details or help placing an order."

10. إنشاء فهرس أقرب جار

بالنسبة إلى مجموعات البيانات الكبيرة التي تحتوي على ملايين المتجهات، قد يتطلّب البحث عن المتجهات موارد حوسبة كبيرة. لتحسين أداء طلبات البحث، أنشئ فهرسًا لعمليات التضمين المتجهة.

إنشاء فهرس HNSW

‫Hierarchical Navigable Small World (HNSW) هو فهرس متّجه مستند إلى رسم بياني.

لإنشاء فهرس HNSW في العمود embedding، حدِّد دالة المسافة (vector_cosine_ops) والمَعلمات الاختيارية، مثل m وef_construction. لمزيد من المعلومات، يُرجى الاطّلاع على العمل باستخدام التضمينات المتجهة.

CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products
  USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

الناتج المتوقّع:

quickstart_db=> CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products
  USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);
CREATE INDEX
quickstart_db=>

مقارنة أداء طلبات البحث

نفِّذ طلب البحث عن المتجهات باستخدام EXPLAIN (ANALYZE) للتأكّد من أنّ أداة تخطيط الطلبات تستخدم الفهرس:

EXPLAIN (ANALYZE) 
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
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

الناتج المتوقّع:

 Aggregate  (cost=779.12..779.13 rows=1 width=32) (actual time=1.066..1.069 rows=1 loops=1)
   ->  Subquery Scan on trees  (cost=769.05..779.12 rows=1 width=142) (actual time=1.038..1.041 rows=1 loops=1)
         ->  Limit  (cost=769.05..779.11 rows=1 width=158) (actual time=1.022..1.024 rows=1 loops=1)
               ->  Nested Loop  (cost=769.05..9339.69 rows=852 width=158) (actual time=1.020..1.021 rows=1 loops=1)
                     ->  Nested Loop  (cost=768.77..9316.48 rows=852 width=945) (actual time=0.858..0.859 rows=1 loops=1)
                           ->  Index Scan using cymbal_products_embeddings_hnsw on cymbal_products cp  (cost=768.34..2572.47 rows=941 width=941) (actual time=0.532..0.539 rows=3 loops=1)
...
 Planning Time: 112.398 ms
 Execution Time: 1.221 ms

تعرض خطة التنفيذ Index Scan using cymbal_products_embeddings_hnsw.

نفِّذ الطلب بدون EXPLAIN:

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
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

الناتج المتوقّع:

[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]

لمزيد من المعلومات والأمثلة حول استخدام LangChain وفهارس المتجهات، يُرجى الاطّلاع على مستند نظرة عامة على الذكاء الاصطناعي في Cloud SQL.

11. تنظيف الموارد

احذف مثيل Cloud SQL بعد الانتهاء من تجربة الترميز.

في 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. تهانينا

تهانينا! لقد أكملت درسًا تطبيقيًا حول الترميز.

يشكّل هذا المختبر جزءًا من مسار "الذكاء الاصطناعي الجاهز للإنتاج" التعليمي على Google Cloud.

ملخّص

لقد تعلّمت كيفية:

  • نشر مثيل Cloud SQL for PostgreSQL
  • إنشاء قاعدة بيانات وتفعيل عملية دمج Cloud SQL AI
  • تحميل البيانات إلى قاعدة البيانات
  • استخدام Cloud SQL Studio
  • استخدام نموذج تضمين Gemini Enterprise Agent Platform في Cloud SQL
  • استخدام Agent Platform Studio
  • إثراء نتائج طلب البحث باستخدام نموذج توليدي من Gemini Enterprise Agent Platform
  • تحسين أداء طلبات البحث باستخدام فهرس متّجه

جرِّب الدروس التطبيقية حول تضمينات المتجهات في AlloyDB AI باستخدام فهرس ScaNN بدلاً من HNSW.