当前位置: 首页 > ds >正文

Crewai Community Version(四)——Crew

目录

  • 1. Crew总览
  • 2. Crew属性
  • 3. 与Crew相关的装饰器
  • 4. Crew输出
  • 5. CrewOutput属性
  • 6. Crew使用指标
  • 7. Crew执行流程
  • 8. 启动Crew的方式
  • 9. 重放特定任务
  • 10. 创建Crew
    • 10.1 YAML配置
    • 10.2 直接代码定义
    • 10.3 运行结果
  • 参考

1. Crew总览

  CrewAI框架中的Crew是一组协作的代理,它们一起工作以完成一组任务。每个小组定义任务执行、智能体协作和整个工作流程的策略。

2. Crew属性

属性参数含义
任务tasks分配给crew的任务清单
智能体agentscrew中智能体的名单
过程processcrew遵循的处理流程,默认为sequential
详细日志verbose执行期间记录的详细程度,默认为False
大模型协调官manager_llm在hierarchical过程必须使用的大语言模型
函数调用大语言模型function_calling_llm如果设置,crew将使用该大语言模型来对所有智能体的工具进行函数调用。每个智能体可以有自己的函数调用大语言模型,它会覆盖crew的函数调用大语言模型进行函数调用
配置config可选的crew配置,格式为json或dict
每分钟最大请求数max_rpm在执行过程中,crew每分钟的最大请求数,默认值为None
记忆memory用于存储执行记忆
记忆配置memory_configcrew使用的记忆配置
缓存cache指定是否使用缓存来存储工具执行的结果,默认值为True
嵌入器embeddercrew使用的嵌入器配置,目前主要由记忆使用,默认值为{“provider": “openai”}
步骤回调step_callback在每个智能体进行一个步骤之后调用的函数,可用于记录智能体的操作或执行其他操作。它不会覆盖特定于智能体的step_callback
任务回调task_callback在每个任务完成后调用的函数,用于监视或任务执行后的其他操作
分享crewshare_crew您是否希望与CrewAI团队共享完整的crew信息和执行,以使库更好,并允许我们训练模型
输出日志文件output_log_file设置为True,表示将日志保存为当前目录下的logs.txt或提供文件路径。如果文件名以.JSON结尾,日志将是JSON格式,否则是txt。默认值为None
协调智能体manager_agent用作协调智能体的自定义智能体
提示文件prompt_filecrew使用的JSON提示文件
计划planning为crew增加规划能力。在每次crew迭代之前激活,所有crew数据将发送给AgentPlanner,后者将规划任务,并将此计划添加到每个任务描述中
用于规划的大语言模型planning_llmAgentPlanner在规划过程中使用的语言模型

3. 与Crew相关的装饰器

  CrewAI在annotations.py文件中提供了几个装饰器,用于标记船员类中的方法以进行特殊处理:

装饰器作用
@CrewBase将该类标记为crew基类
@agent表示返回一个Agent对象的方法
@task表示返回一个Task对象的方法
@crew表示返回一个Crew对象的方法
@before_kickoff标记一个方法在crew启动前执行
@after_kickoff标记一个方法在crew完成后执行

4. Crew输出

  CrewAI将crew的输出封装在CrewOutput类中,该类提供了一种结构化的方式来访问crew执行的结果,包括各种格式,如原始字符串、JSON和Pydantic模型。CrewOutput包括来自最终任务输出、词元使用情况和单个任务输出的结果。此外,一旦执行了crew,就可以通过Crew对象的output属性访问它的输出。

5. CrewOutput属性

属性参数类型含义
原始字符串rawstrcrew的原始输出,这是输出的默认格式
Pydantic模型pydanticOptional[BaseModel]一个Pydantic模型对象,表示crew的结构化输出
JSON字典json_dictOptional[Dict[str, Any]]表示crew JSON输出的字典
任务输出tasks_outputList[TaskOutput]TaskOutput对象的列表,每个对象表示crew中一个任务的输出
词元使用情况token_usageDict[str, Any]

6. Crew使用指标

  在crew执行后,您可以访问usage_metrics属性,以查看crew执行所有任务时语言模型使用指标,这提供了对操作效率和改进领域的见解。

7. Crew执行流程

  1. 顺序流程:任务一个接一个地执行,允许线性工作流。
  2. 分级流程:协调智能体协调crew,委派任务并在继续之前验证结果。注意:此流程需要manager_llm或manager_agent,这对于验证流程至关重要。

8. 启动Crew的方式

  CrewAI提供了几种更好地控制启动过程的方法:

启动方式具体流程
kickoff()按照定义的进程流启动执行流程
kickoff_for_each()为集合中提供的每个输入事件或项依次执行任务
kickoff_async()异步启动工作流
kickoff_for_each_async()利用异步处理,为每个提供的输入事件或项并发地执行任务

9. 重放特定任务

  在CrewAI项目所在目录下,执行如下命令:crewai log-tasks-outputs,但是该项目至少执行过一次才能有输出。示例如下:
在这里插入图片描述
  接着通过上面获取的task_id,重放特定任务:crewai replay -t <task_id>

10. 创建Crew

10.1 YAML配置

  通过crewai create crew <your-project-name>后,在<your-project-name>/src/<your-project-name>/config/agents.yaml中以如下的形式定义Agents:

news_reporter:role: >新闻播报员goal: >从科技、人文、军事等方面寻找当前时间{time}范围内的新闻backstory: >深入基层实地寻找过新闻,能辨别虚假消息,具备良好的新闻写作能力

    在<your-project-name>/src/<your-project-name>/config/tasks.yaml中以如下的形式定义Tasks:

summary_task:description: >总结当前时间{time}范围内的新闻expected_output: >一份简练但又内容丰富的新闻稿子agent: news_reporter

  ;在<your-project-name>/src/<your-project-name>/crew.py创建一个继承CrewBase的类:

from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
# 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 NewsReporter():"""NewsReporter crew"""agents: List[BaseAgent]tasks: List[Task]# 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# 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@agentdef news_reporter(self) -> Agent:return Agent(config=self.agents_config['news_reporter'], # type: ignore[index]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@taskdef summary_task(self) -> Task:return Task(config=self.tasks_config['summary_task'], # type: ignore[index])@crewdef crew(self) -> Crew:"""Creates the NewsReporter crew"""# To learn how to add knowledge sources to your crew, check out the documentation:# https://docs.crewai.com/concepts/knowledge#what-is-knowledgereturn Crew(agents=self.agents, # Automatically created by the @agent decoratortasks=self.tasks, # Automatically created by the @task decoratorprocess=Process.sequential,verbose=True,planning=True,planning_llm="deepseek/deepseek-chat"# process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/)

  在<your-project-name>/src/<your-project-name>/main.py中修改inputs为{”time": str(datetime.now())}:

#!/usr/bin/env python
import sys
import warningsfrom datetime import datetimefrom news_reporter.crew import NewsReporterwarnings.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 informationdef run():"""Run the crew."""inputs = {'time': str(datetime.now())}try:NewsReporter().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 = {'time': str(datetime.now())}try:NewsReporter().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:NewsReporter().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 = {'time': str(datetime.now())}try:NewsReporter().crew().test(n_iterations=int(sys.argv[1]), eval_llm=sys.argv[2], inputs=inputs)except Exception as e:raise Exception(f"An error occurred while testing the crew: {e}")

10.2 直接代码定义

from datetime import datetime
from crewai import Agent, Crew, Process, Tasknews_reporter = Agent(role="""新闻播报员""",goal="""从科技、人文、军事等方面寻找当前时间{time}范围内的新闻""",backstory="""深入基层实地寻找过新闻,能辨别虚假消息,具备良好的新闻写作能力""",verbose=True
)summary_task = Task(description="""总结当前时间{time}范围内的新闻""",expected_output="""一份简练但又内容丰富的新闻稿子""",agent=news_reporter
)NewsReporter = Crew(agents=[news_reporter],tasks=[summary_task],process=Process.sequential,verbose=True,planning=True,planning_llm="deepseek/deepseek-chat"
)NewsReporter.crew().kickoff(inputs={"time": str(datetime.now())}
)

10.3 运行结果

  运行结果如下:
在这里插入图片描述
  由于启动了planning,因此planning_llm在任务的description新增了一些内容,以使任务顺利完成。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参考

https://docs.crewai.com/concepts/crews

http://www.xdnf.cn/news/5456.html

相关文章:

  • Qt QCheckBox 使用
  • 【Java ee初阶】网络编程 TCP
  • 深度学习篇---姿态检测实现
  • 软考错题集
  • Java 23种设计模式 - 行为型模式11种
  • PostgreSQL 的 pg_collation_actual_version 函数
  • 【深度学习-Day 8】让数据说话:Python 可视化双雄 Matplotlib 与 Seaborn 教程
  • Kimball
  • Python 基础语法与数据类型(七) - 函数的定义与调用 (def, return)
  • Ethercat转Profinet网关如何用“协议翻译术“打通自动化产线任督二脉
  • Looper死循环阻塞为什么没有ANR
  • 【大模型面试每日一题】Day 14:大模型训练中显存占用的主要来源有哪些?如何通过激活重计算降低显存?
  • 关于char字符的16进制打印
  • 408考研逐题详解:2009年第11题
  • PySide6 GUI 学习笔记——常用类及控件使用方法(常用类边距QMargins)
  • 数字信号处理|| 快速傅里叶变换(FFT)
  • 软考(信息系统运行管理员)
  • 猿人学第十七题—天杀的http2.0
  • SSH免密登录
  • Java注解之@PostConstruct
  • ts装饰器
  • IPM IMI111T-026H 高效风扇控制板
  • Python打卡 DAY 21
  • 免费 超轻量级便携 内存清理 验证win系统内存优化
  • DeepSeek:为环保领域插上智慧的翅膀
  • 子串简写(JAVA)一维前缀和, 蓝桥杯
  • 前端性能优化全攻略:从基础体验到首屏加载的深度实践
  • 一文理解扩散模型(生成式AI模型)(1)
  • 【工具记录分享】提取bilibili视频字幕
  • Activity动态切换Fragment