快速入门:使用智能体开发套件 (ADK) 构建 AI 智能体并将其部署到 Cloud Run
了解如何使用单个命令,通过适用于 Python 的 智能体开发套件 (ADK) 构建 AI 智能体并将其部署到 Cloud Run 。您部署的智能体可检索您指定的城市的天气预报。
按照本快速入门中的步骤操作时,Cloud Run 会自动 为您构建 Dockerfile,以便您从源代码进行部署。
如需详细了解 Python Buildpack 如何确定 Cloud Run 源代码部署的默认 入口点,请参阅 构建 Python 应用。
准备工作
- 登录您的 Google Cloud 账号。如果您是 Google Cloud新手, 请创建一个账号来评估我们的产品在 实际场景中的表现。新客户还可获享 $300 赠金,用于 运行、测试和部署工作负载。
-
安装 Google Cloud CLI。
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init -
选择或创建项目所需角色
- 选择项目:选择项目不需要特定的 IAM 角色,您可以选择已获授予角色的任何项目。
-
创建项目:如需创建项目,您需要拥有 Project Creator 角色
(
roles/resourcemanager.projectCreator),该角色包含resourcemanager.projects.create权限。了解如何授予 角色。
-
创建 Google Cloud 项目:
gcloud projects create PROJECT_ID
将
PROJECT_ID替换为您要创建的 Google Cloud 项目名称。 -
选择您创建的 Google Cloud 项目:
gcloud config set project PROJECT_ID
将
PROJECT_ID替换为您的 Google Cloud 项目名称。
-
如果您要使用现有项目来完成本指南, 请验证您是否拥有完成本指南所需的权限。如果您创建了新项目, 则您已拥有所需的权限。
-
验证是否已为您的 Google Cloud 项目启用结算功能。
-
安装 Google Cloud CLI。
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init -
选择或创建项目所需角色
- 选择项目:选择项目不需要特定的 IAM 角色,您可以选择已获授予角色的任何项目。
-
创建项目:如需创建项目,您需要拥有 Project Creator 角色
(
roles/resourcemanager.projectCreator),该角色包含resourcemanager.projects.create权限。了解如何授予 角色。
-
创建 Google Cloud 项目:
gcloud projects create PROJECT_ID
将
PROJECT_ID替换为您要创建的 Google Cloud 项目名称。 -
选择您创建的 Google Cloud 项目:
gcloud config set project PROJECT_ID
将
PROJECT_ID替换为您的 Google Cloud 项目名称。
-
如果您要使用现有项目来完成本指南, 请验证您是否拥有完成本指南所需的权限。如果您创建了新项目, 则您已拥有所需的权限。
-
验证是否已为您的 Google Cloud 项目启用结算功能。
-
启用 Cloud Run Admin API、Vertex AI API 和 Cloud Build API:
启用 API 所需的角色
如需启用 API,您需要拥有 Service Usage Admin IAM 角色 (
roles/serviceusage.serviceUsageAdmin),该角色包含serviceusage.services.enable权限。了解如何授予 角色。gcloud services enable run.googleapis.com
aiplatform.googleapis.com cloudbuild.googleapis.com - 按照智能体开发套件文档中的说明安装 ADK。
- 查看 Cloud Run 价格或使用价格计算器估算费用。
所需的角色
如需获得完成本教程所需的权限,请让您的管理员为您授予以下 IAM 角色:
-
项目的 Cloud Run Source Developer (
roles/run.sourceDeveloper) 角色 -
项目的 Vertex AI User (
roles/aiplatform.user) 角色 -
服务身份的 Service Account User (
roles/iam.serviceAccountUser) 角色 -
项目的 Logs Viewer (
roles/logging.viewer) 角色
如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。
授予 Cloud Build 服务账号对项目的访问权限
除非您替换此行为,否则 Cloud Build 会自动使用 Compute Engine 默认服务账号作为默认 Cloud Build 服务账号来构建源代码和 Cloud Run 资源。
为了让 Cloud Build 能够构建来源,请向 Cloud Build 服务账号授予项目的 Cloud Run Builder (roles/run.builder) 角色:
gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS \ --role=roles/run.builder
将 PROJECT_ID 替换为您的 Google Cloud项目 ID,并将 SERVICE_ACCOUNT_EMAIL_ADDRESS 替换为 Cloud Build 服务账号的邮箱。如果您使用 Compute Engine 默认服务账号作为 Cloud Build 服务账号,则服务账号邮箱应采用以下格式:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
将 PROJECT_NUMBER 替换为您的 Google Cloud项目编号。
如需详细了解如何查找项目 ID 和项目编号,请参阅创建和管理项目。
授予 Cloud Run Builder 角色之后,需要几分钟时间才能完成传播。
编写示例应用
如需使用 Python 编写应用,请执行以下操作:
创建一个名为
parent_folder的新父级目录,并转到此目录中:mkdir parent_folder cd parent_folder在
parent_folder目录中,创建一个名为multi_tool_agent的新子目录,并转到此目录中:mkdir multi_tool_agent cd multi_tool_agent创建一个
__init__.py文件以导入智能体:from . import agent创建一个
agent.py文件,用于定义智能体,以回答有关指定城市的时间和天气的问题:import datetime from zoneinfo import ZoneInfo from google.adk.agents import Agent def get_weather(city: str) -> dict: """Retrieves the current weather report for a specified city. Args: city (str): The name of the city for which to retrieve the weather report. Returns: dict: status and result or error msg. """ if city.lower() == "new york": return { "status": "success", "report": ( "The weather in New York is sunny with a temperature of 25 degrees" " Celsius (77 degrees Fahrenheit)." ), } else: return { "status": "error", "error_message": f"Weather information for '{city}' is not available.", } def get_current_time(city: str) -> dict: """Returns the current time in a specified city. Args: city (str): The name of the city for which to retrieve the current time. Returns: dict: status and result or error msg. """ if city.lower() == "new york": tz_identifier = "America/New_York" else: return { "status": "error", "error_message": ( f"Sorry, I don't have timezone information for {city}." ), } tz = ZoneInfo(tz_identifier) now = datetime.datetime.now(tz) report = ( f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}' ) return {"status": "success", "report": report} root_agent = Agent( name="weather_time_agent", model="gemini-2.0-flash", description=( "Agent to answer questions about the time and weather in a city." ), instruction=( "You are a helpful agent who can answer user questions about the time and weather in a city." ), tools=[get_weather, get_current_time], )创建一个
.env文件并添加以下变量:GOOGLE_GENAI_USE_VERTEXAI=TRUE GOOGLE_CLOUD_PROJECT=PROJECT_ID GOOGLE_CLOUD_LOCATION=REGION替换以下内容:
- PROJECT_ID:项目 ID。 Google Cloud
- REGION:您计划在其中部署服务的区域。
导航到父级文件夹目录
parent_folder,并创建一个requirements.txt文件以添加google-adk依赖项:google-adk您的源项目包含以下结构:
parent_folder/ ├── requirements.txt └── multi_tool_agent/ ├── __init__.py ├── agent.py └── .env
您的应用已编写完毕,可以进行部署。
从源代码部署到 Cloud Run
从源代码部署会自动从源代码构建容器映像并进行部署。
在源代码目录 (
parent_folder) 中,使用以下命令部署到 Cloud Run:gcloud run deploy --source .
当系统提示您输入服务名称时,请按 Enter 键接受默认名称,例如
weather-agent。如果系统提示您对项目启用其他 API(例如 Artifact Registry API),请按
y进行响应。当系统提示您输入区域时:请选择您选择的区域 ,例如
europe-west1。如果系统提示您在指定区域中创建仓库,请按
y进行响应。如果系统提示您允许公开访问,请回复
y。如果有网域限制组织政策阻止此提示,您可能不会看到此提示;如需了解详情,请参阅准备工作部分。
然后等待部署完成。成功完成时,命令行会显示服务网址。从服务网址导航到
/list-apps。例如,https://weather-agent-123456789101.us-central1.run.app/list-apps。
运行智能体
如需查询 ADK 智能体,请运行以下 curl 命令:
如需获取应用列表,请运行以下命令:
curl -X GET SERVICE_URL/list-apps将 SERVICE_URL 替换为已部署服务的网址。
如需启动会话,请运行以下命令:
curl -X POST SERVICE_URL/apps/multi_tool_agent/users/u_123/sessions/s_123 -H "Content-Type: application/json" -d '{"key1": "value1", "key2": 42}'如需查询智能体,请运行以下命令:
curl -X POST SERVICE_URL/run \ -H "Content-Type: application/json" \ -d "{\"appName\": \"multi_tool_agent\",\"userId\": \"u_123\",\"sessionId\": \"s_123\",\"newMessage\": { \"role\": \"user\", \"parts\": [{ \"text\": \"What's the weather in New York today?\" }]}}"
智能体会在查询结果中返回天气信息。
如需详细了解受支持的 curl 命令并查看相关示例,请参阅 ADK 文档中的使用 API 服务器。
清理
为避免您的 Google Cloud 账号产生额外费用,请删除您在本快速入门中部署的所有资源。
删除仓库
当您部署的服务未使用时,Cloud Run 不会向您收费。不过,您可能仍需要支付将容器映像存储在 Artifact Registry 中而产生的相关费用。如需删除 Artifact Registry 仓库,请按照 Artifact Registry 文档中删除仓库的步骤操作。
删除服务
Cloud Run 服务在收到请求之前不会产生费用。如需删除 Cloud Run 服务,请按照以下步骤之一操作:
控制台
要删除服务,请执行以下操作:
在 Google Cloud 控制台中,前往 Cloud Run 服务页面:
在服务列表中找到要删除的服务,然后点击该服务对应的复选框以将其选中。
点击删除。这将删除服务的所有修订版本。这将删除服务的所有修订版本。
gcloud
要删除作业,请运行以下命令:
gcloud run services delete SERVICE --region REGION
替换以下内容:
- SERVICE:服务的名称。
- REGION: Google Cloud 服务的区域。
删除测试项目
删除您的 Google Cloud 项目后,系统即会停止对该 项目中的所有资源计费。如需释放项目中的所有 Google Cloud 资源,请按照以下步骤操作:
删除项目: Google Cloud
gcloud projects delete PROJECT_ID
后续步骤
如需详细了解如何使用代码源构建容器并推送到仓库,请参阅: