Lesson 4 of 5 · CrewAI
Processes
How a CrewAI crew runs its work: sequential processes, hierarchical processes with a manager agent, planning, and Flows that add routing, state and plain code.
- 7 min read
- Intermediate
- Reviewed
- Explain sequential and hierarchical processes
- Run a hierarchical crew with a manager that delegates
- Weigh the extra cost and unpredictability of a manager
- Build a Flow with state, a router and listeners
- Combine plain code and crews in one Flow
How the work gets done
A crew's process decides who does which task, and in what order.
A manager that delegates
from crewai import LLM, Agent, Crew, Process, Task
copywriter = Agent(role="Copywriter", goal="Write short, lively announcements",
backstory="You write the shop's newsletters.", llm=LLM(model="anthropic/MODEL_NAME"))
analyst = Agent(role="Sales analyst", goal="Answer questions with figures from the sales data",
backstory="You keep the shop's sales spreadsheets.", llm=LLM(model="anthropic/MODEL_NAME"))
announce = Task( # no agent: the manager decides who does it
description="Announce the spring sale: 15% off all city e-bikes until 30 April.",
expected_output="One sentence for the newsletter.",
)
crew = Crew(
agents=[copywriter, analyst],
tasks=[announce],
process=Process.hierarchical, # a manager agent plans and delegates
manager_llm=LLM(model="anthropic/MODEL_NAME"),
)
result = crew.kickoff()
print(result.raw)
print("Delegations:", announce.delegations)Spring sale is here: 15% off every city e-bike until 30 April! Delegations: 1
The task has no agent. CrewAI creates a manager agent using manager_llm (or your own manager_agent), gives it tools to delegate work and ask questions, and the manager chose the copywriter, not the analyst, for an announcement. announce.delegations counts how often the task was handed off.
What a manager costs
A manager adds model calls to every task: one or more to choose and delegate, and one to review. Here's the difference in plain Python:
# Sequential vs hierarchical, in plain Python. Sequential: you assign each task to an agent.
# Hierarchical: a manager reads each task, picks an agent, then reviews the result.
AGENTS = {"Copywriter": {"write", "announce", "slogan"}, "Sales analyst": {"sales", "figures", "compare"}}
tasks = ["Compare March and April sales figures", "Write a slogan for the spring sale", "Announce the new shop hours"]
calls = {"sequential": 0, "hierarchical": 0}
def agent_works(agent, task, process):
calls[process] += 1 # one model call for the agent
return f"{agent} did: {task}"
# Sequential: the order and the assignments are fixed in code
assigned = ["Sales analyst", "Copywriter", "Copywriter"]
for task, agent in zip(tasks, assigned):
agent_works(agent, task, "sequential")
# Hierarchical: the manager decides who does what (a stand-in for the manager model)
for task in tasks:
calls["hierarchical"] += 1 # manager: choose and delegate
words = set(task.lower().split())
agent = max(AGENTS, key=lambda a: len(AGENTS[a] & words))
print(f"manager -> {agent:<13} {task}")
agent_works(agent, task, "hierarchical")
calls["hierarchical"] += 1 # manager: review the result
print("\nModel calls:", calls)The same three tasks took three model calls sequentially and nine with a manager, and each manager decision is another chance for an unexpected choice.
Crew(..., planning=True) adds another option: before the tasks run, a planning step writes a step-by-step plan for each task and adds it to the task's description. It costs an extra call per run and helps with complex tasks.
Flows: precise control around crews
Sometimes you want certainty about what happens: plain code for the decisions you can make yourself, a crew only where agents add value, and state you can inspect. That's what Flows are for.
from pydantic import BaseModel
from crewai import LLM, Agent, Crew, Task
from crewai.flow.flow import Flow, listen, router, start
class ReviewState(BaseModel):
review: str = ""
stars: int = 0
reply: str = ""
def reply_crew() -> Crew: # a small crew used by one step of the flow
agent = Agent(role="Customer care writer", goal="Reply warmly and helpfully to unhappy customers",
backstory="You answer reviews for Velamuvi Bikes.", llm=LLM(model="anthropic/MODEL_NAME"))
task = Task(description="Write a reply to this {stars}-star review: {review}",
expected_output="A reply of 2 or 3 sentences that offers a concrete fix.", agent=agent)
return Crew(agents=[agent], tasks=[task])
class ReviewFlow(Flow[ReviewState]):
@start()
def read_review(self):
print(f"Review ({self.state.stars} stars): {self.state.review}")
@router(read_review)
def triage(self):
return "unhappy" if self.state.stars <= 3 else "happy" # plain code decides the path
@listen("happy")
def thank(self):
self.state.reply = "Thank you for the kind words! Enjoy the ride." # no model needed
@listen("unhappy")
def write_reply(self):
result = reply_crew().kickoff(inputs={"review": self.state.review, "stars": self.state.stars})
self.state.reply = result.raw
for review, stars in [("Great bike, fast delivery!", 5), ("The charger broke after a week.", 2)]:
flow = ReviewFlow()
flow.kickoff(inputs={"review": review, "stars": stars})
print("Reply:", flow.state.reply)Review (5 stars): Great bike, fast delivery! Reply: Thank you for the kind words! Enjoy the ride. Review (2 stars): The charger broke after a week. Reply: We're sorry the charger failed so soon. It's covered by your warranty: reply with your order number and we'll send a new one today.
The router is plain code: 4 and 5 stars get a fixed thank-you with no model call at all; 3 stars or fewer start a small crew that writes a personal reply. The flow's state (ReviewState) holds the review, the rating and the reply, typed with Pydantic, so every step reads and writes known fields.
Common mistakes
Estimate what a manager agent costs: count the model calls of the same work done by a sequential and a hierarchical crew.
tasks = 5 agent_calls_per_task = 2 # e.g. one tool call and one answer manager_calls_per_task = 2 # choose and delegate, then review # Print the total model calls for a sequential crew and a hierarchical crew, in the form # sequential: <n> hierarchical: <n>
In a hierarchical crew, who decides which agent does a task?
Summary
- Sequential: tasks in order, each by its assigned agent; cheap and predictable.
- Hierarchical: a manager delegates and reviews; flexible but adds calls and unpredictability.
planning=Trueadds a planning step before tasks run.- Flows combine plain code and crews with
@start,@listen,@routerand typed state. - Use code for decisions code can make, and agents where judgement is needed.
Next: the project, a content research crew.
Finished reading? Tick it off to track your progress.