diff --git a/docs/core-concepts/Flows.md b/docs/core-concepts/Flows.md index 4a0986a17..a20fbe958 100644 --- a/docs/core-concepts/Flows.md +++ b/docs/core-concepts/Flows.md @@ -302,8 +302,64 @@ The output of the Flow will be: ### Router +The `@router()` decorator in Flows allows you to define conditional routing logic based on the output of a method. You can specify different routes based on the output of the method, allowing you to control the flow of execution dynamically. + +```python +import asyncio +import random +from crewai.flow.flow import Flow, listen, router, start +from pydantic import BaseModel + +class ExampleState(BaseModel): + success_flag: bool = False + +class RouterFlow(Flow[ExampleState]): + + @start() + async def start_method(self): + print("Starting the structured flow") + random_boolean = random.choice([True, False]) + self.state.success_flag = random_boolean + + @router(start_method) + async def second_method(self): + if self.state.success_flag: + return "success" + else: + return "failed" + + @listen("success") + async def third_method(self): + print("Third method running") + + @listen("failed") + async def fourth_method(self): + print("Fourth method running") + + +async def main(): + flow = RouterFlow() + await flow.kickoff() + + +asyncio.run(main()) +``` + +In the above example, the `start_method` generates a random boolean value and sets it in the state. The `second_method` uses the `@router()` decorator to define conditional routing logic based on the value of the boolean. If the boolean is `True`, the method returns `"success"`, and if it is `False`, the method returns `"failed"`. The `third_method` and `fourth_method` listen to the output of the `second_method` and execute based on the returned value. + +When you run this Flow, the output will change based on the random boolean value generated by the `start_method`, but you should see an output similar to the following: + +``` +Starting the structured flow +Third method running +``` + ## Adding Crews to Flows - The easiest way to create flows with Crews is to use the `crewai create flow ` command. This will create a new CrewAI project for you that includes a folders for your Crews. ## + +``` + +``` diff --git a/src/crewai/flow/structured_test_flow_router.py b/src/crewai/flow/structured_test_flow_router.py index 91fff2d00..b6de32f78 100644 --- a/src/crewai/flow/structured_test_flow_router.py +++ b/src/crewai/flow/structured_test_flow_router.py @@ -9,8 +9,7 @@ class ExampleState(BaseModel): success_flag: bool = False -class StructuredExampleFlow(Flow): - initial_state = ExampleState +class RouterFlow(Flow[ExampleState]): @start() async def start_method(self): @@ -35,7 +34,7 @@ class StructuredExampleFlow(Flow): async def main(): - flow = StructuredExampleFlow() + flow = RouterFlow() await flow.kickoff()