快速入門導覽課程:使用 Agent Development Kit (ADK) 建構 AI 代理並部署至 Cloud Run
瞭解如何使用 Python 版 Agent Development Kit (ADK),透過單一指令在 Cloud Run 建構及部署 AI 代理。您部署的代理程式會擷取指定城市的天氣報告。
按照本快速入門導覽課程的步驟操作,Cloud Run 會在您從原始碼部署時,自動為您建構 Dockerfile。
如要進一步瞭解 Python 建構包如何判斷 Cloud Run 來源部署作業的預設進入點,請參閱「建構 Python 應用程式」。
事前準備
- 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
-
安裝 Google Cloud CLI。
-
若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。
-
執行下列指令,初始化 gcloud CLI:
gcloud init -
選取或建立專案所需的角色
- 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
-
建立專案:如要建立專案,您需要具備專案建立者角色 (
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 CLI。
-
若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。
-
執行下列指令,初始化 gcloud CLI:
gcloud init -
選取或建立專案所需的角色
- 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
-
建立專案:如要建立專案,您需要具備專案建立者角色 (
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 專案名稱。
-
如要使用現有專案進行本指南中的操作,請確認您具有完成本指南所需的權限。如果您建立新專案,則已具備必要權限。
-
啟用 Cloud Run Admin API、Vertex AI API 和 Cloud Build API:
啟用 API 時所需的角色
如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (
roles/serviceusage.serviceUsageAdmin),其中包含serviceusage.services.enable權限。瞭解如何授予角色。gcloud services enable run.googleapis.com
aiplatform.googleapis.com cloudbuild.googleapis.com - 請按照Agent Development Kit 說明文件中的指示安裝 ADK。
- 查看 Cloud Run 定價,或使用 Pricing Calculator 估算費用。
必要的角色
如要取得完成本快速入門導覽課程所需的權限,請要求管理員授予您下列 IAM 角色:
-
Cloud Run 原始碼開發人員 (
roles/run.sourceDeveloper) 專案 -
Vertex AI 使用者 (
roles/aiplatform.user) 專案 -
服務帳戶使用者 (
roles/iam.serviceAccountUser) 服務身分 -
專案的記錄檢視器 (
roles/logging.viewer)
如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
授予 Cloud Build 服務帳戶專案存取權
除非您覆寫這項行為,否則 Cloud Build 會自動使用 Compute Engine 預設服務帳戶做為預設的 Cloud Build 服務帳戶,建構您的原始碼和 Cloud Run 資源。
如要讓 Cloud Build 建構來源,請將專案的 Cloud Run 建構工具 (roles/run.builder) 角色授予 Cloud Build 服務帳戶:
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 建構人員角色後,需要幾分鐘才能傳播。
編寫範例應用程式
如要使用 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: Google Cloud 專案 ID。
- 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「Services」(服務) 頁面:
在服務清單中找出您要刪除的服務,然後按一下核取方塊來選取。
按一下「Delete」(刪除)。如此便會刪除服務的所有修訂版本。
gcloud
如要刪除服務,請執行下列指令:
gcloud run services delete SERVICE --region REGION
更改下列內容:
- SERVICE:服務名稱。
- REGION:服務的 Google Cloud 區域。
刪除測試專案
刪除 Google Cloud 專案後,系統就會停止對該專案中的所有資源收取費用。如要釋出專案中的所有 Google Cloud 資源,請按照下列步驟操作:
刪除 Google Cloud 專案:
gcloud projects delete PROJECT_ID
後續步驟
如要進一步瞭解如何從程式碼來源建構容器並推送至存放區,請參閱: