使用智能体开发套件 (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. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. 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

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

  4. 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

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

  6. Enable the Cloud Run Admin API, Vertex AI API, and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

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

  10. 所需的角色

    如需获得将 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.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],
    )
    
  5. 创建一个 .env 文件并添加以下变量:

    GOOGLE_GENAI_USE_VERTEXAI=TRUE
    GOOGLE_CLOUD_PROJECT=PROJECT_ID
    GOOGLE_CLOUD_LOCATION=REGION
    

    替换以下内容:

    • PROJECT_ID: Google Cloud 项目 ID。
    • 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 beta run deploy --source .
    1. 当系统提示您输入服务名称时,请按 Enter 键接受默认名称,例如 weather-agent

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

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

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

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

    然后等待部署完成。成功完成时,命令行会显示服务网址。通过服务网址前往 /list-apps。例如 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": 42}'
    
  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. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

删除教程资源

  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