Finished talking about controlling flows

This commit is contained in:
Brandon Hancock
2024-09-20 11:24:53 -04:00
parent 4e68015574
commit 734018254d
2 changed files with 58 additions and 3 deletions

View File

@@ -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 <name_of_flow>` command. This will create a new CrewAI project for you that includes a folders for your Crews.
##
```
```

View File

@@ -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()