Pick up where it stopped
Ready for real workChapter 13 of 155 min read
A run can stop halfway: the terminal closes while it waits for a person, or a step fails. The state lived only in the program, so the next run starts again and pays for the memo again. This chapter answers: how does a run pick up where it stopped?
The state is saved after every step, and the next run loads it by the run's id:
@persist: saves the flow's state to a file after every step.- Run's id: the name the state is saved under.
kickoff(inputs={"id": ...})loads that state back.
Set up#
If you closed the terminal, go back into the folder and switch the environment on:
This chapter needs no model. print("writing the memo") stands in for the agent from chapter 9, so you can see each time it would be paid for.
Way 1: the state lives in the program#
file_report writes into a folder called filed, which doesn't exist yet, so the first run stops there. The last line already gives the run an id, the document's name. Let's save this as demo.py:
Let's make the folder, and run it again:
... stands for the lines Python prints about where the error happened. The first run wrote the memo, then stopped at file_report. The second run wrote the memo again, though the first had already done it. With an agent in that step, you'd pay for that memo twice:
The id did nothing here: nothing was saved under it.
Way 2: save the state, and load it back#
@persist goes on the class, and SQLiteFlowPersistence("desk.db") says where to save: a file in the folder. The state is saved under the run's id, the document's name, so the next run for that document finds it. Add the import to demo.py:
Change Desk in demo.py:
Let's remove the folder, so the first run stops again:
The first run found no state saved under acme-saas-agreement, wrote the memo, and stopped as before. @persist had already saved the state when review_contract finished. The second run loaded it, found the memo, and went straight on to file_report. "From memory" is CrewAI's wording; the state came from desk.db:
A step that doesn't look first#
review_contract writes the memo only if the state has none. Let's take that check out. Change review_contract in demo.py:
CrewAI loaded the saved state, and the memo was written again anyway. @persist brings the state back, but it doesn't skip any step: every step runs, and only a step that looks in the state first can tell its work is done:
Let's remove the program, the saved states and the folder. .env and the inbox stay for the next chapter.
The two ways side by side#
Compare what the second run starts from:
When a run can stop halfway, save its state with @persist under an id you can find again, and let each costly step look in the state first.
What comes next#
The desk now reads one document, waits, and goes on to the next:
One document at a time is slow.