1. 簡介
在本程式碼研究室中,您將瞭解如何部署生成式 AI 資料庫擷取服務,並使用已部署的環境建立互動式應用程式範例。
如要進一步瞭解生成式 AI 擷取服務和範例應用程式,請前往這裡。
必要條件
- 對 Google Cloud 控制台的基本概念
- 指令列介面和 Google Cloud Shell 的基本技能
課程內容
- 如何建立 Cloud SQL 執行個體
- 如何連線至執行個體
- 如何設定及部署生成式 AI 資料庫擷取服務
- 如何使用已部署的服務部署範例應用程式
軟硬體需求
- Google Cloud 帳戶和 Google Cloud 專案
- 使用 Chrome 等網路瀏覽器
2. 設定和需求
自修環境設定
- 登入 Google Cloud 控制台,建立新專案或重複使用現有專案。如果您還沒有 Gmail 或 Google Workspace 帳戶,請先建立帳戶。
- 「專案名稱」是這項專案參與者的顯示名稱。這是 Google API 未使用的字元字串。您可以隨時更新付款方式。
- 所有 Google Cloud 專案的專案 ID 均不得重複,而且設定後即無法變更。Cloud 控制台會自動產生一個不重複的字串。但通常是在乎它何在在大部分的程式碼研究室中,您必須參照專案 ID (通常為
PROJECT_ID
)。如果您對產生的 ID 不滿意,可以隨機產生一個 ID。或者,您也可以自行嘗試,看看是否支援。在這個步驟後,這個名稱即無法變更,而且在專案期間內仍會保持有效。 - 資訊中的第三個值是專案編號,部分 API 會使用這個編號。如要進一步瞭解這三個值,請參閱說明文件。
- 接下來,您需要在 Cloud 控制台中啟用計費功能,才能使用 Cloud 資源/API。執行本程式碼研究室不會產生任何費用 (如果有的話)。如要關閉資源,以免產生本教學課程結束後產生的費用,您可以刪除自己建立的資源或刪除專案。新使用者符合 $300 美元免費試用計畫的資格。
啟動 Cloud Shell
雖然 Google Cloud 可以從筆記型電腦遠端操作,但在本程式碼研究室中,您將使用 Google Cloud Shell,這是一種在 Cloud 中執行的指令列環境。
在 Google Cloud 控制台,按一下右上方的工具列上的 Cloud Shell 圖示:
佈建並連線至環境的作業只需幾分鐘的時間。完成後,您應該會看到類似下方的內容:
這部虛擬機器都裝載了您需要的所有開發工具。提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作,大幅提高網路效能和驗證能力。本程式碼研究室的所有工作都可以在瀏覽器中完成。不必安裝任何程式。
3. 事前準備
啟用 API
在 Cloud Shell 中,請確認您已設定專案 ID:
在 Cloud Shell 命令提示字元中,專案 ID 通常會顯示在括號內,如圖所示:
gcloud config set project [YOUR-PROJECT-ID]
然後將 PROJECT_ID 環境變數設為 Google Cloud 專案 ID:
PROJECT_ID=$(gcloud config get-value project)
啟用所有必要服務:
gcloud services enable sqladmin.googleapis.com \
compute.googleapis.com \
cloudresourcemanager.googleapis.com \
servicenetworking.googleapis.com \
vpcaccess.googleapis.com \
aiplatform.googleapis.com \
cloudbuild.googleapis.com \
artifactregistry.googleapis.com \
run.googleapis.com \
iam.googleapis.com
預期的主控台輸出內容:
student@cloudshell:~ (gleb-test-short-004)$ gcloud services enable sqladmin.googleapis.com \ compute.googleapis.com \ cloudresourcemanager.googleapis.com \ servicenetworking.googleapis.com \ vpcaccess.googleapis.com \ aiplatform.googleapis.com \ cloudbuild.googleapis.com \ artifactregistry.googleapis.com \ run.googleapis.com \ iam.googleapis.com Operation "operations/acf.p2-404051529011-664c71ad-cb2b-4ab4-86c1-1f3157d70ba1" finished successfully.
4. 建立 Cloud SQL 執行個體
建立啟用向量支援的 Cloud SQL 執行個體。
建立密碼
定義預設資料庫使用者的密碼。您可以定義自己的密碼,或使用隨機函式來產生一組密碼
export CLOUDSQL_PASSWORD=`openssl rand -hex 12`
請記下系統產生的密碼值
echo $CLOUDSQL_PASSWORD
MySQL
您可以在建立執行個體時啟用 cloudsql_vector
旗標。MySQL 8.0.36 與目前提供向量支援8.0.37.
export region=us-central1
gcloud sql instances create my-cloudsql-instance --region=$region --database-version=MYSQL_8_0_36 --database-flags=cloudsql_vector=ON --root-password=$CLOUDSQL_PASSWORD
預期的主控台輸出內容 (IP 位址已遮蓋):
student@cloudshell:~ export region=us-central1 gcloud sql instances create my-cloudsql-instance --region=$region --database-version=MYSQL_8_0_36 --database-flags=cloudsql_vector=ON --root-password=$CLOUDSQL_PASSWORD Creating Cloud SQL instance for MYSQL_8_0_36...done. Created [https://sqladmin.googleapis.com/sql/v1beta4/projects/test-project-402417/instances/my-cloudsql-instance]. NAME DATABASE_VERSION LOCATION TIER PRIMARY_ADDRESS PRIVATE_ADDRESS STATUS my-cloudsql-instance MYSQL_8_0_36 us-central1-a db-n1-standard-1 00.000.00.00 - RUNNABLE
PostgreSQL
pgvector 擴充功能為 11 以上版本。
export region=us-central1
gcloud sql instances create my-cloudsql-instance --region=$region --database-version=POSTGRES_15 --tier=db-g1-small
預期的主控台輸出內容 (IP 位址已遮蓋):
student@cloudshell:~ export region=us-central1 gcloud sql instances create my-cloudsql-instance --region=$region --database-version=POSTGRES_15 --tier=db-g1-small Creating Cloud SQL instance for POSTGRES_15...done. Created [https://sqladmin.googleapis.com/sql/v1beta4/projects/test-project-402417/instances/my-cloudsql-instance]. NAME DATABASE_VERSION LOCATION TIER PRIMARY_ADDRESS PRIVATE_ADDRESS STATUS my-cloudsql-instance POSTGRES_15 us-central1-a db-g1-small 00.000.00.00 - RUNNABLE
建立執行個體後,我們必須定義執行個體中的預設使用者密碼,然後檢查是否能連線至密碼。準備好連線時,請在提示中輸入密碼。
gcloud sql users set-password postgres \
--instance=my-cloudsql-instance \
--password=$CLOUDSQL_PASSWORD
gcloud sql connect my-cloudsql-instance --user=postgres
預期的主控台輸出內容:
student@cloudshell:~ (test-project-402417)$ gcloud sql users set-password postgres \ --instance=my-cloudsql-instance \ --password=$CLOUDSQL_PASSWORD gcloud sql connect my-cloudsql-instance --user=postgres Updating Cloud SQL user...done. Allowlisting your IP for incoming connection for 5 minutes...done. Connecting to database with SQL user [postgres].Password: psql (16.3 (Ubuntu 16.3-1.pgdg22.04+1), server 15.7) SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off) Type "help" for help. postgres=>
結束 psql 工作階段:
exit
5. 準備 GCE 虛擬機器
建立服務帳戶
由於我們將使用 VM 部署生成式 AI 資料庫擷取服務並託管範例應用程式,因此第一步是建立 Google 服務帳戶 (GSA)。GCE VM 將使用 GSA,且需要授予相關權限,才能搭配其他服務使用。
請在 Cloud Shell 中執行下列指令:
PROJECT_ID=$(gcloud config get-value project)
gcloud iam service-accounts create compute-aip --project $PROJECT_ID
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/cloudbuild.builds.editor"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/artifactregistry.admin"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/storage.admin"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/run.admin"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/iam.serviceAccountUser"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/cloudsql.viewer"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/cloudsql.client"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/aiplatform.user"
部署 GCE VM
在與 Cloud SQL 執行個體相同的區域和虛擬私有雲中建立 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 \
--service-account=compute-aip@$PROJECT_ID.iam.gserviceaccount.com
預期的主控台輸出內容:
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
授權 VM 連線至 Cloud SQL
我們必須將 VM 公開 IP 新增至 Cloud SQL 執行個體的授權網路清單中。在 Cloud Shell 中執行下列指令:
VM_EXTERNAL_IP=$(gcloud compute instances describe instance-1 --zone=us-central1-a --format='get(networkInterfaces[0].accessConfigs[0].natIP)')
gcloud sql instances patch my-cloudsql-instance --authorized-networks=$VM_EXTERNAL_IP
預期的主控台輸出內容:
student@cloudshell:~ (test-project-402417)$ export ZONE=us-central1-a student@cloudshell:~ (test-project-402417)$ VM_EXTERNAL_IP=$(gcloud compute instances describe instance-1 --zone=us-central1-a --format='get(networkInterfaces[0].accessConfigs[0].natIP)') gcloud sql instances patch my-cloudsql-instance --authorized-networks=$VM_EXTERNAL_IP When adding a new IP address to authorized networks, make sure to also include any IP addresses that have already been authorized. Otherwise, they will be overwritten and de-authorized. Do you want to continue (Y/n)? Y The following message will be used for the patch API method. {"name": "my-cloudsql-instance", "project": "test-project-402417", "settings": {"ipConfiguration": {"authorizedNetworks": [{"value": "34.71.252.173"}]}}} Patching Cloud SQL instance...done. Updated [https://sqladmin.googleapis.com/sql/v1beta4/projects/test-project-402417/instances/my-cloudsql-instance].
安裝資料庫用戶端
MySQL
在已部署的 VM 上安裝 MySQL 用戶端軟體。
連線至 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 5.10.0-26-cloud-amd64 #1 SMP Debian 5.10.197-1 (2023-09-29) 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 default-mysql-client
預期的主控台輸出內容:
student@instance-1:~$ sudo apt-get update sudo apt-get install --yes mysql-client Reading package lists... Done Building dependency tree... Done Reading state information... Done The following additional packages will be installed: libconfig-inifiles-perl libdbd-mariadb-perl libdbi-perl libgdbm-compat4 libperl5.32 libterm-readkey-perl mariadb-client-10.5 mariadb-client-core-10.5 perl perl-modules-5.32 Suggested packages: libclone-perl libmldbm-perl libnet-daemon-perl libsql-statement-perl perl-doc libterm-readline-gnu-perl | libterm-readline-perl-perl make libtap-harness-archive-perl The following NEW packages will be installed: default-mysql-client libconfig-inifiles-perl libdbd-mariadb-perl libdbi-perl libgdbm-compat4 libperl5.32 libterm-readkey-perl mariadb-client-10.5 mariadb-client-core-10.5 perl Perl-modules-5.32 ...redacted... Processing triggers for libc-bin (2.31-13+deb11u10) ...
PostgreSQL
在已部署的 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 5.10.0-26-cloud-amd64 #1 SMP Debian 5.10.197-1 (2023-09-29) 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 file:/etc/apt/mirrors/debian.list Mirrorlist [30 B] Get:4 file:/etc/apt/mirrors/debian-security.list Mirrorlist [39 B] Hit:7 https://packages.cloud.google.com/apt google-compute-engine-bookworm-stable InRelease Get:8 https://packages.cloud.google.com/apt cloud-sdk-bookworm InRelease [1652 B] Get:2 https://deb.debian.org/debian bookworm InRelease [151 kB] Get:3 https://deb.debian.org/debian bookworm-updates InRelease [55.4 kB] ...redacted... update-alternatives: using /usr/share/postgresql/15/man/man1/psql.1.gz to provide /usr/share/man/man1/psql.1.gz (psql.1.gz) in auto mode Setting up postgresql-client (15+248) ... Processing triggers for man-db (2.11.2-2) ... Processing triggers for libc-bin (2.36-9+deb12u7) ...
連線至執行個體
MySQL
使用 MySQL 從 VM 連線至主要執行個體。
使用已開啟的 SSH 工作階段連線至 VM。如果您已中斷連線,請使用上述的相同指令重新連線。
使用先前記下的 $CLOUDSQL_PASSWORD 和執行個體名稱,從 GCE VM 連線至 Cloud SQL:
export CLOUDSQL_PASSWORD=<Noted password>
export PROJECT_ID=$(gcloud config get-value project)
export REGION=us-central1
export INSTANCE_NAME=my-cloudsql-instance
export INSTANCE_IP=$(gcloud sql instances list --filter=name:$INSTANCE_NAME --format="value(PRIMARY_ADDRESS)")
mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD
預期的主控台輸出內容:
student@instance-1:~$ export CLOUDSQL_PASSWORD=P9... student@instance-1:~$ export REGION=us-central1 student@instance-1:~$ export INSTANCE_NAME=my-cloud-sql-instance student@instance-1:~$ export INSTANCE_IP=$(gcloud sql instances list --filter=name:$INSTANCE_NAME --format="value(PRIMARY_ADDRESS)") student@instance-1:~$ mysql –host=$INSTANCE_IP –user=root –password=$CLOUDSQL_PASSWORD –sslmode=require Welcome to the MariaDB monitor. Commands end with ; or \g. Your MySQL connection id is 2824706 Server version: 8.0.36-google (Google) Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MySQL [(none)]>
結束 MySQL 工作階段,讓 SSH 連線保持連線:
exit
預期的主控台輸出內容:
MySQL [(none)]> exit Bye student@instance-1:~$
PostgreSQL
使用 psql 從 VM 連線至主要執行個體。
使用已開啟的 SSH 工作階段連線至 VM。如果連線中斷,請使用上述的相同指令重新連線。
使用先前記下的 $CLOUDSQL_PASSWORD 和執行個體名稱,從 GCE VM 連線至 PostgreSQL:
export PGPASSWORD=<Noted password (CLOUDSQL_PASSWORD)>
export CLOUDSQL_PASSWORD=$PGPASSWORD
export PROJECT_ID=$(gcloud config get-value project)
export REGION=us-central1
export INSTANCE_NAME=my-cloudsql-instance
export INSTANCE_IP=$(gcloud sql instances list --filter=name:$INSTANCE_NAME --format="value(PRIMARY_ADDRESS)")
psql "host=$INSTANCE_IP user=postgres sslmode=require"
預期的主控台輸出內容:
student@instance-1:~$ export CLOUDSQL_PASSWORD=P9... student@instance-1:~$ export REGION=us-central1 student@instance-1:~$ export INSTANCE_IP=$(gcloud sql instances list --filter=name:$INSTANCE_NAME --format="value(PRIMARY_ADDRESS)") student@instance-1:~$ psql "host=$INSTANCE_IP user=postgres sslmode=require" 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. postgres=>
結束 psql 工作階段,讓 SSH 連線保持連線:
exit
預期的主控台輸出內容:
postgres=> exit student@instance-1:~$
6. 初始化資料庫
我們將使用用戶端 VM 做為在資料庫中填入資料及託管應用程式的平台。第一步是建立資料庫並填入資料。
建立資料庫
MySQL
建立名稱為「assistantdemo」的資料庫。
在 GCE VM 工作階段中,執行下列指令:
mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD -e "CREATE DATABASE assistantdemo"
預期的主控台輸出內容 (沒有輸出內容):
student@instance-1:~$ mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD -e "CREATE DATABASE assistantdemo" student@instance-1:~$
PostgreSQL
建立名稱為「assistantdemo」的資料庫。
在 GCE VM 工作階段中,執行下列指令:
psql "host=$INSTANCE_IP user=postgres" -c "CREATE DATABASE assistantdemo"
預期的主控台輸出內容:
student@instance-1:~$ psql "host=$INSTANCE_IP user=postgres" -c "CREATE DATABASE assistantdemo" CREATE DATABASE student@instance-1:~$
啟用 pgvector 擴充功能。
psql "host=$INSTANCE_IP user=postgres dbname=assistantdemo" -c "CREATE EXTENSION vector"
預期的主控台輸出內容 (沒有輸出內容):
student@instance-1:~$ psql "host=$INSTANCE_IP user=postgres dbname=assistantdemo" -c "CREATE EXTENSION vector" CREATE EXTENSION student@instance-1:~$
準備 Python 環境
如要繼續,我們要使用 GitHub 存放區中已備妥的 Python 指令碼,但在執行前,我們必須安裝必要的軟體。
在 GCE VM 中,執行下列指令:
sudo apt install -y python3.11-venv git
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
預期的主控台輸出內容:
student@instance-1:~$ sudo apt install -y python3.11-venv git python3 -m venv .venv source .venv/bin/activate pip install --upgrade pip Reading package lists... Done Building dependency tree... Done Reading state information... Done The following additional packages will be installed: git-man liberror-perl patch python3-distutils python3-lib2to3 python3-pip-whl python3-setuptools-whl Suggested packages: git-daemon-run | git-daemon-sysvinit git-doc git-email git-gui gitk gitweb git-cvs git-mediawiki git-svn ed diffutils-doc The following NEW packages will be installed: git git-man liberror-perl patch python3-distutils python3-lib2to3 python3-pip-whl python3-setuptools-whl python3.11-venv 0 upgraded, 9 newly installed, 0 to remove and 2 not upgraded. Need to get 12.4 MB of archives. After this operation, 52.2 MB of additional disk space will be used. Get:1 file:/etc/apt/mirrors/debian.list Mirrorlist [30 B] ...redacted... Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 23.0.1 Uninstalling pip-23.0.1: Successfully uninstalled pip-23.0.1 Successfully installed pip-24.0 (.venv) student@instance-1:~$
驗證 Python 版本。
在 GCE VM 中,執行下列指令:
python -V
預期的主控台輸出內容:
(.venv) student@instance-1:~$ python -V Python 3.11.2 (.venv) student@instance-1:~$
準備設定檔
使用擷取服務和範例應用程式的程式碼,複製 GitHub 存放區。
在 GCE VM 中,執行下列指令:
git clone https://github.com/GoogleCloudPlatform/genai-databases-retrieval-app.git
預期的主控台輸出內容:
student@instance-1:~$ git clone https://github.com/GoogleCloudPlatform/genai-databases-retrieval-app.git Cloning into 'genai-databases-retrieval-app'... remote: Enumerating objects: 525, done. remote: Counting objects: 100% (336/336), done. remote: Compressing objects: 100% (201/201), done. remote: Total 525 (delta 224), reused 179 (delta 135), pack-reused 189 Receiving objects: 100% (525/525), 46.58 MiB | 16.16 MiB/s, done. Resolving deltas: 100% (289/289), done.
MySQL
在 GCE VM 中,執行下列指令:
cd ~/genai-databases-retrieval-app/retrieval_service
cp example-config-cloudsql.yml config.yml
cp example-config-cloudsql.yml config.yml
sed -i s/engine/mysql/g config.yml
sed -i s/my-project/$PROJECT_ID/g config.yml
sed -i s/my-region/$REGION/g config.yml
sed -i s/my-instance/$INSTANCE_NAME/g config.yml
sed -i s/my-password//g config.yml
sed -i s/my_database/assistantdemo/g config.yml
sed -i s/my-user/root/g config.yml
cat config.yml
預期的主控台輸出內容:
student@instance-1:~$ cd genai-databases-retrieval-app/retrieval_service cp example-config-cloudsql.yml config.yml sed -i s/127.0.0.1/$INSTANCE_IP/g config.yml sed -i s/my-password/$CLOUDSQL_PASSWORD/g config.yml sed -i s/my_database/assistantdemo/g config.yml sed -i s/my-user/postgres/g config.yml cat config.yml host: 0.0.0.0 # port: 8080 datastore: # Example for MySQL kind: "cloudsql-mysql" host: 10.65.0.2 # port: 5432 database: "assistantdemo" user: "root" password: "P9..."
Postgres
在 GCE VM 中,執行下列指令:
cd ~/genai-databases-retrieval-app/retrieval_service
cp example-config-cloudsql.yml config.yml
sed -i s/engine/postgres/g config.yml
sed -i s/my-project/$PROJECT_ID/g config.yml
sed -i s/my-region/$REGION/g config.yml
sed -i s/my-instance/$INSTANCE_NAME/g config.yml
sed -i s/my-password/$PGPASSWORD/g config.yml
sed -i s/my_database/assistantdemo/g config.yml
sed -i s/my-user/postgres/g config.yml
cat config.yml
預期的主控台輸出內容:
student@instance-1:~$ cd genai-databases-retrieval-app/retrieval_service cp example-config-cloudsql.yml config.yml sed -i s/engine/postgres/g config.yml sed -i s/my-project/$PROJECT_ID/g config.yml sed -i s/my-region/$REGION/g config.yml sed -i s/my-instance/$INSTANCE_NAME/g config.yml sed -i s/my-password/$CLOUDSQL_PASSWORD/g config.yml sed -i s/my_database/assistantdemo/g config.yml sed -i s/my-user/postgres/g config.yml cat config.yml host: 0.0.0.0 # port: 8080 datastore: # Example for Postgres kind: "cloudsql-postgres" host: 10.65.0.2 # port: 5432 database: "assistantdemo" user: "postgres" password: "P9..."
填入資料庫
使用範例資料集填入資料庫。第一項指令是將所有必要套件新增至 Python 虛擬環境,第二個指令就是在資料庫中填入資料。
在 GCE VM 中,執行下列指令:
cd ~/genai-databases-retrieval-app/retrieval_service
pip install -r requirements.txt
python run_database_init.py
預期的控制台輸出內容 (已遮蓋):
student@instance-1:~/genai-databases-retrieval-app/retrieval_service$ pip install -r requirements.txt python run_database_init.py Collecting asyncpg==0.28.0 (from -r requirements.txt (line 1)) Obtaining dependency information for asyncpg==0.28.0 from https://files.pythonhosted.org/packages/77/a4/88069f7935b14c58534442a57be3299179eb46aace2d3c8716be199ff6a6/asyncpg-0.28.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata Downloading asyncpg-0.28.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.3 kB) Collecting fastapi==0.101.1 (from -r requirements.txt (line 2)) ... database init done. student@instance-1:~/genai-databases-retrieval-app/retrieval_service$
7. 將擷取服務部署至 Cloud Run
現在可以將擷取服務部署至 Cloud Run。這項服務負責與資料庫搭配運作,並根據 AI 應用程式的要求,從資料庫擷取必要資訊。
建立服務帳戶
建立擷取服務的服務帳戶並授予必要權限。
使用加號「+」開啟另一個 Cloud Shell 分頁。
在新 Cloud Shell 分頁中執行:
export PROJECT_ID=$(gcloud config get-value project)
gcloud iam service-accounts create retrieval-identity
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:retrieval-identity@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/aiplatform.user"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:retrieval-identity@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/cloudsql.client"
預期的主控台輸出內容:
student@cloudshell:~ (gleb-test-short-003)$ gcloud iam service-accounts create retrieval-identity Created service account [retrieval-identity].
透過執行指令「exit」關閉分頁標籤:
exit
部署擷取服務
部署服務,繼續前往透過 SSH 連線至 VM 的第一個分頁。
在 VM SSH 工作階段中,執行下列指令:
cd ~/genai-databases-retrieval-app
gcloud alpha run deploy retrieval-service \
--source=./retrieval_service/\
--no-allow-unauthenticated \
--service-account retrieval-identity \
--region us-central1 \
--network=default \
--quiet
預期的主控台輸出內容:
student@instance-1:~/genai-databases-retrieval-app$ gcloud alpha run deploy retrieval-service \ --source=./retrieval_service/\ --no-allow-unauthenticated \ --service-account retrieval-identity \ --region us-central1 \ --network=default This command is equivalent to running `gcloud builds submit --tag [IMAGE] ./retrieval_service/` and `gcloud run deploy retrieval-service --image [IMAGE]` Building using Dockerfile and deploying container to Cloud Run service [retrieval-service] in project [gleb-test-short-003] region [us-central1] X Building and deploying... Done. ✓ Uploading sources... ✓ Building Container... Logs are available at [https://console.cloud.google.com/cloud-build/builds/6ebe74bf-3039-4221-b2e9-7ca8fa8dad8e?project=1012713954588]. ✓ Creating Revision... ✓ Routing traffic... Setting IAM Policy... Completed with warnings: Setting IAM policy failed, try "gcloud beta run services remove-iam-policy-binding --region=us-central1 --member=allUsers --role=roles/run.invoker retrieval-service" Service [retrieval-service] revision [retrieval-service-00002-4pl] has been deployed and is serving 100 percent of traffic. Service URL: https://retrieval-service-onme64eorq-uc.a.run.app student@instance-1:~/genai-databases-retrieval-app$
驗證服務
現在可以檢查服務是否正常運作,以及 VM 能否存取端點。我們使用 gcloud 公用程式取得擷取服務端點。您也可以在 Cloud 控制台中查看,並在 curl 指令中替換 "$(gcloud run services list –filter="(retrieval-service)"。
在 VM SSH 工作階段中,執行下列指令:
curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" $(gcloud run services list --filter="(retrieval-service)" --format="value(URL)")
預期的主控台輸出內容:
student@instance-1:~/genai-databases-retrieval-app$ curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" $(gcloud run services list --filter="(retrieval-service)" --format="value(URL)") {"message":"Hello World"}student@instance-1:~/genai-databases-retrieval-app$
如果看到「Hello World」訊息,表示我們的服務已啟動並處理要求。
8. 部署範例應用程式
現在,當擷取服務開始運作之後,就可以部署將使用此服務的範例應用程式。應用程式可以部署至 VM 或任何其他服務,例如 Cloud Run、Kubernetes,甚至是本機筆記型電腦。我們將說明如何在 VM 上部署這項工具。
準備環境
我們會繼續透過相同的 SSH 工作階段在 VM 上執行作業。如要執行我們的應用程式,我們必須新增一些 Python 模組。系統會在相同 Python 虛擬環境中的應用程式目錄中執行這個指令。
在 VM SSH 工作階段中,執行下列指令:
cd ~/genai-databases-retrieval-app/llm_demo
pip install -r requirements.txt
預期的輸出內容 (已遮蓋):
student@instance-1:~$ cd ~/genai-databases-retrieval-app/llm_demo pip install -r requirements.txt Collecting fastapi==0.104.0 (from -r requirements.txt (line 1)) Obtaining dependency information for fastapi==0.104.0 from https://files.pythonhosted.org/packages/db/30/b8d323119c37e15b7fa639e65e0eb7d81eb675ba166ac83e695aad3bd321/fastapi-0.104.0-py3-none-any.whl.metadata Downloading fastapi-0.104.0-py3-none-any.whl.metadata (24 kB) ...
準備用戶端 ID
如要使用應用程式的預訂功能,請務必透過 Cloud 控制台備妥 OAuth 2.0 用戶端 ID。我們登入應用程式時,就會使用用戶端憑證在資料庫中記錄預訂資料。
在 Cloud 控制台中,前往「API 和服務」頁面,然後按一下「OAuth 同意畫面」然後選擇 [內部]內容。
接著按下「建立」然後進入下一個畫面
您必須填寫必填欄位,例如「應用程式名稱」以及「使用者支援電子郵件」並加入要顯示在同意畫面的網域,最後是「開發人員聯絡資訊」
接著按下「Save and Continue」(儲存並繼續)按鈕,即可前往下一頁。
除非您要指定範圍,否則您不必在這裡變更任何內容。最後,按下「儲存並繼續」按鈕確認這項操作可以選取「重新建立」,再次生成新的提示這樣就能設定應用程式同意畫面。
下一步是建立用戶端 ID。按一下左側面板上的「憑證」您會取得 OAuth2 的憑證
點選這裡的「建立憑證」並選擇「OAuth ClientID」然後開啟另一個畫面。
挑選「網頁應用程式」,然後將應用程式 URI (以及通訊埠 - 選用) 放入「已授權的 JavaScript 來源」。並需要將新增到「已授權的重新導向 URI」帶有「/login/google」連結的應用程式主機才能使用授權彈出式畫面。在上圖中,您會看到我已使用 http://localhost 做為我的基本應用程式 URI。
推送「Create」後按鈕後,畫面上會出現顯示用戶端憑證的彈出式視窗。
稍後我們需要使用用戶端 ID (以及選擇性的用戶端密碼),才能與應用程式搭配使用
執行 Google 助理應用程式
必須先設定一些環境變數,才能啟動應用程式。應用程式的基本功能 (例如查詢航班和機場設施) 只需要 BASE_URL,其會指向擷取服務。只要使用 gcloud 指令 即可。
在 VM SSH 工作階段中,執行下列指令:
export BASE_URL=$(gcloud run services list --filter="(retrieval-service)" --format="value(URL)")
預期的輸出內容 (已遮蓋):
student@instance-1:~/genai-databases-retrieval-app/llm_demo$ export BASE_URL=$(gcloud run services list --filter="(retrieval-service)" --format="value(URL)")
如要使用這個應用程式的進階功能 (例如預訂及變更航班),我們需要使用 Google 帳戶登入應用程式,以便提供 CLIENT_ID 環境變數。
export CLIENT_ID=215....apps.googleusercontent.com
預期的輸出內容 (已遮蓋):
student@instance-1:~/genai-databases-retrieval-app/llm_demo$ export CLIENT_ID=215....apps.googleusercontent.com
現在我們可以執行應用程式:
python run_app.py
預期輸出內容:
student@instance-1:~/genai-databases-retrieval-app/llm_demo$ python main.py INFO: Started server process [28565] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:8081 (Press CTRL+C to quit)
連結至應用程式
您可以透過多種方式連線至在 VM 上執行的應用程式。舉例來說,您可以使用虛擬私有雲中的防火牆規則,在 VM 上開啟通訊埠 8081,或是建立採用公開 IP 的負載平衡器。這裡我們要使用 SSH 通道到 VM,將本機通訊埠 8080 轉譯為 VM 通訊埠 8081。
從本機電腦連線
當我們要從本機電腦連線時,必須執行 SSH 通道。您可以使用 gcloud compute ssh 完成這項作業:
gcloud compute ssh instance-1 --zone=us-central1-a -- -L 8081:localhost:8081
預期輸出內容:
student-macbookpro:~ student$ gcloud compute ssh instance-1 --zone=us-central1-a -- -L 8080:localhost:8081 Warning: Permanently added 'compute.7064281075337367021' (ED25519) to the list of known hosts. Linux instance-1.us-central1-c.c.gleb-test-001.internal 6.1.0-21-cloud-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.90-1 (2024-05-03) 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:~$
現在,我們可以開啟瀏覽器並使用 http://localhost:8081 連線到應用程式。我們應該會看到應用程式畫面。
從 Cloud Shell 連線
或者,您也可以使用 Cloud Shell 進行連線。使用加號「+」開啟另一個 Cloud Shell 分頁。
在新 Cloud Shell 分頁中執行 gcloud 指令,系統就會將通道啟動到您的 VM:
gcloud compute ssh instance-1 --zone=us-central1-a -- -L 8080:localhost:8081
系統會顯示「無法指派要求的地址」錯誤訊息- 請忽略。
預期的輸出內容如下:
student@cloudshell:~ gcloud compute ssh instance-1 --zone=us-central1-a -- -L 8080:localhost:8081 bind [::1]:8081: Cannot assign requested address inux instance-1.us-central1-a.c.gleb-codelive-01.internal 6.1.0-21-cloud-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.90-1 (2024-05-03) 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. Last login: Sat May 25 19:15:46 2024 from 35.243.235.73 student@instance-1:~$
系統會在 Cloud Shell 開啟通訊埠 8080,以便用於「網頁預覽」。
按一下 [網頁預覽]按鈕,然後在下拉式選單中,選取「透過以下通訊埠預覽:8080」。
這會在網路瀏覽器中開啟新分頁,其中顯示應用程式介面。您應該會看到「Cymbal Air 客戶服務助理」頁面。我們在網頁的網址列中會顯示預覽網頁的 URI。我們需要將「/?authuser=0&redirectedPreviously=true」部分移除結尾
並使用 URI 的第一個部分,例如「https://8080-cs-35704030349-default.cs-us-east1-vpcf.cloudshell.dev/」位於瀏覽器視窗中,並做為「已授權的 JavaScript 來源」和「授權的重新導向 URI」產生第一個 Deployment 的憑證章節,取代或新增原本提供的 http://localhost:8080 值。上限值如下所示:「https://8080-cs-35704030349-default.cs-us-east1-vpcf.cloudshell.dev」較低者會是「https://8080-cs-35704030349-default.cs-us-east1-vpcf.cloudshell.dev/login/google」
登入應用程式
完成所有設定且應用程式開啟後,我們就能使用「登入」按鈕以提供憑證。只有在您想試用應用程式的預訂功能時,才需要執行這項操作。
系統隨即會開啟彈出式視窗,供您選取憑證。
應用程式已準備好登入,您即可開始將要求張貼到視窗底部的欄位中。
此示範內容展示 Cymbal Air 客戶服務助理。Cymbal Air 是虛構的航空公司,Google 助理是 AI 聊天機器人,可協助旅客管理航班,以及查詢舊金山國際機場 (SFO) Cymbal Air 中心的資訊。
如果未登入 (沒有 CLIENT_ID) 登入,還能為您解答使用者的問題,例如:
下一班飛往丹佛的航班是什麼時候?
C28 大門附近是否有任何奢華商店?
A6 號門附近要去哪裡買咖啡?
我可以在哪裡購買禮物?
請預訂在上午 10:35 出發前往丹佛的航班
登入應用程式後,你可以試用其他功能,例如預訂航班,或確認指派給你的座位是否為窗戶或走道座位。
這個應用程式使用最新的 Google 基礎模型來產生回應,並利用營運 Cloud SQL 資料庫中航班和設施的相關資訊,擴充模型。如要進一步瞭解這個應用程式示範,請前往專案的 GitHub 頁面。
9. 清除環境資源
完成所有工作後,我們就能清理環境。
刪除 Cloud Run 服務
請在 Cloud Shell 中執行下列指令:
gcloud run services delete retrieval-service --region us-central1
預期的主控台輸出內容:
student@cloudshell:~ (gleb-test-short-004)$ gcloud run services delete retrieval-service --region us-central1 Service [retrieval-service] will be deleted. Do you want to continue (Y/n)? Y Deleting [retrieval-service]...done. Deleted service [retrieval-service].
刪除 Cloud Run 服務的服務帳戶
請在 Cloud Shell 中執行下列指令:
PROJECT_ID=$(gcloud config get-value project)
gcloud iam service-accounts delete retrieval-identity@$PROJECT_ID.iam.gserviceaccount.com --quiet
預期的主控台輸出內容:
student@cloudshell:~ (gleb-test-short-004)$ PROJECT_ID=$(gcloud config get-value project) Your active configuration is: [cloudshell-222] student@cloudshell:~ (gleb-test-short-004)$ gcloud iam service-accounts delete retrieval-identity@$PROJECT_ID.iam.gserviceaccount.com --quiet deleted service account [retrieval-identity@gleb-test-short-004.iam.gserviceaccount.com] student@cloudshell:~ (gleb-test-short-004)$
刪除 Cloud SQL 執行個體
完成研究室後,請刪除 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].
現在可以刪除 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
刪除 GCE VM 和擷取服務的服務帳戶
請在 Cloud Shell 中執行下列指令:
PROJECT_ID=$(gcloud config get-value project)
gcloud iam service-accounts delete compute-aip@$PROJECT_ID.iam.gserviceaccount.com --quiet
預期的主控台輸出內容:
student@cloudshell:~ (gleb-test-short-004)$ PROJECT_ID=$(gcloud config get-value project) gcloud iam service-accounts delete compute-aip@$PROJECT_ID.iam.gserviceaccount.com --quiet Your active configuration is: [cloudshell-222] deleted service account [compute-aip@gleb-test-short-004.iam.gserviceaccount.com] student@cloudshell:~ (gleb-test-short-004)$
10. 恭喜
恭喜您完成本程式碼研究室。
涵蓋內容
- 如何建立 Cloud SQL 執行個體
- 如何連線至 Cloud SQL 執行個體
- 如何設定及部署生成式 AI 資料庫擷取服務
- 如何使用已部署的服務部署範例應用程式