在 AI 时代构建应用

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 食谱天堂”的食谱和烹饪网站。该网站将使用 Python 和 Streamlit 构建,包含两个主要页面。“烹饪建议”将托管一个聊天机器人,该聊天机器人将使用 Gemini 和 Vertex AI Agent Builder 创建,其接地源与一组食谱相关联,并且它将提供烹饪建议并回答与烹饪相关的问题。食谱搜索将是一个由 Gemini 提供支持的搜索引擎,这次它将基于 BigQuery 食谱数据库。

如果您在练习中遇到任何代码问题,可以在练习 GitHub 代码库的 solution 分支中找到所有代码文件的解决方案。

目标

在本实验中,您将学习如何执行以下任务:

  • 激活和使用 Gemini Cloud Assist
  • 在 Vertex AI Agent Builder 中为烹饪建议聊天机器人创建搜索应用
  • 在 Colab Enterprise 笔记本中加载和清理数据,并借助 Gemini Code Assist 的帮助
  • 在 Vertex AI Agent Builder 中为食谱生成器创建搜索应用
  • 在 Gemini 的帮助下,构建核心 Python 和 Streamlit Web 应用框架
  • 将 Web 应用部署到 Cloud Run
  • 将“烹饪建议”页面连接到我们的食谱搜索 Agent Builder 应用
  • (可选)将食谱搜索页面连接到食谱搜索 Agent Builder 应用
  • (可选)探索最终应用

2. 设置和要求

点击“开始实验”按钮前的注意事项

请阅读以下说明。实验有时间限制,且无法暂停。您点击“开始实验”后,计时器即开始计时,显示 Google Cloud 资源可供您使用多长时间。

Qwiklabs 实操实验可让您在真实的云环境中开展实验活动,免受模拟或演示环境的局限。为此,我们会向您提供新的临时凭据,您可以在该实验的规定时间内通过此凭据登录和访问 Google Cloud。

所需条件

为完成此实验,您需要:

  • 能够使用标准的互联网浏览器(建议使用 Chrome 浏览器)。
  • 为完成实验留出时间。

注意:如果您已有自己的个人 Google Cloud 账号或项目,请不要在此实验中使用。

注意:如果您使用的是 Pixelbook,请在无痕式窗口中运行此实验。

如何开始实验并登录 Google Cloud 控制台

  1. 点击“开始实验”按钮。如果该实验需要付费,系统会打开一个弹出式窗口供您选择支付方式。左侧面板中包含您在进行本实验时必须使用的临时凭证。

52e0878388c0d9ed.png

  1. 复制用户名,然后点击“打开 Google 控制台”。该实验会启动资源并打开另一个标签页,显示“登录”页面。

2a4b7165afebf5ab.png

提示:请在不同的窗口中打开标签页,让它们并排显示。

如果您看到“选择账号”页面,请点击“使用其他账号”。

6463aa9b492a3b60.png

  1. 登录页面中,粘贴您从“连接详情”面板复制的用户名,然后复制并粘贴相应的密码。

重要提示:您必须使用“连接详情”面板中的凭据,不能使用您的 Qwiklabs 凭据。如果您拥有自己的 Google Cloud 账号,请不要在此实验中使用,以免产生费用。4. 继续在后续页面中点击以完成相应操作:

  1. 接受条款及条件。
  2. 由于这是临时账号,请勿添加账号恢复选项或双重身份验证。
  3. 请勿注册免费试用。

片刻之后,系统会在此标签页中打开 Cloud 控制台。

注意:您可以点击左上角的导航菜单来查看列有 Google Cloud 产品和服务的菜单。

bbdc8ea800bf0adc.png

3. 任务 0. 检查工作站集群

在本实验的后续部分中,您将使用 Google Cloud Workstation 完成一些开发工作。本实验的启动流程应已开始创建工作站的集群。在继续之前,我们先确保集群正在构建。

  1. 在 Google Cloud 控制台中,使用搜索框前往 Cloud Workstations
  2. 使用左侧导航菜单查看集群管理
  3. 如果您的集群处于“正在更新”状态,则可以继续执行任务 1。如果您没有看到任何处于任何状态的集群,请刷新页面。如果您仍然没有看到集群正在更新(构建),请使用这些说明左上角的按钮结束实验,然后重新开始实验。

4. 任务 1. 激活和使用 Gemini Cloud Assist

在此任务中,我们将激活并使用 Gemini Cloud Assist。在 Google Cloud 控制台中工作时,Gemini Cloud Assist 可以提供建议,帮助您构建、配置和监控 Google Cloud 基础架构,甚至可以建议 gcloud 命令并编写 Terraform 脚本。

  1. 如需激活 Cloud Assist 以供使用,请点击 Cloud 控制台界面顶部的搜索框,然后选择问问 Gemini(或问问 Gemini - 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 Web 应用而被屏蔽,只需跳过此步骤并继续操作即可。这不会影响您完成本练习。

5. 任务 2. 在 Vertex AI Agent Builder 中为烹饪建议聊天机器人创建搜索应用

我们将构建的网站会包含一个烹饪建议页面,其中包含一个聊天机器人,旨在帮助用户找到与烹饪相关的问题的答案。该应用将由 Gemini 提供支持,并以包含 70 本公共领域食谱的来源为基础。食谱将作为 Gemini 回答问题时使用的可信来源。

  1. 使用 Cloud 控制台搜索框前往 Vertex AI。在信息中心内,点击启用所有推荐的 API。如果您看到一个弹出式框,提示 Vertex AI API 本身需要启用,请也启用它。
  2. 使用搜索功能前往 Agent Builder,然后点击继续并激活 API
  3. 正如 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 支持多种应用类型,而数据存储区是每种应用类型的可靠来源。搜索应用非常适合一般用途和搜索。聊天应用适用于 Dataflow 驱动的聊天机器人/语音聊天机器人应用中的生成式流程。推荐应用有助于创建更好的推荐引擎。而 Agent 应用则用于创建由生成式 AI 驱动的智能体。最终,Agent 可能会在我们需要完成的任务方面为我们提供最佳服务,但由于该产品目前处于预览阶段,我们将继续使用“搜索”应用类型。7. 使用左侧菜单前往应用,然后点击创建应用。8. 选择搜索应用类型。检查但不更改各种选项。为应用命名:cookbook-search修改,并将应用 ID 设置为 cookbook-search-id。将公司设置为 Google,然后点击继续。9. 选中您在几个步骤前创建的 old-cookbooks 数据存储区,然后创建搜索应用。

如果您查看活动标签页,可能会看到食谱仍在导入和编入索引。Agent Builder 需要 5 分钟以上的时间来为我们提供给它的 70 本食谱中的数千个页面编制索引。在等待期间,我们来加载并清理一些食谱数据库数据,以供食谱生成器使用。

6. 任务 3. 在 Colab Enterprise 笔记本中加载和清理数据,并借助 Gemini Code Assist 完成此任务

Google Cloud 提供了多种主要方式来处理 Jupyter 笔记本。我们将使用 Google 的最新产品 Colab Enterprise。部分用户可能熟悉 Google 的 Colab 产品,个人和组织通常会使用该产品在免费环境中试用 Jupyter 笔记本。Colab Enterprise 是一项商业 Google Cloud 产品,可与 Google 的其他云产品完全集成,并充分利用 GCP 环境的安全性和合规性功能。

Colab Enterprise 提供的一项功能是与 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 键以查看浅灰色的建议代码。再次按 Tab 键接受建议。如果建议不包含 head() 函数调用,请添加该调用。
df = pd.read_csv('gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv')
df.head()
  1. 点击第一个代码单元格(您在其中导入了 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。

  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. 移除 sourceNER 列,并使用 head() 查看前几行。再次让 Gemini 帮忙。运行最后两行代码并检查结果。
# 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 表示小)的新 DataFrame 中。
# Sample out 150,000 records into a DataFrame named dfs
dfs = df.sample(n=150000)
  1. 我们的食谱源数据已准备好加载到 BigQuery 中。在加载之前,我们先前往 BigQuery 并准备一个用于存放表的数据库。在 Google Cloud 控制台中,使用搜索框前往 BigQuery。您可以右键点击 BigQuery,然后在新的浏览器标签页中打开它。
  2. 如果 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?将结果与以下几个步骤进行比较。

3c38e5975c5c519.png

  1. 在 BigQuery 探索器窗格中,点击项目 ID 旁边的三点状查看操作菜单。然后选择创建数据集

e28c2fc55a04c694.png

  1. 提供数据集和 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'
  1. 使用提示 > 代码方法创建一个代码块,该代码块会将 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 搜索应用的步骤,也可以按照下面列出的步骤操作。

  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.

(是的,我在提示时会说“请”。我妈妈会非常自豪。)

我注意到,其中一个辣椒食谱包含蘑菇,谁会在辣椒里放蘑菇呢?我让 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 Web 应用

在我们的两个 Vertex AI Agent Builder 数据存储区都完成索引编制,并且我们的搜索应用即将准备就绪后,我们开始构建 Web 应用。

我们将在工作时利用 Gemini Code Assist。如需详细了解如何在 Visual Studio Code 中使用 Gemini Code Assist,请点击此处查看相关文档

我们将在 Google Cloud Workstation(一种基于云的开发环境)中进行开发;在本例中,该环境预加载了 Eclipse Theia(开源 Visual Studio Code)。本练习中的自动化脚本已为我们创建了 Cloud Workstations 集群和配置,但我们仍需创建 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. 对于代码库网址,请输入 https://github.com/haggman/recipe-app。将代码库克隆到 user 文件夹中,然后打开克隆的代码库进行编辑。
  2. 在探索克隆的文件夹并开始处理 Web 应用之前,我们需要让编辑器的 Cloud Code 插件登录 Google Cloud,并启用 Gemini。现在我们就开始吧。在编辑器左下角,点击 Cloud Code - Sign in(Cloud Code - 登录)。如果您没有看到该链接,请稍等片刻,然后再次检查。

f4ebfbd96026c0d8.png

  1. 终端窗口将显示一个长网址。在浏览器中打开该网址,然后按照步骤向 Cloud Code 授予对您的 Google Cloud 环境的访问权限。请务必使用练习临时 student-... 账号(而非个人 Google Cloud 账号)进行身份验证。在最终对话框中,复制验证码,然后将其粘贴回 Cloud Workstation 浏览器标签页中等待的终端窗口。
  2. 片刻之后,编辑器左下角的 Cloud Code 链接将变为 Cloud Code - 无项目。点击新链接以选择项目。命令面板应在编辑器顶部打开。点击选择 Google Cloud 项目,然后选择您的 qwiklabs-gcp-... 项目。片刻之后,编辑器左下角的链接会更新为显示您的项目 ID。这表示 Cloud Code 已成功附加到您的工作项目。
  3. 将 Cloud Code 连接到项目后,您现在可以激活 Gemini Code Assist。在编辑器界面的右下角,点击带有删除线的 Gemini 徽标。Gemini Chat 窗格将在编辑器左侧打开。点击选择 Google Cloud 项目。当命令面板打开时,选择您的 qwiklabs-gcp-... 项目。如果您已正确执行这些步骤(并且 Google 没有更改任何内容),那么您现在应该会看到一个活跃的 Gemini 对话窗口。

70e4e06ed6565329.png

  1. 最后,我们来配置编辑器终端窗口。使用汉堡菜单 > 查看 > 终端打开终端窗口。执行 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. 因此,我们将使用 Python 和 Streamlit 构建一个与 Vertex AI 和 Discovery Engine 交互的交互式 Web 应用。目前,我们先重点介绍 Web 应用组件。正如 Gemini 所说,Streamlit 是一个用于在 Python 中构建数据驱动型 Web 应用的框架。现在,请询问:
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?

请注意,我们不必说“of Streamlit”,因为 Gemini 对话是对话式(多轮)的。由于我们处于聊天会话中,因此 Gemini 知道我们一直在讨论什么。如果您想随时彻底清除 Gemini 对话记录,请使用 Gemini 代码对话窗口顶部的回收站图标。

9. 任务 6:将 Web 应用部署到 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?

这两组建议是否相同?您是否同意/不同意任何建议?请注意,Gemini 是一款生成式 AI 助理,与人类助理一样,您可能并不总是赞同它所说的一切。不过,在 Google Cloud 和代码编辑器中工作时,始终有这样一位助手在您身边,可以大大提高您的效率。

  1. 对于无状态的短期容器化 Web 应用,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("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!