Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:CrewAIInc CrewAI Crew Hierarchical Constructor

From Leeroopedia

Overview

Concrete Crew class configured with Process.hierarchical and manager agent settings for centralized task coordination provided by the CrewAI framework.

Source

Import

from crewai import Crew, Process

Signature

The Crew class orchestrates the overall multi-agent workflow. For hierarchical execution, the key parameters are:

Parameter Type Default Description
agents list[Agent] required The list of specialist worker agents. Does not include the manager agent.
tasks list[Task] required The list of tasks to execute. In hierarchical mode, tasks typically have no pre-assigned agent.
process Process Process.sequential Must be set to Process.hierarchical to enable hierarchical execution.
manager_llm str or LLM or None None LLM for auto-creating a manager agent. Mutually exclusive with manager_agent (manager_agent takes precedence).
manager_agent Agent or None None A custom manager Agent instance. Takes precedence over manager_llm if both are provided.
verbose bool False Whether to log detailed execution information for the entire crew.
memory bool False Whether to enable shared memory across agents in the crew.
max_rpm int or None None Maximum requests per minute across all agents in the crew.
planning bool False Whether to enable planning mode where the crew creates an execution plan before starting.
output_log_file str or None None Optional file path to log crew execution output.

Validation

The check_manager_llm validator enforces the following rule at initialization:

@model_validator(mode="after")
def check_manager_llm(self):
    if self.process == Process.hierarchical:
        if self.manager_agent is None and self.manager_llm is None:
            raise PydanticCustomError(
                "missing_manager_llm_or_manager_agent",
                "For a hierarchical process, either manager_llm or manager_agent must be provided.",
            )
    return self

This ensures that every hierarchical crew has a manager configured before any execution begins. The error is raised during Crew instantiation, not at runtime.

Key Behaviors

  • Process flag activation -- Setting process=Process.hierarchical switches the execution engine from sequential iteration to manager-driven delegation. Without this flag, the crew runs tasks sequentially even if a manager is configured.
  • Manager creation -- If manager_agent is not provided, the framework auto-creates one using manager_llm via the internal _create_manager_agent method.
  • Tool injection -- The manager agent automatically receives DelegateWorkTool and AskQuestionTool, which are configured with references to the specialist agents in the crew.
  • Specialist discovery -- The delegation tools are initialized with the list of specialist agents, enabling role-based lookup when the manager delegates by coworker name.

Example

Complete Hierarchical Crew with Auto-Created Manager

from crewai import Crew, Agent, Task, Process
from crewai_tools import SerperDevTool

# Define specialists
researcher = Agent(
    role="Senior Research Analyst",
    goal="Find comprehensive and accurate information",
    backstory="You are an expert researcher with 15 years of experience in data analysis.",
    tools=[SerperDevTool()],
    allow_delegation=False,
)

writer = Agent(
    role="Expert Content Writer",
    goal="Write clear and engaging content based on research",
    backstory="You are a skilled writer who transforms complex findings into readable content.",
    tools=[],
    allow_delegation=False,
)

reviewer = Agent(
    role="Quality Assurance Reviewer",
    goal="Ensure content accuracy, clarity, and completeness",
    backstory="You are a meticulous reviewer with expertise in fact-checking and editing.",
    tools=[],
    allow_delegation=False,
)

# Define tasks (no agent assignment)
research_task = Task(
    description="Research the impact of large language models on software development in 2024.",
    expected_output="A detailed research summary with key findings, statistics, and source citations.",
)

writing_task = Task(
    description="Write a comprehensive article based on the research findings.",
    expected_output="A 2000-word article with introduction, body sections, and conclusion.",
    context=[research_task],
)

review_task = Task(
    description="Review the article for accuracy, clarity, grammar, and completeness.",
    expected_output="The final polished article with any corrections applied.",
    context=[writing_task],
)

# Assemble hierarchical crew
crew = Crew(
    agents=[researcher, writer, reviewer],
    tasks=[research_task, writing_task, review_task],
    process=Process.hierarchical,
    manager_llm="openai/gpt-4o",
    verbose=True,
)

# Execute
result = crew.kickoff()
print(result)

Complete Hierarchical Crew with Custom Manager

from crewai import Crew, Agent, Task, Process

# Specialists (same as above)
researcher = Agent(
    role="Senior Research Analyst",
    goal="Find comprehensive and accurate information",
    backstory="Expert researcher with deep analytical skills.",
    allow_delegation=False,
)

writer = Agent(
    role="Expert Content Writer",
    goal="Write clear and engaging content",
    backstory="Skilled writer who excels at making complex topics accessible.",
    allow_delegation=False,
)

# Custom manager with detailed coordination instructions
custom_manager = Agent(
    role="Editorial Director",
    goal=(
        "Coordinate the team to produce a high-quality article. "
        "Ensure research is thorough before writing begins. "
        "Review all outputs and request revisions if needed."
    ),
    backstory=(
        "You are an editorial director who has managed content teams for 20 years. "
        "You know exactly when to push for more depth and when to move forward."
    ),
)

# Tasks
research_task = Task(
    description="Research renewable energy trends for 2024.",
    expected_output="Comprehensive research summary with data and sources.",
)

article_task = Task(
    description="Write an article on renewable energy trends based on the research.",
    expected_output="A polished 1500-word article.",
    context=[research_task],
)

# Assemble with custom manager
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, article_task],
    process=Process.hierarchical,
    manager_agent=custom_manager,
    verbose=True,
)

result = crew.kickoff()

Notes

  • The agents list should only contain specialist workers. The manager is specified via manager_agent or manager_llm, not in the agents list.
  • The Process enum is imported from crewai and has two values: Process.sequential (default) and Process.hierarchical.
  • If planning=True is combined with hierarchical mode, the crew will generate an execution plan before starting, but the manager still has final authority over delegation decisions at runtime.
  • The check_manager_llm validator also checks that sequential crews do not unnecessarily specify manager_agent or manager_llm, issuing a warning if they do.

Principle:CrewAIInc_CrewAI_Hierarchical_Crew_Assembly

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment