协作
如何在 CrewAI 团队中让 Agent 彼此协作、委派任务并高效沟通。
概览
CrewAI 中的协作机制使 Agent 能够像团队一样工作,通过委派任务和相互提问来利用彼此的专业能力。当设置 allow_delegation=True 时,Agent 会自动获得强大的协作工具。
快速开始:启用协作
from crewai import Agent, Crew, Task# Enable collaboration for agentsresearcher = Agent(role="Research Specialist",goal="Conduct thorough research on any topic",backstory="Expert researcher with access to various sources",allow_delegation=True, # 🔑 Key setting for collaborationverbose=True)writer = Agent(role="Content Writer",goal="Create engaging content based on research",backstory="Skilled writer who transforms research into compelling content",allow_delegation=True, # 🔑 Enables asking questions to other agentsverbose=True)# Agents can now collaborate automaticallycrew = Crew(agents=[researcher, writer],tasks=[...],verbose=True)
Agent 协作如何工作
当设置 allow_delegation=True 时,CrewAI 会自动为 Agent 提供两个强大的工具:
1. Delegate Work Tool
允许 Agent 将任务分配给具备特定专长的队友。
# Agent automatically gets this tool:# Delegate work to coworker(task: str, context: str, coworker: str)
2. Ask Question Tool
允许 Agent 向同事提出具体问题,以获取所需信息。
# Agent automatically gets this tool:# Ask question to coworker(question: str, context: str, coworker: str)
协作实战
下面是一个完整示例,展示 Agent 如何协作完成内容创作任务:
from crewai import Agent, Crew, Task, Process# Create collaborative agentsresearcher = Agent(role="Research Specialist",goal="Find accurate, up-to-date information on any topic",backstory="""You're a meticulous researcher with expertise in findingreliable sources and fact-checking information across various domains.""",allow_delegation=True,verbose=True)writer = Agent(role="Content Writer",goal="Create engaging, well-structured content",backstory="""You're a skilled content writer who excels at transformingresearch into compelling, readable content for different audiences.""",allow_delegation=True,verbose=True)editor = Agent(role="Content Editor",goal="Ensure content quality and consistency",backstory="""You're an experienced editor with an eye for detail,ensuring content meets high standards for clarity and accuracy.""",allow_delegation=True,verbose=True)# Create a task that encourages collaborationarticle_task = Task(description="""Write a comprehensive 1000-word article about 'The Future of AI in Healthcare'.The article should include:- Current AI applications in healthcare- Emerging trends and technologies- Potential challenges and ethical considerations- Expert predictions for the next 5 yearsCollaborate with your teammates to ensure accuracy and quality.""",expected_output="A well-researched, engaging 1000-word article with proper structure and citations",agent=writer # Writer leads, but can delegate research to researcher)# Create collaborative crewcrew = Crew(agents=[researcher, writer, editor],tasks=[article_task],process=Process.sequential,verbose=True)result = crew.kickoff()
协作模式
模式 1:研究 → 写作 → 编辑
research_task = Task(description="Research the latest developments in quantum computing",expected_output="Comprehensive research summary with key findings and sources",agent=researcher)writing_task = Task(description="Write an article based on the research findings",expected_output="Engaging 800-word article about quantum computing",agent=writer,context=[research_task] # Gets research output as context)editing_task = Task(description="Edit and polish the article for publication",expected_output="Publication-ready article with improved clarity and flow",agent=editor,context=[writing_task] # Gets article draft as context)
模式 2:单任务协作
collaborative_task = Task(description="""Create a marketing strategy for a new AI product.Writer: Focus on messaging and content strategyResearcher: Provide market analysis and competitor insightsWork together to create a comprehensive strategy.""",expected_output="Complete marketing strategy with research backing",agent=writer # Lead agent, but can delegate to researcher)
分层协作
对于复杂项目,可以使用带有 manager Agent 的分层流程:
from crewai import Agent, Crew, Task, Process# Manager agent coordinates the teammanager = Agent(role="Project Manager",goal="Coordinate team efforts and ensure project success",backstory="Experienced project manager skilled at delegation and quality control",allow_delegation=True,verbose=True)# Specialist agentsresearcher = Agent(role="Researcher",goal="Provide accurate research and analysis",backstory="Expert researcher with deep analytical skills",allow_delegation=False, # Specialists focus on their expertiseverbose=True)writer = Agent(role="Writer",goal="Create compelling content",backstory="Skilled writer who creates engaging content",allow_delegation=False,verbose=True)# Manager-led taskproject_task = Task(description="Create a comprehensive market analysis report with recommendations",expected_output="Executive summary, detailed analysis, and strategic recommendations",agent=manager # Manager will delegate to specialists)# Hierarchical crewcrew = Crew(agents=[manager, researcher, writer],tasks=[project_task],process=Process.hierarchical, # Manager coordinates everythingmanager_llm="gpt-4o", # Specify LLM for managerverbose=True)
协作最佳实践
1. 清晰定义角色
# ✅ Good: Specific, complementary rolesresearcher = Agent(role="Market Research Analyst", ...)writer = Agent(role="Technical Content Writer", ...)# ❌ Avoid: Overlapping or vague rolesagent1 = Agent(role="General Assistant", ...)agent2 = Agent(role="Helper", ...)
2. 有策略地启用委派
# ✅ Enable delegation for coordinators and generalistslead_agent = Agent(role="Content Lead",allow_delegation=True, # Can delegate to specialists...)# ✅ Disable for focused specialists (optional)specialist_agent = Agent(role="Data Analyst",allow_delegation=False, # Focuses on core expertise...)
3. 共享上下文
# ✅ Use context parameter for task dependencieswriting_task = Task(description="Write article based on research",agent=writer,context=[research_task], # Shares research results...)
4. 清晰的任务描述
# ✅ Specific, actionable descriptionsTask(description="""Research competitors in the AI chatbot space.Focus on: pricing models, key features, target markets.Provide data in a structured format.""",...)# ❌ Vague descriptions that don't guide collaborationTask(description="Do some research about chatbots", ...)
协作问题排查
问题:Agent 没有发生协作
现象: Agent 各自独立工作,没有发生任务委派
# ✅ Solution: Ensure delegation is enabledagent = Agent(role="...",allow_delegation=True, # This is required!...)
问题:来回沟通过多
现象: Agent 提问过于频繁,导致进度缓慢
# ✅ Solution: Provide better context and specific rolesTask(description="""Write a technical blog post about machine learning.Context: Target audience is software developers with basic ML knowledge.Length: 1200 wordsInclude: code examples, practical applications, best practicesIf you need specific technical details, delegate research to the researcher.""",...)
问题:委派循环
现象: Agent 之间来回反复委派,无法结束
# ✅ Solution: Clear hierarchy and responsibilitiesmanager = Agent(role="Manager", allow_delegation=True)specialist1 = Agent(role="Specialist A", allow_delegation=False) # No re-delegationspecialist2 = Agent(role="Specialist B", allow_delegation=False)
高级协作功能
自定义协作规则
# Set specific collaboration guidelines in agent backstoryagent = Agent(role="Senior Developer",backstory="""You lead development projects and coordinate with team members.Collaboration guidelines:- Delegate research tasks to the Research Analyst- Ask the Designer for UI/UX guidance- Consult the QA Engineer for testing strategies- Only escalate blocking issues to the Project Manager""",allow_delegation=True)
监控协作过程
def track_collaboration(output):"""Track collaboration patterns"""if "Delegate work to coworker" in output.raw:print("🤝 Delegation occurred")if "Ask question to coworker" in output.raw:print("❓ Question asked")crew = Crew(agents=[...],tasks=[...],step_callback=track_collaboration, # Monitor collaborationverbose=True)
记忆与学习
启用 Agent 记忆,让它们记住过去的协作过程:
agent = Agent(role="Content Lead",memory=True, # Remembers past interactionsallow_delegation=True,verbose=True)
启用记忆后,Agent 可以从过去的协作中学习,并随着时间推移不断优化其委派决策。
下一步
- 尝试这些示例:先从基础协作示例开始
- 实验不同角色:测试不同的 Agent 角色组合
- 观察交互过程:使用
verbose=True查看协作如何发生 - 优化任务描述:清晰的任务会带来更好的协作效果
- 逐步扩展:对于复杂项目,尝试分层流程
协作能够把单个 AI Agent 转变为强大的团队,使它们可以共同应对复杂、多维度的挑战。
