使用智能体开发套件 (ADK) 构建 AI 智能体并将其部署到 Cloud Run

智能体开发套件 (ADK) 框架简化了 AI 智能体的创建、评估和部署流程。ADK 提供了一种模块化、代码优先的方法来构建能够推理、规划和利用工具的智能体。

本教程介绍了如何使用 ADK for Python 构建 AI 智能体并将其部署到 Cloud Run。此智能体可检索您指定的城市的天气预报。

如需详细了解如何使用 Google Cloud CLI 托管 ADK 智能体,请参阅 ADK 文档中的部署到 Cloud Run

目标

费用

在本文档中,您将使用的以下收费组件: Google Cloud

您可使用 价格计算器 根据您的预计使用情况来估算费用。

新 Google Cloud 用户可能有资格申请免费试用

准备工作

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Google Cloud project.

  3. 启用 Cloud Run Admin API、Vertex AI API 和 Cloud Build API。

    启用 API 所需的角色

    如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您 创建了项目,则可能已通过 所有者角色 (roles/owner) 拥有此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获取此权限。 了解如何授予角色

    启用 API

  4. 在项目中 设置 Cloud Run 开发环境 Google Cloud 。
  5. 按照智能体开发套件文档中的说明安装 ADK。
  6. 如果您通过网域限制组织政策限制项目的未经身份验证的调用,则您需要按照测试专用服务中的说明访问已部署的服务。

所需的角色

如需获得将 AI 智能体部署到 Cloud Run 所需的权限,请让管理员向您授予以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义 角色或其他预定义 角色来获取所需的权限。

编写示例应用

如需使用 Python 编写应用,请执行以下操作:

  1. 创建一个名为 parent_folder 的新父级目录,并转到此目录中:

    mkdir parent_folder
    cd parent_folder
    
  2. parent_folder 目录中,创建一个名为 multi_tool_agent 的新子目录,并转到此目录中:

    mkdir multi_tool_agent
    cd multi_tool_agent
    
  3. 创建一个 __init__.py 文件以导入智能体:

    from . import agent
    
  4. 创建一个 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.5-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],
    )
    
  5. 创建一个 .env 文件,并添加以下变量:

    GOOGLE_GENAI_USE_VERTEXAI=TRUE
    GOOGLE_CLOUD_PROJECT=PROJECT_ID
    GOOGLE_CLOUD_LOCATION=REGION
    

    替换以下内容:

    • PROJECT_ID:项目 ID。 Google Cloud
    • REGION:您计划在其中部署服务的区域。
  6. 导航到父级文件夹目录 parent_folder,并创建一个 requirements.txt 文件以添加 google-adk 依赖项:

    google-adk
    

    您的源项目包含以下结构:

    parent_folder/
    ├── requirements.txt
    └── multi_tool_agent/
        ├── __init__.py
        ├── agent.py
        └── .env
    

您的应用已编写完毕,可以进行部署。

从源代码部署到 Cloud Run

从源代码部署会自动从源代码构建容器映像并进行部署。

  1. 在源代码目录 (parent_folder) 中,使用以下命令部署到 Cloud Run:

    gcloud run deploy --source .
    1. 当系统提示您输入服务名称时,请按 Enter 键接受默认名称,例如 weather-agent

    2. 如果系统提示您对项目启用其他 API(例如 Artifact Registry API),请按 y 进行响应。

    3. 当系统提示您输入区域时:请选择您选择的区域 ,例如 europe-west1

    4. 如果系统提示您在指定区域中创建仓库,请按 y 进行响应。

    5. 如果系统提示您允许公开访问,请回复 y。如果有网域限制组织政策阻止此提示,您可能不会看到此提示;如需了解详情,请参阅准备工作部分。

    然后等待部署完成。成功完成时,命令行会显示已部署智能体的服务网址;其格式如下:https://weather-agent-123456789101.us-central1.run.app/list-apps

运行智能体

如需使用 ADK 智能体,您可以运行以下 curl 命令:

  1. 如需获取应用列表,请运行以下命令:

    curl -X GET SERVICE_URL/list-apps
    

    SERVICE_URL 替换为已部署服务的网址。

  2. 如需启动会话,请运行以下命令:

    curl -X POST SERVICE_URL/apps/multi_tool_agent/users/u_123/sessions/s_123 -H "Content-Type: application/json" -d '{"key1": "value1", "key2": "value2"}'
    
  3. 如需查询智能体,请运行以下命令:

    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 账号产生额外费用,请删除您在本教程中部署的所有资源。

删除项目

如果您为本教程创建了一个新项目,请删除项目。 如果您使用的是某个现有项目,并且需要保留此项目但不保留在本教程中所做的更改,请删除为本教程创建的资源

为了避免产生费用,最简单的方法是删除您为本教程创建的项目。

要删除项目,请执行以下操作:

  1. 在 Google Cloud 控制台中,前往 管理资源 页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击 关闭以删除项目。

删除教程资源

  1. 删除您在本教程中部署的 Cloud Run 服务。Cloud Run 服务在收到请求之前不会产生费用。

    如需删除 Cloud Run 服务,请运行以下命令:

    gcloud run services delete SERVICE-NAME

    SERVICE-NAME 替换为服务的名称。

    您还可以通过Google Cloud 控制台删除 Cloud Run 服务。

  2. 移除您在教程设置过程中添加的 gcloud 默认区域配置:

     gcloud config unset run/region
    
  3. 移除项目配置:

     gcloud config unset project