使用 Agent Development Kit (ADK) 建構 AI 代理,並部署至 Cloud Run

Agent Development Kit (ADK) 框架可簡化 AI 代理的建立、評估和部署作業。ADK 採用模組化、以程式碼為優先的做法,可建構能推論、規劃及使用工具的代理。

本教學課程說明如何使用 Python 適用的 ADK,建構 AI 代理並部署至 Cloud Run。這個代理會擷取指定城市的天氣報告。

如要進一步瞭解如何使用 Google Cloud CLI 代管 ADK 代理,請參閱 ADK 說明文件的「部署至 Cloud Run」一節。

目標

費用

在本文件中,您會使用下列 Google Cloud計費元件:

您可以使用 Pricing Calculator,根據預測用量估算費用。

初次使用 Google Cloud 的使用者可能符合免費試用期資格。

事前準備

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  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. 啟用 Cloud Run Admin API、Vertex AI API 和 Cloud Build API (如有尚未啟用的 API)。

    啟用 API 所需的角色

    如要啟用 API,您必須具備 serviceusage.services.enable 權限。如果您建立了專案,可能已透過擁有者角色 (roles/owner) 取得這項權限。否則,您可以透過服務使用情形管理員角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    啟用 API

  7. 在 Google Cloud 專案中設定 Cloud Run 開發環境。
  8. 按照 Agent Development Kit 說明文件中的指示安裝 ADK。
  9. 如果您的專案受到網域限制組織政策限制,無法進行未經驗證的叫用,則必須按照「測試私人服務」一節所述的方式存取已部署的服務。

必要的角色

如要取得將 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: 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 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 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

刪除教學課程資源

  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