CrewAI Community Version(五)——Flows基础
目录
1. Flows简介
CrewAI Flows是一项强大的功能,旨在简化AI工作流的创建与管理。通过流程,开发者能够高效组合和协调编码任务与团队协作,为构建复杂的AI自动化提供坚实框架。
Flows功能让你能够创建结构化、事件驱动的工作流。它提供了一种无缝连接多个任务、管理状态并控制AI应用程序执行流程的方式。通过Flows,你可以轻松设计和实现多步骤流程,充分发挥CrewAI的全部潜能:
1. 简化工作流创建:轻松将多个Crews和任务串联起来,构建复杂的AI工作流程。
2. 状态管理:Flows使管理和共享工作流中不同任务间的状态变得极其简单。
3. 事件驱动架构:基于事件驱动模型构建,支持动态响应式的工作流程。
4. 灵活控制流:在工作流中实现条件逻辑、循环和分支。
2. 创建Flows
创建Flow项目:crewai create flow <your-project-name>。
安装依赖:crewai install。
2.1 项目结构

| 路径 | 含义 |
|---|---|
| src/<your-project-name>/crews | 工作流中使用的Crew |
| src/<your-project-name>/tools | 自定义工具 |
| src/<your-project-name>/main.py | 定义工作流 |
| 其余的同Crew项目 |
2.2 Poem Crew(创建项目时自动生成的)
智能体的设定如下:
poem_writer:
role: >
CrewAI Poem Writer
goal: >
Generate a funny, light heartedpoem about how CrewAI
is awesome with a sentence count of {sentence_count}
backstory: >
You're a creative poet with a talent for capturing the essence of any topic
in a beautiful and engaging way. Known for your ability to craft poems that
resonate with readers, you bring a unique perspective and artistic flair to
every piece you write.
智能体需要执行的任务如下:
write_poem:
description: >
Write a poem about how CrewAI is awesome.
Ensure the poem is engaging and adheres to the specified sentence count of {sentence_count}.
expected_output: >
A beautifully crafted poem about CrewAI, with exactly {sentence_count} sentences.
agent: poem_writer
2.3 PoemFlow(创建项目时自动生成的)
2.3.1 PoemState
PoemState是PoemFlow的流程状态,其中包含句子数sentence_count和诗歌poem,流程中的变量会在流执行过程中进行更新。
class PoemState(BaseModel):
sentence_count: int = 1
poem: str = ""
2.3.2 PoemFlow
PoemFlow中通过start()和listen()装饰器来指定流的执行过程:
1. @start()装饰器用于将方法标记为流的起点。当流启动时,所有用@start()装饰的方法将并行执行。一个流可以有多个起始方法,它们都会在流程启动时被执行。
2. @listen()装饰器用于将方法标记为流程中另一个任务的监听器。被@listen()装饰的方法将在指定任务发出输出时执行。该方法可以访问其监听任务的输出作为参数。@listen()可以通过方法名或方法本身来进行监听,例如@listen(generate_sentence_count)或@listen(“generate_sentence_count”)。
class PoemFlow(Flow[PoemState]):
@start()
def generate_sentence_count(self):
print("Generating sentence count")
self.state.sentence_count = randint(1, 5)
@listen(generate_sentence_count)
def generate_poem(self):
print("Generating poem")
result = (
PoemCrew()
.crew()
.kickoff(inputs={"sentence_count": self.state.sentence_count})
)
print("Poem generated\n", result.raw)
self.state.poem = result.raw
@listen(generate_poem)
def save_poem(self):
print("Saving poem")
with open("poem.txt", "w") as f:
f.write(self.state.poem)
2.3.3 PoemFlow的流程图展示
运行命令:crewai flow plot。
运行后得到crewai_flow.html网页,选择浏览器或Pycharm自身打开,得到如下的流程图:

2.4 演示
安装项目依赖并运行:
crewai run
crewai install
运行结果:




参考
更多推荐
所有评论(0)