中文 EN
Easy 🌍 Regional Pricing Reliability: High

CrewAI多Agent协作框架完整指南

CrewAI是45K+ Stars的多Agent协作框架,让多个AI Agent扮演不同角色协同完成复杂任务。本文介绍安装和使用教程

4.6 (2,900 ratings)
38,000 views Updated 5/18/2024
CrewAI多Agent协作Agent框架开源角色扮演

一、CrewAI简介

CrewAI是一个多Agent协作框架,GitHub 45K+ Stars。通过定义多个具有不同角色的Agent,让它们协作完成复杂任务。

核心特点

  • 多角色Agent:定义不同的角色和职责

  • 任务协作:Agent之间可以共享信息和结果

  • 流程控制:支持顺序和并行执行

  • 工具集成:内置和自定义工具支持

  • 简易API:Pythonic的简洁接口
  • 二、安装部署

    基本安装

    使用pip安装


    pip install crewai

    安装额外依赖


    pip install crewai[tools]

    Poetry安装

    poetry add crewai crewai-tools

    三、使用教程

    基本示例

    from crewai import Agent, Crew, Task, Process
    from crewai.tools import SerpAPITool

    创建工具


    search_tool = SerpAPITool()

    创建Agent


    researcher = Agent(
    role='Research Analyst',
    goal='Find and summarize the latest AI news',
    backstory='An expert at researching technology trends',
    tools=[search_tool]
    )

    writer = Agent(
    role='Tech Writer',
    goal='Write clear and engaging tech articles',
    backstory='A professional tech writer with years of experience',
    tools=[]
    )

    创建任务


    research_task = Task(
    description='Research the latest developments in AI',
    agent=researcher
    )

    write_task = Task(
    description='Write an article about the AI news',
    agent=writer,
    context=[research_task]
    )

    创建团队


    crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, write_task],
    process=Process.sequential
    )

    执行


    result = crew.kickoff()
    print(result)

    并行执行

    crew = Crew(
    agents=[researcher, writer, editor],
    tasks=[research_task, write_task, edit_task],
    process=Process.hierarchical # 层级协作
    )

    四、支付相关

    CrewAI本身免费,但需要配置AI模型API:

    推荐API配置

    DeepSeek(推荐)

    import os
    os.environ['OPENAI_API_KEY'] = 'your-deepseek-key'
    os.environ['OPENAI_API_BASE'] = 'https://api.deepseek.com/v1'
    os.environ['OPENAI_MODEL_NAME'] = 'deepseek-chat'

    成本控制

  • CrewAI免费

  • 主要成本来自API调用

  • 推荐使用DeepSeek等低成本模型

  • 设置任务数量限制避免过度调用
  • 五、高级用法

    自定义工具

    from crewai.tools import BaseTool
    from pydantic import Field

    class MyCustomTool(BaseTool):
    name: str = Field(default="my_tool")
    description: str = Field(default="A custom tool")

    def _run(self, argument: str) -> str:
    # 实现逻辑
    return "result"

    记忆管理

    from crewai import Crew
    from crewai.memory import Memory

    crew = Crew(
    agents=[...],
    tasks=[...],
    memory=Memory()
    )

    六、常见问题

    Q: 如何选择Agent数量?
    A: 根据任务复杂度,通常2-5个Agent足够。

    Q: Agent之间如何通信?
    A: 通过共享任务上下文,每个Agent可以看到前置任务的输出。

    Q: 如何调试Agent行为?
    A: 使用verbose模式查看详细执行日志。

    Related Tools

    Found this helpful? Share with your classmates!