According to the documentation, it is possible to apply persistence at the method level, but it seems that this blocks the flow execution before the method on which persistence is specified is actually executed.
This is the example code edited to make persistance works
from crewai.flow.flow import Flow, listen, start
from crewai.flow.persistence import persist
class SelectivePersistFlow(Flow):
@start()
def first_step(self):
self.state["count"] = 1
return self.state["count"]
@persist # Only persist after this method
@listen(first_step)
def important_step(self, prev_result):
self.state["count"] += 1
self.state["important_data"] = "This will be persisted"
return "Important step completed"
@listen(important_step)
def final_step(self, prev_result):
self.state["count"] += 1
return self.state["count"]
# First run
flow1 = SelectivePersistFlow()
result1 = flow1.kickoff()
flow1.plot()
print(f"First run result: {result1}")
# Second run - state is automatically loaded
flow2 = SelectivePersistFlow()
result2 = flow2.kickoff(
inputs={
"id": flow1.state["id"], # Use the same ID to load the persisted state
}
)
print(f"Second run result: {result2}") # Will be higher due to persisted state
As can be seen from the log below, during the first execution the first_step function is executed, but then the flow stops without executing the other two functions.
Flow Execution
Starting Flow Execution
Name: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
Flow: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
└──
Starting Flow…
Flow started with ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
Flow: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
├──
Starting Flow…
└──
Running: first_step
Flow: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
├── Flow Method Step
└──
Completed: first_step
Flow Finished: SelectivePersistFlow
├── Flow Method Step
└──
Completed: first_step
Flow Completion
Flow Execution Completed
Name: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
First run result: First step
Flow Execution
Starting Flow Execution
Name: SelectivePersistFlow
ID: 47899c18-f6f7-4ef5-a4dd-e0a65a834a7e
Flow: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
└──
Starting Flow…
Flow started with ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
Flow: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
├──
Starting Flow…
└──
Running: first_step
Flow: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
├── Flow Method Step
└──
Completed: first_step
Flow Finished: SelectivePersistFlow
├── Flow Method Step
└──
Completed: first_step
Flow Completion
Flow Execution Completed
Name: SelectivePersistFlow
ID: e940f8fa-5687-48f4-abf1-a32c38b051f5
Second run result: First step
Edit:
Using @persist(verbose=False)
or @persist(verbose=True)
seems to solve the problem