跳转到主要内容

简介

CrewAI 提供了一个灵活的框架,用于以结构化方式执行任务,支持顺序和层级两种流程。本指南概述了如何有效实施这些流程,以确保高效的任务执行和项目完成。

顺序流程概述

顺序流程确保任务按线性进展一个接一个地执行。这种方法非常适用于需要按特定顺序完成任务的项目。

主要特点

  • 线性任务流:通过按预定序列处理任务,确保有序进展。
  • 简单性:最适合具有明确、逐步任务的项目。
  • 易于监控:便于轻松跟踪任务完成情况和项目进度。

实施顺序流程

要使用顺序流程,请组建您的团队,并按照需要执行的顺序定义任务。
代码
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 参数。

工作流程实践

  1. 初始任务:在顺序流程中,第一个代理完成其任务并发出完成信号。
  2. 后续任务:代理根据流程类型接手任务,其执行受先前任务的结果或指令的引导。
  3. 完成:一旦最终任务执行完毕,流程即告结束,项目完成。

高级功能

任务委派

在顺序流程中,如果代理的 allow_delegation 设置为 True,他们可以将任务委派给团队中的其他代理。当团队中有多个代理时,此功能会自动设置。

异步执行

任务可以异步执行,从而在适当时允许并行处理。要创建异步任务,请在定义任务时设置 async_execution=True

记忆与缓存

CrewAI 支持记忆和缓存功能
  • 记忆:在创建 Crew 时设置 memory=True 来启用。这使得代理可以在不同任务之间保留信息。
  • 缓存:默认情况下,缓存是启用的。设置 cache=False 来禁用它。

回调

您可以在任务和步骤两个级别设置回调
  • task_callback:在每个任务完成后执行。
  • step_callback:在代理执行的每个步骤后执行。

用量指标

CrewAI 会跟踪所有任务和代理的 token 使用情况。您可以在执行后访问这些指标。

顺序流程的最佳实践

  1. 顺序至关重要:按逻辑顺序排列任务,使每个任务都建立在前一个任务的基础上。
  2. 清晰的任务描述:为每个任务提供详细的描述,以有效引导代理。
  3. 合适的代理选择:将代理的技能和角色与每个任务的要求相匹配。
  4. 利用上下文:利用先前任务的上下文为后续任务提供信息。
这份更新后的文档确保了细节准确反映了代码库的最新变化,并清楚地描述了如何利用新功能和配置。内容保持简单直接,以确保易于理解。