文章目录
- 智能体间通信(A2A)
-
- [一、核心概念:为什么需要 A2A?](#一、核心概念:为什么需要 A2A?)
- [二、A2A 核心架构](#二、A2A 核心架构)
-
- [2.1 三大角色](#2.1 三大角色)
- [2.2 Agent Card(智能体数字身份)](#2.2 Agent Card(智能体数字身份))
- [2.3 三种发现方式](#2.3 三种发现方式)
- 三、四种交互机制
-
- [3.1 同步请求/响应](#3.1 同步请求/响应)
- [3.2 流式更新(SSE)](#3.2 流式更新(SSE))
- [3.3 四种机制对比](#3.3 四种机制对比)
- [四、源码解构:ADK 搭建 A2A 服务器](#四、源码解构:ADK 搭建 A2A 服务器)
-
- [4.1 创建 ADK 智能体](#4.1 创建 ADK 智能体)
- [4.2 搭建 A2A 服务器](#4.2 搭建 A2A 服务器)
- [五、A2A vs MCP 对比](#五、A2A vs MCP 对比)
- 六、安全机制
- 七、关键要点
- 八、与前几章的联系
智能体间通信(A2A)
一、核心概念:为什么需要 A2A?
一句话:A2A 是让不同框架(ADK、LangGraph、CrewAI)构建的智能体能够跨平台协作的开放标准。
打个比方:
- 没有 A2A:像一群说不同语言的人,各自为政,无法沟通
- 有 A2A:像一个通用翻译系统,让不同框架的智能体无缝协作
支持者:Google、Atlassian、Box、LangChain、MongoDB、Salesforce、SAP、微软(Azure AI Foundry)
二、A2A 核心架构
2.1 三大角色
┌──────┐ ┌──────────────┐ ┌──────────────┐
│ 用户 │ → │ A2A 客户端 │ → │ A2A 服务器 │
│ │ │(客户端Agent)│ │(远程Agent) │
└──────┘ └──────────────┘ └──────────────┘
↕
第三方服务/API
| 角色 | 说明 |
|---|---|
| 用户 | 发起智能体协助请求 |
| A2A 客户端 | 代表用户请求操作或信息 |
| A2A 服务器 | 提供 HTTP 端点,处理请求并返回结果(黑盒) |
2.2 Agent Card(智能体数字身份)
Agent Card 是 JSON 格式的数字身份证,包含智能体的所有关键信息。
源码解构:
python
agent_card = {
"name": "WeatherBot", # 智能体名称
"description": "提供准确的天气预报和历史数据。", # 功能描述
"url": "http://weather-service.example.com/a2a", # HTTP 端点
"version": "1.0.0", # 版本号
"capabilities": { # 能力声明
"streaming": True, # 支持流式传输
"pushNotifications": False, # 不支持推送通知
"stateTransitionHistory": True # 支持状态转换历史
},
"authentication": { # 认证方式
"schemes": ["apiKey"]
},
"defaultInputModes": ["text"], # 默认输入格式
"defaultOutputModes": ["text"], # 默认输出格式
"skills": [ # 技能列表
{
"id": "get_current_weather",
"name": "获取当前天气",
"description": "检索任意地点的实时天气。",
"examples": ["巴黎现在的天气如何?"],
"tags": ["weather", "current", "real-time"]
}
]
}
源码解读:
capabilities:声明支持哪些交互方式,客户端据此选择通信模式skills:类似 MCP 的工具列表,但粒度更粗------一个 skill 可能包含多个工具调用authentication:集中管理认证要求,安全第一examples:提供示例输入,帮助客户端理解如何使用
2.3 三种发现方式
| 方式 | 说明 | 适用场景 |
|---|---|---|
| Well-Known URI | 标准路径 /.well-known/agent.json |
公开服务 |
| 管理型注册表 | 集中式目录,按条件查询 | 企业环境 |
| 直接配置 | 嵌入或私下共享 | 私有系统 |
三、四种交互机制
3.1 同步请求/响应
python
sync_request = {
"jsonrpc": "2.0",
"id": "1",
"method": "sendTask", # 同步方法
"params": {
"id": "task-001",
"sessionId": "session-001",
"message": {
"role": "user",
"parts": [{"type": "text", "text": "美元兑欧元汇率是多少?"}]
},
"acceptedOutputModes": ["text/plain"],
"historyLength": 5 # 保留最近 5 轮历史
}
}
源码解读:
method: "sendTask":同步请求,客户端等待一次性返回完整响应sessionId:关联多轮对话historyLength:控制返回的历史消息数量,减少上下文开销
3.2 流式更新(SSE)
python
streaming_request = {
"jsonrpc": "2.0",
"id": "2",
"method": "sendTaskSubscribe", # 流式方法
"params": {
"id": "task-002",
"sessionId": "session-001",
"message": {
"role": "user",
"parts": [{"type": "text", "text": "今天日元兑英镑汇率是多少?"}]
},
"acceptedOutputModes": ["text/plain"],
"historyLength": 5
}
}
源码解读:
method: "sendTaskSubscribe":建立持久 SSE 连接,服务器持续推送增量结果- 客户端无需多次轮询,服务器主动推送
3.3 四种机制对比
| 机制 | 方法 | 适用场景 | 特点 |
|---|---|---|---|
| 同步请求 | sendTask |
快速操作 | 简单,一次性返回 |
| 异步轮询 | sendTask + getTask |
耗时任务 | 客户端定期查询状态 |
| 流式(SSE) | sendTaskSubscribe |
实时增量结果 | 服务器主动推送 |
| 推送通知 | Webhook | 超长/资源密集型 | 状态变化时异步通知 |
四、源码解构:ADK 搭建 A2A 服务器
4.1 创建 ADK 智能体
python
import datetime
from google.adk.agents import LlmAgent
from google.adk.tools.google_api_tool import CalendarToolset
async def create_agent(client_id, client_secret) -> LlmAgent:
# 初始化 Google Calendar 工具集
toolset = CalendarToolset(client_id=client_id, client_secret=client_secret)
return LlmAgent(
model='gemini-2.0-flash-001',
name='calendar_agent',
description="可帮助管理用户日历的 Agent",
instruction=f"""
你是一个可以帮助用户管理日历的 Agent。
用户会请求日历状态信息或修改日历。
请使用提供的工具与日历 API 交互。
使用 Calendar API 工具时,请采用规范的 RFC3339 时间戳。
今天是 {datetime.datetime.now()}。
""",
tools=await toolset.get_tools(), # 获取工具列表
)
源码解读:
CalendarToolset:封装 Google Calendar API,通过 OAuth2 认证await toolset.get_tools():异步获取可用工具列表- 动态插入当前日期到 instruction 中,提供时序上下文
4.2 搭建 A2A 服务器
python
from a2a import (AgentSkill, AgentCard, AgentCapabilities,
DefaultRequestHandler, A2AStarletteApplication)
from adk import (Runner, InMemoryArtifactService, InMemorySessionService,
InMemoryMemoryService, ADKAgentExecutor, InMemoryTaskStore)
def main(host: str, port: int):
# 1. 定义技能
skill = AgentSkill(
id='check_availability',
name='检查可用性',
description="使用 Google Calendar 检查用户某一时间段的空闲情况",
tags=['calendar'],
examples=['我明天上午 10 点到 11 点有空吗?'],
)
# 2. 创建 Agent Card(数字身份)
agent_card = AgentCard(
name='Calendar Agent',
description="可管理用户日历的 Agent",
url=f'http://{host}:{port}/',
version='1.0.0',
defaultInputModes=['text'],
defaultOutputModes=['text'],
capabilities=AgentCapabilities(streaming=True), # 声明支持流式
skills=[skill],
)
# 3. 创建 ADK 智能体 + Runner
adk_agent = asyncio.run(create_agent(
client_id=os.getenv('GOOGLE_CLIENT_ID'),
client_secret=os.getenv('GOOGLE_CLIENT_SECRET'),
))
runner = Runner(
app_name=agent_card.name,
agent=adk_agent,
artifact_service=InMemoryArtifactService(), # 工件存储
session_service=InMemorySessionService(), # 会话管理
memory_service=InMemoryMemoryService(), # 长期记忆
)
# 4. 创建 A2A 执行器
agent_executor = ADKAgentExecutor(runner, agent_card)
# 5. 创建请求处理器
request_handler = DefaultRequestHandler(
agent_executor=agent_executor,
task_store=InMemoryTaskStore() # 任务存储
)
# 6. 创建 A2A Starlette 应用
a2a_app = A2AStarletteApplication(
agent_card=agent_card,
http_handler=request_handler
)
# 7. 启动 HTTP 服务
app = Starlette(routes=a2a_app.routes())
uvicorn.run(app, host=host, port=port)
源码解读:
- 步骤 1-2:定义智能体能力(技能)和身份(Agent Card)
- 步骤 3:创建 Runner,配置三大服务(工件/会话/记忆)
- 步骤 4 :
ADKAgentExecutor将 ADK Runner 包装为 A2A 兼容的执行器 - 步骤 5 :
DefaultRequestHandler处理 A2A 协议的 HTTP 请求 - 步骤 6 :
A2AStarletteApplication自动生成 A2A 端点路由 - 步骤 7:通过 Uvicorn 启动 HTTP 服务,暴露 A2A 端点
核心流程:
外部请求 → Starlette → A2AStarletteApplication → DefaultRequestHandler
→ ADKAgentExecutor → Runner → ADK Agent → 工具/API → 响应
五、A2A vs MCP 对比
| 特性 | A2A | MCP |
|---|---|---|
| 关注点 | 智能体间协调与通信 | LLM 与外部资源交互 |
| 通信对象 | Agent ↔ Agent | LLM ↔ 工具/数据 |
| 核心概念 | Agent Card(数字身份) | 工具/资源/Prompt |
| 协议 | HTTP + JSON-RPC 2.0 | STDIO/HTTP + JSON-RPC |
| 发现机制 | Well-Known URI / 注册表 | 客户端查询服务器能力 |
| 典型场景 | 跨框架多智能体协作 | 工具集成、数据访问 |
| 互补关系 | 高层协调 | 底层工具连接 |
一句话总结:MCP 连接工具,A2A 连接智能体。两者互补,共同构建复杂 AI 系统。
六、安全机制
| 机制 | 说明 |
|---|---|
| 双向 TLS(mTLS) | 加密 + 认证连接 |
| 审计日志 | 记录所有智能体间通信 |
| Agent Card 声明 | 集中管理身份和能力 |
| OAuth 2.0 / API Key | 凭证通过 HTTP 头传递 |
七、关键要点
- A2A 是开放标准:不同框架的智能体可以跨平台协作
- Agent Card 是核心:JSON 格式的数字身份,支持动态发现
- 四种交互模式:同步、异步轮询、流式(SSE)、推送通知
- JSON-RPC 2.0 协议:所有 A2A 通信都通过 HTTP(S) + JSON-RPC
- 模块化架构:专用智能体独立运行,通过 A2A 编排复杂流程
- A2A + MCP 互补:MCP 管工具连接,A2A 管智能体通信
- 安全是核心:mTLS + 审计日志 + OAuth 2.0
八、与前几章的联系
| 模式 | 与 A2A 的关系 |
|---|---|
| 多智能体(Ch7) | A2A 是多智能体协作的标准化通信协议 |
| MCP(Ch10) | MCP 连接工具,A2A 连接智能体,互补关系 |
| 记忆管理(Ch8) | A2A 服务器可共享记忆服务 |
| 异常处理(Ch12) | A2A 协议定义了错误处理和状态转换 |