Skip to content
/

A state with rules

Code in chargeChapter 4 of 154 min read

A dictionary takes any key and any value, so this chapter answers: what stops a step from putting the wrong thing in the state?


The answer is a list of what the state may hold, written before the flow runs. Look at what each field promises:

Drawing diagram…
InputResultThe state's fields, and what each one holds
  • Field: one thing the state holds, with a name and a type.
  • Type: the kind of value a field takes: str for text, int for a whole number.
  • Model: a class that lists the fields. We write ours with Pydantic, a library that comes with CrewAI.

Set up#

If you closed the terminal, go back into the folder and switch the environment on:

Terminal
$ cd document-desk
$ source env/bin/activate

The state as a model#

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
# demo.py
from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel


class DeskState(BaseModel):
    contract: str = ""
    summary: str = ""
    notice_days: int = 0


class Desk(Flow[DeskState]):
    suppress_flow_events = True

    @start()
    def read_document(self):
        self.state.contract = "Cancel 60 days before it ends."
        self.state.notice_days = 60

    @listen(read_document)
    def review_contract(self):
        self.state.summary = "Cancel 30 days before it ends."

    @listen(review_contract)
    def check_summary(self):
        if self.state.summary in self.state.contract:
            return "the summary matches the contract"
        return "the summary is not in the contract"


desk = Desk()
print(desk.kickoff())
print(desk.state.notice_days)
Terminal
(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"].

A field spelled wrong#

Change review_contract in demo.py:

Python
    @listen(read_document)
    def review_contract(self):
        self.state.sumary = "Cancel 30 days before it ends."
Terminal
(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.

A word where a number belongs#

Spell summary right again, and put a word in notice_days. Change read_document and review_contract in demo.py:

Python
    @start()
    def read_document(self):
        self.state.contract = "Cancel 60 days before it ends."
        self.state.notice_days = "sixty"

    @listen(read_document)
    def review_contract(self):
        self.state.summary = "Cancel 30 days before it ends."
Terminal
(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.

Checking every change#

model_config holds the model's settings, and validate_assignment=True checks every =. Change DeskState in demo.py:

Python
from pydantic import BaseModel, ConfigDict


class DeskState(BaseModel):
    model_config = ConfigDict(validate_assignment=True)

    contract: str = ""
    summary: str = ""
    notice_days: int = 0
Terminal
(env)$ python demo.py
Output
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.

Terminal
(env)$ rm demo.py

A dictionary or a model?#

A model names every field and its type before the run, and with validate_assignment=True it checks every change.

Drawing diagram…
InputResultA dictionary or a model?

CrewAI's docs call these two kinds structured and unstructured state.

What comes next#

Every document still goes through the same steps, in one line.

So how does each document take its own path?