# 同步执行:串行等待
def sync_weather_check():
temp1 = get_weather("北京") # 等待1秒
temp2 = get_weather("上海") # 再等待1秒
temp3 = get_weather("广州") # 再等待1秒
# 总耗时:3秒+# 异步执行:并发处理
async def async_weather_check():
tasks = [
get_weather("北京"),
get_weather("上海"),
get_weather("广州")
]
results = await asyncio.gather(*tasks) # 并发执行
# 总耗时:1秒+ (最慢的那个)- 并发工具调用: 多个工具同时执行,不再串行等待
- 资源利用率: IO等待期间CPU可以处理其他任务
- 响应速度: 大幅减少用户等待时间
- 多用户并发: 同时处理多个用户请求
- 高吞吐量: 系统整体处理能力显著提升
- 资源优化: 更好的内存和CPU利用率
- 非阻塞: 一个慢请求不会影响其他用户
- 实时响应: 更快的交互反馈
- 系统稳定: 更好的负载处理能力
# 支持同步和异步工具
@agent.tool()
async def async_weather(city: str):
"""获取天气信息(异步)"""
await asyncio.sleep(1) # 模拟网络请求
return {"city": city, "temperature": 25}
@agent.tool()
def sync_weather(city: str):
"""获取天气信息(同步)"""
time.sleep(1) # 同步函数自动在线程池执行
return {"city": city, "temperature": 25}# 控制最大并发数,避免资源过载
from atomagent import AsyncAgent
agent = AsyncAgent(
name="并发助手",
max_concurrent_tools=10, # 最多同时执行10个工具
verbose=True
)# 异步对话接口
response = await agent.chat("查询多个城市天气")| 模式 | 工具调用方式 | 预期耗时 | 性能提升 |
|---|---|---|---|
| 同步Agent | 串行执行 | ~4秒 | 基准 |
| 异步Agent | 并发执行 | ~1.5秒 | 2.7x |
| 并发用户 | 多用户并发 | ~1.5秒/5用户 | 13x |
python async_agent_demo.pyimport asyncio
from atomagent import AsyncAgent
async def main():
# 创建异步Agent
agent = AsyncAgent(
name="异步助手",
max_concurrent_tools=5,
verbose=True
)
# 注册异步工具
@agent.tool()
async def fetch_data(query: str):
"""异步数据获取"""
await asyncio.sleep(1)
return {"data": f"结果for {query}"}
# 异步对话
response = await agent.chat("请获取多个数据")
print(response)
# 运行
asyncio.run(main())from atomagent import AsyncAgent
async def handle_multiple_users():
agent = AsyncAgent(
name="多用户助手",
max_concurrent_tools=10
)
# 同时处理多个用户请求
user_queries = ["查询1", "查询2", "查询3"]
tasks = [agent.chat(query) for query in user_queries]
# 并发执行
responses = await asyncio.gather(*tasks)
return responses- Web服务: 同时服务多个用户
- API网关: 处理大量并发请求
- 数据处理: 并行处理多个数据源
- API调用: 外部服务请求
- 数据库查询: 多表并发查询
- 文件操作: 并行文件处理
- 聊天机器人: 多用户实时对话
- 监控系统: 并发数据收集
- 推荐系统: 并行特征计算
# 根据系统资源调整
max_concurrent_tools = min(cpu_count() * 2, 20)- 优先使用异步工具
- 避免长时间阻塞操作
- 合理使用缓存机制
# 装饰器方式(推荐)
@agent.tool()
def my_tool(param: str):
return "result"
# 方法调用方式
def another_tool(param: str):
return "result"
agent.register_tool(another_tool)# 使用gather处理异常
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
logger.error(f"工具执行失败: {result}")- 并发数监控: 实时工具执行数量
- 响应时间: 各工具执行耗时
- 错误率: 异步任务失败率
- 详细日志: 开启verbose模式
- 任务追踪: 记录每个异步任务状态
- 性能分析: 使用asyncio调试工具
- 避免创建过多并发任务
- 合理设置超时时间
- 注意内存使用情况
- 异步异常需要特殊处理
- 使用try-except包装异步调用
- 实现优雅的降级机制
- 同步工具自动在线程池执行
- 保持与现有代码的兼容性
- 渐进式迁移策略
异步Agent为现代AI应用提供了强大的并发处理能力,是构建高性能、高可用AI系统的重要基础设施。