一个研究员、一个撰稿人,两个 AI Agent 接力协作,自动产出一篇科普文章。本文完整拆解 CrewAI 的核心概念与实战代码。
一、为什么需要"AI 团队"?
CrewAI 核心由 智能体(Agent)、任务(Task)、团队(Crew)、流程(Process) 四部分组成,支持两种运行模式:顺序模式(sequential) 和层级模式(hierarchical) 。
CrewAI 的设计思想就是模拟组织协作:每个 Agent 拥有角色、目标、人设背景;Task 代表分配给 Agent 的具体工作;Crew 则在指定 Process 规则下调度整套智能体与任务。
本文目标很清晰:使用顺序模式搭建第一个 AI 智能体团队,把真实工作流程转化为可运行代码。
二、选一个贴近业务的场景
我们从一个常见的写作场景入手,搭建一个简易写作团队,包含两个角色:
- 行业资料研究员:围绕指定主题,梳理客观资料,提炼核心要点
- 科普撰稿人:基于调研摘要,产出通俗易懂的科普短文
两个角色职责解耦、分工独立,工作流程为接力模式:研究员先输出调研摘要,摘要作为输入交给撰稿人,撰稿人基于摘要完成文章撰写。
这就是顺序模式:任务按先后次序串行执行,上一个任务的输出自动作为下一个任务的上下文。在顺序流程中,每个任务绑定一个 Agent,上游结果驱动下游任务执行。
三、六步实现流程
整个案例落地分为 6 个步骤:
第 1 步:准备环境
安装依赖:crewai、crewai-tools,搭配 python-dotenv 读取环境变量。本案例采用单文件开发,密钥统一放在 .env,官方安装命令:
pip install crewai
第 2 步:接入大模型
⚠️ 重点:CrewAI 只负责调度流程,真正负责推理生成的是大语言模型。
从 crewai 导入 LLM,传入模型名称、密钥、接口地址、温度参数。
一个实用技巧:根据角色差异化设置 temperature
# 研究员:追求严谨稳定 → 低温
researcher_llm = LLM(model="deepseek-chat", api_key=..., base_url=..., temperature=0.3)
# 撰稿人:需要创意表达 → 高温
writer_llm = LLM(model="deepseek-chat", api_key=..., base_url=..., temperature=0.8)
公共参数一致,只有温度不同,可以封装成函数动态传入。低温可以让调研结果稳定可控;更高温度给撰稿人留出表达发挥空间。
第 3 步:定义两个智能体
Agent 核心由 role、goal、backstory 三个属性定义,backstory 用来塑造智能体的身份风格。
from crewai import Agent
researcher = Agent(
role="行业资料研究员",
goal="围绕指定主题,梳理已掌握的客观资料,提取要点",
backstory="严谨且专业,基于事实,不自由创作",
llm=researcher_llm,
verbose=True, # 打印思考链路,方便调试
max_rpm=20, # 限流:每分钟最多 20 次请求
max_iter=3, # 限制最大迭代次数,避免死循环
)
writer = Agent(
role="科普撰稿人",
goal="基于调研摘要,写出通俗易懂的科普短文",
backstory="擅长转换专业信息,不添加摘要以外的内容",
llm=writer_llm,
verbose=True,
max_rpm=20,
max_iter=3,
)
除角色配置外,还有三个很关键的运行控制参数:
- verbose:True 时打印智能体思考过程,调试阶段开启;正式部署建议关闭,避免日志过多
- max_rpm:请求限流,防止调用接口触发平台频率限制
- max_iter:最大迭代次数,防止智能体卡在任务里无限重试
第 4 步:定义两个工作任务
Agent 相当于岗位人员,Task 就是分配给它的工作。一个 Task 需要明确三件事:做什么、交付物是什么、由谁执行。
from crewai import Task
research_task = Task(
description="围绕 {topic},整理核心知识点,输出要点",
expected_output="调研摘要,语言简洁客观,不确定内容标注「待核实」",
agent=researcher,
)
write_task = Task(
description="参考调研摘要,围绕 {topic} 撰写通俗易懂的科普短文",
expected_output="Markdown 格式科普文章,约 800 字,含标题",
agent=writer,
context=[research_task], # 依赖上游任务结果作为上下文
output_file="article.md", # 结果自动写入文件
)
写作任务额外增加两个参数:
- context:显式声明任务依赖,把调研任务的输出传给写作任务。顺序模式下不写也能自动传递,但显式声明依赖关系可读性更好;任务复杂、非线性依赖时这个参数尤其重要。
- output_file:将输出持久化保存为 md 文件。
{topic} 是变量占位符,支持动态传入主题,提升任务复用能力。
第 5 步:组建并启动团队
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
process=Process.sequential, # 顺序串行执行
verbose=True,
)
result = crew.kickoff(inputs={"topic": user_topic})
print(result.raw)
Crew 作为团队容器,传入智能体列表、任务列表,指定执行流程 Process.sequential。顺序模式也是 CrewAI 默认执行方式,任务按照列表顺序依次跑。调用 kickoff 启动流程并传入变量。
第 6 步:终端交互
读取终端输入的文章主题,做简单判空和退出判断,调用 crew.kickoff() 启动整套智能体流水线,主题会自动填充到任务里的 {topic} 占位符。
四、执行链路与实测结果
整体执行链路:研究员先执行调研输出摘要,摘要自动作为上下文传给撰稿人;撰稿人基于摘要完成科普文章,内容保存到 article.md,同时控制台输出结果。
测试输入主题:写一篇关于开发智能体不同模式的文章
- 研究员输出结构化调研摘要
- 撰稿人基于摘要生成科普文章《智能体不是越自主越好。一篇文章看懂开发智能体的几种模式》
- 成品自动落盘为 article.md
五、小结与扩展思路
本文通过一个写作案例搭建了 CrewAI 多智能体团队,梳理核心要点:
- 四大核心组件:Agent(角色+目标+背景)、Task(描述+预期输出+执行者)、Crew(团队容器)、Process(顺序/层级)
- 顺序模式本质:接力串行,上游产出作为下游上下文
- 三个实用控制参数:verbose(可观测调试)、max_rpm(接口限流)、max_iter(防死循环)
- 温度调优思路:严谨类任务低温,创意写作类任务高温
你可以跟着代码动手复现,理解 CrewAI 多智能体调度逻辑;这套模式也可以迁移到数据整理、报表生成、内容审核等其他业务场景。
本文由 AI图鉴自动抓取并翻译,版权归原作者所有;如需查看原文请点下方链接。
A researcher, a writer, two AI Agent relays, automatically produced a general science article. This article removes the core concept and field code of Crew AI.
I. Why do you need an "AI team"?
The Crew AI core consists of four components: AI agent (Agent), Task, Team (Crew), Process, and two operating models: sequential and hierarchical.
Crew AI is designed to simulate organizational collaboration: each Agent has a role, a goal, a background; Task represents the specific tasks assigned to Agent; and Crew moves the entire AI agent and tasks under the designated Process rule.
The objective of this paper is clear: to create the first AI AI agent team using a sequenced model, turning the real workflow process into a runable code.
Selection of a scenario close to business
We started with a common writing scene and built a simple writing team with two roles:
- Researcher in industry: refining objective information and distilling core points around designated themes
- Coop author: based on research summary, producing comprehensible science shorts
The two roles were detached and separated, and the workflow process was a relay model: the fellows first exported the study summary, summary as input to the author, who wrote the article based on summary.
This is the sequence pattern: tasks are carried out sequentially, and the output of the previous task is automatically context as the next task. In a sequenced process, each task is bound to an Agent, with upstream results driving downstream mission execution.
III. Six-step realization process
The whole case is divided into six steps:
Step 1: Prepare environment
Install dependency: crewai, crewai-tools, with python-dotenv reading environment variables. This case is developed by single file, with a single key in.env, official installation order:
pip install crewai
Step 2: Access to LLM
Focus: Crew AI is responsible only for the movement control process, and the real responsibility for reasoning is to generate a large-language model.
Imports LLM from crewai to enter model name, key, interface address, temperature parameter.
A practical technique: settings based on role differentiation
# Researcher: Seeking stability and coolness
researcher_llm = LLM(model="deepseek-chat", api_key=..., base_url=..., temperature=0.3)
# Author: Need creative expression, high temperature
writer_llm = LLM(model="deepseek-chat", api_key=..., base_url=..., temperature=0.8)
Public parameters are consistent and can be encapsulated into function dynamics only at different temperatures. Temperature allows the results to be stable and manageable; higher temperatures give authors space to express themselves.
Step 3: Definition of two AI agent
The Agent core is defined by three attributes: role, goal, Backstory, Backstory, which is used to shape the identity style of AI agent.
from crewai import Agent
researcher = Agent(
#Role = Industry Researcher
Goal = "To comb the available objective information around the given theme, extract the points."
Backstory: "Screech and professional, based on facts, not free to create."
llm=researcher_llm,
Verbose =True, # Print thought links, easy to debug
max rpm=20, #rate limit: Up to 20 requests per minute
max inter=3, # Limit the maximum number of iterations to avoid the dead cycle
)
writer = Agent(
roger = "Copist."
Goal = "On the basis of research summary, write an easy-to-read science short"
Backstory = "Talking professional information without adding anything other than summary,"
llm=writer_llm,
verbose=True,
max_rpm=20,
max_iter=3,
)
In addition to the role configuration, there are three key operational control parameters:
- Print AI agent for reflection at verbose:True, start debugging phase; proposal for formal deployment closed to avoid too many logs
- max rpm: Request rate limit to prevent an interface from being called to trigger the frequency limit of the platform
- max iter: maximum number of iteratives to prevent AI agent cards retry in the mission.
Step 4: Define two tasks
Agent is the equivalent of a post, and Task is the job assigned to it. A Task needs to be clear about three things: what to do, what to deliver, who to do.
from crewai import Task
research_task = Task(
Description = "Concentration of core knowledge points, output points"
= Z Z Z Z Z Z = = = = = = = = = = = = = =
agent=researcher,
)
write_task = Task(
Description = "Reference summary, about writing comprehensible science shorts,"
Expected output = "Marktown Format Science article, approximately 800 words, including title",
agent=writer,
Contact=[research task], # Relying on upstream mission results as context
Output file= "article.md", #Auto-written file
)
Add two additional parameters to the writing task:
-Context: A visible statement mission relies on transmitting the output of the research mission to the writing mission. Non-writing can also be transmitted automatically under the sequential model, but a visible statement is better dependent on the readability of the relationship; this parameter is particularly important when the task is complex and non-linear.
-output file: Save output permanently as md file.
{topic} is a variable placeholder that supports dynamically moving themes and enhances task reuse capabilities.
Step 5: Team formation and startup
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer],
tasks=[research_task, write_task],
Process=Process.security, # sequential string execution
verbose=True,
)
result = crew.kickoff(inputs={"topic": user_topic})
print(result.raw)
Crew, as a team container, enters the AI agent list, task list, and specifies the execution processProcess.security. The order mode is also the Crew AI default execution method, and the task runs in the order of the list. Call kickoff to start the process and enter the variable.
Step 6: Terminal interaction
Reads the subject of the post that the terminal has entered, makes a simple emptiness and exit judgement, and calls crew.kickoff() to start the entire AI agent stream line, which will automatically fill the {topic} placeholder in the task.
IV. Implementation links and results
Overall implementation links: Researchers start with the output of summary, summary, which is automatically transmitted as context to the author, who completes the science article based on summary and saves its contents to article.md, while controlling the output of the counter.
Test input theme: Write an article on developing different models of AI agent
- Researcher output structured research summary
- The author ' s scientific article, "AI agent is not as autonomous as possible ", based on summary. An article on models for developing AI agent
- The result is automatic drop.md.
Summary and expansional thinking
The CrewAi MultiZ AI agent team was created by a writing case to combe the core points:
- Four core components: Agent (role + goal + background), Task (description + expected output + implementer), Crew (team container), Procss (order/level)
- The nature of the sequence pattern: relaying, upstream output as downstream context
- Three practical control parameters: Verbose (observable debugging), max rpm (interface rate limit), max iter (mortal protection cycle)
- Temperature-to-temperature approach: strict-type low-temperature, creative writing high-temperature
You can follow the code and understand the Crew AI Multi AI agent movement logic; this model can also be migrated to other business scenarios such as data collation, report generation, content review.
Auto-fetched and translated by AI Atlas. All rights belong to the original author.