A class built on Pydantic's BaseModel can list fields with types, like contract: str = "". Flow[DeskState] tells the flow to make one and use it as self.state. Let's save this as demo.py:
demo.py
1# demo.py2from crewai.flow.flow import Flow, listen, start
3from pydantic import BaseModel
456classDeskState(BaseModel):7 contract:str=""8 summary:str=""9 notice_days:int=0101112classDesk(Flow[DeskState]):13 suppress_flow_events =True1415@start()16defread_document(self):17 self.state.contract ="Cancel 60 days before it ends."18 self.state.notice_days =601920@listen(read_document)21defreview_contract(self):22 self.state.summary ="Cancel 30 days before it ends."2324@listen(review_contract)25defcheck_summary(self):26if self.state.summary in self.state.contract:27return"the summary matches the contract"28return"the summary is not in the contract"293031desk = Desk()32print(desk.kickoff())33print(desk.state.notice_days)
Terminal
1(env)$ python demo.py
Output
the summary is not in the contract60
Each field starts with the value after its =, and a step reaches it as self.state.summary instead of self.state["summary"].
1@listen(read_document)2defreview_contract(self):3 self.state.sumary ="Cancel 30 days before it ends."
Terminal
1(env)$ python demo.py
Output
Error executing listener review_contract: "StateWithId" object has no field "sumary"Traceback (most recent call last):...ValueError: "StateWithId" object has no field "sumary"
CrewAI adds an id field to our model, so the error calls it StateWithId. Compare where each kind of state stops the run:
Drawing diagram…
ToolResultWhere a misspelled name stops the run
The model stops the run in the step that made the mistake.
Spell summary right again, and put a word in notice_days. Change read_document and review_contract in demo.py:
Python
1@start()2defread_document(self):3 self.state.contract ="Cancel 60 days before it ends."4 self.state.notice_days ="sixty"56@listen(read_document)7defreview_contract(self):8 self.state.summary ="Cancel 30 days before it ends."
Terminal
1(env)$ python demo.py
Output
... PydanticSerializationUnexpectedValue(Expected `int` - serialized value may not be as expected [field_name='notice_days', input_value='sixty', input_type=str])...the summary is not in the contractsixty
Pydantic only warns, the run goes on, and notice_days holds a word. A model checks its values when it's built, so a later = in a step slips through.
Traceback (most recent call last):...pydantic_core._pydantic_core.ValidationError: 1 validation error for StateWithIdnotice_days Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='sixty', input_type=str]
Follow "sixty" both ways:
Drawing diagram…
InputToolResultWhat validate_assignment changes
Let's remove the program. The folder stays for the next chapter.