CrewAI Community Version(一)——初步了解以及QuickStart样例

发布于:2025-04-21 ⋅ 阅读:(12) ⋅ 点赞:(0)

1. CrewAI简介

  CrewAI是一个精简、快如闪电的Python框架,完全独立于LangChain或其他Agent框架。它为开发者提供了高层次简洁性与精准低层次控制的双重优势,是创建适用于任何场景的自主AI代理的理想框架,存在如下的两种模式:
  1. CrewAI Crews:优化自主性与协作智能,使您能够创建具备特定角色、工具、目标的智能体团队。
  2. CrewAI Flows:支持细粒度的事件驱动控制,通过单一LLM调用实现精准任务编排,并原生支持智能体团队协作。

1.1 CrewAI Crews

  下图源自CrewAI。
在这里插入图片描述

组成 描述 作用
Crew 最顶层的组织 1. 管理智能体团队
2. 监督工作流
3. 保证协作
4. 输出结果
AI Agents 专业的团队成员 1. 有特定的角色
2. 使用指定的工具
3. 可以委派任务
4. 自主决策
Process 工作流管理系统 1. 定义协作模式
2. 控制任务
3. 管理交互
4. 保证高效执行
Tasks 个人任务 1. 有明确的目标
2. 使用特定的工具
3. 输入到更大的Process
4. 产生可行的结果

1.2 CrewAI Flows

  下图源自CrewAI。
在这里插入图片描述

组成 描述 作用
Flow 结构化工作流安排 1. 管理执行路径
2. 处理state
3. 控制任务顺序
4. 保证执行可靠
Events 工作流行动的触发器 1. 启动特定Processes
2. 启用动态响应
3. 支持条件分支
4. 允许实时适应
States 工作流执行上下文 1. 维持执行数据
2. 启用持久性
3. 支持可恢复性
4. 保证执行完整性
Crew Support 增强工作流自动化 1. 在需要时注入Crew
2. 补充结构化工作流
3. 平衡自动化与智能
4. 支持自适应决策

1.3 Crews和Flows的使用情景

情景 推荐方法 原因
开放性研究 Crews 任务需要创造性思考、探索和适应
生成内容 Crews 文章、报告和营销材料需要联合协作
决策工作流 Flows 决策路径具备可预测性、审计性和精细控制
API编排 Flows 需要按照特定顺序对多个外部服务进行可靠的集成
混合应用 Crews、Flows 使用Flows编排整个过程,同时使用Crews处理复杂子任务

  当你需要自主解决问题、合作创新或进行探索性任务时,应该选择Crews;当你需要确定性的结果、审计能力或对执行的精准控制,应该选择Flows;当你的应用需要结构化过程和一些自主智能时,应该联合Crews和Flows。

2. CrewAI安装

2.1 安装uv

  uv是用Rust编写的Python包管理器,目前使用Python的新项目基本上都使用它来对项目中的依赖进行管理。Windows上安装的命令:
  powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

2.2 安装CrewAI CLI

  安装CrewAI CLI的命令:
  uv tool install crewai
  配置CrewAI的路径:
  uv tool update-shell
  验证CrewAI安装:
  uv tool list
  更新CrewAI:
  uv tool install crewai --upgrade

3. 官网QuickStart样例

3.1 创建CrewAI Crews项目

  创建CrewAI Crews项目:
  crewai create crew <your-project-name>

3.2 项目结构

  项目结构图如下。
在这里插入图片描述

路径 作用
<your-project-name>/.venv 项目下的Python环境
<your-project-name>/knowledge 本地知识库目录
<your-project-name>/src/<your-project-name>/config/agents.yaml 定义智能体及其角色
<your-project-name>/src/<your-project-name>/config/tasks.yaml 设置智能体任务和工作流
<your-project-name>/src/<your-project-name>/tools 自定义智能体工具的目录
<your-project-name>/src/crew.py 协调、编排Crews
<your-project-name>/src/main.py 项目入口、执行流
<your-project-name>/tests 测试目录
<your-project-name>/.env 存放大模型API Keys和环境变量
<your-project-name>/.gitignore 配置git忽略的文件或文件夹
<your-project-name>/pyproject.toml Python项目配置
<your-project-name>/README.md CrewAI官方给出的项目运行指导
<your-project-name>/uv.lock uv锁定的Python依赖

3.3 .env

  CrewAI支持调用和OpenAI的API规范一致的大模型,这里我选择了deepseek-chat。

MODEL=openai/deepseek-chat
OPENAI_API_KEY="your-api-key"
OPENAI_API_BASE="https://api.deepseek.com/v1"

3.4 智能体角色及其任务

3.4.1 agents.yaml

  样例中定义了两个智能体research和reporting_analyst,分别给它们定义了role、goal和backstory。此外,在role、goal和backstory中可以通过{变量名}的方式插入用户输入的内容。

researcher:
  role: >
    {topic}领域的高级数据研究员
  goal: >
    发掘{topic}领域的前沿发展
  backstory: >
    你是一位经验丰富的研究员,擅长发掘{topic}领域的最新进展。你能够找到最相关的信息并以清晰简洁的方式呈现。
    

reporting_analyst:
  role: >
    {topic}领域的报告分析师
  goal: >
    基于{topic}领域的数据分析和研究发现,创建详细的报告
  backstory: >
    你是一位细致入微的分析师,对细节有着敏锐的洞察力。你能够将复杂的数据转化为清晰简洁的报告,使他人能够轻松理解并基于你提供的信息采取行动。

