AI 時代におけるアプリケーションの構築

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 をホストし、料理のアドバイスを提供し、料理に関する質問に回答します。レシピ検索は、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 コンソールにログインする方法

  1. [ラボを開始] ボタンをクリックします。ラボの料金をお支払いいただく必要がある場合は、表示されるポップアップでお支払い方法を選択してください。左側のパネルには、このラボで使用する必要がある一時的な認証情報が表示されます。

52e0878388c0d9ed.png

  1. ユーザー名をコピーし、[Google Console を開く] をクリックします。ラボでリソースがスピンアップし、別のタブで [ログイン] ページが表示されます。

2a4b7165afebf5ab.png

ヒント: タブをそれぞれ別のウィンドウで開き、並べて表示しておきましょう。

[アカウントの選択] ダイアログが表示されたら、[別のアカウントを使用] をクリックします。

6463aa9b492a3b60.png

  1. [ログイン] ページで、[接続の詳細] パネルでコピーしたユーザー名を貼り付けます。パスワードもコピーして貼り付けます。

重要: 認証情報は [Connection Details] パネルに表示されたものを使用してください。(ご自身の Qwiklabs 認証情報は使用しないでください)。請求が発生する事態を避けるため、Google Cloud アカウントをお持ちの場合でも、このラボでは使用しないでください。4. その後次のように進みます。

  1. 利用規約に同意します。
  2. 一時的なアカウントなので、復元オプションや 2 要素認証プロセスは設定しないでください。
  3. 無料トライアルには登録しないでください。

その後このタブで Cloud Console が開きます。

注: 左上にあるナビゲーション メニューをクリックすると、Google Cloud のプロダクトやサービスのリストが含まれるメニューが表示されます。

bbdc8ea800bf0adc.png

3. タスク 0. ワークステーション クラスタを確認する

このラボの後半では、Google Cloud Workstation を使用して開発作業を行います。このラボの起動プロセスで、ワークステーションのクラスタの作成が開始されているはずです。次に進む前に、クラスタがビルドされていることを確認しましょう。

  1. Google Cloud コンソールの検索ボックスを使用して、[Cloud Workstations] に移動します。
  2. 左側のナビゲーション メニューを使用して、[クラスタ管理] を表示します。
  3. クラスタが更新中の場合は、そのままタスク 1 に進んでください。どの状態のクラスタも表示されない場合は、ページを更新します。クラスタの [Updating (building)] が表示されない場合は、この手順の左上にあるボタンを使用してこのラボを終了し、ラボを再開します。

4. タスク 1. Gemini Cloud Assist を有効にして使用する

このタスクでは、Gemini Cloud Assist を有効にして使用します。Google Cloud コンソールで作業しているときに、Gemini Cloud Assist はアドバイスを提供し、Google Cloud インフラストラクチャの構築、構成、モニタリングを支援します。また、gcloud コマンドを提案したり、Terraform スクリプトを作成したりすることもできます。

  1. Cloud Assist を使用するには、Cloud コンソール UI の上部にある検索ボックスをクリックし、[Gemini に質問](または [Gemini for Cloud コンソールに質問])を選択します。
  2. ページの [必要な API] セクションまでスクロールし、Gemini for Google Cloud API を有効にします。
  3. チャット インターフェースがすぐに表示されない場合は、[チャットを開始] をクリックします。まず、Gemini に Cloud Workstations を使用するメリットについて説明してもらいます。生成されたレスポンスを数分かけて確認します。
  4. 次に、Agent Builder のメリットと、生成された回答のグラウンディングにどのように役立つかについて質問します。
  5. 最後に、比較を見てみましょう。Google Cloud コンソールの Gemini チャット ウィンドウで、次の質問をします。
What are the major steps to creating a search app grounded in a
GCS data source using Vertex AI Agent builder?
  1. 次に、シークレット ウィンドウ以外のウィンドウで、こちらの Gemini の一般公開ウェブサイトにアクセスし、必要に応じてログインして、同じ質問をします。回答は同じか、少なくとも類似していますか?具体的な手順は?どちらかが明らかに優れているということはありますか?いずれにしても、次の手順に進む際に回答を念頭に置いてください。

注: 上記の手順を一時的な Qwiklabs アカウントを使用して実行しようとすると、ブロックされます。組織で Gemini ウェブアプリの使用が許可されていないため、仕事用アカウントもブロックされている場合は、この手順をスキップして次の手順に進んでください。このことは、この演習を完了するうえで影響しません。

