透過 AlloyDB AI 開始使用向量嵌入功能

1. 簡介

在這個程式碼研究室中,您將瞭解如何透過結合向量搜尋與 Vertex AI 嵌入項目,使用 AlloyDB AI。

17e86406ab251142.png

必要條件

  • 對 Google Cloud 控制台的基本概念
  • 指令列介面和 Google Shell 的基本技能

課程內容

  • 如何部署 AlloyDB 叢集和主要執行個體
  • 如何從 Google Compute Engine VM 連線至 AlloyDB
  • 如何建立資料庫並啟用 AlloyDB AI
  • 如何將資料載入資料庫
  • 如何在 AlloyDB 中使用 Vertex AI 嵌入模型
  • 如何使用 Vertex AI 生成式模型充實結果

軟硬體需求

  • Google Cloud 帳戶和 Google Cloud 專案
  • 使用 Chrome 等網路瀏覽器

2. 設定和需求

自修環境設定

  1. 登入 Google Cloud 控制台,建立新專案或重複使用現有專案。如果您還沒有 Gmail 或 Google Workspace 帳戶,請先建立帳戶

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • 「專案名稱」是這項專案參與者的顯示名稱。這是 Google API 未使用的字元字串。您可以隨時更新付款方式。
  • 所有 Google Cloud 專案的專案 ID 均不得重複,而且設定後即無法變更。Cloud 控制台會自動產生一個不重複的字串。但通常是在乎它何在在大部分的程式碼研究室中,您必須參照專案 ID (通常為 PROJECT_ID)。如果您對產生的 ID 不滿意,可以隨機產生一個 ID。或者,您也可以自行嘗試,看看是否支援。在這個步驟後,這個名稱即無法變更,而且在專案期間內仍會保持有效。
  • 資訊中的第三個值是專案編號,部分 API 會使用這個編號。如要進一步瞭解這三個值,請參閱說明文件
  1. 接下來,您需要在 Cloud 控制台中啟用計費功能,才能使用 Cloud 資源/API。執行本程式碼研究室不會產生任何費用 (如果有的話)。如要關閉資源,以免產生本教學課程結束後產生的費用,您可以刪除自己建立的資源或刪除專案。新使用者符合 $300 美元免費試用計畫的資格。

啟動 Cloud Shell

雖然 Google Cloud 可以從筆記型電腦遠端操作,但在本程式碼研究室中,您將使用 Google Cloud Shell,這是一種在 Cloud 中執行的指令列環境。

Google Cloud 控制台,按一下右上方的工具列上的 Cloud Shell 圖示:

55efc1aaa7a4d3ad.png

佈建並連線至環境的作業只需幾分鐘的時間。完成後,您應該會看到類似下方的內容:

7ffe5cbb04455448.png

這部虛擬機器都裝載了您需要的所有開發工具。提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作,大幅提高網路效能和驗證能力。本程式碼研究室的所有工作都可以在瀏覽器中完成。不必安裝任何程式。

3. 事前準備

啟用 API

輸出:

在 Cloud Shell 中,請確認您已設定專案 ID:

gcloud config set project [YOUR-PROJECT-ID]

設定環境變數 PROJECT_ID:

PROJECT_ID=$(gcloud config get-value project)

啟用所有必要服務:

gcloud services enable alloydb.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 alloydb.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.

設定預設區域以使用 Vertex AI 嵌入模型。進一步瞭解 Vertex AI 的適用位置。在這個範例中,我們使用的是 us-central1 區域。

gcloud config set compute/region us-central1

4. 部署 AlloyDB

建立 AlloyDB 叢集之前,我們需要虛擬私有雲中的可用私人 IP 範圍,供日後的 AlloyDB 執行個體使用。如果尚未建立叢集和執行個體,就必須建立叢集,再指派給內部 Google 服務使用。

建立私人 IP 範圍

我們必須在虛擬私有雲中,為 AlloyDB 設定私人服務存取權設定。這裡假設使用的是「default」這個專案會用於所有動作。

建立私人 IP 範圍:

gcloud compute addresses create psa-range \
    --global \
    --purpose=VPC_PEERING \
    --prefix-length=24 \
    --description="VPC private service access" \
    --network=default

使用分配的 IP 範圍建立私人連線:

gcloud services vpc-peerings connect \
    --service=servicenetworking.googleapis.com \
    --ranges=psa-range \
    --network=default

預期的主控台輸出內容:

student@cloudshell:~ (test-project-402417)$ gcloud compute addresses create psa-range \
    --global \
    --purpose=VPC_PEERING \
    --prefix-length=24 \
    --description="VPC private service access" \
    --network=default
Created [https://www.googleapis.com/compute/v1/projects/test-project-402417/global/addresses/psa-range].

student@cloudshell:~ (test-project-402417)$ gcloud services vpc-peerings connect \
    --service=servicenetworking.googleapis.com \
    --ranges=psa-range \
    --network=default
Operation "operations/pssn.p24-4470404856-595e209f-19b7-4669-8a71-cbd45de8ba66" finished successfully.

student@cloudshell:~ (test-project-402417)$

建立 AlloyDB 叢集

請在 us-central1 區域中建立 AlloyDB 叢集。

定義 postgres 使用者的密碼。您可以定義自己的密碼,或使用隨機函式來產生一組密碼

export PGPASSWORD=`openssl rand -hex 12`

預期的主控台輸出內容:

student@cloudshell:~ (test-project-402417)$ export PGPASSWORD=`openssl rand -hex 12`

請注意 PostgreSQL 密碼,供日後使用:

echo $PGPASSWORD

預期的主控台輸出內容:

student@cloudshell:~ (test-project-402417)$ echo $PGPASSWORD
bbefbfde7601985b0dee5723

定義區域和 AlloyDB 叢集名稱,我們將使用 us-central1 區域和 alloydb-aip-01 做為叢集名稱:

export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01

執行指令來建立叢集:

gcloud alloydb clusters create $ADBCLUSTER \
    --password=$PGPASSWORD \
    --network=default \
    --region=$REGION

預期的主控台輸出內容:

export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
gcloud alloydb clusters create $ADBCLUSTER \
    --password=$PGPASSWORD \
    --network=default \
    --region=$REGION
Operation ID: operation-1697655441138-6080235852277-9e7f04f5-2012fce4
Creating cluster...done.                                                                                                                                                                                                                                                           

建立 AlloyDB 主要執行個體

在同一個 Cloud Shell 工作階段中,為叢集建立 AlloyDB 主要執行個體。如果中斷連線,您必須重新定義區域和叢集名稱環境變數。

gcloud alloydb instances create $ADBCLUSTER-pr \
    --instance-type=PRIMARY \
    --cpu-count=2 \
    --region=$REGION \
    --cluster=$ADBCLUSTER

預期的主控台輸出內容:

student@cloudshell:~ (test-project-402417)$ gcloud alloydb instances create $ADBCLUSTER-pr \
    --instance-type=PRIMARY \
    --cpu-count=2 \
    --region=$REGION \
    --availability-type ZONAL \
    --cluster=$ADBCLUSTER
Operation ID: operation-1697659203545-6080315c6e8ee-391805db-25852721
Creating instance...done.                                                                                                                                                                                                                                                     

5. 連線至 AlloyDB

AlloyDB 是透過僅限私人連線部署,因此必須安裝 PostgreSQL 用戶端的 VM,才能與資料庫搭配運作。

部署 GCE VM

在 AlloyDB 叢集所在的區域和虛擬私有雲中建立 GCE VM。

請在 Cloud Shell 中執行下列指令:

export ZONE=us-central1-a
gcloud compute instances create instance-1 \
    --zone=$ZONE \
    --create-disk=auto-delete=yes,boot=yes,image=projects/debian-cloud/global/images/$(gcloud compute images list --filter="family=debian-12 AND family!=debian-12-arm64" --format="value(name)") \
    --scopes=https://www.googleapis.com/auth/cloud-platform

預期的主控台輸出內容:

student@cloudshell:~ (test-project-402417)$ export ZONE=us-central1-a
student@cloudshell:~ (test-project-402417)$ export ZONE=us-central1-a
gcloud compute instances create instance-1 \
    --zone=$ZONE \
    --create-disk=auto-delete=yes,boot=yes,image=projects/debian-cloud/global/images/$(gcloud compute images list --filter="family=debian-12 AND family!=debian-12-arm64" --format="value(name)") \
    --scopes=https://www.googleapis.com/auth/cloud-platform

Created [https://www.googleapis.com/compute/v1/projects/test-project-402417/zones/us-central1-a/instances/instance-1].
NAME: instance-1
ZONE: us-central1-a
MACHINE_TYPE: n1-standard-1
PREEMPTIBLE: 
INTERNAL_IP: 10.128.0.2
EXTERNAL_IP: 34.71.192.233
STATUS: RUNNING

安裝 Postgres 用戶端

在已部署的 VM 上安裝 PostgreSQL 用戶端軟體

連線至 VM:

gcloud compute ssh instance-1 --zone=us-central1-a

預期的主控台輸出內容:

student@cloudshell:~ (test-project-402417)$ gcloud compute ssh instance-1 --zone=us-central1-a
Updating project ssh metadata...working..Updated [https://www.googleapis.com/compute/v1/projects/test-project-402417].                                                                                                                                                         
Updating project ssh metadata...done.                                                                                                                                                                                                                                              
Waiting for SSH key to propagate.
Warning: Permanently added 'compute.5110295539541121102' (ECDSA) to the list of known hosts.
Linux instance-1.us-central1-a.c.gleb-test-short-001-418811.internal 6.1.0-18-cloud-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.76-1 (2024-02-01) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
student@instance-1:~$ 

在 VM 中安裝執行指令的軟體:

sudo apt-get update
sudo apt-get install --yes postgresql-client

預期的主控台輸出內容:

student@instance-1:~$ sudo apt-get update
sudo apt-get install --yes postgresql-client
Get:1 https://packages.cloud.google.com/apt google-compute-engine-bullseye-stable InRelease [5146 B]
Get:2 https://packages.cloud.google.com/apt cloud-sdk-bullseye InRelease [6406 B]   
Hit:3 https://deb.debian.org/debian bullseye InRelease  
Get:4 https://deb.debian.org/debian-security bullseye-security InRelease [48.4 kB]
Get:5 https://packages.cloud.google.com/apt google-compute-engine-bullseye-stable/main amd64 Packages [1930 B]
Get:6 https://deb.debian.org/debian bullseye-updates InRelease [44.1 kB]
Get:7 https://deb.debian.org/debian bullseye-backports InRelease [49.0 kB]
...redacted...
update-alternatives: using /usr/share/postgresql/13/man/man1/psql.1.gz to provide /usr/share/man/man1/psql.1.gz (psql.1.gz) in auto mode
Setting up postgresql-client (13+225) ...
Processing triggers for man-db (2.9.4-2) ...
Processing triggers for libc-bin (2.31-13+deb11u7) ...

連線至執行個體

使用 psql 從 VM 連線至主要執行個體。

同一個 Cloud Shell 分頁設有開啟給 instance-1 VM 的 SSH 工作階段。

使用註明的 AlloyDB 密碼 (PGPASSWORD) 值和 AlloyDB 叢集 ID,從 GCE VM 連線至 AlloyDB:

export PGPASSWORD=<Noted password>
export PROJECT_ID=$(gcloud config get-value project)
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
export INSTANCE_IP=$(gcloud alloydb instances describe $ADBCLUSTER-pr --cluster=$ADBCLUSTER --region=$REGION --format="value(ipAddress)")
psql "host=$INSTANCE_IP user=postgres sslmode=require"

預期的主控台輸出內容:

student@instance-1:~$ export PGPASSWORD=CQhOi5OygD4ps6ty
student@instance-1:~$ ADBCLUSTER=alloydb-aip-01
student@instance-1:~$ REGION=us-central1
student@instance-1:~$ INSTANCE_IP=$(gcloud alloydb instances describe $ADBCLUSTER-pr --cluster=$ADBCLUSTER --region=$REGION --format="value(ipAddress)")
gleb@instance-1:~$ psql "host=$INSTANCE_IP user=postgres sslmode=require"
psql (15.6 (Debian 15.6-0+deb12u1), server 15.5)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.

postgres=>

關閉 psql 工作階段:

exit

6. 準備資料庫

我們必須建立資料庫、啟用 Vertex AI 整合服務、建立資料庫物件,以及匯入資料,

將必要權限授予 AlloyDB

將 Vertex AI 權限新增至 AlloyDB 服務代理。

使用加號「+」開啟另一個 Cloud Shell 分頁。

4ca978f5142bb6ce.png

在新 Cloud Shell 分頁中執行:

PROJECT_ID=$(gcloud config get-value project)
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"

預期的主控台輸出內容:

student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project)
Your active configuration is: [cloudshell-11039]
student@cloudshell:~ (test-project-001-402417)$ gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"
Updated IAM policy for project [test-project-001-402417].
bindings:
- members:
  - serviceAccount:service-4470404856@gcp-sa-alloydb.iam.gserviceaccount.com
  role: roles/aiplatform.user
- members:
...
etag: BwYIEbe_Z3U=
version: 1
 

透過執行指令「exit」關閉分頁標籤:

exit

建立資料庫

建立資料庫快速入門導覽課程

在 GCE VM 工作階段中,執行下列指令:

建立資料庫:

psql "host=$INSTANCE_IP user=postgres" -c "CREATE DATABASE quickstart_db"

預期的主控台輸出內容:

student@instance-1:~$ psql "host=$INSTANCE_IP user=postgres" -c "CREATE DATABASE quickstart_db"
CREATE DATABASE
student@instance-1:~$  

啟用 Vertex AI 整合功能

啟用資料庫中的 Vertex AI 整合功能和 pgvector 擴充功能。

在 GCE VM 中,執行下列指令:

psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "CREATE EXTENSION IF NOT EXISTS google_ml_integration CASCADE"
psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "CREATE EXTENSION IF NOT EXISTS vector"

預期的主控台輸出內容:

student@instance-1:~$ psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "CREATE EXTENSION IF NOT EXISTS google_ml_integration CASCADE"
psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "CREATE EXTENSION IF NOT EXISTS vector"
CREATE EXTENSION
CREATE EXTENSION
student@instance-1:~$ 

匯入資料

請下載準備好的資料,並匯入新的資料庫。

在 GCE VM 中,執行下列指令:

gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db"
gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "\copy cymbal_products from stdin csv header"
gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "\copy cymbal_inventory from stdin csv header"
gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "\copy cymbal_stores from stdin csv header"

預期的主控台輸出內容:

student@instance-1:~$ gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db"
SET
SET
SET
SET
SET
 set_config 
------------
 
(1 row)
SET
SET
SET
SET
SET
SET
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
CREATE SEQUENCE
ALTER TABLE
ALTER SEQUENCE
ALTER TABLE
ALTER TABLE
ALTER TABLE
student@instance-1:~$ gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "\copy cymbal_products from stdin csv header"
COPY 941
student@instance-1:~$ gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "\copy cymbal_inventory from stdin csv header"
COPY 263861
student@instance-1:~$ gsutil cat gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv |psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db" -c "\copy cymbal_stores from stdin csv header"
COPY 4654
student@instance-1:~$

7. 計算嵌入

匯入資料後,我們在 cymbal_products 資料表中取得產品資料,這個目錄會在 cymbal_inventory 資料表中,顯示每間商店的可用產品數量,以及 cymbal_stores 表格中的商店清單。我們需要根據產品說明計算向量資料,並使用函式嵌入功能進行計算。我們將透過 Vertex AI 整合功能使用函式,根據產品說明計算向量資料,並將資料新增至表格。如要進一步瞭解使用技術,請參閱說明文件

建立嵌入資料欄

使用 psql 連線至資料庫,並使用 cymbal_products 資料表中的嵌入函式,建立含有向量資料的虛擬資料欄。嵌入函式會根據透過 product_description 欄提供的資料,傳回 Vertex AI 的向量資料。

psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db"

在連線至資料庫後的 psql 工作階段中,執行以下動作:

ALTER TABLE cymbal_products ADD COLUMN embedding vector GENERATED ALWAYS AS (embedding('text-embedding-004',product_description)) STORED;

這個指令會建立虛擬資料欄,並在其中填入向量資料。

預期的主控台輸出內容:

student@instance-1:~$ psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db"
psql (13.11 (Debian 13.11-0+deb11u1), server 14.7)
WARNING: psql major version 13, server major version 14.
         Some psql features might not work.
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

quickstart_db=> ALTER TABLE cymbal_products ADD COLUMN embedding vector GENERATED ALWAYS AS (embedding('text-embedding-004',product_description)) STORED;
ALTER TABLE
quickstart_db=> 

8. 執行相似度搜尋

我們現在可以根據系統針對說明計算出的向量值和我們針對要求所取得的向量值,使用相似度進行搜尋來執行搜尋作業。

SQL 查詢可以在同一個 psql 指令列介面上執行,或是從 AlloyDB Studio 改為執行。在 AlloyDB Studio 中,任何多列和複雜的輸出內容看起來可能會更好。

連線至 AlloyDB Studio

在下列章節中,所有需要連線至資料庫的 SQL 指令均可在 AlloyDB Studio 中執行。如要執行指令,請按一下主要執行個體,開啟 AlloyDB 叢集的網頁控制台介面。

ef4bfbcf0ed2ef3a.png

接著按一下左側的 AlloyDB Studio:

5c155cbcd7d43a1.png

選擇 quickstart_db 資料庫、使用者 postgres,並提供建立叢集時記下的密碼。然後按一下 [驗證]按鈕。

432613065cac864f.png

即可開啟 AlloyDB Studio 介面。如要在資料庫中執行指令,請按一下「Editor 1」分頁。

b36c28f8165119ca.png

您可以在此開啟介面,以便執行 SQL 指令

cf43aa20f292797e.png

如果想使用指令列 psql,請按照替代路徑,從 VM SSH 工作階段連線至資料庫,如同先前的章節所述。

從 psql 執行相似度搜尋

如果資料庫工作階段已中斷連線,請使用 psql 或 AlloyDB Studio 再次連線至資料庫。

連線至資料庫:

psql "host=$INSTANCE_IP user=postgres dbname=quickstart_db"

執行查詢,取得與客戶要求最密切相關的可用產品清單。我們要將要求傳遞至 Vertex AI,取得向量值聽起來像是「哪種果樹在這裡生長?」

您可以執行下列查詢,來選擇最符合要求的前 10 個項目:

SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        (cp.embedding <=> embedding('text-embedding-004','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;

預期的輸出內容如下:

quickstart_db=> SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        (cp.embedding <=> embedding('text-embedding-004','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;
    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.287184013172779
 Toyon               | This is a beautiful toyon tree that can grow to be over 20 feet tall. It is an e |      10.00 |    93230 | 0.30574073611569963
 Secateurs           | These secateurs are perfect for pruning small branches and vines.                |      15.00 |    93230 |  0.3264385326189635
 Trimming Shears     | These trimming shears are perfect for trimming hedges and bushes.                |      20.00 |    93230 | 0.33293036535756393
 Cypress Tree        | This is a beautiful cypress tree that will provide shade and privacy. It is an e |      75.00 |    93230 | 0.33485770716129326
 Madrone             | This is a beautiful madrona tree that can grow to be over 80 feet tall. It is an |      50.00 |    93230 |  0.3354408801293012
 California Redwood  | This is a beautiful redwood tree that can grow to be over 300 feet tall. It is a |    1000.00 |    93230 |  0.3427243109636263
 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.3427628377929176
 California Sycamore | This is a beautiful sycamore tree that can grow to be over 100 feet tall. It is  |     300.00 |    93230 |  0.3430208475356905
 Maple Tree          | This is a beautiful maple tree that will produce colorful leaves in the fall. It |     100.00 |    93230 |  0.3432609589330091
(10 rows)

quickstart_db=> 

9. 改善回應

您可以運用查詢結果提升回應用戶端應用程式的回應,並在 Vertex AI 生成式基礎語言模型的提示中,使用提供的查詢結果準備有意義的輸出內容。

為此,我們打算以向量搜尋的結果產生 JSON,並在 Vertex AI 中,將生成的 JSON 做為提示,做為文字 LLM 模型的提示,產生有意義的輸出內容。第一個步驟中我們產生 JSON,然後在 Vertex AI Studio 中進行測試。最後,我們會在最後一個步驟中將 JSON 合併到 SQL 陳述式中,以便用於應用程式。

以 JSON 格式產生輸出內容

修改查詢以產生 JSON 格式的輸出內容,且只傳回一個資料列來傳送至 Vertex AI

查詢範例如下:

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-004','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"}]

在 Vertex AI Studio 中執行提示

我們可以使用產生的 JSON,在 Vertex AI Studio 中,將產生的 JSON 做為提示的一部分提供給生成式 AI 文字模型。

在 Cloud 控制台中開啟 Vertex AI Studio。

e514b176aef7945e.png

54712e5ade7121f.png

系統可能會請您啟用其他 API,但您可以忽略要求。我們不需要任何其他 API 就能完成研究室。

以下是要使用的提示:

你是親切的顧問,能幫助你根據客戶需求尋找產品。

我們根據客戶的要求,載入了與搜尋字詞密切相關的產品清單。

JSON 格式清單,其中包含下列值的清單:{"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "produt_id": "02056727942aeb714dc9a2313654e1b0"}

產品清單如下:

[填入 JSON 的地方]

顧客詢問「哪個樹最生長最出色?」

請務必提供產品、價格和補充資訊視為提示

使用 JSON 值執行提示並使用 gemini-1.5-flash 模型時,結果如下:

30e5072cd2975685.png

這個範例中模型取得的答案如下。請注意,您的答案可能會因為模型和參數隨著時間而改變。

「據瞭解,你正在尋找種植所在區域的樹木。根據你的郵遞區號「93230」,櫻桃樹看起來是不錯的選擇!

這裡是一份美麗的樹,可生產美味的櫻桃。目前特價 $75.00 美元。

雖然無法確切說明你所在地區的成長率,不過可以告訴你,櫻花樹通常比較喜歡經過充分的土壤和全日照。

為確保最佳成效,建議你諮詢當地的養護理工或園藝專家,由對方根據你所在的地點和土壤條件,提供更加符合需求的建議。這些專家也能協助您選擇最符合需求的方案,並提供有關植栽和照顧的提示。」

在 PSQL 中執行提示

AlloyDB AI 整合 Vertex AI,就能直接在資料庫中使用 SQL,從生成式模型取得相同的回應。但如要使用 gemini-1.5-flash 模型,就必須先註冊該模型。

將擴充功能升級至 1.3 版。請依先前 (或使用 AlloyDB Studio) 顯示的 pSQL 連線至 quickstart_db 資料庫,然後執行下列指令:

ALTER EXTENSION google_ml_integration UPDATE TO '1.3'

然後將 google_ml_integration.enable_model_support 資料庫旗標設為「on」。如要執行這項作業,您可以使用 AlloyDB 網頁控制台介面或執行下列 gcloud 指令。

PROJECT_ID=$(gcloud config get-value project)
REGION=us-central1
ADBCLUSTER=alloydb-aip-01
gcloud beta alloydb instances update $ADBCLUSTER-pr \
  --database-flags google_ml_integration.enable_model_support=on \
  --region=$REGION \
  --cluster=$ADBCLUSTER \
  --project=$PROJECT_ID \
  --update-mode=FORCE_APPLY

這項指令會在背景執行大約 3 到 5 分鐘。接著,您就能在 psql 工作階段或使用 AlloyDB Studio 連線至 quickstart_db 資料庫中驗證新旗標。

show google_ml_integration.enable_model_support;

psql 工作階段的預期輸出內容為「on」:

postgres=> show google_ml_integration.enable_model_support;
 google_ml_integration.enable_model_support 
--------------------------------------------
 on
(1 row)

接著,我們要註冊兩個模型。第一種是已經使用的 text-embedding-004 模型。我們已啟用模型註冊功能,因此需要註冊。

如要註冊在 psql 或 AlloyDB Studio 中執行模型,請將下列程式碼:

CALL
  google_ml.create_model(
    model_id => 'text-embedding-004',
    model_provider => 'google',
    model_qualified_name => 'text-embedding-004',
    model_type => 'text_embedding',
    model_auth_type => 'alloydb_service_agent_iam',
    model_in_transform_fn => 'google_ml.vertexai_text_embedding_input_transform',
    model_out_transform_fn => 'google_ml.vertexai_text_embedding_output_transform');

下一個需要註冊的模型是 gemini-1.5-flash-001,用來產生使用者容易使用的輸出內容。

CALL
  google_ml.create_model(
    model_id => 'gemini-1.5-flash-001',
    model_request_url => 'https://$REGION-aiplatform.googleapis.com/v1/projects/$PROJECT_ID/locations/$REGION/publishers/google/models/gemini-1.5-flash-001:streamGenerateContent',
    model_provider => 'google',
    model_auth_type => 'alloydb_service_agent_iam');

您可隨時從 google_ml.model_info_view 中選取資訊,以驗證已註冊模型清單。

select model_id,model_type from google_ml.model_info_view;

以下是輸出內容範例

quickstart_db=> select model_id,model_type from google_ml.model_info_view;
        model_id         |   model_type   
-------------------------+----------------
 textembedding-gecko     | text_embedding
 textembedding-gecko@001 | text_embedding
 text-embedding-004      | text_embedding
 gemini-1.5-flash-001    | generic
(4 rows)

我們現在可以使用在子查詢 JSON 中產生的生成內容,做為使用 SQL 生成式 AI 文字模型的提示的一部分。

在對資料庫的 psql 或 AlloyDB Studio 工作階段中執行查詢

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-004',
        '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
        json_array_elements(google_ml.predict_row( model_id =>'gemini-1.5-flash-001',
        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
        string_agg(resp::text,
        ' ')
FROM
        response;

預期的輸出內容如下輸出內容可能會依模型版本和參數而有所不同。

--------------------------------------------------------------------------------------------------------
 "I" " see you're interested in fruit trees! Based on your location, I found" " one great option:\n\n**Cherry Tree:** \n\nThis beautiful cherry tree will" " produce delicious cherries. It's a deciduous tree, meaning it loses its leaves in the fall, and can grow up to 15 feet tall. The" " leaves are a vibrant dark green in the summer, turning a beautiful red in the fall. \n\nCherry trees are known for their beauty and ability to provide shade" " and privacy. They prefer a cool, moist climate and sandy soil, making them a good fit for your area. \n\nThe Cherry Tree is currently on sale for $75.00.\n\nWould you like to know more about" " the Cherry Tree, or are you interested in exploring other fruit tree options? \n" ""
(1 row)

10. 清除環境資源

完成研究室後,請刪除 AlloyDB 執行個體和叢集

刪除 AlloyDB 叢集和所有執行個體

系統會透過選項強制刪除叢集,這也會刪除屬於叢集的所有執行個體。

如果連線中斷,之前的所有設定都會遺失,請在 Cloud Shell 中定義專案和環境變數:

gcloud config set project <your project id>
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
export PROJECT_ID=$(gcloud config get-value project)

刪除叢集:

gcloud alloydb clusters delete $ADBCLUSTER --region=$REGION --force

預期的主控台輸出內容:

student@cloudshell:~ (test-project-001-402417)$ gcloud alloydb clusters delete $ADBCLUSTER --region=$REGION --force
All of the cluster data will be lost when the cluster is deleted.

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

Operation ID: operation-1697820178429-6082890a0b570-4a72f7e4-4c5df36f
Deleting cluster...done.   

刪除 AlloyDB 備份

刪除叢集的所有 AlloyDB 備份:

for i in $(gcloud alloydb backups list --filter="CLUSTER_NAME: projects/$PROJECT_ID/locations/$REGION/clusters/$ADBCLUSTER" --format="value(name)" --sort-by=~createTime) ; do gcloud alloydb backups delete $(basename $i) --region $REGION --quiet; done

預期的主控台輸出內容:

student@cloudshell:~ (test-project-001-402417)$ for i in $(gcloud alloydb backups list --filter="CLUSTER_NAME: projects/$PROJECT_ID/locations/$REGION/clusters/$ADBCLUSTER" --format="value(name)" --sort-by=~createTime) ; do gcloud alloydb backups delete $(basename $i) --region $REGION --quiet; done
Operation ID: operation-1697826266108-60829fb7b5258-7f99dc0b-99f3c35f
Deleting backup...done.                                                                                                                                                                                                                                                            

現在可以刪除 VM

刪除 GCE VM

請在 Cloud Shell 中執行下列指令:

export GCEVM=instance-1
export ZONE=us-central1-a
gcloud compute instances delete $GCEVM \
    --zone=$ZONE \
    --quiet

預期的主控台輸出內容:

student@cloudshell:~ (test-project-001-402417)$ export GCEVM=instance-1
export ZONE=us-central1-a
gcloud compute instances delete $GCEVM \
    --zone=$ZONE \
    --quiet
Deleted 

11. 恭喜

恭喜您完成本程式碼研究室。

涵蓋內容

  • 如何部署 AlloyDB 叢集和主要執行個體
  • 如何從 Google Compute Engine VM 連線至 AlloyDB
  • 如何建立資料庫並啟用 AlloyDB AI
  • 如何將資料載入資料庫
  • 如何在 AlloyDB 中使用 Vertex AI 嵌入模型
  • 如何使用 Vertex AI 生成式模型充實結果

12. 問卷調查

輸出:

您會如何使用這個教學課程?

只能閱讀 閱讀並完成練習