主题
顺序流程
关于在 CrewAI 项目中使用顺序流程执行任务的完整指南。
引言
CrewAI 提供了一个灵活的框架,以结构化方式执行任务,同时支持顺序流程和层级流程。 本指南介绍如何有效实施这些流程,以确保高效的任务执行和项目完成。
顺序流程概览
顺序流程确保任务按照线性顺序依次执行。 这种方法非常适合需要按特定顺序完成任务的项目。
主要特性
- 线性任务流:按预定的顺序处理任务,确保有序推进。
- 简单性:最适合任务清晰、分步骤的项目。
- 易于监控:便于跟踪任务完成情况和项目进度。
实现顺序流程
要使用顺序流程,请组装你的团队,并按任务需要执行的顺序定义任务。
python
from crewai import Crew, Process, Agent, Task, TaskOutput, CrewOutput
# Define your agents
researcher = Agent(
role='Researcher',
goal='Conduct foundational research',
backstory='An experienced researcher with a passion for uncovering insights'
)
analyst = Agent(
role='Data Analyst',
goal='Analyze research findings',
backstory='A meticulous analyst with a knack for uncovering patterns'
)
writer = Agent(
role='Writer',
goal='Draft the final report',
backstory='A skilled writer with a talent for crafting compelling narratives'
)
# Define your tasks
research_task = Task(
description='Gather relevant data...',
agent=researcher,
expected_output='Raw Data'
)
analysis_task = Task(
description='Analyze the data...',
agent=analyst,
expected_output='Data Insights'
)
writing_task = Task(
description='Compose the report...',
agent=writer,
expected_output='Final Report'
)
# Form the crew with a sequential process
report_crew = Crew(
agents=[researcher, analyst, writer],
tasks=[research_task, analysis_task, writing_task],
process=Process.sequential
)
# Execute the crew
result = report_crew.kickoff()
# Accessing the type-safe output
task_output: TaskOutput = result.tasks[0].output
crew_output: CrewOutput = result.output注意:
顺序流程中的每个任务必须分配一个智能体。请确保每个 Task 都包含 agent 参数。
工作流实战
- 初始任务:在顺序流程中,第一个智能体完成其任务并发出完成信号。
- 后续任务:智能体根据流程类型领取各自的任务,前面任务的结果或指令会指导它们的执行。
- 完成:最后一个任务执行完毕后流程结束,项目随之完成。
高级功能
任务委派
在顺序流程中,如果某个智能体的 allow_delegation 设置为 True,它就可以把任务委派给团队中的其他智能体。 当团队中有多个智能体时,该功能会自动启用。
异步执行
任务可以异步执行,在合适的情况下支持并行处理。 要创建异步任务,在定义任务时设置 async_execution=True。
记忆与缓存
CrewAI 同时支持记忆和缓存功能:
- 记忆:创建 Crew 时设置
memory=True即可启用。这能让智能体在任务之间保留信息。 - 缓存:默认已启用缓存。设置
cache=False可将其禁用。
回调
你可以在任务级别和步骤级别设置回调:
task_callback:在每个任务完成后执行。step_callback:在智能体执行的每个步骤后执行。
用量指标
CrewAI 会跟踪所有任务和智能体的 token 用量。执行完成后你可以访问这些指标。
顺序流程的最佳实践
- 顺序很重要:按逻辑顺序安排任务,让每个任务都建立在前一个任务之上。
- 清晰的任务描述:为每个任务提供详细描述,以有效引导智能体。
- 合适的智能体选择:让智能体的技能和角色与每个任务的要求相匹配。
- 善用上下文:利用前面任务的上下文为后续任务提供信息。
本更新后的文档确保细节准确反映代码库的最新变化,并清晰说明如何利用新的特性和配置。 内容保持简单直接,以确保易于理解。