建構多代理系統並呼叫 A2A 代理

在多代理系統中,自動調度管理代理會將工作委派給專門的目標代理和工具。這些目標代理會成為多代理系統或應用程式的子代理。

有了 Agent Registry,自動化調度管理代理就能在執行階段動態查詢 Agent2Agent (A2A) 和 Model Context Protocol (MCP) 端點,不必在應用程式程式碼中硬式編碼服務網址。您可以使用 Agent Development Kit (ADK) 中的 AgentRegistry 用戶端,或標準 HTTP 和 google-auth 程式庫,擷取已註冊的代理和 MCP 伺服器,建構自動化調度管理代理。

調度代理呼叫目標代理的端點時,會直接將要求傳送至目標代理執行階段或 MCP 伺服器。如要強制執行安全性政策、執行通訊協定中介,以及對目標 Agent Endpoint 套用內容篩選器,可以透過 Agent Gateway 轉送代理通話。

事前準備

查詢目標 Agent Endpoint 網址,或透過 Agent Registry 呼叫 A2A 代理前,請先完成下列步驟:

  1. 設定 Agent Registry。
  2. 如果是單一專案設定,請取得已啟用 Agent Registry 的管理專案 ID。如果您為多個專案設定了管理邊界,請使用管理專案的 ID 進行邊界範圍的探索和註冊,或指定成員專案 ID 進行單一專案作業。

  3. 安裝架構的用戶端依附元件:

    ADK (pip)

    pip install --upgrade "google-adk[a2a,agent-identity,mcp]"
    

    您至少須安裝 google-adk>=1.29.0。

    ADK (uv)

    uv add "google-adk[a2a,agent-identity,mcp]"
    

    您至少須安裝 google-adk>=1.29.0。

    非 ADK Python

    pip install --upgrade google-auth requests httpx
    
  4. 為本機開發作業設定應用程式預設憑證 (ADC)。否則,請在外部環境中附加服務帳戶或 Workload Identity Federation 憑證設定:

    gcloud auth application-default login
    
  5. 設定下列環境變數:

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
    export GOOGLE_CLOUD_LOCATION=LOCATION
    

    更改下列內容:

必要的角色

您可以使用使用者帳戶進行本機開發,也可以使用服務帳戶或代理主體,讓協調器代理探索已註冊的元件,並呼叫目標 A2A 代理。使用者帳戶、服務帳戶或代理主體必須具備適當角色,才能探索元件及呼叫目標 A2A 代理。

為確保使用者帳戶、服務帳戶或代理主體具備必要權限,可探索已註冊的元件並呼叫目標 A2A 代理,請要求管理員在已啟用 Agent Registry 的管理專案中,將下列 IAM 角色授予使用者帳戶、服務帳戶或代理主體:

  • 如要探索已註冊的代理和 MCP 伺服器: Agent Registry API 檢視者 (roles/agentregistry.viewer)
  • 如要在執行階段呼叫目標 A2A 代理,必須具備託管目標代理的服務執行階段或閘道角色,才能呼叫該代理。舉例來說,如果目標代理在 Cloud Run 上執行,帳戶或主體必須具備 Cloud Run 叫用者角色 (roles/run.invoker)。

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

管理員或許也能透過自訂角色或其他預先定義的角色,為您的使用者帳戶、服務帳戶或代理主體授予必要權限。

選擇目標 A2A 代理端點的憑證

在代理註冊資料庫中查詢元件,以及呼叫其目標 A2A 代理端點,需要不同的驗證權杖。當自動化調度管理工具代理呼叫目標 A2A 代理端點時,必須附加該端點預期的不記名權杖類型:

