AlloyDB AI と LangChain を使用して LLM と RAG ベースのチャット アプリケーションをビルドする

1. はじめに

e71e051395674233.gif

この Codelab では、GenAI Databases Retrieval Service をデプロイし、デプロイされた環境を使用してインタラクティブなサンプル アプリケーションを作成する方法を学びます。

98c2676cc78880e.png

GenAI Retrieval Service とサンプル アプリケーションについて詳しくは、こちらをご覧ください。

前提条件

  • Google Cloud コンソールの基本的な知識
  • コマンドライン インターフェースと Google Cloud Shell の基本的なスキル

学習内容

  • AlloyDB クラスタをデプロイする方法
  • AlloyDB に接続する方法
  • GenAI Databases Retrieval Service の構成とデプロイ方法
  • デプロイされたサービスを使用してサンプル アプリケーションをデプロイする方法

必要なもの

  • Google Cloud アカウントと Google Cloud プロジェクト
  • ウェブブラウザ(Chrome など)

2. 設定と要件

セルフペース型の環境設定

  1. Google Cloud Console にログインして、プロジェクトを新規作成するか、既存のプロジェクトを再利用します。Gmail アカウントも Google Workspace アカウントもまだお持ちでない場合は、アカウントを作成してください。

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • プロジェクト名は、このプロジェクトの参加者に表示される名称です。Google API では使用されない文字列です。いつでも更新できます。
  • プロジェクト ID は、すべての Google Cloud プロジェクトにおいて一意でなければならず、不変です(設定後は変更できません)。Cloud コンソールでは一意の文字列が自動生成されます。通常は、この内容を意識する必要はありません。ほとんどの Codelab では、プロジェクト ID(通常は PROJECT_ID と識別されます)を参照する必要があります。生成された ID が好みではない場合は、ランダムに別の ID を生成できます。または、ご自身で試して、利用可能かどうかを確認することもできます。このステップ以降は変更できず、プロジェクトを通して同じ ID になります。
  • なお、3 つ目の値として、一部の API が使用するプロジェクト番号があります。これら 3 つの値について詳しくは、こちらのドキュメントをご覧ください。
  1. 次に、Cloud のリソースや API を使用するために、Cloud コンソールで課金を有効にする必要があります。この Codelab の操作をすべて行って、費用が生じたとしても、少額です。このチュートリアルの終了後に請求が発生しないようにリソースをシャットダウンするには、作成したリソースを削除するか、プロジェクトを削除します。Google Cloud の新規ユーザーは、300 米ドル分の無料トライアル プログラムをご利用いただけます。

Cloud Shell を起動する

Google Cloud はノートパソコンからリモートで操作できますが、この Codelab では、Google Cloud Shell(Cloud 上で動作するコマンドライン環境)を使用します。

Google Cloud Console で、右上のツールバーにある Cloud Shell アイコンをクリックします。

55efc1aaa7a4d3ad.png

プロビジョニングと環境への接続にはそれほど時間はかかりません。完了すると、次のように表示されます。

7ffe5cbb04455448.png

この仮想マシンには、必要な開発ツールがすべて用意されています。永続的なホーム ディレクトリが 5 GB 用意されており、Google Cloud で稼働します。そのため、ネットワークのパフォーマンスと認証機能が大幅に向上しています。この Codelab での作業はすべて、ブラウザ内から実行できます。インストールは不要です。

3. はじめに

API を有効にする

出力:

Cloud Shell で、プロジェクト ID が設定されていることを確認します。

通常、プロジェクト ID は、次の図に示すように、Cloud Shell のコマンド プロンプトのかっこ内に表示されます。

fa6ee779963405d5.png

gcloud config set project [YOUR-PROJECT-ID]

次に、PROJECT_ID 環境変数を Google Cloud プロジェクト ID に設定します。

PROJECT_ID=$(gcloud config get-value project)

必要なサービスをすべて有効にします。

gcloud services enable alloydb.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 alloydb.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. AlloyDB クラスタをデプロイする

AlloyDB クラスタとプライマリ インスタンスを作成します。次の手順では、Google Cloud SDK を使用して AlloyDB クラスタとインスタンスを作成する方法について説明します。コンソールを使用する場合は、こちらのドキュメントをご覧ください。

AlloyDB クラスタを作成する前に、VPC で使用可能なプライベート IP 範囲を割り振り、将来の AlloyDB インスタンスで使用できるようにする必要があります。ない場合は、作成して Google 内部サービスで使用するように割り当てる必要があります。その後、クラスタとインスタンスを作成できます。

プライベート IP 範囲を作成する

AlloyDB の VPC でプライベート サービス アクセスを構成する必要があります。ここでは、プロジェクトに「デフォルト」の VPC ネットワークがあり、すべてのアクションで使用されることを前提としています。

プライベート 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

このパスワードは、postgres ユーザーとしてインスタンスに接続する際に必要になります。後で使用できるように、メモに書き留めるか、どこかにコピーしておくことをおすすめします。

