Loading...
Loading...
Building CrewAI Flows on crewai 1.15.x: structured (Pydantic) vs dict state and state.id, @start/@listen/@router wiring, or_/and_ semantics, router labels vs method names, @persist (correct import, where it stores state, restore_from_state_id), checkpointing with CheckpointConfig, @human_feedback and HumanFeedbackResult.feedback, plot(), calling crews and agents from flow methods, kickoff inputs, and the `crewai create flow` scaffold. Use when writing or debugging a Flow subclass or main.py with `from crewai.flow import ...`, when a listener never fires or fires twice, or when you see errors like "listen condition 'x' references the handler name 'x'", "cannot import name 'persist'", "'StateWithId' object is not subscriptable", "Flow state model must have an 'id' field", "--inputs requires a declarative flow definition", "invoked synchronously from within a running event loop", or HumanFeedbackCollapseError.
npx skill4agent add crewaiinc/skills build-flowcrewai versionask-docscrewai create flow lead-router # the package is still lead_router
cd lead_router
crewai install # uv sync; writes uv.lock
crewai run # runs the `kickoff` script in pyproject.toml
crewai flow plot # runs the `plot` script| File | Contents |
|---|---|
| |
| A |
| A classic |
| |
| Coding-assistant instructions and an empty tests folder |
| |
llm: anthropic/claude-haiku-4-5agents.yamluv add "crewai[anthropic]"ANTHROPIC_API_KEY=<your-key>.envcrewai run.env[tool.crewai] type = "flow"crewai runuv run kickoffplan_content()self.state.topic"AI Agents"kickoff(inputs={"topic": ...})inputsplot()plot()show=Truecrewai flow plotplot("<name>.html", show=False)from lead_router.crews.content_crew.content_crew import ContentCrewkickoff()main.pyNonesys.exit(kickoff())crewai runcrewai runcrewai run --inputs '{...}'Error: --inputs requires a declarative flow definition ([tool.crewai].definition) or --definitionflow.kickoff(inputs=...)sys.argvkickoff()uv run kickoff '<json>'crewai flow kickoffcrewai runAn error occurred while running the flow: Command '['uv', 'run', 'kickoff']' returned non-zero exit status 1.| Structured (recommended) | Unstructured | |
|---|---|---|
| Declare | | |
| Access | | |
| Added for you ( | |
| Validation | | none |
from pydantic import BaseModel
from crewai.flow import Flow, listen, start
class ReportState(BaseModel):
topic: str = "" # give every field a default
draft: str = ""
notes: list[str] = []
class ReportFlow(Flow[ReportState]):
@start()
def plan(self):
self.state.notes.append(f"planning {self.state.topic}")
return self.state.topic.upper()
@listen(plan)
def write(self, plan_output): # receives plan()'s return value
self.state.draft = f"Draft about {plan_output}"
return self.state.draft
flow = ReportFlow()
result = flow.kickoff(inputs={"topic": "bees"}) # inputs set state BEFORE @start runs
print(result) # "Draft about BEES" - kickoff returns the last method's output
print(flow.state.id) # UUID string, generated per run| Rule | What happens if you break it |
|---|---|
Do not declare | A declared |
Use | |
| Give every field a default | A required field: |
| Use attribute access on structured state | |
Spell | Unknown keys are silently dropped on structured state |
Pass | |
Never set | It is the persistence key; use |
GET /inputsididinputsPOST /kickoffkickoff(inputs=...)inputs{"text": "..."}200kickoff_idstate.idkickoff_id@start@listen@routerfrom typing import Literal
from pydantic import BaseModel
from crewai.flow import Flow, listen, router, start
class TicketState(BaseModel):
text: str = ""
queue: str = ""
class TicketFlow(Flow[TicketState]):
@start()
def receive(self):
return self.state.text
@router(receive)
def triage(self) -> Literal["urgent", "normal"]: # labels, not method names
return "urgent" if "outage" in self.state.text else "normal"
@listen("urgent")
def page_oncall(self):
self.state.queue = "oncall"
@listen("normal")
def file_ticket(self):
self.state.queue = "backlog"
flow = TicketFlow()
flow.kickoff(inputs={"text": "outage in eu-west"})
print(flow.state.queue) # oncall| Rule | Why |
|---|---|
| A router label must not equal the name of the method that listens for it | |
| Pick labels that match no method name at all | A label is just an event name, and so is every method name. A router that returns the name of the method that triggers it re-runs that branch until |
| Make sure every label the router can return has a listener | An unmatched label ends the flow silently; |
Declare labels with a | Only for |
| A typo in a string is just an event nobody emits |
or_and_from crewai.flow import Flow, and_, listen, or_, start
calls = []
class FanIn(Flow):
@start()
def fetch_a(self):
return "A"
@start()
def fetch_b(self):
return "B"
@listen(or_(fetch_a, fetch_b))
def first_result(self, value):
calls.append(("or", value))
@listen(and_(fetch_a, fetch_b))
def all_results(self, value):
calls.append(("and", value))
FanIn().kickoff()
print(calls) # e.g. [('or', 'A'), ('and', 'B')] - the start methods run concurrently, so the values (and order) can varyor_or_@listen(or_(write_draft, "needs_revision"))needs_revision@listen("needs_revision")v1@router("needs_revision") def revise(...): ...; return "revised"or_(write_draft, "revised")and_self.state@listen(or_(page_oncall, file_ticket))from crewai import Agent, Crew, Task
from crewai.flow import Flow, listen, start
class ResearchFlow(Flow):
@start()
def research(self):
researcher = Agent(role="Researcher", goal="Research {topic}",
backstory="You find facts.", llm="openai/gpt-4o-mini")
task = Task(description="List three facts about {topic}.",
expected_output="Three bullets.", agent=researcher)
out = Crew(agents=[researcher], tasks=[task]).kickoff(inputs={"topic": "bees"})
return out.raw # CrewOutput: .raw .pydantic .json_dict
@listen(research)
def summarize(self, facts):
writer = Agent(role="Writer", goal="Summarize", backstory="Concise.",
llm="openai/gpt-4o-mini")
return writer.kickoff(f"One sentence summary: {facts}").raw # LiteAgentOutput| Method kind | Call | Wrong form |
|---|---|---|
| | - |
| | |
await crew.akickoff()mcps=["https://..."]MCPServerHTTP(url=...)crewai.mcp{placeholders}kickoff(inputs=...){topic}MyCrew().crew()@CrewBaseReportFlow().plan()@persistfrom pydantic import BaseModel
from crewai.flow import Flow, persist, start # or: from crewai.flow.persistence import persist
class CounterState(BaseModel):
count: int = 0
@persist() # class level: state saved after every method
class CounterFlow(Flow[CounterState]):
@start()
def bump(self):
self.state.count += 1
return self.state.count
first = CounterFlow()
first.kickoff() # count == 1
second = CounterFlow()
second.kickoff(restore_from_state_id=first.state.id) # count == 2
print(second.state.id != first.state.id) # True: a fork with a new id| You want | Do | Not |
|---|---|---|
| Import | | |
| Decorate | | Bare |
| Seed a new run from a saved state | | |
| Save only at a checkpoint-worthy step | | Class-level when you only need the final state |
| Change some fields on the restored run | Pass them in | Editing the SQLite file |
SQLiteFlowPersistenceflow_states.dbappdirs.user_data_dir(<CREWAI_STORAGE_DIR or current dir name>, "CrewAI")~/Library/Application Support/<name>/~/.local/share/<name>/CREWAI_STORAGE_DIR@persist(SQLiteFlowPersistence("/abs/path/flows.db"))restore_from_state_idrestore_from_state_id@persist@persistFlowPersistence@persist()restoreFromStateIdinputsPOST /kickoff| Kickoff body | Observed |
|---|---|
| State restored (counter and list carried over, fields not in |
Same, after two | Still restored - the saved state survived the redeploys |
| No error; the run starts from defaults |
| Restored and kept the old |
self.state.idkickoff_id@persistfrom crewai import CheckpointConfig
from crewai.flow import Flow, listen, start
class EtlFlow(Flow):
@start()
def extract(self):
return "rows"
@listen(extract)
def load(self, rows):
return f"loaded {rows}"
flow = EtlFlow(checkpoint=CheckpointConfig(
location="./.checkpoints",
on_events=["method_execution_finished"], # required for flows, see below
))
flow.kickoff()EtlFlow().kickoff(from_checkpoint=CheckpointConfig(restore_from="./.checkpoints/<branch>/<file>.json"))flow = EtlFlow.from_checkpoint(CheckpointConfig(restore_from=path))flow.stateflow.kickoff()on_events=["method_execution_finished"]["task_completed"]checkpoint=Truelocation/<branch>/<timestamp>_<id>_p-<parent>.jsonmax(files, key=os.path.getmtime)crewai checkpoint list <location>@router@human_feedbackemitNonekickoff(from_checkpoint=..., restore_from_state_id=...)ValueError: Cannot combine ...@human_feedbackfrom crewai.flow import Flow, HumanFeedbackResult, human_feedback, listen, start
class ReviewFlow(Flow):
@start()
@human_feedback(
message="Approve this draft?",
emit=["needs_revision", "approved"],
llm="openai/gpt-4o-mini", # maps free-text feedback to one label
default_outcome="needs_revision", # used when feedback is empty
)
def draft(self):
return "Draft v1"
@listen("approved")
def publish(self, result: HumanFeedbackResult):
return f"published: {result.output} ({result.feedback})"
@listen("needs_revision")
def revise(self, result: HumanFeedbackResult):
return f"revise: {result.feedback}"HumanFeedbackResultoutputfeedbackoutcometimestampmethod_namemetadataresult.feedbackfeedback_textself.last_human_feedbackself.human_feedback_historydefault_outcomeemit[0]default_outcomeHumanFeedbackCollapseErrorllmanthropic/claude-haiku-4-5approvedneeds_revisionresult.feedbackdefault_outcomeemitValueError: default_outcome requires emit to be specified.emitHumanFeedbackResultprovider=request_feedback(context, flow) -> strHumanFeedbackPendingMyFlow.from_pending(flow_id, persistence).resume(feedback)< /dev/nullEOFError: EOF when reading a lineinput()plot()path = TicketFlow().plot("ticket_flow.html", show=False)
print(path) # /tmp/.../crewai_flow_xxxx/ticket_flow.htmlplot(filename="crewai_flow.html", show=True)plot("my_flow")my_flow.htmlshow=Trueshow=FalseLiteral[...]emit=[...].js.htmlcrewai.flowConversationConfigConversationStateRouterConfigcrewai.experimental.conversationalflow.handle_turn(message, session_id=...)kickoff(user_message=...)ChatSession| Symptom | Cause | Fix |
|---|---|---|
| | |
| Bare | |
| Router label equals the listening method's name | Rename the label or the method |
| Router returned a label equal to a method name (often its own trigger) | Use labels that are not method names |
| Flow stops after the router, no error | Router returned a label with no | Listen for every label; type the router |
| Listener runs only once though both upstreams finished | That is | Use |
| Input value ignored | Key misspelled; structured state drops unknown keys | Match field names exactly |
| Dict access on structured state | |
| | |
| | Return |
| | Pass inputs in code or via |
| | |
| Resumed run starts from defaults | Unknown id, or no | Check the id and decorator; both cases are silent |
| Same execution id reused across runs | | |
| No checkpoint files for a flow | Default | |
Checkpoint resume returns a label (or | The checkpoint was taken after a router finished | Resume from a checkpoint before the router, or re-run |
| Console provider with no stdin | Pass |
Scaffolded flow ignores the | Template | Remove the assignment |
| Old field name | |
| Feedback matched no | Clear labels, a capable |
| It writes to a temp dir | Use the returned path |
Flow[MyState]idLiteral[...]emit=[...]plot()or_and_async defawait crew.akickoff()kickoff()persistcrewai.flow@persist()restore_from_state_idrestoreFromStateIdCREWAI_STORAGE_DIRon_events=["method_execution_finished"]@human_feedbackdefault_outcome.feedbackmain.kickoff()None[tool.crewai] type = "flow"crewai flow plotplot(show=False)or_FlowPersistencehandle_turnConversationConfigtype = "flow"