crewai-agents

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<!-- Adapted from: AI-research-SKILLs/14-agents/crewai -->
<!-- 改编自:AI-research-SKILLs/14-agents/crewai -->

CrewAI Multi-Agent Orchestration

CrewAI 多智能体编排

Build teams of autonomous AI agents that collaborate on complex tasks.
构建可协作完成复杂任务的自主AI智能体团队。

When to Use

使用场景

  • Building multi-agent systems with specialized roles
  • Need autonomous collaboration between agents
  • Want role-based task delegation (researcher, writer, analyst)
  • Require sequential or hierarchical process execution
  • Building production workflows with memory and observability
  • 构建具有特定角色的多智能体系统
  • 需要智能体之间的自主协作
  • 希望实现基于角色的任务分配(研究员、撰稿人、分析师)
  • 需要执行顺序或分层流程
  • 构建具备记忆和可观测性的生产级工作流

Quick Start

快速开始

bash
pip install crewai
pip install 'crewai[tools]'  # With 50+ built-in tools
bash
pip install crewai
pip install 'crewai[tools]'  # 包含50+内置工具

Simple Crew

简单协作组示例

python
from crewai import Agent, Task, Crew, Process
python
from crewai import Agent, Task, Crew, Process

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 trends.", verbose=True )
writer = Agent( role="Technical Writer", goal="Create clear, engaging content about technical topics", backstory="You excel at explaining complex concepts.", verbose=True )
researcher = Agent( role="Senior Research Analyst", goal="Discover cutting-edge developments in AI", backstory="You are an expert analyst with a keen eye for trends.", verbose=True )
writer = Agent( role="Technical Writer", goal="Create clear, engaging content about technical topics", backstory="You excel at explaining complex concepts.", verbose=True )

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.", 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 )
research_task = Task( description="Research the latest developments in {topic}. Find 5 key trends.", expected_output="A detailed report with 5 bullet points.", 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] # 使用研究输出结果 )

Create and run crew

创建并运行协作组

crew = Crew( agents=[researcher, writer], tasks=[research_task, write_task], process=Process.sequential, verbose=True )
result = crew.kickoff(inputs={"topic": "AI Agents"}) print(result.raw)
undefined
crew = Crew( agents=[researcher, writer], tasks=[research_task, write_task], process=Process.sequential, verbose=True )
result = crew.kickoff(inputs={"topic": "AI Agents"}) print(result.raw)
undefined

Process Types

流程类型

Sequential

顺序流程

Tasks execute in order:
python
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
    process=Process.sequential  # Task 1 -> Task 2 -> Task 3
)
任务按顺序执行:
python
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
    process=Process.sequential  # 任务1 -> 任务2 -> 任务3
)

Hierarchical

分层流程

Auto-creates a manager agent that delegates:
python
crew = Crew(
    agents=[researcher, writer, analyst],
    tasks=[research_task, write_task, analyze_task],
    process=Process.hierarchical,
    manager_llm="gpt-4o"
)
自动创建管理智能体进行任务分配:
python
crew = Crew(
    agents=[researcher, writer, analyst],
    tasks=[research_task, write_task, analyze_task],
    process=Process.hierarchical,
    manager_llm="gpt-4o"
)

Using Tools

工具使用

python
from crewai_tools import (
    SerperDevTool,       # Web search
    ScrapeWebsiteTool,   # Web scraping
    FileReadTool,        # Read files
    PDFSearchTool,       # Search PDFs
)

researcher = Agent(
    role="Researcher",
    goal="Find accurate information",
    backstory="Expert at finding data online.",
    tools=[SerperDevTool(), ScrapeWebsiteTool()]
)
python
from crewai_tools import (
    SerperDevTool,       # 网页搜索
    ScrapeWebsiteTool,   # 网页爬取
    FileReadTool,        # 文件读取
    PDFSearchTool,       # PDF搜索
)

researcher = Agent(
    role="Researcher",
    goal="Find accurate information",
    backstory="Expert at finding data online.",
    tools=[SerperDevTool(), ScrapeWebsiteTool()]
)

