1. 概览
在本实验中,您将使用 Google 的生成式 AI 产品,借助 Gemini Cloud Assist 在 Google Cloud 中构建基础架构,使用 Data Canvas 的自然语言 SQL 功能查询 BigQuery 数据,借助 Gemini Code Assist 在 Colab Enterprise Jupyter 笔记本和 Eclipse Theia(Visual Studio Code)中编写代码,并在 Vertex AI Agent Builder 中集成基于 Cloud Storage 和 BigQuery 基础来源构建的 AI 搜索和聊天功能。
我们的目标是创建一个名为 AI Recipe Haven 的食谱和烹饪网站。该网站将使用 Python 和 Streamlit 构建,并包含两个主要页面。Cooking Advice 将托管一个聊天机器人,我们将使用 Gemini 和与一组食谱相关联的 Vertex AI Agent Builder 基础来源来创建该聊天机器人,它将提供烹饪建议并回答烹饪相关问题。食谱搜索将成为由 Gemini 提供数据的搜索引擎,这次基于 BigQuery 食谱数据库。
如果您在本练习中的任何代码上遇到问题,请前往练习 GitHub 代码库中的 solution 分支,查看所有代码文件的解决方案。
目标
在本实验中,您将学习如何执行以下任务:
- 激活和使用 Gemini Cloud Assist
- 在 Vertex AI Agent Builder 中为烹饪建议聊天机器人创建一个搜索应用
- 借助 Gemini Code Assist,在 Colab Enterprise 笔记本中加载和清理数据
- 在 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 控制台
- 点击“开始实验”按钮。如果该实验需要付费,系统会打开一个弹出式窗口供您选择付款方式。左侧面板中包含您在进行该实验时必须使用的临时凭据。
- 复制用户名,然后点击“打开 Google 控制台”。该实验会启动资源并打开另一个标签页,显示“登录”页面。
提示:请在单独的窗口打开标签页,让它们并排显示。
如果您看到“选择账号”页面,请点击“使用其他账号”。
- 在登录页面中,粘贴您从“连接详情”面板复制的用户名,然后复制并粘贴相应的密码。
重要提示:您必须使用“连接详情”面板中的凭据,不能使用您的 Qwiklabs 凭据。如果您拥有自己的 Google Cloud 账号,请不要在此实验中使用,以免产生费用。4. 继续在后续页面中点击以完成相应操作:
- 接受条款及条件。
- 由于这是临时账号,请勿添加账号恢复选项或双重验证。
- 请勿注册免费试用。
片刻之后,系统会在此标签页中打开 Cloud 控制台。
注意:您可以点击左上角的“导航”菜单,查看列有 Google Cloud 产品和服务的菜单。
3. 任务 0. 检查您的工作站集群
在本实验的后续部分,您将使用 Google Cloud 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 控制台界面顶部的搜索框,然后选择 Ask Gemini(或 Ask Gemini for Cloud console)。
- 滚动到该页面的“必需的 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 Web 版应用,请直接跳过此步骤。这不会影响您完成此练习。
5. 任务 2. 在 Vertex AI Agent Builder 中为烹饪建议聊天机器人创建搜索应用
我们正在构建的网站将有一个烹饪建议页面,其中包含一个聊天机器人,旨在帮助用户找到烹饪相关问题的答案。它将由 Gemini 提供支持,其数据源包含 70 本公共领域食谱。这些食谱将成为 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 支持多种应用类型,而数据存储区则充当每种应用的真相来源。搜索应用适合一般使用和搜索。Chat 应用适用于 Dataflow 驱动的聊天机器人/语音聊天机器人应用中的生成式流程。推荐应用有助于打造更出色的推荐引擎。代理应用用于创建由生成式 AI 驱动的代理。最终,智能助理可能最适合我们要做的事,但由于该产品目前处于预览阶段,我们将继续使用搜索应用类型。7. 使用左侧菜单前往应用,然后点击创建应用。选择“搜索”应用类型。查看但不要更改各种选项。为应用命名:cookbook-search
。修改,然后将应用 ID 设置为 cookbook-search-id
。将公司设置为 Google
,然后点击继续。9. 检查您在前几个步骤中创建的 old-cookbooks
数据存储区,然后创建搜索应用。
如果您查看活动标签页,可能会发现食谱集仍在导入和编入索引。Agent Builder 需要 5 分钟以上的时间才能为我们提供的 70 本食谱中包含的数千个网页编制索引。在等待期间,我们来为食谱生成器加载并清理一些食谱数据库数据。
6. 任务 3. 借助 Gemini Code Assist 在 Colab Enterprise 笔记本中加载和清理数据
Google Cloud 提供了几种主要方式来使用 Jupiter 笔记本。我们将使用 Google 的最新产品 Colab Enterprise。有些人可能熟悉 Google 的 Colab 产品,该产品通常由希望在免费环境中试用 Jupiter 笔记本的个人和组织使用。Colab Enterprise 是一款 Google Cloud 商用产品,与 Google 的其他云产品完全集成,可充分利用 GCP 环境的安全和合规性功能。
Colab Enterprise 提供的一项功能是与 Google 的 Gemini 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 Assistant 生成的代码。如果您在生成的建议上方看到 Python 关键字的自动补全下拉列表,请按 Escape 键以查看浅灰色的建议代码。再次按 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 中的单元格。等待文件加载,然后检查前五行数据。这是我们将加载到 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 中的索引编制过程可能需要太长时间。作为折中方案,我们抽取 15 万个食谱来进行处理。使用提示 > 代码方法获取样本,并将其存储在名为
dfs
(小写字母 s)的新 DataFrame 中。
# Sample out 150,000 records into a DataFrame named dfs
dfs = df.sample(n=150000)
- 我们的食谱来源数据已准备好加载到 BigQuery 中。在加载数据之前,我们先前往 BigQuery 准备一个数据集来存放我们的表。在 Google Cloud 控制台中,使用搜索框前往 BigQuery。您可以右键点击 BigQuery,然后在新浏览器标签页中打开它。
- 如果您还没有看到该面板,请使用 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?
将结果与以下几个步骤进行比较。
- 在 BigQuery 的“探索器”窗格中,点击项目 ID 旁边的三点状图标 View actions(查看操作)菜单。然后选择创建数据集。
- 提供
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'
- 使用提示 > 代码方法创建一个代码块,用于将 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 数据存储类型。
- 在表格选择单元格中,按 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 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 Web 应用
现在,我们的两个 Vertex AI Agent Builder 数据存储区都已编制索引,我们的搜索应用也即将发布,接下来我们来构建 Web 应用。
我们将在工作中利用 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
文件夹中,然后打开克隆的代码库进行修改。 - 在浏览克隆的文件夹并开始处理 Web 应用之前,我们需要让编辑器的 Cloud Code 插件登录 Google Cloud,并启用 Gemini。现在就开始吧。在编辑器的左下角,点击 Cloud Code - Sign in(Cloud Code - 登录)。如果您没有看到链接,请稍等片刻,然后重新检查。
- 终端窗口会显示一个长网址。在浏览器中打开该网址,然后按照相应步骤向 Cloud Code 授予对您 Google Cloud 环境的访问权限。请务必使用您的演练临时
student-...
账号(而非个人 Google Cloud 账号)进行身份验证。在最终对话框中,复制验证码,然后将其粘贴回 Cloud Workstation 浏览器标签页中的等待终端窗口。 - 几秒钟后,编辑器左下角的 Cloud Code 链接将更改为 Cloud Code - No Project(Cloud Code - 无项目)。点击新的链接以选择项目。命令面板应会在编辑器顶部打开。点击选择 Google Cloud 项目,然后选择您的 qwiklabs-gcp-... 项目。几秒钟后,编辑器左下角的链接将更新为显示您的项目 ID。这表示 Cloud Code 已成功附加到您的工作项目。
- 将 Cloud Code 关联到您的项目后,您现在可以激活 Gemini Code Assist。点击编辑器界面右下角带有删除线的 Gemini 徽标。Gemini Chat 窗格会在编辑器左侧打开。点击选择 Google Cloud 项目。当命令面板打开时,选择您的 qwiklabs-gcp-... 项目。如果您已正确按照步骤操作(并且 Google 未更改任何设置),那么您现在应该会看到一个处于活动状态的 Gemini Chat 聊天窗口。
- 最后,我们来对编辑器终端窗口进行相同的配置。依次选择汉堡菜单 > 视图 > 终端以打开终端窗口。执行
gcloud init
。再次使用该链接,允许 Cloud Shell 终端对您的qwiklabs-gcp-...
项目执行操作。出现提示时,选择qwiklabs-gcp-...
项目的数字选项。 - 太棒了,终端、Gemini Chat 和 Cloud Code 配置已全部设置完毕,现在打开 Explorer 标签页,花几分钟时间探索当前项目中的文件。
- 在资源管理器中,打开
requirements.txt
文件进行修改。切换到 Gemini 聊天窗格,然后询问:
From the dependencies specified in the requirements.txt file, what type of application are we building?
- 我们将使用 Python 和 Streamlit 构建一个交互式 Web 应用,该应用可与 Vertex AI 和 Discovery Engine 进行交互,太棒了。目前,我们主要关注 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
获得更好的回答?
- 我们来详细了解一下 Streamlit:
What can you tell me about Streamlit?
太棒了,我们可以看到 Gemini 提供了一个不错的概览,包括优点和缺点。
- 如果您想了解缺点,可以问:
What are the major downsides or shortcomings?
请注意,我们无需说“of Streamlit”,因为 Gemini Chat 是会话式(多轮对话)的。由于我们正在进行聊天会话,Gemini 知道我们一直在讨论什么。如需随时清除 Gemini 聊天记录,请使用 Gemini 代码聊天窗口顶部的回收站图标。
9. 任务 6:将 Web 应用部署到 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?
这两组建议是否相同?您是否赞同/不赞同其中的任何建议?请注意,Gemini 是一款生成式 AI 助理,就像真人助理一样,您并不一定会同意它所说的每一件事。不过,在 Google Cloud 和代码编辑器中工作时,如果有这样一个助手随时随地为您提供帮助,可以让您更高效地工作。
- 对于无状态的短时容器化 Web 应用,Cloud Run 是一个绝佳之选。在代码编辑器的 Gemini Chat 窗口中,试用以下提示:
What steps would be required to run this application in
Cloud Run?
- 我们首先需要创建一个 Dockerfile。使用编辑器在项目文件夹的根目录中创建一个名为
Dockerfile
的文件。请确保您没有意外将其放入“Pages”文件夹中。打开文件进行修改。 - 我们来使用 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.
How can I use gcloud to create a docker registry in Artifact Registry?(如何使用 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!