5. タスク 2. Vertex AI Agent Builder で料理のアドバイスを行うチャットボット用の検索アプリを作成する

構築するウェブサイトには、料理に関する質問の答えを見つけるための chatbot が含まれた料理のアドバイス ページがあります。この機能は、70 冊のパブリック ドメインの料理本を含むソースに基づく Gemini によって実現されます。クックブックは、Gemini が質問に回答する際に使用する信頼できる情報源として機能します。

  1. Cloud コンソールの検索ボックスを使用して、[Vertex AI] に移動します。ダッシュボードで、[すべての推奨 API を有効にする] をクリックします。Vertex AI API 自体を有効にする必要があるというポップアップ ボックスが表示された場合は、それも有効にしてください。
  2. 検索を使用して Agent Builder に移動し、[続行して API を有効にする] をクリックします。
  3. 以前の質問で Gemini が提案したように、Agent Builder で検索アプリを作成するには、まず信頼できるデータソースを作成します。ユーザーが検索すると、Gemini は質問とインテリジェントな回答の作成方法を理解しますが、その回答で使用される情報は、Gemini の生来の知識からではなく、根拠となるソースから取得されます。

左側のメニューで、[データストア] に移動し、[データストアを作成] をクリックします。4. 料理のアドバイス ページで使用しているパブリック ドメインの料理本は、現在、外部プロジェクトの Cloud Storage バケットにあります。Cloud Storage のソースタイプを選択します。5. インポートする情報の種類に関連するデフォルトのオプションを確認しますが、変更はしません。インポート タイプは [フォルダ] のままにして、バケットパスに labs.roitraining.com/labs/old-cookbooks を使用し、[続行] をクリックします。6. データストアに old-cookbooks という名前を付けます。[編集] をクリックして ID を old-cookbooks-id に変更し、データストアを作成します。

Vertex AI Agent Builder は複数のアプリタイプをサポートしており、データストアはそれぞれに対する信頼できる情報源として機能します。検索アプリは、一般的な用途や検索に適しています。Chat 用アプリは、Dataflow で駆動される chatbot/voicebot アプリケーションの生成フロー用です。レコメンデーション アプリは、より優れたレコメンデーション エンジンの作成に役立ちます。エージェント アプリは、GenAI を活用したエージェントの作成に使用します。最終的には、Agent がやりたいことを実現するのに最適な方法になる可能性がありますが、現在はプロダクトのプレビュー版であるため、Search アプリタイプを使用します。7. 左側のメニューを使用して [アプリ] に移動し、[アプリを作成] をクリックします。8. 検索アプリのタイプを選択します。さまざまなオプションを確認しますが、変更はしません。アプリに名前を付けます(cookbook-search)。[編集] をクリックし、アプリ ID を cookbook-search-id に設定します。会社を Google に設定し、[続行] をクリックします。9. 数ステップ前に作成した old-cookbooks データストアを確認し、検索アプリを作成します。

[アクティビティ] タブを確認すると、クックブックのインポートとインデックス作成がまだ進行中であることがわかります。Agent Builder が、提供された 70 冊のクックブックに含まれる数千のページをインデックス登録するのに 5 分以上かかります。その間に、レシピ生成ツール用のレシピ データベース データを読み込んでクリーンアップしましょう。

6. タスク 3. Gemini Code Assist のサポートを受けながら、Colab Enterprise ノートブックでデータを読み込んでクリーンアップする

Google Cloud には、Jupiter ノートブックを操作するためのいくつかの主要な方法が用意されています。Google の最新サービスである Colab Enterprise を使用します。無料の環境で Jupiter ノートブックを試したい個人や組織によく使用されている Google の Colab プロダクトをご存じの方もいらっしゃるかもしれません。Colab Enterprise は、Google の他のクラウド プロダクトと完全に統合され、GCP 環境のセキュリティ機能とコンプライアンス機能を最大限に活用する商用 Google Cloud サービスです。

Colab Enterprise の機能の 1 つに、Google の Gemini Code Assist との統合があります。Code Assist はさまざまなコードエディタで使用でき、コーディング中にシームレスなインライン候補を表示するだけでなく、アドバイスも提供します。レシピデータを整理する際に、この生成アシスタントを活用します。

  1. 検索を使用して Colab Enterprise に移動し、[ノートブックを作成] をクリックします。新しい Colab 機能を試すよう促すメッセージが表示された場合は、閉じます。ランタイム(ノートブックの背後にあるコンピューティング能力)を起動するには、新しいノートブックの右上にある [接続] をクリックします。

