diff --git a/src/crewai/agents/agent_builder/base_agent.py b/src/crewai/agents/agent_builder/base_agent.py index 207a1769a..e5080d86f 100644 --- a/src/crewai/agents/agent_builder/base_agent.py +++ b/src/crewai/agents/agent_builder/base_agent.py @@ -2,7 +2,7 @@ import uuid from abc import ABC, abstractmethod from copy import copy as shallow_copy from hashlib import md5 -from typing import Any, Dict, List, Optional, TypeVar +from typing import Any, Dict, List, Optional, TypeVar, Union from pydantic import ( UUID4, @@ -107,6 +107,10 @@ class BaseAgent(ABC, BaseModel): default=False, description="Enable agent to delegate and ask questions among each other.", ) + allowed_agents: Optional[List[Union[str, 'BaseAgent']]] = Field( + default=None, + description="List of agent roles or agent instances that this agent can delegate tasks to", + ) tools: Optional[List[Any]] = Field( default_factory=list, description="Tools at agents' disposal" ) @@ -236,6 +240,12 @@ class BaseAgent(ABC, BaseModel): """Set the task tools that init BaseAgenTools class.""" pass + @field_validator('allowed_agents') + def validate_allowed_agents(cls, v): + if v is None: + return v + return [agent.role if isinstance(agent, BaseAgent) else agent for agent in v] + @abstractmethod def get_output_converter( self, llm: Any, text: str, model: type[BaseModel] | None, instructions: str diff --git a/src/crewai/crew.py b/src/crewai/crew.py index 38b96a0e0..125edde18 100644 --- a/src/crewai/crew.py +++ b/src/crewai/crew.py @@ -860,8 +860,24 @@ class Crew(BaseModel): return self._merge_tools(tools, code_tools) def _add_delegation_tools(self, task: Task, tools: List[Tool]): - agents_for_delegation = [agent for agent in self.agents if agent != task.agent] - if len(self.agents) > 1 and len(agents_for_delegation) > 0 and task.agent: + # agents_for_delegation = [agent for agent in self.agents if agent != task.agent] + # if len(self.agents) > 1 and len(agents_for_delegation) > 0 and task.agent: + # if not tools: + # tools = [] + # tools = self._inject_delegation_tools( + # tools, task.agent, agents_for_delegation + # ) + # return tools + if not task.agent or not task.agent.allow_delegation: + return tools + + agents_for_delegation = [] + for agent in self.agents: + if agent == task.agent: + continue + if task.agent.allowed_agents is None or agent.role in task.agent.allowed_agents: + agents_for_delegation.append(agent) + if agents_for_delegation: if not tools: tools = [] tools = self._inject_delegation_tools(