This article introduces CrewAI framework's core concepts: Agent, Task, and Crew, along with basic multi-agent collaboration. Includes practical code examples showing how to define professional agents, configure task dependencies, set execution flows (sequential/parallel), and start a Crew.
CrewAI is a Python framework for orchestrating autonomous AI agents, allowing you to form virtual teams where each agent has specific roles and goals to collaboratively handle complex tasks.
Agent is an AI execution unit with a specific role:
from crewai import Agent
researcher = Agent(
role="Research Analyst",
goal="Provide accurate, in-depth research analysis",
backstory="You are a senior research analyst skilled at multi-perspective analysis.",
verbose=True
)
Task is specific work assigned to an agent:
from crewai import Task
research_task = Task(
description="Analyze AI application trends in healthcare",
agent=researcher,
expected_output="A structured analysis report"
)
Crew coordinates multiple agents to complete tasks:
from crewai import Crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process="sequential" # or "parallel"
)
from crewai import Agent, Task, Crew
from crewai.process import Process
# 1. Define Agents
researcher = Agent(
role="Market Researcher",
goal="Collect and analyze market data",
backstory="You are a professional market analyst skilled in data analysis."
)
writer = Agent(
role="Content Writer",
goal="Write clear, professional market reports",
backstory="You are a senior content writer who excels at transforming complex information into readable articles."
)
# 2. Define Tasks
research_task = Task(
description="Collect 2024 AI industry market size and growth trend data",
agent=researcher,
expected_output="Market size data, growth rates, key players list"
)
write_task = Task(
description="Write market analysis report based on research data",
agent=writer,
expected_output="A complete market analysis report with executive summary and conclusions"
)
write_task.context = [research_task] # Depends on research_task
# 3. Create Crew
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential
)
# 4. Execute
result = crew.kickoff()
print(result)
crew = Crew(
agents=[agent1, agent2, agent3],
tasks=[task1, task2, task3],
process=Process.sequential
)
# Tasks execute in defined order
crew = Crew(
agents=[researcher1, researcher2, researcher3],
tasks=[task1, task2, task3],
process=Process.hierarchical
)
Q1: What is the context parameter for Task?
Q2: What's the difference between sequential and hierarchical?
Q3: How to make agents collaborate?
示例代码逻辑完整,可正常导入执行
代码结构符合 CrewAI 框架规范