CrewAI:多 Agent 团队协作
你将学会什么
Section titled “你将学会什么”- 理解 CrewAI 的「团队分工」心智模型:Agent 是演员,Task 是剧本,Crew 是剧组
- 用
Agent、Task、Crew、Process四个概念写一个多 Agent 程序 - 知道
kickoff()才是启动执行的地方
CrewAI 的心智模型最好懂:组建一个 AI 团队——给每个成员定角色(role)、目标(goal)、背景(backstory),把活拆成任务(Task)交给团队(Crew)按流程(Process)执行。这是它和其他框架最大的差异:靠「人设」驱动行为。
# 安装: pip install crewai (API key 放 .env,不要硬编码)from crewai import Agent, Task, Crew, Process
# 1) 定义「团队成员」:role/goal/backstory 是必填的三角色设定researcher = Agent( role="Senior Research Analyst", # 角色:干什么的 goal="Uncover cutting-edge developments in AI", # 目标:为什么干 backstory="You are a seasoned researcher at a tech think tank.", # 背景:人设 verbose=True, # 打印执行过程,方便新手看)
writer = Agent( role="Tech Content Strategist", goal="Craft compelling content based on research findings", backstory="You are a renowned content strategist known for clear writing.", verbose=True,)
# 2) 定义「工作任务单」:写清楚做什么、输出长什么样、谁来做task1 = Task( description="Conduct a thorough research about AI Agents. " "Find interesting and relevant information.", expected_output="A list with 10 bullet points of the most relevant information", agent=researcher, # 指派给研究员)
task2 = Task( description="Review the research context and expand each topic " "into a full section of a report.", expected_output="A fully fledged report with main topics, each with a full section.", agent=writer,)
# 3) 组建「团队」:成员 + 任务 + 流程,然后 kickoff() 开工crew = Crew( agents=[researcher, writer], tasks=[task1, task2], process=Process.sequential, # 顺序执行:task1 -> task2 verbose=True,)
result = crew.kickoff() # 启动!task1 的输出自动成为 task2 的上下文print(result)几个新手容易踩的坑:
Agent不能单独运行,必须放进Crew用kickoff()驱动expected_output必须写清楚,否则输出质量失控- 默认
sequential是排队执行,不是并行;hierarchical流程必须提供manager_llm或manager_agent - 官方 Quickstart 现在默认生成的是 Flow 脚手架,入门先学纯 Python 的 Agent/Task/Crew 更合适
先自己回答,再看答案:
- Agent、Task、Crew、Process 四个概念分别对应「剧组」的什么?
- 为什么
expected_output必须写清楚? sequential和hierarchical两种流程的区别是什么?
参考答案
- Agent 是演员(角色/目标/背景),Task 是剧本(做什么、输出什么),Crew 是剧组(组织协作),Process 是拍摄流程(顺序/层级)。
- 它是给 LLM 的质量基准,写不清楚输出就会失控、评审也无法验收。
- sequential 按顺序一个个执行;hierarchical 由经理 Agent 分配和验收任务,必须提供 manager_llm 或 manager_agent。
- CrewAI 用「角色 + 任务 + 团队」组织多 Agent 协作,上手最快
role/goal/backstory必填,kickoff()启动,expected_output写清- 默认 sequential 排队执行;多 Agent 不等于并行