1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
| class OrchestratorAgent(BaseAgent): """协调者Agent - 负责任务分解和Agent调度"""
def __init__(self, agent_id: str, message_bus: MessageBus, llm: LLMClient): super().__init__(agent_id, "Orchestrator", message_bus, llm) self.worker_agents: Dict[str, Dict] = {}
@property def capabilities(self) -> List[str]: return ["task_decomposition", "agent_coordination", "result_aggregation"]
@property def description(self) -> str: return "负责分解复杂任务、调度Worker Agent、整合执行结果"
def register_worker(self, agent_id: str, capabilities: List[str], description: str): """注册Worker Agent""" self.worker_agents[agent_id] = { "capabilities": capabilities, "description": description, "status": "available" }
async def execute_task(self, task: str) -> Dict[str, Any]: """执行复杂任务"""
subtasks = await self._decompose_task(task)
assignments = await self._assign_tasks(subtasks)
results = await self._execute_assignments(assignments)
final_result = await self._aggregate_results(task, results)
return final_result
async def _decompose_task(self, task: str) -> List[Dict[str, Any]]: """使用LLM分解任务"""
workers_info = "\n".join([ f"- {aid}: {info['description']}, 能力: {info['capabilities']}" for aid, info in self.worker_agents.items() ])
prompt = f""" 你是一个任务分解专家。请将以下任务分解为可以独立执行的子任务。
可用的Agent: {workers_info}
任务:{task}
请以JSON格式返回子任务列表: [ {{ "id": "subtask_1", "description": "子任务描述", "dependencies": [], // 依赖的子任务ID "required_capabilities": ["capability1"] }} ] """
response = await self.llm.generate(prompt) return json.loads(response)
async def _assign_tasks( self, subtasks: List[Dict[str, Any]] ) -> Dict[str, List[Dict]]: """将子任务分配给合适的Agent"""
assignments = defaultdict(list)
for subtask in subtasks: best_agent = self._find_best_agent(subtask["required_capabilities"]) if best_agent: assignments[best_agent].append(subtask) else: raise ValueError(f"No agent can handle: {subtask}")
return dict(assignments)
def _find_best_agent(self, required_capabilities: List[str]) -> Optional[str]: """找到最适合的Agent""" for agent_id, info in self.worker_agents.items(): if info["status"] == "available": if all(cap in info["capabilities"] for cap in required_capabilities): return agent_id return None
async def _execute_assignments( self, assignments: Dict[str, List[Dict]] ) -> Dict[str, Any]: """执行任务分配"""
results = {}
executed = set() pending = []
for agent_id, tasks in assignments.items(): for task in tasks: pending.append((agent_id, task))
while pending: ready = [ (aid, t) for aid, t in pending if all(dep in executed for dep in t.get("dependencies", [])) ]
if not ready: raise ValueError("Circular dependency detected")
tasks_to_run = [] for agent_id, task in ready: tasks_to_run.append(self._execute_single_task(agent_id, task)) pending.remove((agent_id, task))
task_results = await asyncio.gather(*tasks_to_run)
for (agent_id, task), result in zip(ready, task_results): results[task["id"]] = result executed.add(task["id"])
return results
async def _execute_single_task( self, agent_id: str, task: Dict[str, Any] ) -> Dict[str, Any]: """委托单个任务给Worker Agent"""
self.worker_agents[agent_id]["status"] = "busy"
try: result = await self.delegate_task(agent_id, { "type": "execute", "task": task }) return result finally: self.worker_agents[agent_id]["status"] = "available"
async def _aggregate_results( self, original_task: str, results: Dict[str, Any] ) -> Dict[str, Any]: """整合所有子任务结果"""
prompt = f""" 请整合以下子任务的执行结果,生成最终的任务输出。
原始任务:{original_task}
子任务结果: {json.dumps(results, ensure_ascii=False, indent=2)}
请生成结构化的最终结果。 """
response = await self.llm.generate(prompt) return { "status": "completed", "summary": response, "details": results }
async def _handle_task_request(self, message: AgentMessage): """处理任务请求""" task = message.content.get("task") result = await self.execute_task(task) await self.communicator.send_response(message, result)
|