1. 本實驗室的目標
在本實作實驗室中,您將建構多代理程式應用程式,根據提示詞生成圖片,並根據提示詞評估圖片。如果生成的圖片不符合提示中的規定,直到生成符合規定的圖片為止,智慧助理都會持續生成圖片。本實作實驗室中的每個代理程式都有單一用途,代理程式會互相合作,以達成整體目標。
課程內容
- 瞭解 ADK 的基本概念,以及如何建立多代理系統。
- 瞭解如何在 GCP 中輕鬆部署及使用代理程式。
- 瞭解 A2A 通訊協定的基本概念
- 瞭解如何搭配使用 A2A 通訊協定和 ADK 建立開放式代理。
2. 事前準備
- 如果沒有可用的專案,請在 GCP 主控台中建立新專案。
- 在本實驗室中,我們將使用 GCP Cloud Shell 執行工作。開啟 Cloud Shell,並使用 Cloud Shell 設定專案。
- 按下 Cloud Shell 編輯器按鈕,開啟 GCP Cloud Shell 編輯器。如果看到「Authorize Shell」(授權 Shell) 彈出式視窗,請按一下授權 Cloud Shell 編輯器。
- 您可以使用下列指令,檢查專案是否已通過驗證。
gcloud auth list
- 在 Cloud Shell 中執行下列指令,確認專案
gcloud config list project
- 如果未設定專案,請使用下列指令設定
gcloud config set project <YOUR_PROJECT_ID>
- 我們需要啟用一些服務才能執行本實驗室。在 Cloud Shell 中執行下列指令。
gcloud services enable aiplatform.googleapis.com
3. 總覽:Agent Development Kit 的優點
Agent Development Kit 為開發人員建構代理應用程式提供多項重要優點:
- 多代理程式系統:在階層中組合多個專門代理程式,建構模組化且可擴充的應用程式。啟用複雜的協調和委派作業。
- 豐富的工具生態系統:為代理提供多元功能:使用預先建構的工具 (搜尋、程式碼執行等)、建立自訂函式、整合第三方代理架構 (LangChain、CrewAI) 的工具,甚至將其他代理當做工具使用。
- 彈性自動化調度管理:使用工作流程代理程式 (
SequentialAgent
、ParallelAgent
和LoopAgent
) 定義工作流程,建立可預測的管道,或運用 LLM 驅動的動態路徑 (LlmAgent
轉移) 實現適應性行為。 - 整合式開發人員體驗:使用功能強大的 CLI 和互動式開發人員 UI,在本機開發、測試及偵錯。逐步檢查事件、狀態和代理程式執行作業。
- 內建評估:根據預先定義的測試案例,評估最終回覆品質和逐步執行軌跡,有系統地評估代理程式效能。
- 部署就緒:將代理程式容器化並部署至任何位置,包括在本機執行、使用 Vertex AI Agent Engine 擴充,或使用 Cloud Run 或 Docker 整合至自訂基礎架構。
其他生成式 AI SDK 或代理程式架構也能讓您查詢模型,甚至為模型提供工具,但您需要投入大量心力,才能在多個模型之間進行動態協調。
與這些工具相比,Agent Development Kit 提供更高層級的架構,可讓您輕鬆將多個代理程式彼此連結,建立複雜但易於維護的工作流程。
4. A2A 簡介
Agent2Agent (A2A) 通訊協定是開放式標準,旨在讓不同架構、供應商和網域的自主式 AI 代理,能夠順暢安全地通訊及協作。
- 普遍互通性:A2A 可讓代理協同運作,不受底層技術限制,進而打造真正的多代理生態系統。也就是說,不同公司在不同平台上建構的代理程式可以通訊及協調。
- 功能探索:代理程式可使用「代理程式資訊卡」(JSON 文件) 宣傳功能,其中會說明代理程式的身分、支援的 A2A 功能、技能和驗證需求。這樣一來,其他代理程式就能找到並選取最適合特定工作的代理程式。
- 預設安全:安全性是核心原則。A2A 採用企業級驗證和授權機制,並使用 HTTPS/TLS、JWT、OIDC 和 API 金鑰等標準,確保互動安全無虞,並保護機密資料。
- 不限模態:通訊協定支援各種通訊模態,包括文字、音訊和影片串流,以及互動式表單和內嵌 iframe。這項彈性讓代理程式能以最適合工作和使用者的格式交換資訊。
- 結構化工作管理:A2A 會明確定義工作委派、監控和完成的通訊協定。這項功能支援將相關工作分組,並使用專屬工作 ID 跨不同代理程式管理工作。工作可以經歷定義的生命週期 (例如已提交、處理中、已完成)。
- 不透明的執行方式:這項功能的一大特色是,服務專員不必向其他服務專員揭露內部推理程序、記憶體或特定工具。只會公開可呼叫的服務,有助於提升模組化程度和隱私權。
- 以現有標準為基礎:A2A 採用 HTTP、伺服器推送事件 (SSE) 等成熟的網路技術,可即時串流資料,並使用 JSON-RPC 交換結構化資料,因此更容易與現有 IT 基礎架構整合。
- 非同步通訊:通訊協定的設計主要考量非同步通訊,可促進彈性工作進度,即使連線並非持續維持,也能啟用更新的推播通知。
5. 代理程式架構
在本實驗室中,您將建立多代理程式應用程式,根據規格生成圖片,並在向您顯示圖片前進行評估。
系統架構包含一個名為 image_scoring 的主要代理程式,負責協調整個程序。這個主要代理程式有一個名為 image_generation_scoring_agent 的子代理程式,而這個子代理程式本身也有自己的子代理程式,負責執行更具體的任務。這會建立階層式關係,主代理程式會將工作委派給子代理程式。 圖 2:整體代理程式流程。
所有代理程式清單
- image_scoring (主要代理程式):
- 用途:這是管理整體工作流程的根代理程式。這個代理程式會在迴圈中重複執行 image_generation_scoring_agent 和 checker_agent,直到符合終止條件為止。
- 子代理:
- image_generation_scoring_agent
- checker_agent_instance
- image_generation_scoring_agent (image_scoring 的子代理程式):
- 用途:這個代理程式負責生成及評估圖片的核心邏輯。為此,這項工具會執行一連串三個子代理程式。
- 子代理:
- image_generation_prompt_agent
- image_generation_agent
- scoring_images_prompt
- checker_agent_instance (image_scoring 的子代理程式):
- 用途:這個代理程式會檢查圖片評分程序是否應繼續或終止。這項工具會使用 check_tool_condition 工具評估終止條件。
- image_generation_prompt_agent (image_generation_scoring_agent 的子代理程式):
- 用途:這個代理程式擅長建立圖像生成提示。這項工具會根據輸入文字生成詳細提示,供圖像生成模型使用。
- image_generation_agent (image_generation_scoring_agent 的子代理程式):
- 用途:這個代理程式擅長使用 Imagen 3 建立圖片。這個代理程式會從 image_generation_prompt_agent 取得提示,然後生成圖片。
- scoring_images_prompt (image_generation_scoring_agent 的子代理程式):
- 用途:這個代理程式擅長根據各種條件評估圖片並給予分數。並為生成的圖片評分。
服務專員使用的工具
- check_tool_condition:
- 說明:這項工具會檢查是否符合迴圈終止條件,或是否已達到疊代次數上限。如果符合任一條件,迴圈就會停止。
- 使用對象:checker_agent_instance
- generate_images:
- 說明:這項工具會使用 Imagen 3 模型生成圖片。也可以將生成的圖片儲存至 Google Cloud Storage bucket。
- 使用對象:image_generation_agent
- get_policy:
- 說明:這項工具會從 JSON 檔案擷取政策。image_generation_prompt_agent 會使用這項政策建立圖片生成提示,scoring_images_prompt 則會使用這項政策為圖片評分。
- 使用對象:image_generation_prompt_agent、scoring_images_prompt
- get_image:
- 說明:這項工具會載入生成的圖像構件,以便評分。
- 使用者:scoring_images_prompt
- set_score:
- 說明:這項工具會在工作階段狀態中設定生成圖片的總分。
- 使用者:scoring_images_prompt
6. 工作 1:安裝 ADK 並設定環境
在本實作練習中,我們將使用 Cloud Shell 執行工作。
啟用 Vertex AI 建議的 API
- 在 Google Cloud 控制台頂端搜尋 Vertex AI,然後前往該頁面。
- 點選「啟用所有建議的 API」。
準備 Cloud Shell 編輯器分頁
- 選取 Google Cloud 控制台視窗,然後依序按下鍵盤的 G 和 S 鍵,開啟 Cloud Shell。或者,您也可以點選 Google Cloud 控制台右上角的 Cloud Shell 按鈕
。
- 按一下「繼續」。
- 系統提示您授權 Cloud Shell 時,請按一下「Authorize」(授權)。
- 在 Cloud Shell 窗格的右上角,按一下「在新視窗中開啟」按鈕
。
- 按一下窗格頂端的「開啟編輯器」鉛筆圖示 (
),即可查看檔案。
- 在左側導覽選單頂端,按一下「檔案總管」圖示
開啟檔案總管。
- 按一下「開啟資料夾」按鈕。
- 在本實驗的其餘部分,您可以在這個視窗中,將 Cloud Shell 編輯器和 Cloud Shell 終端機當做 IDE 使用。
下載並安裝本實驗室的 ADK 和程式碼範例
- 執行下列指令,從 GitHub 複製所需來源,並安裝必要程式庫。
#create the project directory mkdir imagescoring cd imagescoring #clone the code in the local directory git clone https://github.com/haren-bh/multiagenthandson.git #Create the virtual environment python3 -m venv pythonenv source pythonenv/bin/activate #install google-adk and a2a sdk python3 -m pip install google-adk==1.8.0 python3 -m pip install a2a-sdk==0.2.16
- 我們會使用 poetry 安裝其他需求條件:
cd multiagenthandson #go to the application directory pip install poetry poetry-plugin-export poetry install --with deployment
- 如果沒有雲端儲存空間值區,請在 Google Cloud Storage 中建立新的值區。您也可以使用 gsutil 指令建立 bucket。
gsutil mb gs://YOUR-UNIQUE-BUCKETNAME
- 在編輯器中,依序前往「View」->「Toggle hidden files」。在 image_scoring 資料夾中,建立含有以下內容的 .env 檔案。新增必要詳細資料,例如專案名稱和 Cloud Storage 值區。
GOOGLE_GENAI_USE_VERTEXAI=1 #1 if VERTEXAI has to be used. Can be 0 if API_KEY is specified
GOOGLE_CLOUD_PROJECT=YOUR CLOUD PROJECT NAME
GOOGLE_CLOUD_LOCATION=us-central1
GOOGLE_CLOUD_STORAGE_BUCKET=YOUR BUCKET NAME # Only required for deployment on Agent Engine
GCS_BUCKET_NAME=YOUR BUCKET NAME #Bucket for storing generated images.
SCORE_THRESHOLD=40 # Min threshold for image_score. Max Score is 50 , hence should be less than 50.
#If the computed score is higher then loop will terminate
#MAX_ITERATIONS=5 #Max iterations for evaluating the image_score before terminating the loop.
IMAGEN_MODEL="imagen-3.0-generate-002"
GENAI_MODEL="gemini-2.5-flash"
#AGENT_ENGINE_ID=<AGENT_ENGINE_ID> #The Agent Engine ID obtained after deploying to the agent engine.
- 查看原始碼中的代理程式結構,從 agent.py 開始。這個代理程式包含將連結至其他代理程式的根代理程式。
- 返回終端機中的頂層目錄 multiagenthandson,然後執行下列指令,在本機執行代理程式
# Run the following command to run agents locally export GCS_BUCKET_NAME=your gcs bucket name adk web
圖 1
在終端機上顯示的 http:// 網址上按 Ctrl + 滑鼠左鍵 (MacOS 則為按 CMD + 滑鼠左鍵),開啟 ADK 的瀏覽器型 GUI 用戶端。畫面應與圖 2 類似
- 讓我們生成一些圖片。請嘗試下列提示或自訂提示。
- 日落時分的寧靜山景
- 騎自行車的貓
圖 2
7. 工作 2:部署至 Agent Engine
現在將代理部署至 Agent Engine。Agent Engine 是一項全代管服務,可在 GCP 中部署代理程式。Agent Engine 與 ADK 相容,因此使用 ADK 建構的代理可在 Agent Engine 中部署。
- 定義一些環境變數
export GOOGLE_CLOUD_LOCATION='us-central1' export GOOGLE_CLOUD_PROJECT='your project id'
- 使用 Poetry 建立 requirements.txt 檔案。Poetry 會使用 pyproject.toml 建立 requirements.txt 檔案。執行指令後,請檢查是否已建立 requirements.txt 檔案。
# Go to the parent folder containing pyproject.toml file # install poetry-plugin-export pip install poetry-plugin-export #Create requirements.txt file poetry export -f requirements.txt --output requirements.txt --without-hashes
- 建立套件。我們需要將應用程式打包成 .whl Python 套件。我們會使用 Poetry 執行這項操作。執行指令後,請確認已建立 dist 資料夾,且其中包含 .whl 檔案。
# Go to the parent folder containing pyproject.toml file #Create python package, to create whl file poetry build
- 現在我們要準備部署指令碼。部署指令碼會部署圖片評分代理程式或代理程式引擎服務。請將 image_scoring 資料夾中的 deploy.py 內容變更如下。
# Change the content of the following. Look for #change this comment
import vertexai
from .agent import root_agent
import os
import glob # To easily find the wheel file
PROJECT_ID = "YOUR PROJECT ID" #change this your project
LOCATION = "us-central1" #change this
STAGING_BUCKET = "gs://YOUR BUCKET " #change this to your bucket
from vertexai import agent_engines
vertexai.init(
project=PROJECT_ID,
location=LOCATION,
staging_bucket=STAGING_BUCKET,
)
remote_app = agent_engines.create(
agent_engine=root_agent,
requirements=open(os.path.join(os.getcwd(), "requirements.txt")).readlines()+["./dist/image_scoring-0.1.0-py3-none-any.whl"],#change this to your local location
extra_packages=[
"./dist/image_scoring-0.1.0-py3-none-any.whl", # change this to your location
]
)
print(remote_app.resource_name)
- 現在可以執行部署指令碼。
#run deploy script from the parent folder containing deploy.py python3 -m image_scoring.deploy
部署完成後,畫面應如下所示:
圖 3
- 現在來測試已部署的代理程式。如要測試遠端部署的代理程式引擎,請先從終端機的部署輸出內容複製代理程式位置。格式應類似:projects/85469421903/locations/us-central1/reasoningEngines/7369674597261639680。
前往 testclient 資料夾,開啟 remote_test.py 檔案,然後編輯下列幾行。
PROJECT_ID = "" #change this LOCATION = "" #change this STAGING_BUCKET = "" #change this #replace the id with your own. reasoning_engine_id="your agent engine id" #You can replace this with your own prompt image_prompt="A cat riding a bicycle" #execute remote_test.py python3 remote_test.py
8. 工作 3:建立 A2A 代理程式
在本步驟中,我們將根據先前步驟中建立的代理程式,建立簡單的 A2A 代理程式。現有的 ADK 代理程式可透過 A2A 通訊協定發布。這個步驟的重點如下:
- 瞭解 A2A 通訊協定的基本概念。
- 瞭解 ADK 和 A2A 通訊協定如何搭配運作。
- 瞭解如何與 A2A 通訊協定互動。
在本實作練習中,我們將使用 image_scoring_adk_a2a_server 資料夾中的程式碼。開始工作前,請將目錄變更為這個資料夾。
建立 A2A 代理程式卡片
A2A 協定需要代理程式資訊卡,其中包含代理程式的所有資訊,例如代理程式功能、代理程式使用指南等。部署 A2A 代理程式後,即可使用「.well-known/agent-card.json」連結查看代理程式資訊卡。客戶可以參考這項資訊,將要求傳送給代理商。
在 remote_a2a/image_scoring 資料夾中,確認有 agents.json 檔案,且內容如下。
{
"name": "image_scoring",
"description": "Agent that generates images based on user prompts and scores their adherence to the prompt.",
"url": "http://localhost:8001/a2a/image_scoring",
"version": "1.0.0",
"defaultInputModes": ["text/plain"],
"defaultOutputModes": ["image/png", "text/plain"],
"capabilities": {
"streaming": true,
"functions": true
},
"skills": [
{
"id": "generate_and_score_image",
"name": "Generate and Score Image",
"description": "Generates an image from a given text prompt and then evaluates how well the generated image adheres to the original prompt, providing a score.",
"tags": ["image generation", "image scoring", "evaluation", "AI art"],
"examples": [
"Generate an image of a futuristic city at sunset",
"Create an image of a cat playing a piano",
"Show me an image of a serene forest with a hidden waterfall"
]
}
]
}
建立 A2A 代理
在根資料夾 image_scoring_adk_a2a_server 中,確認有 a2a_agent.py 檔案,這是 a2a 代理程式的進入點。內容應如下所示:
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
root_agent = RemoteA2aAgent(
name="image_scoring",
description="Agent to give interesting facts.",
agent_card="http://localhost:8001/a2a/image_scoring/.well-known/agent.json",
# Optional configurations
timeout=300.0, # HTTP timeout (seconds)
httpx_client=None, # Custom HTTP client
)
執行 A2A 代理程式
現在可以執行代理程式了!如要執行代理程式,請從頂層資料夾 image_scoring_adk_a2a_server 內執行下列指令
#set some environmental variables export GOOGLE_CLOUD_PROJECT=datapipeline-372305 export GOOGLE_CLOUD_LOCATION=us-central1 export GCS_BUCKET_NAME=haren-genai-bucket #following command runs the ADK agent as a2a agent adk api_server --a2a --port 8001 remote_a2a
測試 A2A 代理
代理程式執行後,我們就可以測試代理程式。首先,請檢查代理程式卡片。
#Execute the following curl http://localhost:8001/a2a/image_scoring/.well-known/agent.json
執行上述指令後,應該會顯示 A2A 代理程式的代理程式資訊卡,這主要是我們在上一個步驟中建立的 agent.json 內容。
現在,讓我們向代理程式傳送要求。我們可以使用 curl 將要求傳送至代理程式,
curl -X POST http://localhost:8001/a2a/image_scoring -H 'Content-Type: application/json' -d '{ "id": "uuid-123", "params": { "message": { "messageId": "msg-456", "parts": [{"text": "Create an image of a cat"}], "role": "user" } } }'
在上述要求中,您可以變更「Create an image of a cat」這一行,藉此變更提示。執行指令後,您可以在指定的 Google Cloud Storage 中查看輸出圖片。
9. 清除所用資源
現在,讓我們清除剛才建立的內容。
- 刪除我們剛才建立的 Agent Engine 伺服器。在 Google Cloud 控制台的搜尋列中輸入「Vertex AI」,然後前往 Vertex AI。按一下左側的「代理程式引擎」。按一下「刪除」即可刪除代理程式。
圖 4
- 刪除 Cloud Shell 中的檔案
#Execute the following to delete the files rm -R imagescoring
- 刪除 bucket。前往 GCP 控制台的「Cloud Storage」,選取並刪除 bucket。