1. 總覽
在本實驗室中,您將使用 Google 的生成式 AI 產品,在 Gemini Cloud Assist 的協助下,在 Google Cloud 中建構基礎架構,使用 Data Canvas 的自然語言 SQL 功能查詢 BigQuery 資料,並在 Colab Enterprise Jupyter 筆記本和 Eclipse Theia (Visual Studio Code) 中,透過 Gemini Code Assist 編寫程式碼,以及在 Vertex AI Agent Builder 中,整合以 Cloud Storage 和 BigQuery 基礎來源建構的 AI 搜尋和即時通訊功能。
我們的目標是建立名為 AI Recipe Haven 的食譜和烹飪網站。這個網站將使用 Python 和 Streamlit 建構,並包含兩個主要網頁。我們將使用 Gemini 和 Vertex AI Agent Builder 建立 Cooking Advice 聊天機器人,並將相關資料來源連結至一組食譜,提供烹飪建議和回答烹飪相關問題。食譜搜尋功能將成為由 Gemini 提供內容的搜尋引擎,這次的基礎是 BigQuery 食譜資料庫。
如果您在本練習的任何程式碼中卡住,所有程式碼檔案的解決方案都位於練習 GitHub 存放區的 solution 分支中。
目標
在本研究室中,您將瞭解如何執行下列工作:
- 啟用並使用 Gemini Cloud Assist
- 在 Vertex AI Agent Builder 中為烹飪建議聊天機器人建立搜尋應用程式
- 在 Colab Enterprise 筆記本中載入及清理資料,並透過 Gemini Code Assist 提供的協助
- 在 Vertex AI Agent Builder 中為食譜產生器建立搜尋應用程式
- 在 Gemini 的協助下,勾勒出核心 Python 和 Streamlit 網頁應用程式
- 將網頁應用程式部署至 Cloud Run
- 將「烹飪建議」頁面連結至我們的食譜搜尋 Agent Builder 應用程式
- (選用) 將食譜搜尋頁面連結至食譜搜尋 Agent Builder 應用程式
- (選用) 探索最終應用程式
2. 設定和需求
瞭解以下事項後,再點選「Start Lab」按鈕
請詳閱以下操作說明。研究室活動會計時,中途無法暫停。點選「Start Lab」後就會開始計時,顯示可使用 Google Cloud 資源的時間。
您會在實際雲端環境中完成 Qwiklabs 實作研究室活動,而非模擬或示範環境。為此,我們會提供新的暫時憑證,讓您在研究室活動期間登入及存取 Google Cloud。
需求條件
如要完成這個研究室活動,請先確認:
- 可以使用標準的網際網路瀏覽器 (Chrome 瀏覽器為佳)。
- 已充分預留完成研究室的時間。
注意:如果您擁有個人 Google Cloud 帳戶或專案,請勿用於本研究室。
注意:如果您使用的是 Pixelbook,請先開啟無痕式視窗再執行本研究室。
如何開始研究室及登入 Google Cloud 控制台
- 按一下「Start Lab」按鈕。如果實驗室會產生費用,畫面中會出現選擇付款方式的彈出式視窗。左側面板會顯示必須在這個研究室中使用的暫時憑證。
- 複製使用者名稱,然後點選「Open Google Console」。接著,研究室會啟動相關資源並開啟另一個分頁,當中會顯示「Sign in」(登入) 頁面。
提示:請在不同的視窗中並排開啟分頁。
如果畫面上顯示「選擇帳戶」頁面,請按一下「使用其他帳戶」。
- 在「登入」頁面中,貼上您在「連線詳細資訊」面板中複製的使用者名稱,然後複製並貼上密碼。
重要事項:請務必使用「連線詳細資料」面板中的憑證,而非您自己的 Qwiklabs 憑證。請勿在這個研究室中使用您自己的 Google Cloud 帳戶,否則會產生費用。4. 按過後續的所有頁面:
- 接受條款及細則。
- 由於這是臨時帳戶,請勿新增救援選項或雙重驗證機制。
- 請勿申請免費試用。
Cloud 控制台稍後會在這個分頁中開啟。
注意:點選畫面左上方的導覽選單,即可查看 Google Cloud 產品與服務清單。
3. 工作 0:檢查工作站叢集
在本研究室的後續部分,您將使用 Google Cloud 工作站執行一些開發工作。本實驗室的啟動程序應該已開始建立工作站的叢集。繼續之前,請先確認叢集是否正在建構。
- 在 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 頂端的搜尋方塊,然後選取「Ask Gemini」 (或「Ask Gemini for Cloud 控制台」)。
- 捲動至頁面中的「必要 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 中為烹飪建議機器人建立搜尋應用程式
我們正在建構的網站將設有烹飪建議頁面,其中包含聊天機器人,可協助使用者找到烹飪相關問題的解答。這項服務將由 Gemini 提供支援,並以包含 70 本公版食譜的來源為基礎。食譜會做為 Gemini 回答問題時的資料來源。
- 使用 Cloud 控制台搜尋方塊前往「Vertex AI」。在資訊主頁中,按一下「啟用所有建議的 API」。如果您看到彈出式視窗,指出需要啟用 Vertex AI API,請一併啟用該 API。
- 使用搜尋功能前往「Agent Builder」,然後點選「Continue and Activate the API」。
- 如同 Gemini 先前在建議中提到的,在 Agent Builder 中建立搜尋應用程式時,請先建立可靠的資料來源。使用者搜尋時,Gemini 會瞭解問題,並瞭解如何撰寫智慧回覆,但會從基準來源尋找回覆所用資訊,而非從自身知識庫擷取。
在左側選單中,前往「資料儲存庫」並選擇「建立資料儲存庫」。4. 我們用於提供烹飪建議的公共領域食譜目前位於外部專案的 Cloud Storage 值區中。選取 Cloud Storage 來源類型。5. 請查看與我們要匯入的資訊類型相關的預設選項,但請勿變更。將匯入類型設為「資料夾」,並使用以下值做為資料夾路徑:labs.roitraining.com/labs/old-cookbooks
,然後按一下「繼續」。6. 為資料儲存庫命名:old-cookbooks
。點選「Edit」,將 ID 變更為 old-cookbooks-id
,然後「Create」資料儲存庫。
Vertex AI Agent Builder 支援多種應用程式類型,而資料儲存庫則是每個應用程式的真實來源。搜尋應用程式適合用於一般用途和搜尋。Chat 應用程式適用於 Dataflow 驅動的聊天機器人/語音機器人應用程式中的生成式流程。推薦應用程式有助於打造更優質的推薦引擎。代理程式應用程式則可用來建立由生成式 AI 驅動的代理程式。最終,Agent 可能會根據我們想要執行的操作提供最佳服務,但由於產品目前處於預覽階段,我們會繼續使用搜尋應用程式類型。7. 使用左側選單前往「應用程式」,然後點選「建立應用程式」。8. 選取「搜尋」應用程式類型。請查看各種選項,但不要變更。應用程式名稱:cookbook-search
。點選「編輯」,然後將應用程式 ID 設為 cookbook-search-id
。將公司設為 Google
,然後按一下「繼續」。9. 檢查幾個步驟前建立的 old-cookbooks
資料儲存庫,然後建立搜尋應用程式。
查看「活動」分頁時,你可能會發現食譜仍在匯入及建立索引。代理程式建構工具需要 5 分鐘以上,才能為我們提供的 70 本食譜中的數千個網頁建立索引。在運作期間,我們來為食譜產生器載入及清理一些食譜資料庫資料。
6. 工作 3:在 Colab Enterprise 筆記本中載入及清理資料,並透過 Gemini Code Assist 提供的協助
Google Cloud 提供幾種主要方式,讓您使用 Jupiter Notebook。我們將使用 Google 最新推出的 Colab Enterprise。有些人可能熟悉 Google 的 Colab 產品,這項產品通常由希望在免費環境中嘗試 Jupiter Notebook 的個人和機構使用。Colab Enterprise 是 Google Cloud 的商業產品,可與其他 Google 雲端產品完全整合,充分發揮 GCP 環境的安全性和法規遵循功能。
Colab Enterprise 提供的其中一項功能,就是與 Google 的 Gemini Code Assist 整合。您可以在多個不同的程式碼編輯器中使用 Code Assist,這項功能可在您編寫程式碼時提供建議,以及內嵌建議。我們會在處理食譜資料時,運用這項生成式助理。
- 使用搜尋功能前往「Colab Enterprise」,然後點選「建立筆記本」。如果系統提議您試用新的 Colab 功能,請拒絕。如要啟動 Notebook 的運算能力,請按下新 Notebook 右上角的「Connect」。
- 在 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 Assistant 產生的程式碼。如果您在產生的建議上方看到 Python 關鍵字的自動完成下拉式清單,請按下 Escape 鍵,查看淺灰色的建議程式碼。再次按下 Tab 鍵即可接受建議。如果建議內容未包含 head() 函式呼叫,請新增該函式。
df = pd.read_csv('gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv')
df.head()
- 點選第一個程式碼儲存格 (您在其中匯入 Pandas),然後使用「指令」選單或鍵盤執行所選儲存格。在鍵盤上,按下 Shift + Enter 鍵可執行儲存格,並將焦點轉移至下一個儲存格,並視需要建立一個儲存格。請等待單元格執行完畢,再繼續操作。
注意:如果未執行單元格,左側會顯示「[ ]」。在執行單元格時,您會看到旋轉的動畫。儲存格完成後,畫面上會顯示數字,例如 [13]。9. 執行載入 CSV 至 DataFrame 的儲存格。請等待檔案載入,然後檢查前五列資料。這是我們要載入至 BigQuery 的食譜資料,最終會用於建立食譜產生器。10. 建立新的程式碼區塊,並輸入以下註解。輸入註解後,請移至下一行程式碼,您應該會收到建議 df.columns
。接受後執行儲存格。
# List the current DataFrame column names
我們剛剛示範了在 Jupyter 筆記本中使用 Gemini Code Assist 的兩種方式:程式碼儲存格上方的文字儲存格,或程式碼儲存格內的註解。程式碼單元格中的註解在 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 提供協助。執行最後兩行並查看結果。
# 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 萬筆記錄可能比我們有時間處理的食譜還多。在今天的練習中,Agent Builder 的索引處理程序可能會耗費太多時間。我們可以採取折衷做法,抽樣 150,000 個食譜,並以此做為基礎。使用提示 > 程式碼方法擷取樣本,並儲存在名為
dfs
的新 DataFrame 中 (s 代表小)。
# Sample out 150,000 records into a DataFrame named dfs
dfs = df.sample(n=150000)
- 食譜來源資料現已可載入 BigQuery。在載入資料前,我們先前往 BigQuery,準備資料集來儲存資料表。在 Google Cloud 控制台中,使用搜尋框前往「BigQuery」BigQuery。您可以按一下 BigQuery 的滑鼠右鍵,然後在新瀏覽器分頁中開啟。
- 如果尚未顯示,請使用 Cloud 控制台右上方的 Gemini 標誌開啟 Gemini AI 即時通訊面板。如果系統要求您再次啟用 API,請按下啟用或重新整理頁面。執行提示:
What is a dataset used for in BigQuery?
探索回應後,請問:How can I create a dataset named recipe_data using the Cloud Console?
將結果與下列幾個步驟進行比較。
- 在 BigQuery「Explorer」窗格中,按一下專案 ID 旁邊的三點「查看動作」選單。接著選取「建立資料集」。
- 提供
recipe_data
的資料集和 ID。將位置類型保留為「US」,然後點選「Create Dataset」。如果您收到資料集已存在的錯誤訊息,請直接略過。
在 BigQuery 中建立資料集後,請切換回筆記本並執行插入作業。19. 在 Colab Enterprise 中切換回資料處理筆記本。在新的程式碼儲存格中,建立名為 project_id
的變數,並用於儲存目前的專案 ID。請在這些操作說明的左上方 (「End Lab」按鈕下方) 查看目前的專案 ID。您也可以在 Cloud 控制台首頁上找到這項資訊。將值指派給 project_id
變數,然後執行儲存格。
# Create a variable to hold the current project_id
project_id='YOUR_PROJECT_ID'
- 使用提示 > 程式碼方法建立程式碼區塊,將 DataFrame
dfs
插入剛才建立的資料集recipe_data
中名為recipes
的資料表。執行儲存格。
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 搜尋應用程式時提醒您相關步驟,或是按照下列步驟操作。
- 使用搜尋功能前往「Agent Builder」。開啟「資料儲存庫」並點選「建立資料儲存庫」。這次請選取 BigQuery Data Store 類型。
- 在表格選取儲存格中,按下「Browse」,然後搜尋
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。在 BigQuery Studio 頂端,按一下最右邊分頁旁的向下箭頭,然後選取「資料畫布」。將地區設為 us-central1。
- 在資料資訊圖搜尋框中搜尋
recipes
,然後將其加到資訊圖表格中。 - 系統會將食譜表的視覺化呈現方式載入 BigQuery 資料畫布。您可以探索資料表的結構定義、預覽資料表中的資料,以及查看其他詳細資料。在表格表示法下方,按一下「查詢」。
- 畫布會載入大致相同的 BigQuery 查詢對話方塊,但有一個額外的功能:查詢視窗上方有一個文字方塊,可用來提示 Gemini 提供協助。我們來看看是否能在範例中找到一些蛋糕食譜。執行下列提示 (輸入文字並按下 Enter/Return 鍵觸發 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) 介面。在介面左側展開「Source Control」分頁,然後按下「Clone Repository」。
- 在存放區網址中輸入
https://github.com/haggman/recipe-app
。將存放區複製到user
資料夾,然後開啟複製的存放區進行編輯。 - 在我們探索複製的資料夾並開始處理網頁應用程式之前,必須先讓編輯器的 Cloud Code 外掛程式登入 Google Cloud,並啟用 Gemini。我們現在就來瞭解。在編輯器左下方,點選「Cloud Code - Sign in」。如果沒有看到連結,請稍候片刻,然後再檢查一次。
- 終端機視窗會顯示一組長網址。在瀏覽器中開啟網址,然後按照步驟操作,授予 Cloud Code 存取 Google Cloud 環境的權限。請務必使用練習用臨時
student-...
帳戶,而非個人 Google Cloud 帳戶進行驗證。在最後一個對話方塊中,複製驗證碼,然後貼回 Cloud Workstation 瀏覽器分頁中的等候終端機視窗。 - 過幾秒後,編輯器左下方的 Cloud Code 連結會變更為「Cloud Code - No Project」。按一下新的連結,選取專案。指令面板應會在編輯器頂端開啟。按一下「選取 Google Cloud 專案」,然後選取「qwiklabs-gcp-...」專案。幾分鐘後,編輯器左下方的連結會更新,顯示專案 ID。這表示 Cloud Code 已成功連結至您的工作專案。
- 將 Cloud Code 連結至專案後,您現在就可以啟用 Gemini Code Assist。在編輯器介面的右下方,按一下 Gemini 標誌旁的叉號。Gemini Chat 窗格會在編輯器左側開啟。按一下「選取 Google Cloud 專案」。指令面板開啟後,請選取 qwiklabs-gcp-... 專案。如果您已正確完成步驟 (且 Google 未變更任何內容),現在應該會看到啟用的 Gemini 即時通訊視窗。
- 最後,讓我們將編輯器終端機視窗的設定調整為相同。使用漢堡選單 >「View」>「Terminal」,開啟終端機視窗。執行
gcloud init
。再次使用連結,讓 Cloud Shell 終端機可與qwiklabs-gcp-...
專案搭配運作。系統要求時,請選取qwiklabs-gcp-...
專案的數值選項。 - 很好,終端機、Gemini 即時通訊和 Cloud Code 的設定都已完成,請開啟「Explorer」分頁,花幾分鐘時間探索目前專案中的檔案。
- 在 Explorer 中開啟
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?
請注意,我們不需要說「Streamlit」,因為 Gemini Chat 是會話式 (多輪) 對話。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 Console,然後開啟 Gemini Cloud Assist,並詢問:
If I have a containerized web application, where would be the
best place to run it in Google Cloud?
兩組建議是否相同?您是否同意/不同意其中任何建議?請注意,Gemini 是生成式 AI 助理,就像真人助理一樣,你不一定會同意它說的所有內容。不過,在 Google Cloud 和程式碼編輯器中使用協助工具,有助於提高工作效率。
- 如果是無狀態的短暫容器化網頁應用程式,Cloud Run 會是理想的選擇。在程式碼編輯器的 Gemini 對話視窗中,試試下列提示:
What steps would be required to run this application in
Cloud Run?
- 我們首先要做的,就是建立 Dockerfile。使用編輯器,在專案資料夾的根目錄中建立名為
Dockerfile
的檔案。請確認你不會不小心將檔案放在 Pages 資料夾中。開啟檔案進行編輯。 - 我們來使用 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
複製 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("How can I tell if a tomato is ripe?") 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!