A2A Samples: Hello World Agent
项目概述
这是一个基于 A2A (Agent-to-Agent) SDK 的简单 Hello World 代理示例。该项目演示了如何创建一个基本的智能代理服务器,它可以响应用户消息并返回简单的问候语。
依赖版本说明
Python 版本要求
- Python >= 3.10
核心依赖包
包名 | 版本 | 用途 |
---|---|---|
a2a-sdk | >= 0.2.5 | A2A 核心 SDK,提供代理框架 |
uvicorn | >= 0.34.2 | ASGI 服务器,用于运行 Web 应用 |
click | >= 8.1.8 | 命令行界面工具 |
httpx | >= 0.28.1 | 异步 HTTP 客户端 |
pydantic | >= 2.11.4 | 数据验证和序列化 |
python-dotenv | >= 1.1.0 | 环境变量管理 |
langchain-google-genai | >= 2.1.4 | Google 生成式 AI 集成 |
langgraph | >= 0.4.1 | 语言图处理框架 |
项目结构
helloworld/
├── __init__.py # 包初始化文件
├── __main__.py # 主程序入口
├── agent_executor.py # 代理执行器实现
├── test_client.py # 测试客户端
├── pyproject.toml # 项目配置和依赖
├── uv.lock # 依赖锁定文件
└── README.md # 项目说明
环境搭建
1. 安装 UV 包管理器
如果您还没有安装 UV,请先安装:
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh# 或者使用 pip
pip install uv
2. 克隆项目
git clone https://github.com/google-a2a/a2a-samples.git
cd a2a-samples/samples/python/agents/helloworld
3. 安装依赖
UV 会自动根据 pyproject.toml
和 uv.lock
文件安装所有依赖:
uv sync
代码架构说明
核心组件
1. HelloWorldAgent (agent_executor.py
)
class HelloWorldAgent:"""Hello World Agent."""async def invoke(self) -> str:return 'Hello World'
2. HelloWorldAgentExecutor (agent_executor.py
)
class HelloWorldAgentExecutor(AgentExecutor):"""代理执行器实现"""async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:result = await self.agent.invoke()event_queue.enqueue_event(new_agent_text_message(result))
3. 服务器配置 (__main__.py
)
- 定义代理技能 (AgentSkill)
- 配置公共和扩展代理卡片 (AgentCard)
- 设置请求处理器和任务存储
- 启动 Uvicorn 服务器
运行步骤
1. 启动代理服务器
uv run .
服务器将在 http://localhost:9999
启动。
2. 运行测试客户端
在另一个终端窗口中:
uv run test_client.py
3. 验证服务
您可以通过以下方式验证服务是否正常运行:
访问代理卡片信息
curl http://localhost:9999/.well-known/agent.json
访问扩展代理卡片(需要认证)
curl -H "Authorization: Bearer dummy-token-for-extended-card" \http://localhost:9999/agent/authenticatedExtendedCard
项目流程图
A2A 客户端与服务器交互流程
系统架构流程图
API 端点
公共端点
端点 | 方法 | 描述 |
---|---|---|
/.well-known/agent.json | GET | 获取公共代理卡片信息 |
/agent/message | POST | 发送消息给代理 |
/agent/message/stream | POST | 流式发送消息 |
认证端点
端点 | 方法 | 描述 | 认证 |
---|---|---|---|
/agent/authenticatedExtendedCard | GET | 获取扩展代理卡片 | Bearer Token |
技能配置
基础技能
- ID:
hello_world
- 名称: Returns hello world
- 描述: just returns hello world
- 示例: [‘hi’, ‘hello world’]
扩展技能(需要认证)
- ID:
super_hello_world
- 名称: Returns a SUPER Hello World
- 描述: A more enthusiastic greeting, only for authenticated users
- 示例: [‘super hi’, ‘give me a super hello’]
故障排除
常见问题
-
端口被占用
# 检查端口使用情况 lsof -i :9999 # 杀死占用进程 kill -9 <PID>
-
依赖安装失败
# 清理缓存重新安装 uv cache clean uv sync --reinstall
-
Python 版本不兼容
# 检查 Python 版本 python --version # 确保版本 >= 3.10
扩展开发
添加新技能
- 在
__main__.py
中定义新的AgentSkill
- 修改
agent_executor.py
中的逻辑处理 - 更新代理卡片配置
集成外部 API
- 在
pyproject.toml
中添加新依赖 - 在
agent_executor.py
中实现 API 调用 - 处理异步响应和错误
总结
这个 Hello World 示例展示了 A2A SDK 的基本用法,包括:
- 代理服务器的创建和配置
- 技能定义和管理
- 客户端-服务器通信
- 认证和扩展功能
通过这个示例,您可以快速了解如何构建自己的智能代理应用。
python a2a