使用 Agent2Agent 代理程式

事前準備

本教學課程假設您已詳閱並按照下列教學課程的指示操作:

取得代理程式的執行個體

如要查詢 A2aAgent,您需要先建立新執行個體取得現有執行個體

如要取得特定資源 ID 對應的 A2aAgent

Vertex AI SDK for Python

import vertexai
from google.genai import types

PROJECT_ID = "PROJECT_ID"
LOCATION = "LOCATION"
RESOURCE_ID = "RESOURCE_ID"
RESOURCE_NAME = f"projects/{PROJECT_ID}/locations/{LOCATION}/reasoningEngines/{RESOURCE_ID}"

client = vertexai.Client(
    project=PROJECT_ID,
    location=LOCATION,
    http_options=types.HttpOptions(api_version="v1beta1")
)

remote_agent = client.agent_engines.get(name=RESOURCE_NAME)

print(remote_agent)

其中

A2A Python SDK

這個方法會使用官方 A2A Python SDK,提供用戶端程式庫與符合 A2A 規範的代理程式互動。詳情請參閱 A2A Python SDK 說明文件

首先,請安裝 SDK:

pip install a2a-sdk>=0.3.4

接著,取得代理程式的卡片,建立用戶端例項。A2AClient 會為您處理探索和通訊作業。

from google.auth import default
from google.auth.transport.requests import Request
from a2a.client import ClientConfig, ClientFactory
from a2a.types import TransportProtocol
import httpx

# We assume 'agent_card' is an existing AgentCard object.

# Fetch credentials for authentication for demo purpose. Use your own auth
credentials, _ = default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
credentials.refresh(Request())

# Create the client by chaining the factory and config initialization.
factory = ClientFactory(
    ClientConfig(
        supported_transports=[TransportProtocol.http_json], # only support http_json
        use_client_preference=True,
        httpx_client=httpx.AsyncClient(
            headers={
                "Authorization": f"Bearer {credentials.token}",
                "Content-Type": "application/json",
            }
        ),
    )
)
a2a_client = factory.create(agent_card)

Python requests 程式庫

A2A 通訊協定是以標準 HTTP 端點為基礎建構而成。您可以使用任何 HTTP 用戶端與這些端點互動。

從代理程式資訊卡擷取 A2A 網址,並定義要求標頭。

from google.auth import default
from google.auth.transport.requests import Request

# We assume 'agent_card' is an existing object
a2a_url = agent_card.url

# Get an authentication token for demonstration purposes. Use your own authentication mechanism.
credentials, _ = default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
credentials.refresh(Request())

headers = {
    "Authorization": f"Bearer {credentials.token}",
    "Content-Type": "application/json",
}

使用 Python 適用的 Vertex AI SDK 時,remote_agent 物件會對應至 AgentEngine 類別,其中包含下列項目:

  • 包含已部署代理程式相關資訊的 agent.api_resource。 您也可以呼叫 agent.operation_schemas(),傳回代理程式支援的作業清單。詳情請參閱「支援的作業」。
  • agent.api_client,可進行同步服務互動
  • agent.async_api_client,可進行非同步服務互動

本節其餘部分假設您有名為 remote_agentAgentEngine 執行個體。

支援的作業

Agent Engine 託管的 A2A 代理會公開一組作業,直接對應至 A2A 通訊協定的 API 端點。

擷取代理程式資訊卡

請注意,Agent Engine 不會提供公開的代理程式卡片。如要擷取已通過驗證的代理程式資訊卡:

Vertex AI SDK for Python

response = await remote_agent.handle_authenticated_agent_card()

A2A Python SDK

response = await a2a_client.get_card()

Python requests 程式庫

card_endpoint = f"{a2a_url}/v1/card"
response = httpx.get(card_endpoint, headers=headers)
print(json.dumps(response.json(), indent=4))

傳送訊息

如何傳送電子郵件:

Vertex AI SDK for Python

message_data = {
  "messageId": "remote-agent-message-id",
  "role": "user",
  "parts": [{"kind": "text", "text": "What is the exchange rate from USD to EUR today?"}],
}

response = await remote_agent.on_message_send(**message_data)

A2A Python SDK

from a2a.types import Message, Part, TextPart
import pprint

message = Message(
    message_id="remote-agent-message-id",
    role="user",
    parts=[Part(root=TextPart(text="What's the currency rate of USD and EUR"))],
)

response_iterator = a2a_client.send_message(message)

async for chunk in response_iterator:
    pprint.pp(chunk)

Python requests 程式庫

import httpx
import json

endpoint = f"{a2a_url}/v1/message:send"

payload = {
    "message": {
        "messageId": "remote-agent-message-id",
        "role": "1",
        "content": [{"text": "What is the exchange rate from USD to EUR today?"}],
    },
    "metadata": {"source": "python_script"},
}

response = httpx.post(endpoint, json=payload, headers=headers)
print(json.dumps(response.json(), indent=4))

取得工作

如要取得工作及其狀態

Vertex AI SDK for Python

task_data = {
    "id": task_id,
}

response = await remote_agent.on_get_task(**task_data)

A2A Python SDK

from a2a.types import TaskQueryParams

task_data ={
    "id":task_id,
}
response = await a2a_client.get_task(TaskQueryParams(**task_data))

Python requests 程式庫

task_end_point = f"{a2a_url}/v1/tasks/{task_id}"
response = httpx.get(task_end_point, headers=headers)
print(json.dumps(response.json(), indent=4))

取消工作

如要取消工作:

Vertex AI SDK for Python

task_data = {
    "id": task_id,
}
response = await remote_agent.on_cancel_task(**task_data)

A2A Python SDK

from a2a.types import TaskQueryParams

task_data ={
    "id":task_id,
}
response = await a2a_client.cancel_task(TaskQueryParams(**task_data))

Python requests 程式庫

task_end_point = f"{a2a_url}/v1/tasks/{task_id}:cancel"
response = httpx.post(task_end_point, headers=headers)
print(json.dumps(response.json(), indent=4))

後續步驟