1. 概要
このラボでは、Google の生成 AI プロダクトを使用して、Gemini Cloud Assist を活用して Google Cloud にインフラストラクチャを構築し、Data Canvas の自然言語から SQL への機能を使用して BigQuery データをクエリします。また、Gemini Code Assist を使用して Colab Enterprise Jupyter ノートブックと Eclipse Theia(Visual Studio Code)でコードを記述し、Cloud Storage と BigQuery のグラウンドソース上に構築された AI 検索機能とチャット機能を Vertex AI Agent Builder に統合します。
私たちの目標は、AI Recipe Haven というレシピと料理のウェブサイトを作成することです。このサイトは Python と Streamlit で構築され、2 つの主要なページが含まれます。Cooking Advice は、Gemini と Vertex AI Agent Builder のグラウンディング ソースを使用して作成する chatbot をホストします。この chatbot は、一連の料理本に関連付けられ、料理に関するアドバイスを提供し、料理関連の質問に回答します。Recipe Search は、Gemini からデータを取得する検索エンジンです。今回は、BigQuery のレシピ データベースを基盤としています。
この演習のコードで行き詰まった場合は、すべてのコードファイルのソリューションが、演習の GitHub リポジトリの solution ブランチにあります。
目標
このラボでは、次のタスクの実行方法について学びます。
- Gemini Cloud Assist を有効にして使用する
- Vertex AI Agent Builder で料理のアドバイス chatbot の検索アプリを作成する
- Gemini Code Assist を使用して Colab Enterprise ノートブックでデータを読み込み、クリーンアップする
- Vertex AI Agent Builder でレシピ生成ツールの検索アプリを作成する
- Gemini を活用して、コアとなる Python と Streamlit のウェブ アプリケーションのフレームワークを作成します。
- ウェブ アプリケーションを Cloud Run にデプロイする
- 料理のアドバイス ページを、レシピ検索の Agent Builder アプリに接続する
- (省略可)レシピ検索ページをレシピ検索の Agent Builder アプリに接続する
- (省略可)最終的なアプリケーションを確認する
2. 設定と要件
[ラボを開始] ボタンをクリックする前に
こちらの手順をお読みください。ラボの時間は記録されており、一時停止することはできません。[ラボを開始] をクリックするとスタートするタイマーは、Google Cloud のリソースを利用できる時間を示しています。
この Qwiklabs ハンズオンラボでは、シミュレーションやデモ環境ではなく、実際のクラウド環境を使ってご自身でラボのアクティビティを行うことができます。そのため、ラボの受講中に Google Cloud にログインおよびアクセスするための、新しい一時的な認証情報が提供されます。
必要なもの
このラボを完了するためには、下記が必要です。
- 標準的なインターネット ブラウザ(Chrome を推奨)
- ラボを完了するために十分な時間
注: すでに個人の Google Cloud アカウントやプロジェクトをお持ちの場合でも、ラボでは使用しないでください。
注: Pixelbook を使用している場合は、このラボをシークレット ウィンドウで実施してください。
ラボを開始して Google Cloud コンソールにログインする方法
- [ラボを開始] ボタンをクリックします。ラボの料金をお支払いいただく必要がある場合は、表示されるポップアップでお支払い方法を選択してください。左側のパネルには、このラボで使用する必要がある一時的な認証情報が表示されます。
- ユーザー名をコピーし、[Google Console を開く] をクリックします。ラボでリソースが起動し、別のタブでログインページが表示されます。
ヒント: タブをそれぞれ別のウィンドウで開き、並べて表示しておきましょう。
[アカウントの選択] ページが表示されたら、[別のアカウントを使用] をクリックします。
- [ログイン] ページで、[接続の詳細] パネルでコピーしたユーザー名を貼り付けます。パスワードもコピーして貼り付けます。
重要: 認証情報は [Connection Details] パネルに表示されたものを使用してください。(ご自身の Qwiklabs 認証情報は使用しないでください)。請求が発生する事態を避けるため、Google Cloud アカウントをお持ちの場合でも、このラボでは使用しないでください。4. その後次のように進みます。
- 利用規約に同意してください。
- 一時的なアカウントなので、復元オプションや 2 要素認証プロセスは設定しないでください。
- 無料トライアルには登録しないでください。
その後このタブで Cloud Console が開きます。
注: 左上のナビゲーション メニューをクリックすると、Google Cloud のプロダクトやサービスのリストが含まれるメニューが表示されます。
3. タスク 0. ワークステーション クラスタを確認する
このラボの後半では、Google Cloud Workstation を使用して開発作業を行います。このラボの起動プロセスで、Workstation のクラスタの作成が開始されているはずです。次に進む前に、クラスタがビルドされていることを確認しましょう。
- Google Cloud コンソールで、検索ボックスを使用して [Cloud Workstations] に移動します。
- 左側のナビゲーション メニューを使用して [クラスタ管理] を表示します。
- クラスタが更新中の場合は、タスク 1 に進むことができます。どの状態のクラスタも表示されない場合は、ページを更新します。それでもクラスタの更新(ビルド)が表示されない場合は、手順の左上にあるボタンを使用してこのラボを終了し、ラボを再起動します。
4. タスク 1. Gemini Cloud Assist を有効にして使用する
このタスクでは、Gemini Cloud Assist を有効にして使用します。Google Cloud コンソールで作業しているときに、Gemini Cloud Assist はアドバイスを提供し、Google Cloud インフラストラクチャの構築、構成、モニタリングをサポートします。また、gcloud
コマンドの候補を提示したり、Terraform スクリプトを作成したりすることもできます。
- Cloud Assist を有効にして使用するには、Cloud コンソール UI の上部にある検索ボックスをクリックし、[Gemini に質問](または [Cloud コンソールの Gemini に質問])を選択します。
- ページの [必要な API] セクションまでスクロールし、Gemini for Google Cloud API を有効にする。
- チャット インターフェースがすぐに表示されない場合は、[チャットを開始] をクリックします。まず、Gemini に Cloud Workstations のメリットを説明してもらいます。生成されたレスポンスを確認します。
- 次に、Agent Builder のメリットと、生成された回答を基盤とするうえでのメリットについて尋ねます。
- 最後に、比較を見てみましょう。Google Cloud コンソールの Gemini チャット ウィンドウで、次の質問をします。
What are the major steps to creating a search app grounded in a
GCS data source using Vertex AI Agent builder?
- 次に、シークレット ウィンドウ以外のウィンドウで、Gemini の公開ウェブサイト(こちら)にアクセスし、必要に応じてログインして、同じ質問をします。レスポンスは同じか、少なくとも類似していますか?具体的な手順は次のとおりです。どちらが明らかに優れているか?いずれにしても、次のステップに進む際には、この回答を念頭に置いてください。
注: 一時的な Qwiklabs アカウントを使用して上記の手順を試みると、ブロックされます。組織で Gemini ウェブアプリの使用が許可されていないため、仕事用アカウントもブロックされている場合は、この手順をスキップして次のステップに進みます。この演習の完了には影響しません。
5. タスク 2. Vertex AI Agent Builder で、料理のアドバイス チャットボット用の検索アプリを作成する
作成するウェブサイトには、料理に関する質問の答えを見つけられるように設計された chatbot を含む料理のアドバイス ページがあります。70 個のパブリック ドメイン クックブックを含むソースに基づく Gemini を搭載します。クックブックは、Gemini が質問に回答する際に使用する信頼できる情報源として機能します。
- Cloud コンソールの検索ボックスを使用して、[Vertex AI] に移動します。ダッシュボードで、[すべての推奨 API を有効化] をクリックします。Vertex AI API 自体を有効にする必要があることに関するポップアップ ボックスが表示された場合は、その API も有効にしてください。
- 検索を使用して [Agent Builder] に移動し、[続行して API を有効にする] をクリックします。
- 前回のアドバイスで Gemini が提案したように、Agent Builder で検索アプリを作成する際は、信頼できるデータソースの作成から始めます。ユーザーが検索すると、Gemini は質問を理解し、インテリジェントな回答を作成する方法を理解しますが、その回答で使用する情報は、固有の知識から取得するのではなく、グラウンディングされたソースから取得します。
左側のメニューで [データストア] に移動し、[データストアを作成] をクリックします。4. 料理のアドバイス ページの基盤として使用しているパブリック ドメインの料理本は、現在、外部プロジェクトの Cloud Storage バケットにあります。Cloud Storage のソースタイプを選択します。5. インポートする情報の種類に関連するデフォルト オプションを確認しますが、変更しないでください。インポート タイプはフォルダのままにして、バケットパスに labs.roitraining.com/labs/old-cookbooks
を使用し、[続行] をクリックします。6. データストアに名前を付けます。old-cookbooks
。編集して ID を old-cookbooks-id
に変更し、データストアを作成します。
Vertex AI Agent Builder は複数のアプリタイプをサポートしており、Data Store は各アプリの信頼できる情報源として機能します。検索アプリは、一般的な用途や検索に適しています。Chat アプリは、Dataflow をベースとする chatbot/voicebot アプリケーションの生成フローに使用します。レコメンデーション アプリは、より優れたレコメンデーション エンジンの作成に役立ちます。エージェント アプリは、生成 AI を活用したエージェントを作成するためのものです。最終的には、エージェントが目的に最も適したアプリタイプになると思われますが、現在はプレビュー版であるため、検索アプリタイプのままにします。7. 左側のメニューで [アプリ] に移動し、[アプリを作成] をクリックします。検索アプリの種類を選択します。さまざまなオプションを確認しますが、変更しないでください。アプリに名前を付けます: cookbook-search
。編集して、アプリ ID を cookbook-search-id
に設定します。会社を Google
に設定し、[続行] をクリックします。9. 前の手順で作成した old-cookbooks
データストアを確認し、検索アプリを作成します。
[アクティビティ] タブを調べると、引き続きクックブックのインポートとインデックス処理が行われていることがわかります。エージェント ビルダーが指定した 70 個の Cookbook に含まれる数千のページをインデックスに登録するには、5 分以上かかります。処理が完了するまで、レシピ生成ツール用のレシピ データベースのデータを読み込んでクリーンアップしましょう。
6. タスク 3. Gemini Code Assist を使用して Colab Enterprise ノートブックでデータを読み込み、クリーンアップする
Google Cloud には、Jupiter ノートブックを操作するための主な方法がいくつかあります。Google の最新サービスである Colab Enterprise を使用します。Google の Colab プロダクトをご存じの方も多いと思います。これは、無料の環境で Jupiter Notebook を試したい個人や組織でよく使用されています。Colab Enterprise は、Google の他のクラウド プロダクトと完全に統合され、GCP 環境のセキュリティとコンプライアンス機能を最大限に活用する Google Cloud の商用サービスです。
Colab Enterprise が提供する機能の 1 つは、Google の Gemini Code Assist との統合です。Code Assist はさまざまなコードエディタで使用でき、コーディング中にアドバイスやシームレスなインライン候補を提案します。レシピデータを処理する際に、この生成アシスタントを利用します。
- 検索を使用して [Colab Enterprise] に移動し、[ノートブックを作成] をクリックします。Colab の新しい機能を試すよう求められた場合は、閉じます。ノートブックのランタイム(ノートブックのコンピューティング能力)を起動するには、新しいノートブックの右上にある [接続] を押します。
- Colab Enterprise の [ファイル] ペインで、現在のノートブック名の横にあるその他メニューを使用して、名前を
Data Wrangling
に変更します。
- 新しい [+ テキスト] ボックスを作成し、上矢印を使用してページの最初のセルになるように移動します。
- テキスト ボックスを編集して、次のように入力します。
# Data Wrangling
Import the Pandas library
- 作成したテキスト ブロックの下のコードブロックで「imp」と入力すると、Gemini Code Assist によってインポートの残りの部分がグレーで提案されます。Tab キーを押して提案を承認します。
import pandas as pd
- インポート コード ボックスの下に別のテキスト ボックスを作成し、次のように入力します。
Create a Pandas DataFrame from: gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv. View the first few records.
- 別のコードブロックを作成して編集します。もう一度 df と入力して、Gemini Code Assist によって生成されたコードを確認します。生成された候補の上に Python キーワードのオートコンプリート プルダウン リストが表示された場合は、Esc キーを押して、ライトグレーの候補コードを表示します。もう一度 Tab キーを押して提案を承認します。候補に head() 関数呼び出しが含まれていない場合は、追加します。
df = pd.read_csv('gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv')
df.head()
- Pandas をインポートした最初のコードセルをクリックし、[Commands] メニューまたはキーボードを使用して、選択したセルを実行します。キーボードの Shift+Enter キーを押すと、セルが実行され、フォーカスが次のセルに移動します。必要に応じて、新しいセルが作成されます。セルが実行されるまで待ってから、次に進みます。
注: セルが実行されていない場合は、左側に [ ] が表示されます。セルの実行中は、回転する作業アニメーションが表示されます。セルが終了すると、[13] などの数値が表示されます。9. CSV を DataFrame に読み込むセルを実行します。ファイルが読み込まれるのを待ってから、最初の 5 行のデータを調べます。これは、BigQuery に読み込むレシピデータであり、最終的にはレシピ生成ツールの基盤として使用します。10. 新しいコードブロックを作成し、以下のコメントを入力します。コメントを入力したら、次のコード行に移動すると、候補として df.columns
が表示されます。承認してセルを実行します。
# List the current DataFrame column names
ここまでに説明したように、Jupyter ノートブックで Gemini Code Assist からヘルプを得る方法は、コードセルの上のテキストセルとコードセル内のコメントの 2 つです。コードセル内のコメントは Jupyter ノートブックで適切に機能しますが、このアプローチは Google の Gemini Code Assist をサポートする他の IDE でも機能します。
- 列を少しクリーンアップしましょう。列
Unnamed: 0
の名前をid
に、link
の名前をuri
に変更します。プロンプト > コードのいずれかの方法でコードを作成し、満足したらセルを実行します。
# Rename the column 'Unnamed: 0' to 'id' and 'link' to 'uri'
df.rename(columns={'Unnamed: 0': 'id', 'link': 'uri'}, inplace=True)
source
列とNER
列を削除し、head()
を使用して最初の数行を表示します。Gemini にサポートを依頼します。最後の 2 行を実行して結果を確認します。
# Remove the source and NER columns
df.drop(columns=['source', 'NER'], inplace=True)
df.head()
- データセットに含まれるレコードの数を確認しましょう。プロンプト テクニックを選択して、Gemini でコードを生成できるかどうかを確認します。
# Count the records in the DataFrame
df.shape # count() will also work
- 223 万件のレコードは、おそらく Google が処理できるレシピの数を上回っています。エージェント ビルダーのインデックス処理は、今回の演習では時間がかかりすぎる可能性があります。妥協案として、15 万件のレシピをサンプリングして、そのデータセットで作業します。プロンプト > コードのアプローチを使用してサンプルを取得し、
dfs
(小)という名前の新しい DataFrame に保存します。
# Sample out 150,000 records into a DataFrame named dfs
dfs = df.sample(n=150000)
- レシピ ソースデータは BigQuery に読み込む準備ができました。読み込みを行う前に、BigQuery に移動してテーブルを保持するデータセットを準備します。Google Cloud コンソールの検索ボックスを使用して [BigQuery] に移動します。BigQuery を右クリックして、新しいブラウザタブで開きます。
- Gemini AI Chat パネルがまだ表示されていない場合は、Cloud コンソールの右上にある Gemini ロゴを使用して開きます。API を再度有効にするよう求められたら、有効にするボタンを押すか、ページを更新します。プロンプトを実行します。
What is a dataset used for in BigQuery?
回答を確認したら、次のように尋ねます。How can I create a dataset named recipe_data using the Cloud Console?
結果を次の手順と比較します。
- BigQuery エクスプローラ ペインで、プロジェクト ID の横にある縦に 3 つ並んだ点の [アクションを表示] メニューをクリックします。次に、[データセットを作成] を選択します。
- データセットと ID に
recipe_data
を指定します。ロケーション タイプは [US] のままにして、[データセットを作成] をクリックします。データセットがすでに存在するというエラーが表示された場合は、続行してください。
BigQuery で作成したデータセットを使用して、ノートブックに戻り、挿入を行います。19. Colab Enterprise でデータ ハンドリング ノートブックに戻ります。新しいコードセルで、project_id
という名前の変数を作成し、現在のプロジェクト ID を保持します。手順の左上にある [ラボを終了] ボタンの下で、現在のプロジェクト ID を確認します。Cloud コンソールのホームページでも確認できます。値を project_id
変数に代入し、セルを実行します。
# Create a variable to hold the current project_id
project_id='YOUR_PROJECT_ID'
- プロンプト > コードのアプローチを使用して、作成したデータセット
recipe_data
のrecipes
という名前のテーブルに DataFramedfs
を挿入するコードブロックを作成します。セルを実行します。
dfs.to_gbq(destination_table='recipe_data.recipes', project_id=project_id, if_exists='replace')
7. タスク 4. Vertex AI Agent Builder でレシピ生成ツールの検索アプリを作成する
レシピデータのテーブルが作成されました。このテーブルを使用して、レシピ生成ツールの基盤となるデータソースを構築しましょう。使用するアプローチは、料理のチャットボットの場合と同様です。Vertex AI Agent Builder を使用してデータストアを作成し、それを検索アプリの信頼できる情報源として使用します。
必要に応じて、Google Cloud コンソールの Gemini に、エージェント ビルダー検索アプリを作成する手順を尋ねることができます。または、以下の手順に沿って作成することもできます。
- 検索を使用して [Agent Builder] に移動します。[データストア] を開き、[データストアを作成] をクリックします。今回は、BigQuery データストア タイプを選択します。
- テーブル選択セルで [参照] を押して、
recipes
を検索します。表の横にあるラジオボタンをオンにします。他の qwiklabs-gcp-... プロジェクトのレシピが表示された場合は、自分のレシピを選択してください。
注: recipes
の横にあるラジオボタンを選択するのではなく、recipes
をクリックすると、ブラウザで新しいタブが開き、BigQuery のテーブルの概要ページが表示されます。ブラウザのタブを閉じて、エージェント ビルダーでラジオボタンを選択するだけです。3. 残りのデフォルト オプションを確認して変更せず、[続行] をクリックします。4. スキーマ確認ページで、初期のデフォルト構成を確認します。ただし、変更は行いません。続行 5. データストアに recipe-data
という名前を付けます。データストア ID を編集して recipe-data-id
に設定します。データストアを作成します。6. 左側のナビゲーション メニューで [アプリ] に移動し、[アプリを作成] をクリックします。検索アプリをもう一度選択します。アプリの名前を recipe-search
に設定し、ID を recipe-search-id
に設定します。会社名を Google
に設定して [続行] をクリックします。8. 今回は、recipe-data データソースを確認します。アプリを作成します。
データベース テーブルのインデックス作成にはしばらく時間がかかります。待っている間に、BigQuery の新しいデータ キャンバスを試して、興味深いレシピがないか探してみましょう。9. 検索ボックスを使用して BigQuery に移動します。BigQuery Studio の上部にある、右端のタブの横にある下矢印をクリックし、[データキャンバス] を選択します。リージョンを us-central1 に設定します。
- データ キャンバスの検索ボックスで
recipes
を検索し、テーブルを [キャンバスに追加] します。 - レシピ テーブルのビジュアル データが BigQuery データ キャンバスに読み込まれます。テーブルのスキーマの確認、テーブル内のデータのプレビュー、その他の詳細の確認を行えます。テーブル表示の下にある [クエリ] をクリックします。
- キャンバスには、ほぼ一般的な BigQuery クエリ ダイアログが読み込まれます。ただし、クエリ ウィンドウの上に、Gemini にヘルプをリクエストできるテキスト ボックスがあります。サンプルにケーキのレシピが含まれているかどうかを確認しましょう。次のプロンプトを実行します(テキストを入力して Enter キーを押して SQL の生成をトリガーします)。
Please select the title and ingredients for all the recipes with a title that contains the word cake.
- 生成された SQL を確認します。問題がなければ、クエリを実行します。
- 悪くないですね。次のステップに進む前に、他のいくつかのプロンプトとクエリを試してみてください。テストを行う際は、より一般的なプロンプトを使って、効果的なものかどうかを判断します。たとえば、次のようなプロンプトです。
Do I have any chili recipes?
(新しいクエリを実行することを忘れないでください)チリのレシピのリストが返されましたが、次のように変更するまで材料は返されませんでした。
Do I have any chili recipes? Please include their title and ingredients.
(はい、プロンプトが表示されたら「お願いします」と言っています。ママは誇りに思うでしょう。
チリのレシピにキノコが含まれていることに気づきました。チリにキノコを入れたい人なんていませんよね?そのようなレシピを除外するよう Gemini に指示しました。
Do I have any chili recipes? Please include their title and ingredients, and ignore any recipes with mushrooms as an ingredient.
8. タスク 5. Gemini を少し使って、コアとなる Python と Streamlit のウェブ アプリケーションのフレームワークを作成します。
Vertex AI Agent Builder のデータストアのインデックス登録が完了し、検索アプリの準備も整ったので、ウェブ アプリケーションの作成に移りましょう。
作業中は Gemini Code Assist を利用します。Visual Studio Code で Gemini Code Assist を使用する方法については、こちらのドキュメントをご覧ください。
開発は Google Cloud Workstation で行います。これはクラウドベースの開発環境で、この場合は Eclipse Theia(オープンソースの Visual Studio Code)がプリロードされています。この演習の自動スクリプトによって Cloud Workstation クラスタと構成が作成されましたが、Cloud Workstation 自体は作成する必要があります。Cloud Workstations とその使用方法について詳しくは、Gemini Cloud Assist にお問い合わせください。
- 検索を使用して [Cloud Workstations]、[ワークステーションを作成] の順に移動します。ワークステーションに
dev-env
という名前を付け、my-config 構成を使用します。ワークステーションを作成します。 - 数分後、新しいワークステーションが [マイ ワークステーション] リストに表示されます。
dev-env
を起動し、実行したら開発環境を起動します。 - ワークステーション エディタが新しいブラウザタブで開き、しばらくすると使い慣れた Theia(Visual Studio Code)インターフェースが表示されます。インターフェースの左側で [ソース コントロール] タブを開き、[リポジトリのクローンを作成] をクリックします。
- リポジトリ URL に「
https://github.com/haggman/recipe-app
」と入力します。リポジトリをuser
フォルダにクローンを作成し、クローンを作成したリポジトリを開いて編集します。 - クローンを作成したフォルダを調べてウェブ アプリケーションの作成を開始する前に、エディタの Cloud Code プラグインを Google Cloud にログインさせ、Gemini を有効にする必要があります。それでは、エディタの左下にある [Cloud Code - ログイン] をクリックします。リンクが表示されない場合は、1 分ほど待ってからもう一度確認してください。
- ターミナル ウィンドウに長い URL が表示されます。ブラウザで URL を開き、手順に沿って Cloud Code に Google Cloud 環境へのアクセス権を付与します。認証時には、個人の Google Cloud アカウントではなく、演習用の一時的な
student-...
アカウントを使用してください。最後のダイアログで、確認コードをコピーし、Cloud Workstation ブラウザタブの待機中のターミナル ウィンドウに貼り付けます。 - しばらくすると、エディタの左下にある Cloud Code リンクが [Cloud Code - No Project] に変わります。新しいリンクをクリックしてプロジェクトを選択します。エディタの上部にコマンドパレットが開きます。[Google Cloud プロジェクトを選択] をクリックして、qwiklabs-gcp-... プロジェクトを選択します。しばらくすると、エディタの左下にプロジェクト ID が表示されます。これは、Cloud Code が作業中のプロジェクトに正常に接続されたことを示します。
- Cloud Code がプロジェクトに接続されたら、Gemini Code Assist を有効にできます。エディタ インターフェースの右下にある、取り消し線が引かれた Gemini のロゴをクリックします。エディタの左側に Gemini チャット ペインが開きます。[Google Cloud プロジェクトを選択] をクリックします。コマンド パレットが開いたら、qwiklabs-gcp-... プロジェクトを選択します。手順を正しく行った場合(および Google が何も変更していない場合)、アクティブな Gemini Chat ウィンドウが表示されます。
- 最後に、エディタ ターミナル ウィンドウも同様に設定します。ハンバーガー メニュー > [表示] > [ターミナル] を使用して、ターミナル ウィンドウを開きます。
gcloud init
を実行します。リンクを使用して、Cloud Shell ターミナルがqwiklabs-gcp-...
プロジェクトに対して動作できるようにします。プロンプトが表示されたら、qwiklabs-gcp-...
プロジェクトの数値オプションを選択します。 - ターミナル、Gemini チャット、Cloud Code の設定がすべて完了しました。[エクスプローラ] タブを開き、現在のプロジェクト内のファイルを確認します。
- エクスプローラで
requirements.txt
ファイルを開いて編集します。[Gemini] チャットペインに切り替えて、次のように尋ねます。
From the dependencies specified in the requirements.txt file, what type of application are we building?
- これで、Python と Streamlit を使用して、Vertex AI と Discovery Engine とやり取りするインタラクティブなウェブ アプリケーションを構築できました。ここでは、ウェブ アプリケーション コンポーネントに焦点を当てます。Gemini によると、Streamlit は、Python でデータドリブンのウェブ アプリケーションを構築するためのフレームワークです。次のように尋ねます。
Does the current project's folder structure seem appropriate for a Streamlit app?s
Gemini で問題が発生する傾向があるのは、この点です。Gemini は、現在エディタで開いているファイルにアクセスできますが、プロジェクト全体を実際に表示することはできません。次のように質問してみてください。
Given the below, does the current project's file and folder structure seem appropriate for a Streamlit app?
- build.sh
- Home.py
- requirements.txt
- pages
-- Cooking_Advice.py
-- Recipe_Search.py
より適切な回答を取得する
- Streamlit の詳細を確認しましょう。
What can you tell me about Streamlit?
Gemini は、メリットとデメリットを含む概要をわかりやすく提供しています。
- デメリットについて確認したい場合は、次のように尋ねます。
What are the major downsides or shortcomings?
Gemini チャットは会話型(マルチターン)であるため、「Streamlit の」と指定する必要はありません。チャット セッション中であるため、Gemini は会話の内容を把握しています。Gemini のチャット履歴を消去するには、Gemini コード チャット ウィンドウの上部にあるゴミ箱アイコンを使用します。
9. タスク 6: ウェブ アプリケーションを Cloud Run にデプロイする
これで、コア アプリケーションの構造が完成しました。しかし、すべてが機能するでしょうか?では、Google Cloud のどこでホストすればよいでしょうか?
- Gemini のチャット ウィンドウで、次のように質問します。
If I containerize this application, what compute technologies
in Google Cloud would be best for hosting it?
- IDE で作業していない場合は、Google Cloud Assist を使用することもできます。Google Cloud コンソールを開き、Gemini Cloud Assist を開いて、次のように尋ねます。
If I have a containerized web application, where would be the
best place to run it in Google Cloud?
2 つのアドバイスは同じでしたか?アドバイスのいずれかに同意または反対しますか?Gemini は生成 AI アシスタントであり、人間のアシスタントと同じように、Gemini の提案に常に同意できるとは限りません。それでも、Google Cloud とコードエディタで作業する際に、このヘルパーを常に利用できるようにしておけば、作業効率を大幅に高めることができます。
- ステートレスで存続期間の短いコンテナ化されたウェブ アプリケーションには、Cloud Run が最適です。コードエディタの Gemini チャット ウィンドウで、次のプロンプトを試します。
What steps would be required to run this application in
Cloud Run?
- 最初に行う必要があるのは、Dockerfile の作成です。エディタを使用して、プロジェクト フォルダのルートに
Dockerfile
という名前のファイルを作成します。誤ってページフォルダに配置しないようにしてください。ファイルを開いて編集します。 - サイドパネルの Gemini Chat を使用して
Dockerfile
を作成しましょう。次のようなプロンプトを使用します。結果がチャットに表示された場合は、提案された Dockerfile のすぐ上にあるコピーアイコンの横にある + を使用して、提案されたコードを Dockerfile に挿入します。
Create a Dockerfile for the application in the current folder.
The dependencies are defined in requirements.txt and I want you
to use the Python 3 slim bookworm base image.
Gemini は、同じプロンプトに対して常に同じ回答を返すわけではありません。Gemini に Dockerfile を初めてリクエストしたときに、私がおすすめするファイルが返されました。先ほど、次のような提案を受け取りました。
```docker
# Base image
FROM python:3-bookworm-slim
# Set working directory
WORKDIR /app
# Install dependencies
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
gcc \
python3-dev \
&& rm -rf /var/lib/apt/lists/*
# Install pip and virtualenv
RUN pip install --upgrade pip virtualenv
# Create virtual environment
RUN python3 -m venv venv
# Activate virtual environment
WORKDIR /app/venv/bin
RUN . activate
# Install Streamlit and libraries from requirements.txt
RUN pip install -r requirements.txt
# Copy application files
COPY . /app
# Expose port 8501 for Streamlit
EXPOSE 8501
# Start Streamlit app
CMD ["streamlit", "run", "main.py"]
That's a heck of a Dockerfile. I'd simplify it a bit. We don't need the apt-get section as anything needed for Python is already in our base image. Also, using a virtual environment in a Python container is a waste of space, so I'd remove that. The expose command isn't strictly necessary, but it's fine. Also, it's trying to start main.py which I don't have.
6. Tweak the Dockerfile so it resembles the following:
FROM python:3.11-slim-bookworm
WORKDIR /app
COPY requirements.txt . RUN pip install –no-cache-dir –upgrade pip &&
pip install –no-cache-dir -r requirements.txt
COPY . .
CMD ["streamlit", "run", "Home.py"]
7. We need a place in Google cloud where we can store our container image. Let's get a little help from Gemini. In the Google Cloud Console Gemini Cloud Assist ask:
Google Cloud で Docker イメージを保存するのに最適な場所はどこですか?
8. If one of the answers you received is the Google Container Registry, then I guess Gemini hasn't gotten word that GCR is deprecated. Again, just like human assistants, you may get out of date or simply wrong answers (hallucinations). Always make sure to consider your choices carefully, even when Gemini is recommending something.
Let's go with Artifact Registry. Ask Gemini Cloud Assist how to create a docker registry in Artifact Registry named cooking-images.
gcloud を使用して Artifact Registry に Docker レジストリを作成するにはどうすればよいですか?
9. Now ask Gemini how you could use Cloud Build to build a new image named `recipe-web-app` from the Dockerfile in the current folder.
gcloud を使用して、Artifact Registry リポジトリに作成した同じ名前のイメージから、recipe-web-app という名前の新しい Cloud Run サービスをビルドするにはどうすればよいですか?
10. To save you a little time, I've created a script that will create the Artifact Registry repo (if needed), use Cloud Build to build and push the image to the repo, and finally to deploy the application to Cloud Run. In your code editor use the **Explorer** view to open `build.sh` and explore the file.
11. Gemini can operate via the chat window, but it can also work directly in your code file using comments, like we used in the Data Wrangling notebook, and it also may be invoked using Control+i on Windows or Command+i on Mac. Click somewhere in the build.sh script file, activate Gemini using the appropriate Command+i / Control+i command.
<img src="img/61ac2c9a245a3695.png" alt="61ac2c9a245a3695.png" width="624.00" />
12. At the prompt enter the below. Examine and **Accept** the change.
現在のファイルをコメント化してください。
How cool is that?! How many times have you had to work with someone elses code, only to have to waste time gaining a base understanding of their commentless work before you can even start making your changes. Gemini to the rescue!
13. Let's build and deploy our application. In the terminal window execute the `build.sh` file.
. build.sh
14. If you watch the build process, first it will build the Artifact Registry docker repo. Then, it uses Cloud Build to create the container image from the Dockerfile in the local folder (since we didn't supply a `cloudbuild.yaml`). Lastly, the docker image will be deployed into a new Cloud Run service. At the end of the script you'll get a Cloud Run test URL to use.
Open the returned link in a new tab of your browser. Take a moment and explore the application's structure and pages. Nice, now we need a hook in our generative AI functionality.
## Task 7: Connect the Cooking Advice page to our cookbook-search Agent Builder app
We have the framework for the web application running, but we need to connect the two work pages to our two Vertex AI Agent Builder search apps. Let's start with Cooking Advice.
1. In the Google Cloud console use search to navigate to **Chat** in Vertex AI.
2. In the right hand settings page pane set the model to **gemini-1.5-flash-002**. Slide the output token limit up to the max so the model can return longer answers if needed. Open the **Safety Filter Settings**. Set Hate speech, Sexually explicit content, and Harassment content to **Block some**. Set Dangerous content to **Block few** and **Save**. We're setting Dangerous Content a bit lower because talking about knives and cutting can be misinterpreted by Gemini as violence.
3. Slide on the toggle to enable **Grounding** then click **Customize**. Set the grounding source to **Vertex AI search** and for the datastore path use the following. Change YOUR_PROJECT_ID to the project ID found up near the End Lab button in these instructions, then **Save** the grounding settings
projects/YOUR_PROJECT_ID/locations/global/collections/default_collection/dataStores/old-cookbooks-id
**Note:** If you get an error then you either didn't change the project ID to your actual project ID, or you may have missed the step where you changed the old-cookbooks Agent Builder Data Store ID. Check your Agent Builder > Data Stores > old-cookbooks for its actual Data store ID.
4. Test a couple of chat messages. Perhaps start with the below. Try a few others if you like.
トマトが熟しているかどうかを判断するにはどうすればよいですか?
5. The model works, now let's experiment with the code. Click **Clear Conversation** so our conversations don't become part of the code then click **Get Code**.
<img src="img/dce8ad7ee006cca1.png" alt="dce8ad7ee006cca1.png" width="624.00" />
6. At the top of the code window, press Open Notebook so we can experiment and perfect the code in Colab Enterprise before integrating it into our app.
7. Take a few minutes to familiarize yourself with the code. Let's make a couple of changes to adapt it to what we want. Before we start, run the first code cell to connect to the compute and install the AI Platform SDK. After the block runs you will be prompted to restart the session. Go ahead and do that.
8. Move to the code we pulled out of Vertex AI Studio. Change the name of the method *multiturn_generate_content* to `start_chat_session`.
9. Scroll to the `model = GenerativeModel(` method call. The existing code defines the `generation_config` and `safety_settings` but doesn't actually use them. Modify the creation of the `GenerativeModel` so it resembles:
model = GenerativeModel( "gemini-1.5-flash-002", tools=tools, generation_config=generation_config, safety_settings=safety_settings, )
10. Lastly, add a final line to the method, just below `chat = model.start_chat()`, so the function returns the `chat` object. The finished function should look like the below.
**Note:** DO NOT COPY this code into your notebook. It is simply here as a sanity check.
def start_chat_session(): vertexai.init(project="qwiklabs-gcp-02-9a7298ceaaec", location="us-central1") tools = [ Tool.from_retrieval( retrieval=grounding.Retrieval( source=grounding.VertexAISearch(datastore="projects/qwiklabs-gcp-02-9a7298ceaaec/locations/global/collections/default_collection/dataStores/old-cookbooks-id"), ) ), ] model = GenerativeModel( "gemini-1.5-flash-002", tools=tools, generation_config=generation_config, safety_settings=safety_settings, ) chat = model.start_chat() return chat
11. Scroll to the bottom of the code cell and change the final line calling the old function so it calls the new function name and stores the returned object in a variable `chat`. Once you are satisfied with your changes, run the cell.
chat = start_chat_session()
12. Create a new code cell and add the comment `# Use chat to invoke Gemini and print out the response`. Move to the next line and type resp and Gemini should auto complete the block for you. Update the prompt to `How can I tell if a tomato is ripe?`. Run the cell
response = chat.send_message("トマトが熟しているかどうかを判断するにはどうすればよいですか?") print(response)
13. That's the response alright, but the part we really want is that nested text field. Modify the codeblock to print just that section, like:
response = chat.send_message("How can I tell if a tomato is ripe?") print(response.candidates[0].content.parts[0].text)
14. Good, now that we have working chat code, let's integrate it into our web application. Copy all the contents of the code cell that creates the `start_chat_session` function (we won't need the test cell). If you click into the cell you can click the triple dot menu in the upper right corner and copy from there
<img src="img/17bf8d947393d4b.png" alt="17bf8d947393d4b.png" width="326.00" />
15. Switch to your Cloud Workstation editor and open pages\Cooking_Advice.py for editing.
16. Locate the comment:
ノートブックからコピーしたコードをこのメッセージの下に追加します
17. Paste your copied code just below the above comment. Nice, now we have the section which drives the chat engine via a grounded call to Gemini. Now let's integrate it into Streamlit.
18. Locate section of commented code directly below the comment:
セッション変数を設定するコードは次のとおりです。
指示に従ってこのブロックのコメント化を解除します
19. Uncomment this section of code (Up till the next `Setup done, let's build the page UI` section) and explore it. It creates or retrieves the chat and history session variables.
20. Next, we need to integrate the history and chat functionality into the UI. Scroll in the code until you locate the below comment.
チャット インターフェースを作成するコードを次に示します。
指示に従って、以下のコードのコメント化を解除します。
21. Uncomment the rest of the code below the comment and take a moment to explore it. If you like, highlight it and get Gemini to explain its functionality.
22. Excellent, now let's build the application and deploy it. When the URL comes back, launch the application and give the Cooking Advisor page a try. Perhaps ask it about ripe tomatoes, or the bot knows a good way to prepare brussels sprouts.
. build.sh
How cool is that! Your own personal AI cooking advisor :-)
## Task 8: (Optional) Connect the Recipe Search page to the recipe-search Agent Builder app
When we connected the Cooking Advice page to its grounded source, we did so using the Gemini API directly. For Recipe Search, let's connect to the Vertex AI Agent Builder search app directly.
1. In your Cloud Workstation editor, open the `pages/Recipe_Search.py` page for editing. Investigate the structure of the page.
2. Towards the top of the file, set your project ID.
3. Examine the `search_sample` function. This code more or less comes directly from the Discovery Engine documentation [here](https://cloud.google.com/generative-ai-app-builder/docs/preview-search-results#genappbuilder_search-python). You can find a working copy in this notebook [here](https://github.com/GoogleCloudPlatform/generative-ai/blob/main/search/create_datastore_and_search.ipynb).
4. The only change I made was to return the `response.results` instead of just the results. Without this, the return type is an object designed to page through results, and that's something we don't need for our basic application.
5. Scroll to the very end of the file and uncomment the entire section below `Here are the first 5 recipes I found`.
6. Highlight the whole section you just uncommented and open Gemini Code chat. Ask, `Explain the highlighted code`. If you don't have something selected, Gemini can explain the whole file. If you highlight a section and ask Gemini to explain, or comment, or improve it, Gemini will.
Take a moment and read through the explanation. For what it's worth, using a Colab Enterprise notebook is a great way to explore the Gemini APIs before you integrate them into your application. It's especially helpful at exploring some of the newer APIs which may not be documented as well as they could be.
7. At your editor terminal window, run `build.sh` to deploy the final application. Wait until the new version is deployed before moving to the next step.
## Task 9: (Optional) Explore the final application
Take a few minutes to explore the final application.
1. In the Google Cloud console, use search to navigate to **Cloud Run**, then click into your **recipe-web-app**.
2. Locate the application test URL (towards the top) and open it in a new browser tab.
3. The application home page should appear. Note the basic layout and navigation provided by Streamlit, with the python files from the `pages` folder displayed as navigational choices, and the `Home.py` loaded as the home page. Navigate to the **Cooking Advice** page.
4. After a few moments the chat interface will appear. Again, note the nice core layout provided by Streamlit.
5. Try a few cooking related questions and see how the bot functions. Something like:
ブロッコリーの調理方法について、アドバイスはありますか?
定番のチキンスープのレシピはいかがですか?
メレンゲについて教えてください。
6. Now let's find a recipe or two. Navigate to the Recipe Search page and try a few searches. Something like:
チリコンカン
チリ、トウモロコシ、米
レモンメレンゲパイ
イチゴを含むデザート
## Congratulations!
You have created an application leveraging Vertex AI Agent Builder applications. Along the way you've explored Gemini Cloud Assist, Gemini Code Assist, and the natural language to SQL features of BigQuery's Data Canvas. Fantastic job!