想定されるコンソール出力:

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

無料トライアル クラスタを作成する

AlloyDB を初めて使用する場合は、無料のトライアル クラスタを作成できます。

リージョンと 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 \
    --subscription-type=TRIAL

想定されるコンソール出力:

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

同じ Cloud Shell セッションで、クラスタの AlloyDB プライマリ インスタンスを作成します。切断した場合は、リージョンとクラスタ名の環境変数を再度定義する必要があります。

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

想定されるコンソール出力:

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

AlloyDB Standard クラスタを作成する

プロジェクトで初めての AlloyDB クラスタでない場合は、標準クラスタの作成に進みます。

リージョンと 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.                                                                                                                                                                                                                                                           

同じ 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. GCE 仮想マシンを準備する

サービス アカウントを作成する

VM を使用して GenAI Databases Retrieval サービスをデプロイし、サンプル アプリケーションをホストするため、最初のステップとして Google サービス アカウント(GSA)を作成します。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/alloydb.viewer"
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:compute-aip@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/serviceusage.serviceUsageConsumer"

GCE VM をデプロイする

AlloyDB クラスタと同じリージョンと VPC に 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

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 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) ...

インスタンスに接続する

psql を使用して VM からプライマリ インスタンスに接続します。

VM への SSH セッションは開いたままにします。接続が切断された場合は、上記と同じコマンドを使用して再度接続します。

先ほどメモした $PGASSWORD とクラスタ名を使用して、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=P9...
student@instance-1:~$ export REGION=us-central1
student@instance-1:~$ export ADBCLUSTER=alloydb-aip-01
student@instance-1:~$ export INSTANCE_IP=export INSTANCE_IP=$(gcloud alloydb instances describe $ADBCLUSTER-pr --cluster=$ADBCLUSTER --region=$REGION --format="value(ipAddress)")
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=> 

SSH 接続を維持したまま psql セッションを終了します。

exit

想定されるコンソール出力:

postgres=> exit
student@instance-1:~$ 

6. データベースを初期化する

クライアント VM をプラットフォームとして使用し、データベースにデータを入力してアプリケーションをホストします。最初のステップは、データベースを作成してデータを入力することです。

データベースを作成する

「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:~$ 

データベースにデータを入力する

Retrieval サービスとサンプル アプリケーションのコードを含む 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.

構成ファイルを準備します。

GCE VM で次のコマンドを実行します。

cd genai-databases-retrieval-app/retrieval_service
cp example-config.yml config.yml
sed -i s/127.0.0.1/$INSTANCE_IP/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.yml config.yml
sed -i s/127.0.0.1/$INSTANCE_IP/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
host: 0.0.0.0
# port: 8080
datastore:
  # Example for AlloyDB
  kind: "postgres"
  host: 10.65.0.2
  # port: 5432
  database: "assistantdemo"
  user: "postgres"
  password: "P9..."

サンプル データセットをデータベースに入力します。最初のコマンドは、必要なすべてのパッケージを Python 仮想環境に追加し、2 番目のコマンドはデータベースにデータを取り込みます。

GCE VM で次のコマンドを実行します。

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 タブを開きます。

4ca978f5142bb6ce.png

新しい 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"

想定されるコンソール出力:

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 を準備する必要があります。これがないと、Google 認証情報でアプリにログインして予約を完了できません。予約データをデータベースに記録するために必要です。

Cloud コンソールで [API とサービス] に移動し、[OAuth 同意画面] をクリックします。Oauth の概要ページが開くので、[使ってみる] をクリックします。

2f13a26289362f20.png

次のページで、アプリケーション名とユーザー サポート用メールアドレスを入力し、[次へ] をクリックします。

dd3721c042db26ae.png

次の画面で、アプリケーションの [内部] を選択し、もう一度 [次へ] をクリックします。

71b6d11179ed872b.png

再度連絡先メールアドレスを入力し、[次へ] をクリックします。

8ff29dfd959b41f0.png

次に、Google API サービスのポリシーに同意して [作成] ボタンをクリックします。

f615dc15193717a6.png

OAuth クライアントを作成できるページが表示されます。

56e5040805632a53.png

画面でプルダウン メニューから [ウェブ アプリケーション] を選択し、アプリケーションとして [Cymbal Air] を指定して、[URI を追加] ボタンをクリックします。

4e28c6700426735a.png

URI は、アプリケーションの信頼できるソースを表します。URI は、アプリケーションにアクセスしようとしている場所によって異なります。承認済み URI として「https://localhost:8081」、リダイレクト URI として「https://localhost:8081/login/google」を指定します。これらの値は、ブラウザに接続 URI として「https://localhost:8081」を入力すると機能します。たとえば、コンピュータから SSH トンネル経由で接続する場合などです。後ほど、その方法を説明します。

9dc25f2d318097e2.png

[作成] ボタンをクリックすると、クライアントの認証情報が記載されたポップアップ ウィンドウが表示されます。認証情報がシステムに記録されます。アプリケーションの起動時に使用するクライアント ID はいつでもコピーできます。