3.4.2 tasks.yaml

  tasks.yaml中给researcher和reporting_analyst分别分配了任务research_task和reporting_task,在每个任务中给出了任务描述description、任务输出expected_output和该任务所属的智能体agent。同样,在description、expected_output中可以通过{变量名}的方式插入用户的内容。

research_task:
  description: >
    对{topic}领域进行深入研究,确保在当前年份{current_year}下找到所有有趣且相关的信息。
  expected_output: >
    列出关于{topic}的10个要点,涵盖最相关的信息。
  agent: researcher

reporting_task:
  description: >
    审查获取的内容,并将每个主题扩展为完整的报告章节。确保报告详尽,包含所有相关信息。
  expected_output: >
    一份完整的报告,每个主要主题均包含详细的信息章节,以Markdown格式呈现(不包含代码块标记)。
  agent: reporting_analyst

3.5 crew.py

 &emsp以下代码皆是创建项目时自动生成的,从下面的代码中可以看出FirstAgent类主要完成3个任务:1. 创建智能体Agent。2. 创建智能体的任务Task。3. 创建最顶层组织Crew。

from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task

# If you want to run a snippet of code before or after the crew starts,
# you can use the @before_kickoff and @after_kickoff decorators
# https://docs.crewai.com/concepts/crews#example-crew-class-with-decorators

@CrewBase
class FirstAgent():
    """FirstAgent crew"""

    # Learn more about YAML configuration files here:
    # Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended
    # Tasks: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommended
    agents_config = 'config/agents.yaml'
    tasks_config = 'config/tasks.yaml'

    # If you would like to add tools to your agents, you can learn more about it here:
    # https://docs.crewai.com/concepts/agents#agent-tools
    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config['researcher'],
            verbose=True
        )

    @agent
    def reporting_analyst(self) -> Agent:
        return Agent(
            config=self.agents_config['reporting_analyst'],
            verbose=True
        )

    # To learn more about structured task outputs,
    # task dependencies, and task callbacks, check out the documentation:
    # https://docs.crewai.com/concepts/tasks#overview-of-a-task
    @task
    def research_task(self) -> Task:
        return Task(
            config=self.tasks_config['research_task'],
        )

    @task
    def reporting_task(self) -> Task:
        return Task(
            config=self.tasks_config['reporting_task'],
            output_file='report.md'
        )

    @crew
    def crew(self) -> Crew:
        """Creates the FirstAgent crew"""
        # To learn how to add knowledge sources to your crew, check out the documentation:
        # https://docs.crewai.com/concepts/knowledge#what-is-knowledge

        return Crew(
            agents=self.agents, # Automatically created by the @agent decorator
            tasks=self.tasks, # Automatically created by the @task decorator
            process=Process.sequential,
            verbose=True,
            # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/
        )

3.6 main.py

  main.py文件主要功能是让你在本地运行Crew,以达到测试的目的。以下代码也是在创建项目时自动生成的。

import sys
import warnings

from datetime import datetime

from first_agent.crew import FirstAgent

warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")

# This main file is intended to be a way for you to run your
# crew locally, so refrain from adding unnecessary logic into this file.
# Replace with inputs you want to test with, it will automatically
# interpolate any tasks and agents information

def run():
    """
    Run the crew.
    """
    inputs = {
        'topic': '大语言模型',
        'current_year': str(datetime.now().year)
    }
    
    try:
        FirstAgent().crew().kickoff(inputs=inputs)
    except Exception as e:
        raise Exception(f"An error occurred while running the crew: {e}")


def train():
    """
    Train the crew for a given number of iterations.
    """
    inputs = {
        "topic": "大语言模型"
    }
    try:
        FirstAgent().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)

    except Exception as e:
        raise Exception(f"An error occurred while training the crew: {e}")

def replay():
    """
    Replay the crew execution from a specific task.
    """
    try:
        FirstAgent().crew().replay(task_id=sys.argv[1])

    except Exception as e:
        raise Exception(f"An error occurred while replaying the crew: {e}")

def test():
    """
    Test the crew execution and returns the results.
    """
    inputs = {
        "topic": "大语言模型",
        "current_year": str(datetime.now().year)
    }
    try:
        FirstAgent().crew().test(n_iterations=int(sys.argv[1]), openai_model_name=sys.argv[2], inputs=inputs)

    except Exception as e:
        raise Exception(f"An error occurred while testing the crew: {e}")

3.7 本地运行

  在项目路径下先安装依赖,然后运行:

crewai install
crewai run

  从上面的Agents.yaml和Tasks.yaml中可以看出,该样例的目的是产出一份指定topic、指定年份year的报告,报告最终输出为Markdown文件。
  生成该报告的过程如下:
  1. research Agent查找关于指定主题topic、指定年份year的内容,并将其总结成10个要点。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
  2. research Agent完成任务后,将得到10个要点交给reporting_analyst Agent。reporting_analyst审查获取的10个要点,并将其扩写成一份指定主题topic、指定年份year的报告,并以Markdown文件格式输出。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参考

https://docs.crewai.com/introduction
https://docs.crewai.com/installation
https://docs.crewai.com/quickstart


网站公告

今日签到

点亮在社区的每一天
去签到