What the steps remember
Code in chargeChapter 3 of 155 min read
The check must compare the summary with the contract, so this chapter answers: where can a later step find what an earlier step made?
Our contract says "Cancel 60 days before it ends.", and the review's summary says 30, wrong on purpose. Follow what happens if somebody believes the summary:
- State: the flow's own memory, a dictionary that every step can read and change.
- Key: the name a value is kept under in the state, such as
"contract".
Set up#
If you closed the terminal, go back into the folder and switch the environment on:
Way 1: hand the contract along#
A new stand-in step, shorten_summary, sits between the review and the check, and needs only the summary. Look at what each arrow has to carry:
Let's save this as demo.py:
The check found the mistake, but shorten_summary had to take the contract and hand it on without ever using it.
Way 2: put it in the state#
Each step puts what it makes in self.state, and any later step reads it from there:
Change demo.py to this:
CrewAI made the state with the desk. Before kickoff(), it held only id, which CrewAI puts in for every desk; after it, the contract and the summary were there too.
Each step now takes only self, and shorten_summary never touches the contract. Nobody had to hand the contract to check_summary. It was in the memory the whole time.
Why every step sees the same state#
All the steps belong to one desk, so self in each of them is that desk:
A key spelled wrong#
A dictionary takes any key, so a typo makes no error where it's written. Change review_contract in demo.py:
Follow the key from where it's put to where it's read:
Let's remove the program. The folder stays for the next chapter.
The two ways side by side#
Compare who has to carry the contract:
Three other places seem to work too, and each one breaks somewhere:
- A variable outside the class: with two desks at once, the second contract replaced the first, 5 times of 5, with no error.
self.contract: works while the program runs, but it isn't part of the state, so the saving in a later chapter leaves it out.self.method_outputs[0]: works until a step is added in front, and the places in the list move.
Return what only the next step needs, and put in the state what a later step needs.
LangGraph, another library for building programs with AI, also gives all its steps one shared state.
What comes next#
The state takes any key and any value, so self.state["notice_days"] = "sixty" puts in a word where a number belongs, with no error.
So what stops a step from putting the wrong thing in?