f5a7b6ad0858d95c.png

後で、そのクライアント ID を指定する場所について説明します。

アシスタント アプリケーションを実行する

アプリケーションを起動する前に、いくつかの環境変数を設定する必要があります。フライトや空港の設備の検索といったアプリケーションの基本的な機能を使用するには、アプリケーションを検索サービスに指す 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 で実行されているアプリケーションに接続するには、いくつかの方法があります。たとえば、VPC のファイアウォール ルールを使用して VM でポート 8081 を開いたり、パブリック IP を使用してロードバランサを作成したりできます。ここでは、ローカルポート 8080 を VM ポート 8081 に変換する VM への SSH トンネルを使用します。

ローカルマシンからの接続

ローカルマシンから接続する場合は、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 を使用してアプリケーションに接続できます。アプリケーション画面が表示されます。

c667b9013afac3f9.png

Cloud Shell からの接続

また、Google Cloud Shell を使用して接続することもできます。上部の「+」記号を選択して、別の Cloud Shell タブを開きます。

4ca978f5142bb6ce.png

新しいタブで、gcloud コマンドを実行してウェブ クライアントのオリジンとリダイレクト URI を取得します。

echo "origin:"; echo "https://8080-$WEB_HOST"; echo "redirect:"; echo "https://8080-$WEB_HOST/login/google"

想定される出力は次のとおりです。

student@cloudshell:~ echo "origin:"; echo "https://8080-$WEB_HOST"; echo "redirect:"; echo "https://8080-$WEB_HOST/login/google"
origin:
https://8080-cs-35704030349-default.cs-us-east1-rtep.cloudshell.dev
redirect:
https://8080-cs-35704030349-default.cs-us-east1-rtep.cloudshell.dev/login/google

また、URI のオリジンとリダイレクトを「承認済みの JavaScript 生成元」と「承認済みリダイレクト URI」として、「クライアント ID を準備する」で作成した認証情報に使用します。元の http://localhost:8080 の値を置き換えるか、追加します。

[OAuth 2.0 クライアント ID] ページで [Cymbal Air] をクリックします。

b4c1430329886d9c.png

Cloud Shell のオリジンとリダイレクト URI を指定して、[保存] ボタンをクリックします。

5651bdd6d0d1c88.png

新しい 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 でプレビュー] を選択します。

444fbf54dcd4d160.png

ウェブブラウザで新しいタブが開き、アプリケーションのインターフェースが表示されます。[Cymbal Air Customer Service Assistant] ページが表示されます。

389f0ae2945beed5.png

アプリケーションにログインする

すべての設定が完了し、アプリケーションが開いたら、アプリケーション画面の右上にある [ログイン] ボタンを使用して認証情報を入力します。これは省略可能です。アプリの予約機能を試す場合にのみ必要です。

a1f571371b957129.png

認証情報を選択できるポップアップ ウィンドウが開きます。

ログインすると、アプリケーションの準備が整い、ウィンドウの下部にあるフィールドにリクエストを投稿できるようになります。

このデモでは、Cymbal Air のカスタマー サービス アシスタントを紹介します。Cymbal Air は架空の航空会社です。このアシスタントは、旅行者がフライトを管理したり、サンフランシスコ国際空港(SFO)にある Cymbal Air のハブに関する情報を検索したりできるようにする AI の chatbot です。

ログインせずに(CLIENT_ID なしで)次のようなユーザーの質問に答えることができます。

デンバー行きの次のフライトはいつですか?

C28 ゲートの周辺に高級ショップはありますか?

A6 ゲート付近でコーヒーを飲める場所はどこですか?

ギフトはどこで購入できますか?

午前 10 時 35 分発のデンバー行きフライトを予約してください

アプリにログインすると、フライトの予約や、割り当てられた座席が窓側か通路側かを確認するなどの他の機能を試すことができます。

6e7758f707c67c3e.png

このアプリケーションは、最新の Google 基盤モデルを使用して、レスポンスを生成し、運用中の AlloyDB データベースのフライトと設備に関する情報で拡張しています。このデモ アプリケーションについて詳しくは、プロジェクトの 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)$

ラボの終了時に AlloyDB インスタンスとクラスタを破棄します。

AlloyDB クラスタとすべてのインスタンスを削除する

クラスタは force オプションで破棄され、クラスタに属するすべてのインスタンスも削除されます。

接続が切断され、以前の設定がすべて失われた場合は、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 

GCE VM と Retrieval サービスのサービス アカウントを削除します。

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. 完了

以上で、この Codelab は完了です。

学習した内容

  • AlloyDB クラスタをデプロイする方法
  • AlloyDB に接続する方法
  • GenAI Databases Retrieval Service の構成とデプロイ方法
  • デプロイされたサービスを使用してサンプル アプリケーションをデプロイする方法

11. アンケート

出力:

このチュートリアルをどのように使用されますか?

全体を通して読むだけ 内容を読んで演習をやり遂げる