Custom Tools

自定义工具

python
from crewai.tools import BaseTool

class CalculatorTool(BaseTool):
    name: str = "Calculator"
    description: str = "Performs mathematical calculations."

    def _run(self, expression: str) -> str:
        try:
            return f"Result: {eval(expression)}"
        except Exception as e:
            return f"Error: {str(e)}"
python
from crewai.tools import BaseTool

class CalculatorTool(BaseTool):
    name: str = "Calculator"
    description: str = "Performs mathematical calculations."

    def _run(self, expression: str) -> str:
        try:
            return f"Result: {eval(expression)}"
        except Exception as e:
            return f"Error: {str(e)}"

YAML Configuration

YAML配置

agents.yaml

agents.yaml

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}.

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.
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}.

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.

tasks.yaml

tasks.yaml

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.
  expected_output: >
    A detailed report in markdown format.
  agent: reporting_analyst
  output_file: report.md
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.
  expected_output: >
    A detailed report in markdown format.
  agent: reporting_analyst
  output_file: report.md

Memory System

记忆系统

python
crew = Crew(
    agents=[researcher],
    tasks=[research_task],
    memory=True,  # Enable memory
    embedder={
        "provider": "openai",
        "config": {"model": "text-embedding-3-small"}
    }
)
python
crew = Crew(
    agents=[researcher],
    tasks=[research_task],
    memory=True,  # 启用记忆功能
    embedder={
        "provider": "openai",
        "config": {"model": "text-embedding-3-small"}
    }
)

LLM Providers

大语言模型提供商

python
from crewai import LLM

llm = LLM(model="gpt-4o")  # OpenAI
llm = LLM(model="claude-sonnet-4-5-20250929")  # Anthropic
llm = LLM(model="ollama/llama3.1", base_url="http://localhost:11434")  # Local

agent = Agent(role="Analyst", goal="Analyze data", llm=llm)
python
from crewai import LLM

llm = LLM(model="gpt-4o")  # OpenAI
llm = LLM(model="claude-sonnet-4-5-20250929")  # Anthropic
llm = LLM(model="ollama/llama3.1", base_url="http://localhost:11434")  # 本地模型

agent = Agent(role="Analyst", goal="Analyze data", llm=llm)

Best Practices

最佳实践

  1. Clear roles - Each agent should have a distinct specialty
  2. YAML config - Better organization for larger projects
  3. Enable memory - Improves context across tasks
  4. Set max_iter - Prevent infinite loops (default 15)
  5. Limit tools - 3-5 tools per agent max
  6. Rate limiting - Set max_rpm to avoid API limits
  1. 明确角色 - 每个智能体应具备独特的专业领域
  2. YAML配置 - 大型项目的更佳组织方式
  3. 启用记忆 - 提升跨任务的上下文连贯性
  4. 设置max_iter - 防止无限循环(默认值为15)
  5. 限制工具数量 - 每个智能体最多使用3-5个工具
  6. 速率限制 - 设置max_rpm以避免API调用超限

Common Issues

常见问题

Agent stuck in loop:
python
agent = Agent(
    role="...",
    max_iter=10,
    max_rpm=5
)
Task not using context:
python
task2 = Task(
    description="...",
    context=[task1],  # Explicitly pass context
    agent=writer
)
智能体陷入循环:
python
agent = Agent(
    role="...",
    max_iter=10,
    max_rpm=5
)
任务未使用上下文:
python
task2 = Task(
    description="...",
    context=[task1],  # 显式传递上下文
    agent=writer
)

vs Alternatives

与竞品对比

FeatureCrewAILangChainLangGraph
Best forMulti-agent teamsGeneral LLM appsStateful workflows
Learning curveLowMediumHigher
Agent paradigmRole-basedTool-basedGraph-based
特性CrewAILangChainLangGraph
适用场景多智能体团队通用LLM应用有状态工作流
学习曲线中等较高
智能体范式基于角色基于工具基于图结构

Resources

资源