Buckets:

download
raw
21.4 kB
#!/usr/bin/env python3
"""
CrewAI-Inspired Role-Based Agent System
Extends BaseAgent with crew-style roles, tasks, and orchestration.
Supports sequential and hierarchical task execution with delegation.
"""
import asyncio
import logging
import uuid
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional
from agents.agent_base import AgentMessage, AgentRole, BaseAgent
from core.workflow_engine import EventBus
logger = logging.getLogger("ZenAI.Crew")
class CrewAgent(BaseAgent):
"""An agent that participates in a Crew, with role, goal, backstory, and tools."""
def __init__(
self,
name: str,
role: str = "",
goal: str = "",
backstory: str = "",
agent_role: AgentRole = AgentRole.RESEARCHER,
tools: Optional[List[Callable]] = None,
allow_delegation: bool = False,
orchestrator=None,
):
super().__init__(name=name, role=agent_role, orchestrator=orchestrator)
self.role_description = role
self.goal = goal
self.backstory = backstory
self.tools = tools or []
self.allow_delegation = allow_delegation
self._assigned_tasks: List["CrewTask"] = []
self._output: Dict[str, Any] = {}
def has_tool(self, tool_name: str) -> bool:
return any(getattr(t, "__name__", type(t).__name__) == tool_name for t in self.tools)
def tool_names(self) -> List[str]:
return [getattr(t, "__name__", type(t).__name__) for t in self.tools]
async def execute_task(self, task: Dict) -> Dict:
task_id = task.get("id", "unknown")
description = task.get("description", "")
logger.info(f"[CrewAgent:{self.name}] Executing task {task_id}: {description[:60]}...")
await asyncio.sleep(0.1)
result = {
"task_id": task_id,
"agent": self.name,
"output": f"Executed by {self.name}: {description}",
"timestamp": datetime.now().isoformat(),
}
self._output[task_id] = result
self.update_context(f"task_{task_id}_result", result, share=True)
return result
async def delegate_work(self, task: "CrewTask", target_agent: "CrewAgent") -> Dict:
logger.info(f"[CrewAgent:{self.name}] Delegating '{task.description[:40]}...' to {target_agent.name}")
msg = AgentMessage(
sender=f"{self.name}[{self.id}]",
recipient=target_agent.name,
msg_type="delegation",
content=task.description,
context={"task_id": task.id, "expected_output": task.expected_output},
priority=2,
)
if self.orchestrator:
await self.orchestrator.route_message(msg)
return await target_agent.execute_task(task.to_dict())
def get_summary(self) -> Dict:
return {
"id": self.id,
"name": self.name,
"role": self.role_description,
"goal": self.goal,
"tools": self.tool_names(),
"allow_delegation": self.allow_delegation,
"assigned_tasks": len(self._assigned_tasks),
}
@dataclass
class CrewTask:
"""A task that can be assigned to a CrewAgent."""
id: str = field(default_factory=lambda: f"task_{uuid.uuid4().hex[:8]}")
description: str = ""
agent: Optional[CrewAgent] = None
expected_output: str = ""
tools: List[Callable] = field(default_factory=list)
context: List["CrewTask"] = field(default_factory=list)
_output: Optional[Dict] = None
_status: str = "pending"
def to_dict(self) -> Dict:
return {
"id": self.id,
"description": self.description,
"expected_output": self.expected_output,
"agent": self.agent.name if self.agent else None,
"tools": [getattr(t, "__name__", type(t).__name__) for t in self.tools],
"context_ids": [t.id for t in self.context],
"status": self._status,
"output": self._output,
}
def requires_tools(self) -> List[str]:
return [getattr(t, "__name__", type(t).__name__) for t in self.tools]
def set_output(self, output: Dict):
self._output = output
self._status = "completed"
def set_failed(self, error: str):
self._output = {"error": error}
self._status = "failed"
@dataclass
class CrewResult:
"""Result of a Crew.kickoff() execution."""
tasks_output: List[Dict] = field(default_factory=list)
usage_metrics: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict:
return {"tasks_output": self.tasks_output, "usage_metrics": self.usage_metrics}
@property
def successful(self) -> bool:
return all(t.get("status") == "completed" for t in self.tasks_output)
class Crew:
"""Orchestrates a group of CrewAgents in sequential or hierarchical process."""
def __init__(
self,
agents: List[CrewAgent],
tasks: List[CrewTask],
process: str = "sequential",
manager_agent: Optional[CrewAgent] = None,
verbose: bool = False,
event_bus: Optional[EventBus] = None,
):
if process not in ("sequential", "hierarchical"):
raise ValueError(f"Unknown process: {process}. Use 'sequential' or 'hierarchical'.")
if not agents:
raise ValueError("At least one agent is required.")
if not tasks:
raise ValueError("At least one task is required.")
self.id = f"crew_{uuid.uuid4().hex[:8]}"
self.agents = agents
self.tasks = tasks
self.process = process
self.manager_agent = manager_agent
self.verbose = verbose
self.event_bus = event_bus or EventBus()
self._context: Dict[str, Any] = {}
self._started_at: Optional[datetime] = None
self._completed_at: Optional[datetime] = None
self._usage: Dict[str, Any] = {
"total_tasks": len(tasks),
"completed_tasks": 0,
"failed_tasks": 0,
"skipped_tasks": 0,
"start_time": None,
"end_time": None,
"duration_seconds": 0.0,
"delegations": 0,
}
logger.info(f"[Crew:{self.id}] {len(agents)} agent(s), {len(tasks)} task(s), process='{process}'")
async def kickoff(self) -> CrewResult:
self._started_at = datetime.now()
self._usage["start_time"] = self._started_at.isoformat()
await self.event_bus.emit("crew.started", {"crew_id": self.id, "process": self.process})
logger.info(f"[Crew:{self.id}] Kickoff ({self.process})...")
try:
if self.process == "sequential":
await self._run_sequential()
elif self.process == "hierarchical":
await self._run_hierarchical()
except Exception as e:
logger.error(f"[Crew:{self.id}] Execution failed: {e}")
for task in self.tasks:
if task._status in ("pending", "running"):
task.set_failed(str(e))
self._completed_at = datetime.now()
self._usage["end_time"] = self._completed_at.isoformat()
self._usage["duration_seconds"] = (self._completed_at - self._started_at).total_seconds()
result = self._build_result()
await self.event_bus.emit("crew.completed", {"crew_id": self.id, "result": result.to_dict()})
logger.info(f"[Crew:{self.id}] Done in {self._usage['duration_seconds']:.2f}s")
return result
def get_context(self, key: str, default: Any = None) -> Any:
return self._context.get(key, default)
def set_context(self, key: str, value: Any):
self._context[key] = value
def find_agent_by_name(self, name: str) -> Optional[CrewAgent]:
for a in self.agents:
if a.name == name:
return a
return None
def find_agent_by_role(self, role: str) -> Optional[CrewAgent]:
for a in self.agents:
if a.role_description.lower() == role.lower():
return a
return None
def find_agent_by_tool(self, tool_name: str) -> Optional[CrewAgent]:
for a in self.agents:
if a.has_tool(tool_name):
return a
return None
def _assign_task(self, task: CrewTask) -> CrewAgent:
if task.agent is not None:
if task.agent in self.agents:
return task.agent
logger.warning(f"Assigned agent {task.agent.name} not in crew; re-evaluating")
required_tools = task.requires_tools()
for tool_name in required_tools:
agent = self.find_agent_by_tool(tool_name)
if agent is not None:
return agent
best, best_score = None, -1.0
for agent in self.agents:
score = self._score_agent_for_task(agent, task)
if score > best_score:
best_score, best = score, agent
return best or self.agents[0]
def _score_agent_for_task(self, agent: CrewAgent, task: CrewTask) -> float:
score = 0.1
goal_words = set(agent.goal.lower().split())
desc_words = set(task.description.lower().split())
role_words = set(agent.role_description.lower().split())
score += len(goal_words & desc_words) * 0.15
score += len(role_words & desc_words) * 0.1
atn = set(agent.tool_names())
ttn = set(task.requires_tools())
if atn and ttn:
score += len(atn & ttn) * 0.25
return min(score, 1.0)
async def _run_sequential(self):
executed: set = set()
ordered = self._topological_sort()
for task in ordered:
if task._status == "failed":
continue
if task._status == "completed":
executed.add(task.id)
continue
if not all(dep.id in executed for dep in task.context):
task._status = "skipped"
self._usage["skipped_tasks"] += 1
continue
agent = self._assign_task(task)
task.agent = agent
agent._assigned_tasks.append(task)
task._status = "running"
await self.event_bus.emit(
"task.started",
{
"task_id": task.id,
"agent": agent.name,
"description": task.description[:60],
},
)
if self.verbose:
logger.info(f"[Crew:{self.id}] Running '{task.id}' on {agent.name}")
try:
output = await agent.execute_task(task.to_dict())
task.set_output(output)
self._usage["completed_tasks"] += 1
executed.add(task.id)
self._merge_agent_context(agent)
await self.event_bus.emit("task.completed", {"task_id": task.id, "agent": agent.name, "output": output})
except Exception as e:
task.set_failed(str(e))
self._usage["failed_tasks"] += 1
logger.error(f"[Crew:{self.id}] Task '{task.id}' failed: {e}")
await self.event_bus.emit("task.failed", {"task_id": task.id, "agent": agent.name, "error": str(e)})
async def _run_hierarchical(self):
if self.manager_agent is None:
available = [a for a in self.agents if a.allow_delegation]
if not available:
logger.warning("No manager; falling back to sequential")
return await self._run_sequential()
self.manager_agent = available[0]
logger.info(f"Auto-selected {self.manager_agent.name} as manager")
sub_agents = [a for a in self.agents if a != self.manager_agent]
for task in self.tasks:
if task._status == "failed":
continue
if task.agent and task.agent != self.manager_agent:
delegate = task.agent
else:
delegate = self._assign_task(task)
if delegate == self.manager_agent and sub_agents:
delegate = sub_agents[hash(task.id) % len(sub_agents)]
task.agent = delegate
delegate._assigned_tasks.append(task)
task._status = "running"
self._usage["delegations"] += 1
if self.verbose:
logger.info(f"[Crew:{self.id}] {self.manager_agent.name} delegates '{task.id}' to {delegate.name}")
await self.event_bus.emit(
"task.delegated",
{
"task_id": task.id,
"manager": self.manager_agent.name,
"delegate": delegate.name,
},
)
await self.event_bus.emit(
"task.started",
{
"task_id": task.id,
"agent": delegate.name,
"description": task.description[:60],
},
)
try:
await self.manager_agent.delegate_work(task, delegate)
task.set_output(delegate._output.get(task.id, {}))
self._usage["completed_tasks"] += 1
self._merge_agent_context(delegate)
await self.event_bus.emit(
"task.completed", {"task_id": task.id, "agent": delegate.name, "output": task._output}
)
except Exception as e:
task.set_failed(str(e))
self._usage["failed_tasks"] += 1
logger.error(f"[Crew:{self.id}] Hierarchical task '{task.id}' failed: {e}")
await self.event_bus.emit("task.failed", {"task_id": task.id, "agent": delegate.name, "error": str(e)})
def _topological_sort(self) -> List[CrewTask]:
task_map = {t.id: t for t in self.tasks}
in_degree: Dict[str, int] = {t.id: 0 for t in self.tasks}
adjacency: Dict[str, List[str]] = {t.id: [] for t in self.tasks}
for task in self.tasks:
for dep in task.context:
if dep.id in task_map:
adjacency.setdefault(dep.id, []).append(task.id)
in_degree[task.id] = in_degree.get(task.id, 0) + 1
queue = [tid for tid, deg in in_degree.items() if deg == 0]
sorted_ids = []
while queue:
queue.sort(key=lambda tid: self._task_order_index(tid))
tid = queue.pop(0)
sorted_ids.append(tid)
for nxt in adjacency.get(tid, []):
in_degree[nxt] -= 1
if in_degree[nxt] == 0:
queue.append(nxt)
if len(sorted_ids) != len(self.tasks):
remaining = set(task_map.keys()) - set(sorted_ids)
logger.warning(f"Cycle detected: {remaining}; appending in order")
sorted_ids.extend(remaining)
return [task_map[tid] for tid in sorted_ids]
def _task_order_index(self, task_id: str) -> int:
for i, t in enumerate(self.tasks):
if t.id == task_id:
return i
return 0
def _merge_agent_context(self, agent: CrewAgent):
for key, value in agent.context.items():
if key not in self._context:
self._context[key] = value
def _build_result(self) -> CrewResult:
outputs = [
{
"task_id": t.id,
"description": t.description,
"agent": t.agent.name if t.agent else None,
"status": t._status,
"output": t._output,
}
for t in self.tasks
]
self._usage["outputs_by_status"] = {
"completed": self._usage["completed_tasks"],
"failed": self._usage["failed_tasks"],
"skipped": self._usage["skipped_tasks"],
}
return CrewResult(tasks_output=outputs, usage_metrics=dict(self._usage))
def get_crew_summary(self) -> Dict:
return {
"id": self.id,
"process": self.process,
"agents": [a.get_summary() for a in self.agents],
"tasks": [t.to_dict() for t in self.tasks],
"context_keys": list(self._context.keys()),
"usage": self._usage,
}
def create_crew(
agents: List[CrewAgent],
tasks: List[CrewTask],
process: str = "sequential",
verbose: bool = False,
event_bus: Optional[EventBus] = None,
) -> Crew:
return Crew(agents=agents, tasks=tasks, process=process, verbose=verbose, event_bus=event_bus)
if __name__ == "__main__":
logger.info("=" * 60)
logger.info("CrewAI-Inspired Agent System — Demo")
logger.info("=" * 60)
event_bus = EventBus()
async def _demo_recon():
await asyncio.sleep(0.2)
return {"open_ports": [22, 80, 443], "services": ["ssh", "http", "https"]}
async def _demo_scan():
await asyncio.sleep(0.3)
return {"vulnerabilities": ["CVE-2024-1234", "CVE-2024-5678"]}
async def _demo_report():
await asyncio.sleep(0.1)
return {"report": "Final pentest report generated."}
async def main():
recon_agent = CrewAgent(
name="ReconBot",
role="Senior Recon Specialist",
goal="Discover open ports and running services on target systems",
backstory="Expert in network reconnaissance with years of port scanning experience.",
tools=[_demo_recon],
allow_delegation=False,
)
scan_agent = CrewAgent(
name="VulnBot",
role="Vulnerability Analyst",
goal="Identify and categorize security vulnerabilities",
backstory="Specialist in vulnerability assessment with CVE analysis expertise.",
tools=[_demo_scan],
allow_delegation=False,
)
report_agent = CrewAgent(
name="ReportBot",
role="Report Generator",
goal="Generate comprehensive penetration test reports",
backstory="Automated reporting specialist for professional security documents.",
tools=[_demo_report],
allow_delegation=True,
)
recon_task = CrewTask(
description="Scan target for open ports and running services",
expected_output="List of open ports and service banners",
tools=[_demo_recon],
)
scan_task = CrewTask(
description="Scan identified services for known vulnerabilities",
expected_output="List of CVEs and vulnerability descriptions",
tools=[_demo_scan],
context=[recon_task],
)
report_task = CrewTask(
description="Compile a final penetration test report",
expected_output="A comprehensive PDF report of all findings",
tools=[_demo_report],
context=[recon_task, scan_task],
)
crew = Crew(
agents=[recon_agent, scan_agent, report_agent],
tasks=[recon_task, scan_task, report_task],
process="sequential",
verbose=True,
event_bus=event_bus,
)
event_bus.on("crew.started", lambda d: logger.info(f" [Event] Crew started: {d['process']}"))
event_bus.on("task.started", lambda d: logger.info(f" [Event] Task started: {d['task_id']} -> {d['agent']}"))
event_bus.on("task.completed", lambda d: logger.info(f" [Event] Task completed: {d['task_id']}"))
event_bus.on("crew.completed", lambda _: logger.info(" [Event] Crew completed"))
result = await crew.kickoff()
logger.info("--- Results ---")
logger.info(f" Successful: {result.successful}")
logger.info(f" Duration: {result.usage_metrics.get('duration_seconds', 0):.2f}s")
logger.info(f" Completed: {result.usage_metrics.get('completed_tasks', 0)}")
logger.info(f" Failed: {result.usage_metrics.get('failed_tasks', 0)}")
logger.info(f" Skipped: {result.usage_metrics.get('skipped_tasks', 0)}")
for t_out in result.tasks_output:
icon = "+" if t_out["status"] == "completed" else "-"
logger.info(f" [{icon}] {t_out['task_id']:<20} {t_out['status']}")
logger.info("--- Hierarchical Demo ---")
mgr = CrewAgent(
name="ManagerBot",
role="Pentest Manager",
goal="Coordinate penetration testing activities",
backstory="Experienced security team lead.",
allow_delegation=True,
)
h_crew = Crew(
agents=[mgr, recon_agent, scan_agent, report_agent],
tasks=[
CrewTask(description="Port scan target", expected_output="ports"),
CrewTask(description="Vulnerability assessment", expected_output="vulns"),
],
process="hierarchical",
manager_agent=mgr,
verbose=True,
)
h_result = await h_crew.kickoff()
logger.info(
f" Hierarchical: {len(h_result.tasks_output)} task(s), "
f"{h_result.usage_metrics.get('delegations', 0)} delegation(s)"
)
asyncio.run(main())

Xet Storage Details

Size:
21.4 kB
·
Xet hash:
3468a10f48408e598d74b6904f55c6fd1b0e69f91c066c26d0be06f2c1ec60fb

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.