386577c713522b4d.png

  1. Colab Enterprise の [ファイル] ペインで、現在のノートブック名の横にあるその他メニューを使用して、名前を変更します Data Wrangling

4cb787f255bac415.png

  1. 新しい [+ テキスト] ボックスを作成し、上矢印を使用してページの一番上のセルに移動します。

6a08b3ccc9c2174b.png

  1. テキスト ボックスを編集して、次のように入力します。
# Data Wrangling

Import the Pandas library
  1. 作成したテキスト ブロックの下のコードブロックで、「imp」と入力し始めると、Gemini Code Assist が残りのインポートをグレーで提案します。Tab キーを押して提案を承認します。
import pandas as pd
  1. インポート コード ボックスの下に別のテキスト ボックスを作成し、次のように入力します。
Create a Pandas DataFrame from: gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv. View the first few records.
  1. 別のコードブロックを作成して編集します。もう一度「df」と入力して、Gemini Code Assistant が生成したコードを確認します。生成された候補の上に Python キーワードのオートコンプリート ドロップダウン リストが表示された場合は、Esc キーを押して、薄いグレーの候補コードを表示します。もう一度タブを押して提案を受け入れます。提案に head() 関数呼び出しが含まれていない場合は、追加します。
df = pd.read_csv('gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv')
df.head()
  1. Pandas をインポートした最初のコードセルをクリックし、[コマンド] メニューまたはキーボードを使用して、選択したセルを実行します。キーボードの 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 でも機能します。

  1. 列を少しクリーンアップしましょう。列 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)
  1. source 列と NER 列を削除し、head() を使用して最初の数行を表示します。ここでも Gemini を活用しましょう。最後の 2 行を実行し、結果を確認します。
# Remove the source and NER columns
df.drop(columns=['source', 'NER'], inplace=True)
df.head()
  1. データセットにレコードがいくつあるか見てみましょう。ここでも、プロンプト技術を選択して、Gemini にコードの生成を依頼してみましょう。
# Count the records in the DataFrame
df.shape # count() will also work
  1. 230 万件のレシピは、おそらく時間が足りないほど多いでしょう。Agent Builder のインデックス登録プロセスは、今日の演習には時間がかかりすぎる可能性があります。妥協案として、15 万件のレシピをサンプリングして、それを使用することにします。プロンプトとコードのアプローチを使用して、サンプルを取得し、dfs(s は small の略)という名前の新しい DataFrame に保存します。
# Sample out 150,000 records into a DataFrame named dfs
dfs = df.sample(n=150000)
  1. レシピのソースデータは、BigQuery に読み込む準備が整いました。読み込みを行う前に、BigQuery に移動して、テーブルを保持するデータセットを準備しましょう。Google Cloud コンソールで、検索ボックスを使用して [BigQuery] に移動します。[BigQuery] を右クリックして、新しいブラウザタブで開くこともできます。
  2. まだ表示されていない場合は、Cloud コンソールの右上にある Gemini ロゴを使用して、Gemini AI Chat パネルを開きます。API を再度有効にするよう求められた場合は、[有効にする] を押すか、ページを更新します。プロンプトを実行します。What is a dataset used for in BigQuery? 回答を確認したら、次の質問をします。How can I create a dataset named recipe_data using the Cloud Console? 結果を次の手順と比較します。

3c38e5975c5c519.png

  1. BigQuery エクスプローラ ペインで、プロジェクト ID の横にある三点リーダーの [アクションを表示] メニューをクリックします。次に、[データセットを作成] を選択します。

