|
1 | 1 | import asyncio |
| 2 | +import importlib |
| 3 | +import inspect |
| 4 | +from pathlib import Path |
2 | 5 |
|
3 | | -from .chatbot.graph import ChatbotAgent |
4 | | -from .react.graph import ReActAgent |
| 6 | +from src.agents.common.base import BaseAgent |
| 7 | +from src.utils import logger |
5 | 8 |
|
6 | 9 |
|
7 | 10 | class AgentManager: |
@@ -35,10 +38,51 @@ async def get_agents_info(self): |
35 | 38 | agents = self.get_agents() |
36 | 39 | return await asyncio.gather(*[a.get_info() for a in agents]) |
37 | 40 |
|
| 41 | + def auto_discover_agents(self): |
| 42 | + """自动发现并注册 src/agents/ 下的所有智能体。 |
| 43 | +
|
| 44 | + 遍历 src/agents/ 目录下的所有子文件夹,如果子文件夹包含 __init__.py, |
| 45 | + 则尝试从中导入 BaseAgent 的子类并注册。(使用自动导入的方式,支持私有agent) |
| 46 | + """ |
| 47 | + # 获取 agents 目录的路径 |
| 48 | + agents_dir = Path(__file__).parent |
| 49 | + |
| 50 | + # 遍历所有子目录 |
| 51 | + for item in agents_dir.iterdir(): |
| 52 | + logger.info(f"尝试导入模块:{item}") |
| 53 | + # 跳过非目录、common 目录、__pycache__ 等 |
| 54 | + if not item.is_dir() or item.name.startswith("_") or item.name == "common": |
| 55 | + continue |
| 56 | + |
| 57 | + # 检查是否有 __init__.py 文件 |
| 58 | + init_file = item / "__init__.py" |
| 59 | + if not init_file.exists(): |
| 60 | + logger.warning(f"{item} 不是一个有效的模块") |
| 61 | + continue |
| 62 | + |
| 63 | + # 尝试导入模块 |
| 64 | + try: |
| 65 | + module_name = f"src.agents.{item.name}" |
| 66 | + module = importlib.import_module(module_name) |
| 67 | + |
| 68 | + # 查找模块中所有 BaseAgent 的子类 |
| 69 | + for name, obj in inspect.getmembers(module): |
| 70 | + if ( |
| 71 | + inspect.isclass(obj) |
| 72 | + and issubclass(obj, BaseAgent) |
| 73 | + and obj is not BaseAgent |
| 74 | + and obj.__module__.startswith(module_name) |
| 75 | + ): |
| 76 | + logger.info(f"自动发现智能体: {obj.__name__} 来自 {item.name}") |
| 77 | + self.register_agent(obj) |
| 78 | + |
| 79 | + except Exception as e: |
| 80 | + logger.warning(f"无法从 {item.name} 加载智能体: {e}") |
| 81 | + |
38 | 82 |
|
39 | 83 | agent_manager = AgentManager() |
40 | | -agent_manager.register_agent(ChatbotAgent) |
41 | | -agent_manager.register_agent(ReActAgent) |
| 84 | +# 自动发现并注册所有智能体 |
| 85 | +agent_manager.auto_discover_agents() |
42 | 86 | agent_manager.init_all_agents() |
43 | 87 |
|
44 | 88 | __all__ = ["agent_manager"] |
|
0 commit comments