目標 A2A 代理端點 必要的不記名權杖 憑證來源和指南
Google Cloud API 代理端點 (https://*.googleapis.com) OAuth 2.0 存取權杖,具有 https://www.googleapis.com/auth/cloud-platform 範圍或更窄的服務範圍。使用未設定預設配額專案的應用程式預設憑證 (ADC) 時,請加入 X-Goog-User-Project 標頭,指定要支付 API 配額費用的專案。詳情請參閱「使用 REST 要求設定配額專案」。 google.auth.default(),方法是使用應用程式預設憑證 (ADC)、附加的服務帳戶,或 Workload Identity Federation 憑證設定。如要限制每次呼叫的權限,請參閱「使用服務帳戶模擬功能」。
Cloud Run 或 Identity-Aware Proxy (IAP) HTTPS 代理端點 (https://*.run.app 或自訂網域) ID 權杖,其 aud 宣告與目標服務網址或 IAP OAuth 2.0 用戶端 ID 相符。 google.oauth2.id_token.fetch_id_token()。如需設定操作說明,請參閱「取得 ID 權杖」、「Cloud Run 服務對服務驗證」和「IAP 的程式輔助驗證」。
繫結 OAuth 的外部或 SaaS 代理 雙足式 OAuth 2.0 權杖、三足式 OAuth 2.0 權杖或 API 金鑰。 當 Agent Identity 驗證管理工具繫結附加至代理時,ADK 會自動管理。如需設定操作說明,請參閱「驗證工具和資源」。

在 ADK 中初始化 AgentRegistry 用戶端

如要透過 ADK 與 Agent Registry 互動,請在 Python 程式碼中,使用治理專案 ID 和 Agent Registry 位置初始化 AgentRegistry 用戶端:

import os
from google.adk.integrations.agent_registry import AgentRegistry

project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")

if not project_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set.")

registry = AgentRegistry(
    project_id=project_id,
    location=location,
)

初始化 ADK AgentRegistry 用戶端後,即可從 Agent Registry 擷取遠端 A2A 代理和遠端 MCP 工具。在 ADK 中,已註冊的 A2A 代理會包裝為 RemoteA2aAgent 例項。這些執行個體稱為「遠端代理」,因為 ADK 會透過網路將工作委派給這些執行個體,而不是在本機程序中執行。同樣地,已註冊的遠端 MCP 伺服器會包裝為 McpToolset 執行個體。

使用 ADK 建構多代理系統

如要從 Agent Registry 擷取遠端 A2A 子代理和遠端 MCP 工具組,並納入 LlmAgent 協調器代理定義,請使用初始化的 AgentRegistry 用戶端:

  • 如要擷取遠端 A2A 代理:請使用子代理的相對資源名稱呼叫 registry.get_remote_a2a_agent()。這個資源名稱可以是相對資源名稱,格式為 agents/AGENT_ID,使用 AgentRegistry 用戶端上設定的專案 ID 和位置;也可以是完整資源名稱,格式為 projects/PROJECT_ID/locations/LOCATION/agents/AGENT_ID。如果代理程式有驗證管理員 Binding,get_remote_a2a_agent() 會自動設定要求憑證。如果沒有 Binding,請傳遞使用 httpx.Auth 處理常式設定的自訂 httpx_client。
  • 如要擷取遠端 MCP 工具集:請使用 MCP 伺服器的相對資源名稱 (mcpServers/SERVER_ID) 或完整資源名稱 (projects/PROJECT_ID/locations/LOCATION/mcpServers/SERVER_ID) 呼叫 registry.get_mcp_toolset()。

以下範例說明如何在 ADK agent.py 檔案中定義協調器代理。在這個範例中,請考量下列事項:

  • GoogleApiAuth 類別會實作 httpx.Auth 處理常式,用於呼叫Google Cloud API (https://*.googleapis.com) A2A 子代理。它會使用 google.auth.default() 載入應用程式預設憑證、附加服務帳戶或 Workload Identity Federation 憑證,並在每項要求中設定 Authorization 和 X-Goog-User-Project 標頭。

  • registry 用戶端會從 Agent Registry 擷取遠端 A2A 子代理和遠端 MCP 工具集,並透過 sub_agents 和 tools 參數傳遞至 LlmAgent。

import httpx
import google.auth
from google.auth.transport.requests import Request
from google.adk.agents.llm_agent import LlmAgent

class GoogleApiAuth(httpx.Auth):
    def __init__(self, user_project_id: str):
        self.user_project_id = user_project_id
        self.creds, _ = google.auth.default(
            scopes=["https://www.googleapis.com/auth/cloud-platform"]
        )

    def auth_flow(self, request):
        if not self.creds.valid:
            self.creds.refresh(Request())
        request.headers["Authorization"] = f"Bearer {self.creds.token}"
        request.headers["X-Goog-User-Project"] = self.user_project_id
        yield request

quota_project_id = "QUOTA_PROJECT_ID"
agent_name = "agents/AGENT_ID"
httpx_client = httpx.AsyncClient(
    auth=GoogleApiAuth(quota_project_id),
    timeout=httpx.Timeout(60.0),
)
my_remote_agent = registry.get_remote_a2a_agent(
    agent_name=agent_name,
    httpx_client=httpx_client,
)

mcp_server_name = "mcpServers/SERVER_ID"
my_mcp_toolset = registry.get_mcp_toolset(mcp_server_name=mcp_server_name)

root_agent = LlmAgent(
    model="MODEL_ID",
    name="travel_orchestrator",
    instruction=(
        "You are a travel coordinator. Use your subagents to book travel "
        "and your tools to query historical travel data."
    ),
    tools=[my_mcp_toolset],
    sub_agents=[my_remote_agent],
)

更改下列內容:

  • QUOTA_PROJECT_ID:向Google Cloud API 代理端點提出要求時,用於配額和帳單歸因的專案 ID。
  • AGENT_ID:已註冊的 A2A 子代理 ID,也就是要讓自動調度管理工具代理呼叫的 ID,例如 agentregistry-01234456-7890-abcd-1234-567890abcdef。
  • SERVER_ID:要讓自動化調度管理代理使用的已註冊 MCP 伺服器 ID。
  • MODEL_ID:orchestrator 代理的模型 ID,例如 gemini-2.5-flash。

將 root_agent 儲存至 ADK 專案的 agent.py 檔案後,您可以使用 adk run 或 adk web CLI 指令,在本機測試及執行自動化調度管理代理,或將其部署至 Gemini Enterprise Agent Platform 的 Agent Runtime。如需完整的專案結構和執行操作說明,請參閱 ADK Python 快速入門導覽課程和 GitHub 上的 ADK 代理程式註冊範例。

從非 ADK 用戶端呼叫 A2A 代理

如果您在不使用 ADK 的情況下建構自訂自動調度管理代理或用戶端,應用程式會執行兩個驗證步驟:

  1. 探索:使用 OAuth 2.0 存取權杖向 Agent Registry API 驗證,擷取目標子代理的 Agent 資源,並檢查其代理資訊卡。
  2. 執行階段呼叫:附加目標 Agent Endpoint 所需的不記名權杖,也就是 *.googleapis.com Agent Endpoint 的 OAuth 2.0 存取權杖,或 Cloud Run 和 IAP Agent Endpoint 的 OIDC ID 權杖。接著,傳送 A2A SendMessage 要求。輸出內容會傳回 SendMessageResponse JSON 物件,其中包含 task 或 message 欄位,格式為 {"task": ...} 或 {"message": ...}。這個欄位包含子代理的回覆,可供 orchestrator 代理剖析並用於工作流程。

如要使用 google-auth 和 httpx 查詢及呼叫已註冊的 A2A 子代理,請完成下列步驟:

  1. 使用 OAuth 2.0 存取權杖向 Agent Registry 進行驗證,並從 Agent Registry API 擷取子代理的 Agent 資源:

    import os
    import uuid
    from urllib.parse import urlparse
    import google.auth
    from google.auth.transport.requests import Request
    from google.oauth2 import id_token
    import httpx
    
    project_id = os.environ["GOOGLE_CLOUD_PROJECT"]
    location = os.environ.get("GOOGLE_CLOUD_LOCATION", "global")
    agent_id = "AGENT_ID"
    
    creds, _ = google.auth.default(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    creds.refresh(Request())
    
    registry_url = (
        f"https://agentregistry.googleapis.com/v1/projects/{project_id}"
        f"/locations/{location}/agents/{agent_id}"
    )
    client = httpx.Client(timeout=60.0)
    reg_response = client.get(
        registry_url,
        headers={
            "Authorization": f"Bearer {creds.token}",
            "X-Goog-User-Project": project_id,
        },
    )
    reg_response.raise_for_status()
    agent_resource = reg_response.json()
    

    將 AGENT_ID 替換為要呼叫的已註冊 A2A 子代理 ID,例如 agentregistry-01234456-7890-abcd-1234-567890abcdef。

  2. 從 Agent 資源的代理卡中擷取 HTTP 型 A2A 介面:

    card = agent_resource.get("card", {}).get("content", {})
    interfaces = card.get("supportedInterfaces") or (
        (agent_resource.get("protocols") or [{}])[0].get("interfaces", [])
    )
    iface = next(
        i for i in interfaces
        if i.get("protocolBinding", "HTTP+JSON")
        in ("HTTP+JSON", "HTTP_JSON", "JSONRPC")
    )
    endpoint_url = iface["url"]
    binding = iface.get("protocolBinding", "HTTP+JSON")
    tenant = iface.get("tenant", "")
    
  3. 準備要求標頭,並為 *.googleapis.com Agent Endpoint 提供 OAuth 2.0 存取權杖,或為 Cloud Run 或 IAP 代理端點提供 OIDC ID 權杖:

    host = urlparse(endpoint_url).hostname or ""
    headers = {"Content-Type": "application/json", "A2A-Version": "1.0"}
    if host == "googleapis.com" or host.endswith(".googleapis.com"):
        headers["Authorization"] = f"Bearer {creds.token}"
        headers["X-Goog-User-Project"] = project_id
    else:
        oidc_audience = f"https://{host}"
        oidc_jwt = id_token.fetch_id_token(Request(), oidc_audience)
        headers["Authorization"] = f"Bearer {oidc_jwt}"
    
  4. 使用代理資訊卡中的通訊協定繫結,設定 A2A SendMessage 要求的格式並傳送,然後剖析子代理的回覆:

    message = {
        "messageId": str(uuid.uuid4()),
        "role": "ROLE_USER",
        "parts": [{"text": "Summarize recent deployment status."}],
    }
    if binding == "JSONRPC":
        params = {"message": message}
        if tenant:
            params["tenant"] = tenant
        payload = {
            "jsonrpc": "2.0",
            "id": str(uuid.uuid4()),
            "method": "SendMessage",
            "params": params,
        }
        target_url = endpoint_url
    else:
        payload = {"message": message}
        prefix = f"/{tenant.strip('/')}" if tenant else ""
        target_url = f"{endpoint_url.rstrip('/')}{prefix}/message:send"
    
    response = client.post(target_url, headers=headers, json=payload)
    response.raise_for_status()
    body = response.json()
    if binding == "JSONRPC":
        if "error" in body:
            raise RuntimeError(f"JSON-RPC error: {body['error']}")
        send_message_response = body["result"]
    else:
        send_message_response = body
    print(send_message_response)
    client.close()
    

    這個步驟會為 A2A 1.0 版設定 SendMessage 要求的格式。如需在 A2A 通訊協定版本 1.0 和 0.3 之間自動協商,請使用 ADK 或 a2a-sdk Python 用戶端。

在 ADK 中跨自動化調度管理工具代理重複使用遠端代理

為盡可能縮短網路延遲時間,請在應用程式啟動時,從代理程式登錄檔擷取遠端代理程式和工具集一次,而不是在每次要求時呼叫 get_remote_a2a_agent()。

在 ADK 中,RemoteA2aAgent 執行個體一次只能有一個父項 orchestrator 代理。接續初始化設定,呼叫 .clone() 為每個父項協調器代理建立獨立副本:

agent_path = (
    f"projects/{project_id}/locations/{location}"
    "/agents/AGENT_ID"
)
base_remote_agent = registry.get_remote_a2a_agent(
    agent_name=agent_path,
    httpx_client=httpx_client,
)

flight_orchestrator = LlmAgent(
    model="gemini-2.5-flash",
    name="flight_orchestrator",
    sub_agents=[base_remote_agent.clone()],
)

hotel_orchestrator = LlmAgent(
    model="gemini-2.5-flash",
    name="hotel_orchestrator",
    sub_agents=[base_remote_agent.clone()],
)

將 AGENT_ID 替換為已註冊的 A2A 子代理 ID,也就是要讓自動化調度管理代理呼叫的子代理。

後續步驟