mcpField
C
crewai-multi-agent

crewai-multi-agent

github.com/davila7Agent 工作流33.0k985 次安装1 天前更新
代码仓库

关于 crewai-multi-agent

crewai-multi-agent 介绍面向 Python 开发者的 CrewAI 框架,用于构建协作型 AI Agent 团队。它结合基于角色的 Agent、支持自主协作的 Crews,以及事件驱动的 Flows。

主要功能

  1. 01基于角色定义 Agent
  2. 02使用 Crew 和 Flow 编排
  3. 03顺序与层级流程
  4. 04内置短期和长期记忆
  5. 05内置工具与自定义工具

适用场景

  1. 01由专职 Agent 分担研究与写作
  2. 02按顺序或由管理 Agent 分派任务
  3. 03构建带条件逻辑的事件驱动工作流

MCP 相关

该技能提及涵盖内置工具、自定义工具和 MCP 的 Tools Guide。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/davila7/claude-code-templates --skill crewai-multi-agent

安装后在 Claude Code 中输入/crewai-multi-agent确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
flows.md
tools.md
troubleshooting.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 与替代方案对比

特性CrewAILangChainLangGraph
最适合多 Agent 团队通用大模型应用有状态工作流
学习曲线低中较高
Agent 范式基于角色基于工具基于图
记忆内置基于插件自定义

最佳实践

  1. 明确的角色 - 每个 Agent 应有独特的专长
  2. YAML 配置 - 更适合大型项目的组织方式
  3. 启用记忆 - 改善跨任务的上下文
  4. 设置 max_iter - 防止无限循环(默认 15)
  5. 限制工具 - 每个 Agent 最多 3-5 个工具
  6. 速率限制 - 设置 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"

参考

资源

评论

支持 Markdown