crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

feat: implement hierarchical agent delegation with allowed_agents parameter

Open Vardaan-Grover opened this issue 9 months ago • 9 comments

Overview

Enhances CrewAI's delegation system by introducing controlled hierarchical agent structures through the allowed_agents parameter.

Current State

  • Agents can delegate tasks using allow_delegation=True
  • The given agent has access to delegate to any other agent within the crew with no limitations
  • No hierarchy or access control in delegation flow
  • As the number of agents increase within a crew, delegation becomes more and more unreliable and inconsistent

New Feature

Adds allowed_agents parameter to Agent class:

agent = Agent(
    role="Executive Director",
    allow_delegation=True,
    allowed_agents=["Communications Manager", "Research Manager"]
)

Visual Representation

WhatsApp Image 2025-02-09 at 19 53 22 WhatsApp Image 2025-02-09 at 19 53 22 (1)

Benefits

  • Controlled Delegation: Agents can only delegate to specified subordinates
  • Hierarchical Structure: Enables multi-level organizational hierarchies
  • Reduced Choice Paralysis: Agents make decisions from a focused subset
  • Better Specialization: Clear delegation paths for specific tasks
  • Improved Reliability: Consistent delegation patterns

Example Usage

# Top-level management
executive = Agent(
    role="Executive Director",
    allow_delegation=True,
    allowed_agents=["Communications Manager", "Research Manager"]
)

# Mid-level management
comms_manager = Agent(
    role="Communications Manager",
    allow_delegation=True,
    allowed_agents=["Email Agent", "Social Media Agent"]
)

# Specialized workers
email_agent = Agent(
    role="Email Agent",
    allow_delegation=False
)

crew = Crew(
    agents=[executive, comms_manager, email_agent],
    tasks=[task]
)

This pull request includes several changes to improve the delegation capabilities of agents and refactor related code. The most important changes include adding a new allowed_agents field to the BaseAgent class, updating the delegation logic, and enhancing the delegation tool's execution.

Technical Changes

Enhancements to agent delegation:

  • src/crewai/agents/agent_builder/base_agent.py: Added a new allowed_agents field to the BaseAgent class to specify which agents an agent can delegate tasks to.
  • src/crewai/agents/agent_builder/base_agent.py: Introduced a validate_allowed_agents method to ensure the allowed_agents field contains valid agent roles or instances.

Refactoring delegation logic:

  • src/crewai/crew.py: Refactored the _add_delegation_tools method to use the new allowed_agents field and added debug prints to trace the delegation process.
  • src/crewai/tools/agent_tools/base_agent_tools.py: Simplified the _execute method by removing redundant code and improving the delegation process with better logging and error handling.

Vardaan-Grover avatar Feb 09 '25 17:02 Vardaan-Grover

Disclaimer: This review was made by a crew of AI Agents.

Code Review Comment: Agent Delegation Capabilities Enhancement

Overview

This pull request introduces enhanced capabilities for agent delegation within the crewAI framework, which expands the system's flexibility and effectiveness. The changes made are a solid step forward but could greatly benefit from further refinements and improvements.

Detailed Findings

1. Base Agent Implementation Changes

  • Field Validation: The implementation of the allowed_agents field is a valuable addition, but the current validation method lacks thoroughness. Consider implementing a more granular check for allowed agent types, potentially alongside custom exceptions for better error handling.

    Example Improvement: Implement stricter validation like what is proposed in the following code snippet:

    @field_validator('allowed_agents')
    def validate_allowed_agents(cls, v):
        # Advanced validation ensuring all agents are valid roles or BaseAgent instances
        ...
    

2. Crew Class Delegation Logic

  • Complex Logic and Debug Statements: The _setup_delegation method contains complicated logic that handles both task delegation and tool management. This could be separated into distinct methods or even a delegate manager class for clarity.

  • Logging Improvements: Replace the debug print statements with a structured logging approach to facilitate tracking the delegation process, as raw print statements can clutter the production output.

3. BaseAgentTool Execution Logic

  • Direct Print Statements: The _execute_delegation method currently uses print statements, which should be replaced with an appropriate logging mechanism. This adjusts the visibility of execution flows without flooding stdout in production.

  • Error Handling: Introduce custom exceptions for clearer error messaging and to provide callers with specific information on failure points. Consider using:

    class DelegationExecutionError(Exception):
        pass
    

4. General Code Quality

  • Documentation: While several functions have docstrings, many lack detailed examples. Comprehensive documentation would assist future developers by clarifying the intent and usage of methods.

  • Testing: A heavy emphasis on unit tests is essential for any newly implemented feature. Please ensure that tests cover normal operation as well as edge cases in your delegation logic.

  • Performance Considerations: Usage patterns indicate that caching results from delegation validation and optimizing agent lookups would not only enhance performance but also streamline the user experience when handling multiple agents.

Historical Pattern Observations

  • Historically, similar PRs have focused on validating agent interactions and configurations, indicating an ongoing effort to fortify agent management. Analysis of similar alterations suggested improvements in the error handling and logging frameworks.

Conclusion

Overall, the proposed changes significantly advance the delegation capabilities of the crewAI framework. However, addressing the outlined issues related to validation, logging, error handling, and documentation will be crucial for maintaining a robust and maintainable codebase. I look forward to seeing how these recommendations can be integrated into future iterations of the PR.

Thank you for your efforts on this valuable enhancement!

joaomdmoura avatar Feb 09 '25 17:02 joaomdmoura

I like this! Please let me know when it's ready!

bhancockio avatar Feb 19 '25 20:02 bhancockio

This is amazing

SHIXOOM avatar Mar 10 '25 04:03 SHIXOOM

This PR is stale because it has been open for 45 days with no activity.

github-actions[bot] avatar Apr 24 '25 12:04 github-actions[bot]

@Vardaan-Grover any update here?

lucasgomide avatar Apr 24 '25 21:04 lucasgomide

This PR is stale because it has been open for 45 days with no activity.

github-actions[bot] avatar Jun 09 '25 12:06 github-actions[bot]

Is it planned to still work on this ?

Paillat-dev avatar Jul 31 '25 14:07 Paillat-dev

This PR is stale because it has been open for 45 days with no activity.

github-actions[bot] avatar Sep 15 '25 12:09 github-actions[bot]

This PR is stale because it has been open for 45 days with no activity.

github-actions[bot] avatar Nov 01 '25 12:11 github-actions[bot]