A flow: steps in plain Python
A flow is a class whose methods are steps. @start marks where it begins, @listen runs a method when another finishes, and kickoff runs it all.
Crews let a model decide. Much of a support desk needs no model: finding an order id is a regular expression. CrewAI's documentation recommends starting an application with a flow, which runs ordinary Python and calls a crew only where one is needed.
import re
import shop_llm
from crewai.flow.flow import Flow, listen, startclass Desk(Flow):
@start()
def read_ticket(self):
found = re.findall(r"\b[A-Z]\d+\b", self.state["message"])
return found[0] if found else None
@listen(read_ticket)
def answer(self, order_id):
return f"Looking into {order_id}." if order_id else "Which order is this about?"@start() marks read_ticket as an entry point. @listen(read_ticket) runs answer when read_ticket finishes, and passes it that method's return value. import shop_llm is there for its three settings; no model is used yet.
desk = Desk(suppress_flow_events=True)
result = desk.kickoff(inputs={"message": "Where is my order A17?"})
print(result)kickoff runs the flow and returns the last method's return value. inputs goes into the flow's state, a dictionary every method can read as self.state. suppress_flow_events=True turns off the panel a flow prints for each method; leave it out and you see them.
desk = Desk(suppress_flow_events=True)
print(desk.kickoff(inputs={"message": "Hello there"}))
print(desk.state)No order id, so read_ticket returned None and answer asked for one. The state holds the message and an id CrewAI generated for this run; lesson 24 uses that id to come back to a paused flow.
- Add a third method that listens to
answerand adds a signature. - Put two order ids in the message and see which one is used.
- Remove
suppress_flow_events=Trueand count the panels.
Every expert started right here.