实战四:多 Agent 调研团队
本实验将演示如何使用 CrewAI 组建一个包含“研究员”和“撰稿人”的虚拟团队,自动完成一份行业报告。
[LIVE_CHAT_BANNER]
1. 为什么用 CrewAI?
CrewAI 是目前最流行的 Multi-Agent 编排框架之一。它采用了基于角色 (Role-based) 的设计,非常符合人类团队的直觉。
pip install crewai crewai-tools
2. 定义 Agents
我们需要两个角色:
- Researcher: 负责搜集信息,要求事实准确。
- Writer: 负责基于信息写文章,要求文笔流畅。
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool
search_tool = SerperDevTool() # Google Search 工具
# 定义研究员
researcher = Agent(
role='Senior Research Analyst',
goal='Uncover cutting-edge developments in AI Agents',
backstory="""You work at a leading tech think tank.
Your expertise lies in identifying emerging trends.
You have a knack for dissecting complex data and presenting actionable insights.""",
verbose=True,
allow_delegation=False,
tools=[search_tool] # 只有研究员能用搜索工具
)
# 定义撰稿人
writer = Agent(
role='Tech Content Strategist',
goal='Craft compelling content on tech advancements',
backstory="""You are a renowned Content Strategist, known for your insightful and engaging articles.
You transform complex concepts into compelling narratives.""",
verbose=True,
allow_delegation=True
)
3. 定义 Tasks
任务必须具体,并指派给特定的 Agent。
# 任务 1:调研
task1 = Task(
description="""Conduct a comprehensive analysis of the latest advancements in AI Agents in 2024.
Identify key trends, breakthrough technologies, and potential industry impacts.""",
expected_output="Full analysis report in bullet points",
agent=researcher
)
# 任务 2:写作
task2 = Task(
description="""Using the insights provided, develop an engaging blog post that highlights the most significant AI Agent trends.
Your post should be informative yet accessible to a general tech-savvy audience.
Avoid complex jargon.""",
expected_output="Full blog post of at least 4 paragraphs",
agent=writer
)
4. 组建 Crew 并起飞
crew = Crew(
agents=[researcher, writer],
tasks=[task1, task2],
verbose=2, # 打印详细日志
process=Process.sequential # 顺序执行:先调研,后写作
)
result = crew.kickoff()
print("######################")
print(result)
5. 观察运行过程
当你运行这段代码时,你会看到:
- Researcher 开始调用 Google Search,搜索 "AI Agent trends 2024"。
- 它会阅读搜索结果,提取关键点(如 AutoGen, BabyAGI)。
- 任务完成后,它把调研报告传递给下一棒。
- Writer 接收到报告,开始撰写文章。
- 最终输出一篇完整的博客。
小结
Multi-Agent 的魔力在于分工。
- 如果你让一个 Agent 既搜索又写文章,它容易分心或产生幻觉。
- 拆分后,Researcher 专注于准确性,Writer 专注于可读性,效果往往更好。