1. 简介
此 Codelab 演示了如何调用一个 Cloud Functions 函数,该函数会初始化 Vertex AI 模块,然后提供一个端点来调用 PaLM Text Bison 模型。此 Cloud Functions 函数是用 Python 编写的。以下是所用服务的列表:
- Cloud Functions
- Vertex AI PaLM API
构建内容
您将创建并部署一个 Cloud Functions 函数,该函数提供一个用于调用 PaLM Text Bison 模型的端点。
2. 要求
3. 准备工作
- 在 Google Cloud 控制台的项目选择器页面上,选择或创建一个 Google Cloud 项目
- 确保您的 Google Cloud 项目已启用结算功能。了解如何检查项目是否已启用结算功能
- 按照此处的说明从 Google Cloud 控制台激活 Cloud Shell
- 如果项目未设置,请使用以下命令进行设置:
gcloud config set project <YOUR_PROJECT_ID>
- 在 Cloud Shell 中,设置以下环境变量:
export GCP_PROJECT=<YOUR_PROJECT_ID>
export GCP_REGION=us-central1
- 在 Cloud Shell 终端中执行以下命令,以启用必要的 Google Cloud API:
gcloud services enable cloudbuild.googleapis.com cloudfunctions.googleapis.com run.googleapis.com logging.googleapis.com storage-component.googleapis.com aiplatform.googleapis.com
4. 部署 Cloud Functions 函数
如需创建和部署 Cloud Functions 函数,请按以下步骤操作:
- 在 Cloud Shell 终端中执行以下命令,从代码库 https://github.com/rominirani/genai-apptemplates-googlecloud 克隆代码:
git clone https://github.com/rominirani/genai-apptemplates-googlecloud
- 此命令会将代码库内容克隆到 genai-templates-googlecloud 文件夹中。
- 在 Cloud Shell 终端中执行以下命令,前往我们关心的项目的文件夹:
cd genai-apptemplates-googlecloud/text-predict-cloudfunction
- 您应该会看到 text-predict-cloudfunction 文件夹中包含 main.py 和 requirements.txt 这两个文件,您可以通过执行 dir 命令或前往 Cloud Shell 编辑器来查看。
- 如需部署 Cloud Functions 函数,请运行 gcloud functions deploy 命令:
gcloud functions deploy predictText --gen2 --runtime=python311 --region=$GCP_REGION --source=. --entry-point=predictText --trigger-http --set-env-vars=GCP_PROJECT=$GCP_PROJECT,GCP_REGION=$GCP_REGION --allow-unauthenticated --max-instances=1
部署 Cloud Functions 函数后,Cloud Shell 终端上会显示已部署的 Cloud Functions 函数的网址。网址的格式如下:
https://$GCP_REGION-$GCP_PROJECT.cloudfunctions.net/predictText
5. 调用 Cloud Functions 函数
由于此 Cloud Functions 函数是使用 HTTP 触发器部署的,因此您可以直接调用它。以下是调用示例:
curl -m 70 -X POST https://$GCP_REGION-$GCP_PROJECT.cloudfunctions.net/predictText \
-H "Content-Type: application/json" \
-d '{
"prompt": "What are the best places to visit in the United States?"
}'
输出结果如下所示:

6. 清理
为避免系统因本博文中使用的资源向您的 Google Cloud 账号收取费用,请按照以下步骤操作:
- 在 Google Cloud 控制台中,前往管理资源页面。
- 在项目列表中,选择要删除的项目,然后点击删除。
- 在对话框中输入项目 ID,然后点击关停以删除项目。
- 如果您想保留项目,请跳过上述步骤,然后前往 Cloud Functions,从函数列表中选中要删除的 Cloud Functions 函数,然后点击“删除”以删除该函数。
7. 恭喜
恭喜!您已成功使用封装 PaLM Text Bison 模型的 Cloud Functions 函数。如需详细了解可用模型,请参阅 Vertex AI LLM 产品文档。