1. 簡介
在本程式碼研究室中,您將瞭解如何部署生成式 AI 資料庫擷取服務,以及使用部署環境開發範例互動式應用程式。

如要進一步瞭解生成式 AI 檢索服務和範例應用程式,請參閱這篇文章。
必要條件
- Google Cloud 控制台的基本知識
- 指令列介面和 Google Cloud Shell 的基本技能
課程內容
- 如何建立 Cloud SQL 執行個體
- 如何連線至執行個體
- 如何設定及部署生成式 AI 資料庫檢索服務
- 如何使用已部署的服務部署範例應用程式
軟硬體需求
- Google Cloud 帳戶和 Google Cloud 專案
- 網路瀏覽器,例如 Chrome
2. 設定和需求
自修實驗室環境設定
- 登入 Google Cloud 控制台,然後建立新專案或重複使用現有專案。如果沒有 Gmail 或 Google Workspace 帳戶,請先建立帳戶。



- 專案名稱是這個專案參與者的顯示名稱。這是 Google API 未使用的字元字串。你隨時可以更新。
- 專案 ID 在所有 Google Cloud 專案中都是不重複的,而且設定後即無法變更。Cloud 控制台會自動產生專屬字串,通常您不需要在意該字串為何。在大多數程式碼研究室中,您需要參照專案 ID (通常標示為
PROJECT_ID)。如果您不喜歡產生的 ID,可以產生另一個隨機 ID。你也可以嘗試使用自己的名稱,看看是否可用。完成這個步驟後就無法變更,且專案期間會維持不變。 - 請注意,有些 API 會使用第三個值,也就是「專案編號」。如要進一步瞭解這三種值,請參閱說明文件。
- 接著,您需要在 Cloud 控制台中啟用帳單,才能使用 Cloud 資源/API。完成這個程式碼研究室的費用不高,甚至可能完全免費。如要關閉資源,避免在本教學課程結束後繼續產生費用,請刪除您建立的資源或專案。Google Cloud 新使用者可參加價值$300 美元的免費試用計畫。
啟動 Cloud Shell
雖然可以透過筆電遠端操作 Google Cloud,但在本程式碼研究室中,您將使用 Google Cloud Shell,這是可在雲端執行的指令列環境。
在 Google Cloud 控制台中,點選右上工具列的 Cloud Shell 圖示:

佈建並連線至環境的作業需要一些時間才能完成。完成後,您應該會看到如下的內容:

這部虛擬機器搭載各種您需要的開發工具,並提供永久的 5GB 主目錄,而且可在 Google Cloud 運作,大幅提升網路效能並強化驗證功能。您可以在瀏覽器中完成本程式碼研究室的所有作業。您不需要安裝任何軟體。
3. 事前準備
啟用 API
在 Cloud Shell 中,確認專案 ID 已設定完畢:
通常專案 ID 會顯示在 Cloud Shell 的命令提示字元中,並以半形括號括住,如圖片所示:

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,因此我們必須授予 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 連線至主要執行個體。
繼續使用已開啟的 VM SSH 工作階段。如果連線中斷,請使用與上述相同的指令重新連線。
使用先前記下的 $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 連線至主要執行個體。
繼續使用已開啟的 VM SSH 工作階段。如果連線中斷,請使用上述相同指令重新連線。
使用先前記錄的 $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 Console 中查看,並在 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 Console 準備 OAuth 2.0 用戶端 ID。我們登入應用程式時就會發生這種情況,因為預訂功能會使用用戶端憑證,在資料庫中記錄預訂資料。
在 Cloud 控制台中,前往「API 和服務」,然後按一下「OAuth 同意畫面」,並選擇「內部」使用者。

然後按下「建立」,並按照下一個畫面中的指示操作。

您必須填寫「應用程式名稱」和「使用者支援電子郵件地址」等必填欄位。您也可以新增要在同意畫面中顯示的網域,最後是「開發人員聯絡資訊」

然後按下頁面底部的「儲存並繼續」按鈕,系統就會將你帶往下一頁。

除非您想指定範圍,否則不需要變更任何內容。最後,再次按下「儲存並繼續」按鈕,確認變更。這樣就會設定應用程式同意畫面。
下一步是建立用戶端 ID。按一下左側面板的「憑證」,即可前往 OAuth 2.0 的憑證頁面。

按一下頂端的「建立憑證」,然後選擇「OAuth 用戶端 ID」。然後開啟另一個畫面。

從應用程式類型的下拉式清單中選取「Web application」,然後將應用程式 URI (和連接埠 - 視需要) 設為「Authorized JavaScript origins」。此外,您還需要在「已授權的重新導向 URI」中新增應用程式主機,並在結尾加上「/login/google」,才能使用授權彈出式視窗畫面。如上圖所示,我已使用 http://localhost 做為基本應用程式 URI。
按下「建立」按鈕後,系統會顯示彈出式視窗,內含用戶端憑證。

稍後我們需要用戶端 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 帳戶登入應用程式,因此需要使用「準備用戶端 ID」一章中的 OAuth 用戶端 ID,提供 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
系統會顯示「Cannot assign requested address」錯誤訊息,請忽略。
預期的輸出內容如下:
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,可用於「網頁預覽」。
按一下 Cloud Shell 右上方的「網頁預覽」按鈕,然後從下拉式選單中選擇「透過以下通訊埠預覽:8080」。

網路瀏覽器會開啟新分頁,顯示應用程式介面。您應該會看到「Cymbal Air Customer Service Assistant」頁面。在頁面的網址列中,我們會看到預覽頁面的 URI。請移除網址結尾的「/?authuser=0&redirectedPreviously=true」部分

並使用 URI 的第一部分 (例如「https://8080-cs-35704030349-default.cs-us-east1-vpcf.cloudshell.dev/」),保留在瀏覽器視窗中,並做為「準備用戶端 ID」一章中建立憑證的「已授權的 JavaScript 來源」和「已授權的重新導向 URI」,取代或新增至原先提供的 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 是虛構的客運航空公司,這款 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 資料庫檢索服務
- 如何使用已部署的服務部署範例應用程式