CrewAI多Agent协作框架完整指南
CrewAI是45K+ Stars的多Agent协作框架,让多个AI Agent扮演不同角色协同完成复杂任务。本文介绍安装和使用教程
一、CrewAI简介
CrewAI是一个多Agent协作框架,GitHub 45K+ Stars。通过定义多个具有不同角色的Agent,让它们协作完成复杂任务。
核心特点
二、安装部署
基本安装
使用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'
成本控制
五、高级用法
自定义工具
from crewai.tools import BaseTool
from pydantic import Fieldclass 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 Memorycrew = Crew(
agents=[...],
tasks=[...],
memory=Memory()
)
六、常见问题
Q: 如何选择Agent数量?
A: 根据任务复杂度,通常2-5个Agent足够。
Q: Agent之间如何通信?
A: 通过共享任务上下文,每个Agent可以看到前置任务的输出。
Q: 如何调试Agent行为?
A: 使用verbose模式查看详细执行日志。