关于 crewai-multi-agent
CrewAI 是用于构建多 Agent 协作系统的编排框架,面向需要按角色分工和执行任务流程的开发者。它同时提供自主协作的 Crews 与事件驱动的 Flows,并内置记忆机制。
主要功能
- 01按角色定义 Agent 与任务
- 02顺序和层级任务流程
- 03Crews 与事件驱动 Flows
- 04内置短期、长期及实体记忆
- 05内置工具与自定义工具
适用场景
- 01组建研究、写作和分析 Agent 团队
- 02按顺序执行多阶段任务
- 03用事件驱动流程处理条件逻辑
- 04为协作任务保留上下文记忆
MCP 相关
README 提及 Tools Guide 涵盖 MCP,但未说明具体的 MCP 能力或接口。
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ orchestra-research/ ai-research-skills --skill crewai-multi-agent安装后在 Claude Code 中输入/crewai-multi-agent确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/flows.mdtools.mdtroubleshooting.md详细介绍
CrewAI - 多 Agent 编排框架
构建能够协作解决复杂任务的自主 AI Agent 团队。
何时使用 CrewAI
在以下情况下使用 CrewAI:
- 构建具有专门角色的多 Agent 系统
- 需要 Agent 之间的自主协作
- 希望实现基于角色的任务委派(研究员、撰稿人、分析师)
- 需要顺序或层级式流程执行
- 构建具有记忆和可观测性的生产工作流
- 需要比 LangChain/LangGraph 更简单的设置
关键特性:
- 独立:无 LangChain 依赖,占用精简
- 基于角色:Agent 具有角色、目标和背景故事
- 双重范式:Crews(自主)+ Flows(事件驱动)
- 50+ 工具:网页抓取、搜索、数据库、AI 服务
- 记忆:短期、长期和实体记忆
- 生产就绪:追踪、企业级功能
改用替代方案的情况:
- LangChain:通用大模型应用、RAG 管道
- LangGraph:带循环的复杂有状态工作流
- AutoGen:Microsoft 生态、多 Agent 对话
- LlamaIndex:文档问答、知识检索
快速开始
安装
# Core framework
pip install crewai
# With 50+ built-in tools
pip install 'crewai[tools]'
使用命令行创建项目
# Create new crew project
crewai create crew my_project
cd my_project
# Install dependencies
crewai install
# Run the crew
crewai run
简单 crew(仅代码)
from crewai import Agent, Task, Crew, Process
# 1. Define agents
researcher = Agent(
role="Senior Research Analyst",
goal="Discover cutting-edge developments in AI",
backstory="You are an expert analyst with a keen eye for emerging trends.",
verbose=True
)
writer = Agent(
role="Technical Writer",
goal="Create clear, engaging content about technical topics",
backstory="You excel at explaining complex concepts to general audiences.",
verbose=True
)
# 2. Define tasks
research_task = Task(
description="Research the latest developments in {topic}. Find 5 key trends.",
expected_output="A detailed report with 5 bullet points on key trends.",
agent=researcher
)
write_task = Task(
description="Write a blog post based on the research findings.",
expected_output="A 500-word blog post in markdown format.",
agent=writer,
context=[research_task] # Uses research output
)
# 3. Create and run crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # Tasks run in order
verbose=True
)
# 4. Execute
result = crew.kickoff(inputs={"topic": "AI Agents"})
print(result.raw)
核心概念
Agent - 自主工作者
from crewai import Agent
agent = Agent(
role="Data Scientist", # Job title/role
goal="Analyze data to find insights", # What they aim to achieve
backstory="PhD in statistics...", # Background context
llm="gpt-4o", # LLM to use
tools=[], # Tools available
memory=True, # Enable memory
verbose=True, # Show reasoning
allow_delegation=True, # Can delegate to others
max_iter=15, # Max reasoning iterations
max_rpm=10 # Rate limit
)
Task - 工作单元
from crewai import Task
task = Task(
description="Analyze the sales data for Q4 2024. {context}",
expected_output="A summary report with key metrics and trends.",
agent=analyst, # Assigned agent
context=[previous_task], # Input from other tasks
output_file="report.md", # Save to file
async_execution=False, # Run synchronously
human_input=False # No human approval needed
)
Crew - Agent 团队
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer, editor], # Team members
tasks=[research, write, edit], # Tasks to complete
process=Process.sequential, # Or Process.hierarchical
verbose=True,
memory=True, # Enable crew memory
cache=True, # Cache tool results
max_rpm=10, # Rate limit
share_crew=False # Opt-in telemetry
)
# Execute with inputs
result = crew.kickoff(inputs={"topic": "AI trends"})
# Access results
print(result.raw) # Final output
print(result.tasks_output) # All task outputs
print(result.token_usage) # Token consumption
流程类型
顺序式(默认)
任务按顺序执行,每个 Agent 在下一个开始前完成自己的任务:
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential # Task 1 → Task 2 → Task 3
)
层级式
自动创建管理 Agent 进行委派和协调:
crew = Crew(
agents=[researcher, writer, analyst],
tasks=[research_task, write_task, analyze_task],
process=Process.hierarchical, # Manager delegates tasks
manager_llm="gpt-4o" # LLM for manager
)
使用工具
内置工具(50+)
pip install 'crewai[tools]'
from crewai_tools import (
SerperDevTool, # Web search
ScrapeWebsiteTool, # Web scraping
FileReadTool, # Read files
PDFSearchTool, # Search PDFs
WebsiteSearchTool, # Search websites
CodeDocsSearchTool, # Search code docs
YoutubeVideoSearchTool, # Search YouTube
)
# Assign tools to agent
researcher = Agent(
role="Researcher",
goal="Find accurate information",
backstory="Expert at finding data online.",
tools=[SerperDevTool(), ScrapeWebsiteTool()]
)
自定义工具
from crewai.tools import BaseTool
from pydantic import Field
class CalculatorTool(BaseTool):
name: str = "Calculator"
description: str = "Performs mathematical calculations. Input: expression"
def _run(self, expression: str) -> str:
try:
result = eval(expression)
return f"Result: {result}"
except Exception as e:
return f"Error: {str(e)}"
# Use custom tool
agent = Agent(
role="Analyst",
goal="Perform calculations",
tools=[CalculatorTool()]
)
YAML 配置(推荐)
项目结构
my_project/
├── src/my_project/
│ ├── config/
│ │ ├── agents.yaml # Agent definitions
│ │ └── tasks.yaml # Task definitions
│ ├── crew.py # Crew assembly
│ └── main.py # Entry point
└── pyproject.toml
agents.yaml
researcher:
role: "{topic} Senior Data Researcher"
goal: "Uncover cutting-edge developments in {topic}"
backstory: >
You're a seasoned researcher with a knack for uncovering
the latest developments in {topic}. Known for your ability
to find relevant information and present it clearly.
reporting_analyst:
role: "Reporting Analyst"
goal: "Create detailed reports based on research data"
backstory: >
You're a meticulous analyst who transforms raw data into
actionable insights through well-structured reports.
tasks.yaml
research_task:
description: >
Conduct thorough research about {topic}.
Find the most relevant information for {year}.
expected_output: >
A list with 10 bullet points of the most relevant
information about {topic}.
agent: researcher
reporting_task:
description: >
Review the research and create a comprehensive report.
Focus on key findings and recommendations.
expected_output: >
A detailed report in markdown format with executive
summary, findings, and recommendations.
agent: reporting_analyst
output_file: report.md
crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
@CrewBase
class MyProjectCrew:
"""My Project crew"""
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
tools=[SerperDevTool()],
verbose=True
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'],
verbose=True
)
@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:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
main.py
from my_project.crew import MyProjectCrew
def run():
inputs = {
'topic': 'AI Agents',
'year': 2025
}
MyProjectCrew().crew().kickoff(inputs=inputs)
if __name__ == "__main__":
run()
Flows - 事件驱动编排
对于具有条件逻辑的复杂工作流,请使用 Flows:
from crewai.flow.flow import Flow, listen, start, router
from pydantic import BaseModel
class MyState(BaseModel):
confidence: float = 0.0
class MyFlow(Flow[MyState]):
@start()
def gather_data(self):
return {"data": "collected"}
@listen(gather_data)
def analyze(self, data):
self.state.confidence = 0.85
return analysis_crew.kickoff(inputs=data)
@router(analyze)
def decide(self):
return "high" if self.state.confidence > 0.8 else "low"
@listen("high")
def generate_report(self):
return report_crew.kickoff()
# Run flow
flow = MyFlow()
result = flow.kickoff()
完整文档请参阅 Flows 指南。
记忆系统
# Enable all memory types
crew = Crew(
agents=[researcher],
tasks=[research_task],
memory=True, # Enable memory
embedder={ # Custom embeddings
"provider": "openai",
"config": {"model": "text-embedding-3-small"}
}
)
记忆类型: 短期(ChromaDB)、长期(SQLite)、实体(ChromaDB)
大模型提供商
from crewai import LLM
llm = LLM(model="gpt-4o") # OpenAI (default)
llm = LLM(model="claude-sonnet-4-5-20250929") # Anthropic
llm = LLM(model="ollama/llama3.1", base_url="http://localhost:11434") # Local
llm = LLM(model="azure/gpt-4o", base_url="https://...") # Azure
agent = Agent(role="Analyst", goal="Analyze data", llm=llm)
CrewAI 与替代方案对比
| 特性 | CrewAI | LangChain | LangGraph |
|---|---|---|---|
| 最适合 | 多 Agent 团队 | 通用大模型应用 | 有状态工作流 |
| 学习曲线 | 低 | 中 | 较高 |
| Agent 范式 | 基于角色 | 基于工具 | 基于图 |
| 记忆 | 内置 | 基于插件 | 自定义 |
最佳实践
- 明确的角色 - 每个 Agent 应有独特的专长
- YAML 配置 - 更适合大型项目的组织方式
- 启用记忆 - 改善跨任务的上下文
- 设置 max_iter - 防止无限循环(默认 15)
- 限制工具 - 每个 Agent 最多 3-5 个工具
- 速率限制 - 设置 max_rpm 以避免 API 限制
常见问题
Agent 陷入循环:
agent = Agent(
role="...",
max_iter=10, # Limit iterations
max_rpm=5 # Rate limit
)
任务未使用上下文:
task2 = Task(
description="...",
context=[task1], # Explicitly pass context
agent=writer
)
记忆错误:
# Use environment variable for storage
import os
os.environ["CREWAI_STORAGE_DIR"] = "./my_storage"
参考
资源
- GitHub:https://github.com/crewAIInc/crewAI (25k+ stars)
- 文档:https://docs.crewai.com
- 工具:https://github.com/crewAIInc/crewAI-tools
- 示例:https://github.com/crewAIInc/crewAI-examples
- 版本:1.2.0+
- 许可证:MIT
评论
支持 Markdown