快速入门:通过 A2A 协议暴露远程代理¶
这个快速入门指南涵盖了所有开发者最常见的起点。 “我有一个代理(agent)。我该如何公开这个代理,以便其他代理能够通过 A2A(即代理对代理)的方式使用它呢?”这对于构建复杂的多智能体系统至关重要;在这些系统中,不同的智能体需要相互协作和交流。
A2A Python SDK 的版本兼容性
ADK的A2A集成功能支持A2A SDK的两个主要版本。)a2a-sdk 0.3.x 和 1.x.x 版本)。已安装的 A2A SDK 版本会自动被检测到,因此无需对您的 ADK 应用程序代码进行任何修改。
尽管…… a2a-sdk 0.3.x 版本在兼容模式下仍被支持,但新的集成功能应优先针对 1.x.x 版本进行开发。如果您的代码中引用了 0.3.x 的相关内容,请确保在进行更新时考虑到这些兼容性问题。 a2a-sdk 类型
可以直接使用(例如,自定义执行器或手动构建的执行器)。 AgentCard
有关实例的更多信息,请参阅…… A2A SDK v1.0 迁移指南
在升级到 1.x.x 版本时……
概述¶
这个示例展示了如何轻松地暴露一个 ADK(Android Development Kit)代理,以便另一个代理可以使用 A2A(Ad Hoc Two-Way)协议来调用该代理的功能。
通过 A2A(点对点)方式暴露 ADK(应用程序开发套件)代理主要有两种方法。
- 通过使用……
to_a2a(root_agent)function:如果您只是想将现有的代理(agent)转换为支持 A2A(即代理之间的直接通信)的模式,并希望通过服务器将其暴露给外部用户或系统使用,那么可以使用这个函数。uvicorn……而不是……adk deploy api_server这意味着你可以更精确地控制自己希望通过哪些方式来公开(或展示)某些信息。uvicorn当您希望将您的代理(agent)投入实际生产环境(即实现其商业化应用)时,这一点尤为重要。此外,to_a2a()该函数会根据您的代理代码自动生成代理卡片。 - 通过创建自己的代理卡片……)
agent.json)并通过以下方式来托管它:adk api_server --a2a使用这种方法主要有两个好处。首先,adk api_server --a2a可以与……配合使用(或协同工作)adk web这使得您的代理程序易于使用、调试和测试。其次,通过……adk api_server您可以指定一个包含多个独立代理的父文件夹。那些拥有代理卡(agent card)的代理程序将会被包含在该父文件夹中。agent.json这些信息将通过同一服务器自动实现“A2A”(即代理之间的直接通信)功能,从而让其他代理能够使用这些信息。不过,您需要自己创建代理卡片(agent cards)。要创建代理卡片,您可以按照以下步骤操作: A2A Python 教程.
这个快速入门指南将重点介绍…… to_a2a()因为这是暴露你的代理(agent)的最简单方法,并且系统还会在后台自动生成代理的卡片(agent card)。如果你想使用其他方式的话…… adk api_server 在“approach”这个词的用法中,你可以看到它被用于……(具体内容在原文中被省略了)。 A2A 快速入门(消费者端)文档.
Before:
┌────────────────────┐
│ Hello World Agent │
│ (Python Object) │
| without agent card │
└────────────────────┘
│
│ to_a2a()
▼
After:
┌────────────────┐ ┌───────────────────────────────┐
│ Root Agent │ A2A Protocol │ A2A-Exposed Hello World Agent │
│(RemoteA2aAgent)│────────────────────────────▶│ (localhost: 8001) │
│(localhost:8000)│ └───────────────────────────────┘
└────────────────┘
该样本包含以下内容:
- 远程“Hello World”代理程序 (
remote_a2a/hello_world/agent.py): 这个代理是你想要公开给其他代理使用的,以便它们可以通过 A2A(代理对代理)的方式来使用它。该代理负责执行掷骰子以及检查数字是否为质数的功能。你可以通过以下方式来公开这个代理:to_a2a()该功能通过某种方式(未具体说明)被提供或实现,并通过相应的渠道或方式(同样未具体说明)被用户使用。uvicorn. - 根代理(Root Agent) (
agent.py这是一个简单的代理程序,它的作用仅仅是调用远程的 “Hello World” 代理程序。
通过……公开远程代理(Remote Agent)。 to_a2a(root_agent) function¶
你可以使用现有的、基于 ADK 构建的代理程序,并通过对其进行简单的封装处理,使其具备 A2A(代理对代理)通信的能力。 to_a2a() 函数。例如,如果你定义了一个如下所示的代理(agent): root_agent:
# Your agent code here
root_agent = Agent(
model='gemini-flash-latest',
name='hello_world_agent',
<...your agent code...>
)
然后,你只需使用相应的工具或方法,就可以让该系统具备 A2A(点对点)通信功能。 to_a2a(root_agent):
from google.adk.a2a.utils.agent_to_a2a import to_a2a
# Make your agent A2A-compatible
a2a_app = to_a2a(root_agent, port=8001)
The to_a2a() 该函数甚至会在后台(内存中)自动生成代理卡(agent card)。 从 ADK 代理中提取技能、功能以及元数据这样一来,当使用代理端点(agent endpoint)提供服务时,用户就可以看到那张知名的代理卡片(agent card)了。 uvicorn.
您也可以通过使用相应的工具或方法,自行制作代理卡(agent card)。 agent_card 参数。其值可以是一个…… AgentCard 一个对象,或者指向代理卡片 JSON 文件的路径。
带有一个示例…… AgentCard object:
from google.adk.a2a.utils.agent_to_a2a import to_a2a
from a2a.types import AgentCard
# Define A2A agent card
my_agent_card = AgentCard(
name="file_agent",
url="http://example.com",
description="Test agent from file",
version="1.0.0",
capabilities={},
skills=[],
default_input_modes=["text/plain"],
default_output_modes=["text/plain"],
supports_authenticated_extended_card=False,
)
a2a_app = to_a2a(root_agent, port=8001, agent_card=my_agent_card)
使用 JSON 文件路径的示例:
from google.adk.a2a.utils.agent_to_a2a import to_a2a
# Load A2A agent card from a file
a2a_app = to_a2a(root_agent, port=8001, agent_card="/path/to/your/agent-card.json")
内部原理:to_a2a() 方法¶
当你调用(某个函数或方法)时…… to_a2a()ADK 会自动完成多个设置步骤,以便让您的代理程序能够正常运行。
- A2aAgentExecutor 的设置: An
A2aAgentExecutor它充当 A2A 协议与您的 ADK 代理之间的桥梁。如果您不提供自定义配置(即不使用任何自定义设置),系统将使用默认的配置方式来确保 A2A 协议与 ADK 代理之间的正常通信。Runner它会自动创建一个默认配置,该配置依赖于内存中的服务(用于管理工件、会话、内存数据以及凭据等信息)。 - 状态管理(State Management): 创建一个……
InMemoryTaskStore用于跟踪 A2A(点对点)任务及相关信息。InMemoryPushNotificationConfigStore用于处理推送通知。 - 请求处理: 创建一个
DefaultRequestHandler将传入的 A2A HTTP 请求路由到……A2aAgentExecutor此外,该系统还负责存储各种状态信息(state stores)。 - Starlette 应用程序与代理卡: 创建一个 Starlette 应用程序。在启动阶段,该应用程序会加载您提供的代理卡片(Agent Card),或者根据代理的配置信息自动生成一个代理卡片。
AgentCardBuilder然后,它会加载所有必要的 A2A(点对点)API 路由。
参数¶
agent(必填项): 您希望通过 A2A 协议公开的主要 ADK 代理实例。host(可选): 主机用于生成代理卡(agent card)中显示的 A2A RPC(点对点远程过程调用)URL。默认值为……"localhost".protocol(可选): 该 URL 使用的协议。默认值为……"http".port(可选): 在同一 URL 中使用的端口。默认值为……8000.to_a2a()它本身并不会绑定任何端口,因此您需要确保所指定的端口与您的实际服务端口相匹配(请参阅相关文档)。uvicorn --port(请根据下面的标志进行操作),否则所宣传的卡片可能会指向一个无法到达的地方。push_config_store(可选): 这是一个用于管理 A2A(点对点)推送通知的自定义存储实现方案。如果未提供该实现方案,系统将默认使用内存中的存储机制来存储推送通知数据。InMemoryPushNotificationConfigStore).agent_card(可选): AnAgentCard一个 JSON 文件的对象或路径。如果省略了该参数,ADK 会自动根据您的代理代码生成代理卡片(agent card)。runner(可选): 一个预先构建好的(pre-built)……Runner如果省略了该参数,系统会创建一个默认的运行器(runner),该运行器依赖于内存中的服务(in-memory services)来完成任务。lifespan(可选): 这是一个用于 Starlette 应用程序生命周期事件的异步上下文管理器(async context manager),用于执行应用程序的启动(startup)和关闭(shutdown)逻辑。详见…… 管理应用程序的生命周期.
管理应用程序的生命周期¶
使用 lifespan “argument of the” 的完整含义可能是 “某个论点或观点的依据/理由”(例如:“The argument of his argument was based on solid evidence.”)。不过,这个短语在英语中并不常用,可能更容易被理解为 “某个论点本身”(例如:“This is the main argument of his speech.”)。具体含义需要根据上下文来判断。 to_a2a 这是一个用于管理应用程序生命周期的函数。该函数接收一个异步上下文管理器(async context manager),用于执行初始化(setup)和销毁(teardown)操作,例如在应用程序启动时建立数据库连接,在应用程序关闭时关闭该连接。
上下文管理器接收到了…… Starlette 应用程序实例。请使用该实例。 app.state 用于存储应用程序需要全局访问的资源。
from contextlib import asynccontextmanager
from google.adk.a2a.utils.agent_to_a2a import to_a2a
from starlette.applications import Starlette
@asynccontextmanager
async def lifespan(app: Starlette):
# Initialize resources on application startup
app.state.db = await init_db()
yield
# Clean up resources on application shutdown
await app.state.db.close()
a2a_app = to_a2a(agent, lifespan=lifespan)
获取示例代码¶
首先,请确保已经安装了所有必要的依赖项:
您可以克隆该文件,并导航到其中。 a2a_root sample `here:`
如您所见,文件夹结构如下:
a2a_root/
├── remote_a2a/
│ └── hello_world/
│ ├── __init__.py
│ └── agent.py # Remote Hello World Agent
├── README.md
└── agent.py # Root agent
Root Agent(根代理)a2a_root/agent.py)¶
root_agent: ARemoteA2aAgent该组件用于连接到远程的 A2A(点对点)服务。- 代理卡(Agent Card)的 URL 地址:指向远程服务器上著名的代理卡(agent card)信息端点的链接。
远程“Hello World”代理程序(Remote “Hello World” Agent)a2a_root/remote_a2a/hello_world/agent.py)¶
roll_die(sides: int):一个用于掷骰子的功能工具,同时具备状态管理功能。check_prime(nums: list[int]):用于检查质数的异步函数root_agent:这个主要代理拥有全面的操作指南。a2a_app:使用该工具创建的 A2A(点对点)应用程序to_a2a()实用工具;公用设施
启动远程 A2A 代理服务器。¶
现在您可以启动远程代理服务器了,该服务器将用于托管相关资源。 a2a_app 在 `hello_world` 代理内部:
# Ensure current working directory is adk-python/
# Start the remote agent using uvicorn
uvicorn contributing.samples.a2a.a2a_root.remote_a2a.hello_world.agent:a2a_app --host localhost --port 8001
为什么要使用端口 8001?
在这个快速入门指南中,当在本地进行测试时,您的代理程序会使用 `localhost` 作为连接地址。 port 用于 A2A(代理对代理)通信的服务器端口必须与被调用代理(即远程的、主要的代理)的端口不同。默认的端口为…… adk web 您将与使用该服务的代理进行交互的地方是…… 8000这就是为什么 A2A 服务器使用单独的端口进行通信的原因。 8001.
执行完成后,你应该会看到类似以下的内容:
INFO: Started server process [10615]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://localhost:8001 (Press CTRL+C to quit)
请确认您的远程代理程序正在运行中。¶
您可以通过访问之前自动生成的代理卡片来确认您的代理是否已正常运行。该代理卡片是作为您系统配置的一部分而生成的。 to_a2a() ```javascript
function in(obj, prop) {
return obj.hasOwnProperty(prop);
}
``` a2a_root/remote_a2a/hello_world/agent.py:
http://localhost:8001/.well-known/agent-card.json
你应该能看到代理卡(agent card)中的内容,其显示格式应该如下:
{"capabilities":{},"defaultInputModes":["text/plain"],"defaultOutputModes":["text/plain"],"description":"hello world agent that can roll a dice of 8 sides and check prime numbers.","name":"hello_world_agent","protocolVersion":"0.2.6","skills":[{"description":"hello world agent that can roll a dice of 8 sides and check prime numbers. \n I roll dice and answer questions about the outcome of the dice rolls.\n I can roll dice of different sizes.\n I can use multiple tools in parallel by calling functions in parallel(in one request and in one round).\n It is ok to discuss previous dice roles, and comment on the dice rolls.\n When I are asked to roll a die, I must call the roll_die tool with the number of sides. Be sure to pass in an integer. Do not pass in a string.\n I should never roll a die on my own.\n When checking prime numbers, call the check_prime tool with a list of integers. Be sure to pass in a list of integers. I should never pass in a string.\n I should not check prime numbers before calling the tool.\n When I are asked to roll a die and check prime numbers, I should always make the following two function calls:\n 1. I should first call the roll_die tool to get a roll. Wait for the function response before calling the check_prime tool.\n 2. After I get the function response from roll_die tool, I should call the check_prime tool with the roll_die result.\n 2.1 If user asks I to check primes based on previous rolls, make sure I include the previous rolls in the list.\n 3. When I respond, I must include the roll_die result from step 1.\n I should always perform the previous 3 steps when asking for a roll and checking prime numbers.\n I should not rely on the previous history on prime results.\n ","id":"hello_world_agent","name":"model","tags":["llm"]},{"description":"Roll a die and return the rolled result.\n\nArgs:\n sides: The integer number of sides the die has.\n tool_context: the tool context\nReturns:\n An integer of the result of rolling the die.","id":"hello_world_agent-roll_die","name":"roll_die","tags":["llm","tools"]},{"description":"Check if a given list of numbers are prime.\n\nArgs:\n nums: The list of numbers to check.\n\nReturns:\n A str indicating which number is prime.","id":"hello_world_agent-check_prime","name":"check_prime","tags":["llm","tools"]}],"supportsAuthenticatedExtendedCard":false,"url":"http://localhost:8001","version":"0.0.1"}
运行主代理程序(该代理程序会消耗系统资源)。¶
现在,您的远程代理已经启动了,您可以打开开发用户界面(dev UI),并选择 “a2a_root” 作为您的代理。
要打开 ADK Web 服务器,请访问: http://localhost:8000.
示例交互场景¶
一旦这两个服务都运行起来,你就可以与根代理(root agent)进行交互,查看它是如何通过 A2A(即代理之间的直接通信)来调用远程代理(remote agent)的。
简单的骰子投掷游戏: 这种交互使用了一个本地代理程序,即 Roll Agent。
质数检测:
这种交互方式通过 A2A(即点对点)技术使用了一个远程代理——即“Prime Agent”(主要代理)。
联合行动:
这次交互同时使用了本地的 Roll Agent 和远程的 Prime Agent:
User: Roll a 10-sided die and check if it's prime
Bot: I rolled an 8 for you.
Bot: 8 is not a prime number.
高级配置:自定义转换器与拦截器¶
在那些你需要比现有系统更精细的控制能力的场景中…… to_a2a() 如果提供了相应的接口或功能,那么你可以创建相应的对象(实例),并将其作为参数传递给其他函数或方法。 A2aAgentExecutorConfig 直接到…… A2aAgentExecutor这使您能够覆盖默认的数据转换器,并插入执行中间件(execution middleware)。
转换器(Converters)¶
这些转换器负责在 A2A 协议数据包与 ADK(应用程序开发套件)的本地数据结构之间进行双向翻译。 Event 或者 Part `objects`。您可以为以下钩子(hooks)提供自己的映射函数(mapping functions):
a2a_part_converter:将 A2A 消息的各个部分转换为 ADK 格式。Partobjects.gen_ai_part_converter:将原生 ADK 转换为其他格式。Part将这些对象转换为 A2A(点对点)消息的组成部分。request_converter:将传入的 A2A 请求转换为 ADK。RunRequest.event_converter: (传统/旧式产品) 将 ADK 事件转换为 A2A 事件,该事件被旧版本的执行器实现所使用。adk_event_converter: (新) 将 ADK 事件转换为 A2A 事件,该转换过程由新的、经过更新的执行器实现来处理。
执行拦截器(Execute Interceptors)¶
你可以插入一个列表…… execute_interceptors 为了在……中添加中间件逻辑 A2aAgentExecutor 负载处理(Payload Processing):
before_agent:在代理开始处理请求之前执行。这允许您检查或修改传入的请求数据。RequestContext.after_event:已执行 之后;随后 一个 ADK 事件会被转换为 A2A 事件。这允许你在该事件被放入队列之前对其进行修改(即对其进行修改或处理),或者直接返回该事件。None用于过滤掉该事件,并将其完全从系统中删除。after_agent:在代理程序完成执行且最终事件准备好之后,该脚本会被执行。您可以使用该脚本来检查或修改终端状态事件(例如……)。completed或者failed在数据被发送之前,会对其进行处理(即执行某些操作)。
管理应用程序的生命周期¶
使用 lifespan “argument of the” 的完整含义可能是 “某个论点或观点的依据/理由”(例如:“The argument of his argument was based on solid evidence.”)。不过,这个短语在英语中并不常用,可能更容易被理解为 “某个论点本身”(例如:“This is the main argument of his speech.”)。具体含义需要根据上下文来判断。 to_a2a 这是一个用于管理应用程序生命周期的函数。该函数接收一个异步上下文管理器(async context manager),用于执行初始化(setup)和销毁(teardown)操作,例如在应用程序启动时建立数据库连接,在应用程序关闭时关闭该连接。
上下文管理器接收到了…… Starlette 应用程序实例。请使用该实例。 app.state 用于存储应用程序需要全局访问的资源。
from contextlib import asynccontextmanager
from google.adk.a2a.utils.agent_to_a2a import to_a2a
from starlette.applications import Starlette
@asynccontextmanager
async def lifespan(app: Starlette):
# Initialize resources on application startup
app.state.db = await init_db()
yield
# Clean up resources on application shutdown
await app.state.db.close()
a2a_app = to_a2a(agent, lifespan=lifespan)
Agent Executor V2¶
该软件的新版本…… 代理执行器(Agent Executor) 通常在客户端发送所需信息时,该功能才会被启用。 A2A(点对点)扩展功能.
不过,你也可以绕过这个扩展程序,通过设置相关参数来强制服务器使用新的执行器版本。 force_new_version=True 在实例化时设置该标志(flag)。 A2aAgentExecutor这使您能够使用新的执行器逻辑,而无需修改现有的客户端代码来发送相关数据(即扩展信息)。
from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor
executor = A2aAgentExecutor(
...,
force_new_version=True
)
下一步行动¶
既然您已经创建了一个可以通过 A2A 服务器来访问远程代理的代理程序,下一步就是学习如何让另一个代理程序来使用这个远程代理。
- A2A 快速入门(消费者端)了解您的代理如何通过 A2A 协议与其他代理进行交互。