1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
32 small wins to finish your pathNext lesson →
A task that runs only sometimes
A ConditionalTask runs only when a function you write approves the previous task's output. Otherwise the crew skips it and finishes with what it has.
The desk should email a customer about a missing order, and say nothing extra when the order was found. The clerk's output decides.
from crewai import Agent, Crew, Task
from shop_llm import ShopLLM
from tools import lookup_order
clerk = Agent(role="Order clerk", goal="Find the status of customers' orders",
backstory="You can look up any order in the shop's system.",
llm=ShopLLM(model="shop"), tools=[lookup_order])
writer = Agent(role="Reply writer", goal="Write replies to customers",
backstory="You write short, friendly emails.",
llm=ShopLLM(model="shop"))
look = Task(description="Find the order in this message: {question}",
expected_output="The order's status.", agent=clerk)
reply = Task(description="Write the customer a reply.",
expected_output="A short, friendly email.", agent=writer)
crew = Crew(agents=[clerk, writer], tasks=[look, reply])from crewai.tasks.conditional_task import ConditionalTask
def order_missing(output):
return "not an order we have" in output.raw
apology = ConditionalTask(
description="Tell the customer we cannot find the order in: {question}",
expected_output="A short, friendly email.",
agent=writer, condition=order_missing,
)
crew = Crew(agents=[clerk, writer], tasks=[look, apology])condition receives the output of the task before it and returns True to run, False to skip. The clerk and the look task are lesson 14's.
for question in ["Where is my order A17?", "Where is my order B22?"]:
result = crew.kickoff(inputs={"question": question})
print([output.raw for output in result.tasks_output])For A17 the apology was skipped: its output is empty, and the crew's result is the clerk's finding. For B22 the condition held and the writer ran with the clerk's output as context.
Try it yourself
- Make the condition also catch messages with no order id at all.
- Print
result.rawfor both questions. - Put the conditional task first in the list and read the error.
You understood something today that you didn't yesterday.