e28c2fc55a04c694.png

  1. データセットと recipe_data の ID を指定します。ロケーション タイプは [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'
  1. プロンプト > コード アプローチを使用して、DataFrame dfs を、作成したばかりのデータセット recipe_datarecipes という名前のテーブルに挿入するコードブロックを作成します。セルを実行します。
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 検索アプリを作成する手順を思い出させるよう依頼するか、以下の手順に沿って操作してください。

  1. 検索を使用して Agent Builder に移動します。[データストア] を開き、[データストアを作成] をクリックします。今回は、BigQuery データストアのタイプを選択します。
  2. テーブル選択セルで、[参照] を押して recipes を検索します。テーブルの横にあるラジオボタンを選択します。他の qwiklabs-gcp-... プロジェクトのレシピが表示された場合は、自分のレシピを選択してください。

注: ラジオボタンの横にある recipes をクリックすると、ブラウザで新しいタブが開き、BigQuery のテーブルの概要ページに移動します。ブラウザのタブを閉じて、Agent Builder でラジオボタンを選択するだけです。3. 残りのデフォルト オプションを確認し、変更せずに [続行] をクリックします。4. スキーマの確認ページで、初期のデフォルト構成を確認しますが、何も変更しないでください。続行 5. データストアに recipe-data という名前を付けます。データストア ID を編集して recipe-data-id に設定します。データストアを作成します。6. 左側のナビゲーション メニューを使用して [アプリ] に移動し、[アプリを作成] をクリックします。7. 検索アプリをもう一度選択します。アプリの名前を recipe-search に設定し、ID を recipe-search-id に設定します。会社名を Google に設定して、[続行] をクリックします。8. 今回は、recipe-data データソースを確認します。アプリを作成します。

データベース テーブルのインデックス作成にはしばらく時間がかかります。その間に、BigQuery の新しいデータ キャンバスを試して、興味深いレシピを見つけられるかどうかを確認してみましょう。9. 検索ボックスを使用して BigQuery に移動します。BigQuery Studio の上部で、右端のタブの横にある下矢印をクリックし、[データ キャンバス] を選択します。リージョンを us-central1 に設定します。

5d562cddb1717c32.png

  1. データ キャンバスの検索ボックスで recipes を検索し、テーブルを [キャンバスに追加] します。
  2. レシピ テーブルの視覚的な表現が BigQuery データ キャンバスに読み込まれます。テーブルのスキーマを確認したり、テーブル内のデータをプレビューしたり、その他の詳細を確認したりできます。テーブル表現の下にある [クエリ] をクリックします。
  3. キャンバスには、ほぼ標準的な BigQuery クエリ ダイアログが読み込まれます。ただし、クエリ ウィンドウの上に、Gemini にヘルプを求めるためのテキスト ボックスが追加されています。サンプルでケーキのレシピを探してみましょう。次のプロンプトを実行します(テキストを入力して Enter/Return キーを押すと、SQL の生成がトリガーされます)。
Please select the title and ingredients for all the recipes with a title that contains the word cake.
  1. 生成された SQL を確認します。完了したら、クエリを実行します。
  2. 悪くないですね。次に進む前に、他のプロンプトやクエリを試してみてください。テストでは、より一般的なプロンプトを試して、効果があるものとないものを確認します。たとえば、次のプロンプトについて考えてみましょう。
Do I have any chili recipes?

(新しいクエリを実行するのを忘れないでください)チリのレシピのリストが返されましたが、材料は含まれていませんでした。そこで、次のように変更しました。

Do I have any chili recipes?  Please include their title and ingredients.

(プロンプトを出すときは「お願いします」と言います。母もきっと喜んでくれるでしょう。)

1 つのチリレシピにマッシュルームが含まれていることに気づきました。チリにマッシュルームを入れたい人はいないでしょう。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 にお問い合わせください。

  1. 検索を使用して Cloud Workstations に移動し、[ワークステーションを作成] をクリックします。ワークステーションに dev-env という名前を付け、my-config 構成を使用します。ワークステーションを作成します。
  2. 数分後、[マイ ワークステーション] リストに新しいワークステーションが表示されます。dev-env開始し、実行されたら開発環境を起動します。
  3. ワークステーション エディタが新しいブラウザタブで開きます。しばらくすると、使い慣れた Theia(Visual Studio Code)インターフェースが表示されます。インターフェースの左側で [Source Control] タブを開き、[Clone Repository] をクリックします。

c03d05b42d28a518.png

  1. リポジトリの URL に「https://github.com/haggman/recipe-app」と入力します。リポジトリを user フォルダにクローンし、クローンしたリポジトリを開いて編集します。
  2. クローンされたフォルダを調べてウェブ アプリケーションの作業を開始する前に、エディタの Cloud Code プラグインを Google Cloud にログインし、Gemini を有効にする必要があります。それでは、そのための操作を行います。エディタの左下にある [Cloud Code - ログイン] をクリックします。リンクが表示されない場合は、1 分ほど待ってからもう一度ご確認ください。

f4ebfbd96026c0d8.png

  1. ターミナル ウィンドウに長い URL が表示されます。ブラウザで URL を開き、手順に沿って Cloud Code に Google Cloud 環境へのアクセス権を付与します。認証を行う際は、個人用の Google Cloud アカウントではなく、演習用の一時的な student-... アカウントを使用してください。最後のダイアログで、確認コードをコピーし、Cloud Workstation ブラウザタブの待機中のターミナル ウィンドウに貼り付けます。
  2. しばらくすると、エディタの左下にある Cloud Code リンクが [Cloud Code - No Project] に変わります。新しいリンクをクリックしてプロジェクトを選択します。コマンド パレットがエディタの上部に開きます。[Google Cloud プロジェクトを選択] をクリックして、qwiklabs-gcp-... プロジェクトを選択します。しばらくすると、エディタの左下にあるリンクが更新され、プロジェクト ID が表示されます。これは、Cloud Code が作業プロジェクトに正常に接続されたことを示します。
  3. Cloud Code がプロジェクトに接続されたので、Gemini Code Assist を有効にできます。エディタ インターフェースの右下にある、斜線付きの Gemini ロゴをクリックします。エディタの左側に Gemini チャット パネルが開きます。[Google Cloud プロジェクトを選択] をクリックします。コマンド パレットが開いたら、qwiklabs-gcp-... プロジェクトを選択します。手順を正しく実行した場合(Google が変更を行っていない場合)、Gemini チャット ウィンドウがアクティブになっているはずです。

70e4e06ed6565329.png

  1. 最後に、エディタのターミナル ウィンドウを同様に構成します。ハンバーガー メニュー > [View] > [Terminal] を使用してターミナル ウィンドウを開きます。gcloud init を実行します。ここでも、リンクを使用して、Cloud Shell ターミナルが qwiklabs-gcp-... プロジェクトに対して動作できるようにします。プロンプトが表示されたら、qwiklabs-gcp-... プロジェクトの数値オプションを選択します。
  2. ターミナル、Gemini チャット、Cloud Code の構成がすべて設定されたら、[エクスプローラ] タブを開き、現在のプロジェクトのファイルを数分かけて確認します。

3b2dc3820ed643e2.png

  1. エクスプローラで、編集する requirements.txt ファイルを開きます。Gemini チャット ペインに切り替えて、次のように質問します。
From the dependencies specified in the requirements.txt file, what type of application are we building?
  1. そのため、Vertex AI と Discovery Engine を操作する Python と Streamlit を使用して、インタラクティブなウェブ アプリケーションを構築しています。ここでは、ウェブ アプリケーション コンポーネントに焦点を当てます。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

より適切な回答を得る

  1. Streamlit の詳細について説明します。
What can you tell me about Streamlit?

Gemini がメリットとデメリットを含む概要を提示してくれています。

  1. デメリットを検討したい場合は、次のような質問をします。
What are the major downsides or shortcomings?

Gemini Chat は会話型(マルチターン)であるため、「Streamlit の」と言う必要はありません。チャット セッション中であるため、Gemini は会話の内容を把握しています。Gemini チャットの履歴を完全に消去する場合は、Gemini コード チャット ウィンドウの上部にあるゴミ箱アイコンを使用します。

9. タスク 6: ウェブ アプリケーションを Cloud Run にデプロイする

これで、コア アプリケーションの構造が整いましたが、すべてが機能するでしょうか?さらに、Google Cloud のどこでホストすればよいでしょうか?

  1. Gemini のチャット ウィンドウで、次のように質問します。
If I containerize this application, what compute technologies
in Google Cloud would be best for hosting it?
  1. 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 アシスタントであり、人間のアシスタントと同様に、その発言すべてに同意できるとは限りません。それでも、Google Cloud とコードエディタで作業しているときに常にヘルパーがそばにいると、効率が大幅に向上します。

  1. ステートレスの短命コンテナ化ウェブ アプリケーションには、Cloud Run が最適です。コードエディタの Gemini チャット ウィンドウで、次のプロンプトを試してみてください。
What steps would be required to run this application in
Cloud Run?
  1. まず、Dockerfile を作成する必要があるようです。エディタを使用して、プロジェクト フォルダのルートに Dockerfile という名前のファイルを作成します。誤って pages フォルダに配置しないように注意してください。ファイルを編集用に開きます。
  2. Gemini のサイドチャット パネルを使用して 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 &gt; Data Stores &gt; 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("トマトが熟しているかどうかを見分けるにはどうすればよいですか?") 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!