Chapter 9 · Hierarchical Process and Manager Agents
Chapter goals: Master the运行机制 of
Process.hierarchical, learn to configuremanager_llm/manager_agent, make the right choice between sequential and hierarchical process based on cost and controllability, and learn debugging techniques for hierarchical flows.
9.1 From "Assembly Line" to "Project Manager"
The sequential flow from Chapter 5 is like an assembly line: tasks execute in preset order, output from one handoff to the next. The hierarchical flow is like a company organization: a manager (manager) dynamically decides "which task goes to whom, and whether rework is needed after completion."
The official definition of hierarchical flow: tasks are not pre-assigned to specific agents; the manager plans, delegates, reviews output, and judges completion based on each agent's capabilities.
import os
from crewai import Agent, Crew, Process, Task, LLM
llm = LLM(
model="openai/deepseek-chat",
base_url="https://api.deepseek.com/v1",
api_key=os.getenv("DEEPSEEK_API_KEY"),
temperature=0.7,
)
researcher = Agent(
role="Market Researcher",
goal="Collect and verify market data",
backstory="A frontline researcher skilled at rapid retrieval and cross-validating data.",
llm=llm,
)
analyst = Agent(
role="Data Analyst",
goal="Turn raw data into insights",
backstory="A senior analyst proficient in statistics and visualization.",
llm=llm,
)
writer = Agent(
role="Report Writer",
goal="Produce a clearly structured report",
backstory="Ten years of consulting industry report writing experience.",
llm=llm,
)
# Under hierarchical process, tasks describe "what to do" without specifying an agent
research_task = Task(
description="Research the size and major players in China's smart speaker market for 2025.",
expected_output="Market size summary with data sources cited.",
)
analysis_task = Task(
description="Analyze growth drivers and risks based on research findings.",
expected_output="3-5 analysis conclusions with supporting evidence.",
)
report_task = Task(
description="Write a market entry analysis report for management.",
expected_output="A structured Markdown report under 1000 words.",
)
crew = Crew(
agents=[researcher, analyst, writer], # available talent pool
tasks=[research_task, analysis_task, report_task],
process=Process.hierarchical,
manager_llm=llm, # required (either manager_llm or manager_agent)
verbose=True,
)
result = crew.kickoff()manager_llm / manager_agent is required
The official docs state: when using hierarchical process, you must provide either manager_llm (a string model name or LLM instance) or manager_agent, or the crew will fail to start. The manager is auto-created by the framework (or you can supply a custom manager agent).
9.2 Custom Manager Agent
The default manager is a "invisible hand." When you need to control the manager's style (e.g., more conservative, cost-obsessed, requiring English communication), create a custom manager_agent:
manager = Agent(
role="Project Manager",
goal="Deliver high-quality reports on time with minimal token cost, strictly controlling the quality of every output step",
backstory=(
"A senior project manager. Always decomposes tasks before delegating; "
"rejects any ambiguous output for rework; requires all communication in English."
),
llm=llm,
allow_delegation=True, # managers must allow delegation
)
crew = Crew(
agents=[researcher, analyst, writer],
tasks=[research_task, analysis_task, report_task],
process=Process.hierarchical,
manager_agent=manager, # replace the auto-created default manager with a custom one
)Note: when using manager_agent, do not add this agent to the agents list — it is the manager, not an executor.
9.3 Hierarchical vs Sequential: How to Choose
| Dimension | sequential | hierarchical |
|---|---|---|
| Execution path | Fixed (in task definition order) | Dynamic (manager plans + delegates) |
| Token cost | Low | High (manager planning, review, multi-round communication all consume tokens) |
| Predictability | High, easy to debug | Low; same input may produce different paths |
| Suitable for | Well-defined standard pipelines | Open-ended problems where task decomposition itself requires intelligence |
Decision heuristic: if you can describe it in sequential, don't use hierarchical. The value of hierarchical flow lies in scenarios where "what to do first, what to do next" itself requires reasoning (e.g., open-ended research, troubleshooting), not as an upgrade for ordinary pipelines.
Two agent-level switches further control delegation behavior:
allow_delegation=True/False: whether regular members can subcontract work to colleagues;- How strictly the manager reviews output — guided primarily through
manager_agent's goal/backstory.
# Member-level delegation control: executors focus on their own work, no cross-subcontracting
researcher = Agent(
role="Market Researcher",
goal="Collect and verify market data",
backstory="A frontline researcher skilled at rapid retrieval and cross-validating data.",
llm=llm,
allow_delegation=False, # disable subcontracting: prevent uncontrolled secondary delegation chains among members
)Setting all members' allow_delegation to False and keeping delegation rights only with the manager is the more controllable production approach — all scheduling decisions converge on one place, making logs and costs easier to attribute.
9.4 Debugging Hierarchical Flows
Hierarchical flow's non-determinism makes verbose=True a necessity. Recommended three-step debugging:
# 1. Enable verbose logging to observe the manager's delegation decision chain
crew = Crew(..., process=Process.hierarchical, manager_llm=llm, verbose=True)
result = crew.kickoff()
# 2. Check each task's actual executor and output (see Chapter 12 for CrewOutput details)
for i, task_output in enumerate(result.tasks_output, 1):
print(f"Task {i}: agent={task_output.agent!r}")
print(f" raw first 80 chars: {task_output.raw[:80]}")
# 3. Evaluate whether the hierarchical overhead is worth it using usage_metrics
print(crew.usage_metrics)Common issues and fixes:
- Manager keeps re-delegating the same task: usually because members' role/goal are too similar — the manager can't distinguish capability boundaries. Make roles mutually exclusive and specific;
- Unstable output quality: write strict
expected_outputfor each Task; the manager's review criteria will reference them; - Cost explosion: first get the business logic working with sequential, verify output quality, then evaluate whether hierarchical is necessary.
Chapter Summary
- Hierarchical flow: manager dynamically plans, delegates, and reviews; tasks are not pre-assigned;
- Must provide either
manager_llmormanager_agent; do not addmanager_agentto theagentslist; - Hierarchical flow has significantly higher token cost and non-deterministic paths; use only when "task decomposition requires intelligence";
allow_delegationcontrols regular members' subcontracting ability;- Debugging trifecta: verbose logging, per-task
tasks_outputinspection, andusage_metricsfor cost accounting.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. When using hierarchical process, which of the following is required?
2. Regarding sequential vs hierarchical, which statement is correct?
3. After creating a custom manager_agent, what is the correct approach?
4. In a hierarchical flow, the manager keeps re-delegating the same task to the wrong member. Most likely cause?
🛠️ Hands-On Exercises
- Convert the three-role sequential crew from Chapter 5 to hierarchical (start with
manager_llm), then compare the twousage_metricstoken costs. - Switch to a custom
manager_agent; in the backstory require "every task output must include data sources"; observe output quality changes. - Intentionally make two members' roles nearly identical, observe delegation instability, then fix and record your observations.
Next chapter solves "how the team remembers past collaboration experience": Chapter 10 · Memory System.