构建你的第一个 CrewAI 智能体
让我们创建一个简单的 crew,帮助我们针对给定主题或领域研究并报告最新的人工智能发展。 在继续之前,请确保你已经完成了 CrewAI 的安装。如果你还没有安装,可以按照安装指南进行操作。 按照以下步骤开始你的 Crew 之旅吧!🚣♂️1
创建你的 crew
在终端中运行以下命令来创建一个新的 crew 项目。这将在名为
latest-ai-development 的新目录中创建 crew 的基本结构。复制
询问 AI
crewai create crew latest-ai-development
2
导航到你的新 crew 项目
复制
询问 AI
cd latest_ai_development
3
修改你的 `agents.yaml` 文件
你也可以根据你的用例需要修改智能体,或者直接复制粘贴到你的项目中。在你的
agents.yaml 和 tasks.yaml 文件中任何插值的变量,如 {topic},都将被 main.py 文件中的变量值替换。agents.yaml
复制
询问 AI
# src/latest_ai_development/config/agents.yaml
researcher:
role: >
{topic} Senior Data Researcher
goal: >
Uncover cutting-edge developments in {topic}
backstory: >
You're a seasoned researcher with a knack for uncovering the latest
developments in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
reporting_analyst:
role: >
{topic} Reporting Analyst
goal: >
Create detailed reports based on {topic} data analysis and research findings
backstory: >
You're a meticulous analyst with a keen eye for detail. You're known for
your ability to turn complex data into clear and concise reports, making
it easy for others to understand and act on the information you provide.
4
修改你的 `tasks.yaml` 文件
tasks.yaml
复制
询问 AI
# src/latest_ai_development/config/tasks.yaml
research_task:
description: >
Conduct a thorough research about {topic}
Make sure you find any interesting and relevant information given
the current year is 2025.
expected_output: >
A list with 10 bullet points of the most relevant information about {topic}
agent: researcher
reporting_task:
description: >
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
expected_output: >
A fully fledge reports with the mains topics, each with a full section of information.
Formatted as markdown without '```'
agent: reporting_analyst
output_file: report.md
5
修改你的 `crew.py` 文件
crew.py
复制
询问 AI
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
agents: List[BaseAgent]
tasks: List[Task]
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'], # type: ignore[index]
verbose=True,
tools=[SerperDevTool()]
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'], # type: ignore[index]
verbose=True
)
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'], # type: ignore[index]
)
@task
def reporting_task(self) -> Task:
return Task(
config=self.tasks_config['reporting_task'], # type: ignore[index]
output_file='output/report.md' # This is the file that will be contain the final report.
)
@crew
def crew(self) -> Crew:
"""Creates the LatestAiDevelopment crew"""
return Crew(
agents=self.agents, # Automatically created by the @agent decorator
tasks=self.tasks, # Automatically created by the @task decorator
process=Process.sequential,
verbose=True,
)
6
[可选] 添加 crew 前后处理函数
crew.py
复制
询问 AI
# src/latest_ai_development/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task, before_kickoff, after_kickoff
from crewai_tools import SerperDevTool
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
@before_kickoff
def before_kickoff_function(self, inputs):
print(f"Before kickoff function with inputs: {inputs}")
return inputs # You can return the inputs or modify them as needed
@after_kickoff
def after_kickoff_function(self, result):
print(f"After kickoff function with result: {result}")
return result # You can return the result or modify it as needed
# ... remaining code
7
随时向你的 crew 传递自定义输入
例如,你可以将
topic 输入传递给你的 crew,以自定义研究和报告。main.py
复制
询问 AI
#!/usr/bin/env python
# src/latest_ai_development/main.py
import sys
from latest_ai_development.crew import LatestAiDevelopmentCrew
def run():
"""
Run the crew.
"""
inputs = {
'topic': 'AI Agents'
}
LatestAiDevelopmentCrew().crew().kickoff(inputs=inputs)
8
设置你的环境变量
在运行你的 crew 之前,请确保你已将以下密钥在你的
.env 文件中设置为环境变量- 一个 Serper.dev API 密钥:
SERPER_API_KEY=你的密钥 - 你所选模型的配置,例如 API 密钥。请参阅 LLM 设置指南,了解如何配置来自任何提供商的模型。
9
锁定并安装依赖项
- 使用 CLI 命令锁定并安装依赖项
复制询问 AI
crewai install - 如果你有其他需要安装的包,可以运行
复制询问 AI
uv add <package-name>
10
运行你的 crew
- 要在项目根目录运行你的 crew,请执行以下命令
复制询问 AI
crewai run
11
企业级替代方案:在 Crew Studio 中创建
对于 CrewAI AMP 用户,你可以无需编写代码即可创建相同的 crew
- 登录你的 CrewAI AMP 账户(在 app.crewai.com 创建一个免费账户)
- 打开 Crew Studio
- 输入你想要构建的自动化任务
- 可视化地创建你的任务并按顺序连接它们
-
配置你的输入并点击“下载代码”或“部署”

试用 CrewAI AMP
在 CrewAI AMP 开始你的免费账户
12
查看你的最终报告
你应该会在控制台中看到输出,并且项目根目录中应该会创建
report.md 文件,其中包含最终报告。以下是报告样式的示例:复制
询问 AI
# Comprehensive Report on the Rise and Impact of AI Agents in 2025
## 1. Introduction to AI Agents
In 2025, Artificial Intelligence (AI) agents are at the forefront of innovation across various industries. As intelligent systems that can perform tasks typically requiring human cognition, AI agents are paving the way for significant advancements in operational efficiency, decision-making, and overall productivity within sectors like Human Resources (HR) and Finance. This report aims to detail the rise of AI agents, their frameworks, applications, and potential implications on the workforce.
## 2. Benefits of AI Agents
AI agents bring numerous advantages that are transforming traditional work environments. Key benefits include:
- **Task Automation**: AI agents can carry out repetitive tasks such as data entry, scheduling, and payroll processing without human intervention, greatly reducing the time and resources spent on these activities.
- **Improved Efficiency**: By quickly processing large datasets and performing analyses that would take humans significantly longer, AI agents enhance operational efficiency. This allows teams to focus on strategic tasks that require higher-level thinking.
- **Enhanced Decision-Making**: AI agents can analyze trends and patterns in data, provide insights, and even suggest actions, helping stakeholders make informed decisions based on factual data rather than intuition alone.
## 3. Popular AI Agent Frameworks
Several frameworks have emerged to facilitate the development of AI agents, each with its own unique features and capabilities. Some of the most popular frameworks include:
- **Autogen**: A framework designed to streamline the development of AI agents through automation of code generation.
- **Semantic Kernel**: Focuses on natural language processing and understanding, enabling agents to comprehend user intentions better.
- **Promptflow**: Provides tools for developers to create conversational agents that can navigate complex interactions seamlessly.
- **Langchain**: Specializes in leveraging various APIs to ensure agents can access and utilize external data effectively.
- **CrewAI**: Aimed at collaborative environments, CrewAI strengthens teamwork by facilitating communication through AI-driven insights.
- **MemGPT**: Combines memory-optimized architectures with generative capabilities, allowing for more personalized interactions with users.
These frameworks empower developers to build versatile and intelligent agents that can engage users, perform advanced analytics, and execute various tasks aligned with organizational goals.
## 4. AI Agents in Human Resources
AI agents are revolutionizing HR practices by automating and optimizing key functions:
- **Recruiting**: AI agents can screen resumes, schedule interviews, and even conduct initial assessments, thus accelerating the hiring process while minimizing biases.
- **Succession Planning**: AI systems analyze employee performance data and potential, helping organizations identify future leaders and plan appropriate training.
- **Employee Engagement**: Chatbots powered by AI can facilitate feedback loops between employees and management, promoting an open culture and addressing concerns promptly.
As AI continues to evolve, HR departments leveraging these agents can realize substantial improvements in both efficiency and employee satisfaction.
## 5. AI Agents in Finance
The finance sector is seeing extensive integration of AI agents that enhance financial practices:
- **Expense Tracking**: Automated systems manage and monitor expenses, flagging anomalies and offering recommendations based on spending patterns.
- **Risk Assessment**: AI models assess credit risk and uncover potential fraud by analyzing transaction data and behavioral patterns.
- **Investment Decisions**: AI agents provide stock predictions and analytics based on historical data and current market conditions, empowering investors with informative insights.
The incorporation of AI agents into finance is fostering a more responsive and risk-aware financial landscape.
## 6. Market Trends and Investments
The growth of AI agents has attracted significant investment, especially amidst the rising popularity of chatbots and generative AI technologies. Companies and entrepreneurs are eager to explore the potential of these systems, recognizing their ability to streamline operations and improve customer engagement.
Conversely, corporations like Microsoft are taking strides to integrate AI agents into their product offerings, with enhancements to their Copilot 365 applications. This strategic move emphasizes the importance of AI literacy in the modern workplace and indicates the stabilizing of AI agents as essential business tools.
## 7. Future Predictions and Implications
Experts predict that AI agents will transform essential aspects of work life. As we look toward the future, several anticipated changes include:
- Enhanced integration of AI agents across all business functions, creating interconnected systems that leverage data from various departmental silos for comprehensive decision-making.
- Continued advancement of AI technologies, resulting in smarter, more adaptable agents capable of learning and evolving from user interactions.
- Increased regulatory scrutiny to ensure ethical use, especially concerning data privacy and employee surveillance as AI agents become more prevalent.
To stay competitive and harness the full potential of AI agents, organizations must remain vigilant about latest developments in AI technology and consider continuous learning and adaptation in their strategic planning.
## 8. Conclusion
The emergence of AI agents is undeniably reshaping the workplace landscape in 5. With their ability to automate tasks, enhance efficiency, and improve decision-making, AI agents are critical in driving operational success. Organizations must embrace and adapt to AI developments to thrive in an increasingly digital business environment.
恭喜!你已经成功设置了你的 crew 项目,并准备好开始构建你自己的智能体工作流了!
关于命名一致性的说明
你在 YAML 文件(agents.yaml 和 tasks.yaml)中使用的名称应与你的 Python 代码中的方法名相匹配。例如,你可以从 tasks.yaml 文件中引用特定任务的智能体。这种命名一致性使 CrewAI 能够自动将你的配置与代码链接起来;否则,你的任务将无法正确识别引用。
引用示例
请注意,我们在
agents.yaml 文件(email_summarizer)中为智能体使用的名称与在 crew.py 文件(email_summarizer)中的方法名相同。agents.yaml
复制
询问 AI
email_summarizer:
role: >
Email Summarizer
goal: >
Summarize emails into a concise and clear summary
backstory: >
You will create a 5 bullet point summary of the report
llm: provider/model-id # Add your choice of model here
请注意,我们在
tasks.yaml 文件(email_summarizer_task)中为任务使用的名称与在 crew.py 文件(email_summarizer_task)中的方法名相同。tasks.yaml
复制
询问 AI
email_summarizer_task:
description: >
Summarize the email into a 5 bullet point summary
expected_output: >
A 5 bullet point summary of the email
agent: email_summarizer
context:
- reporting_task
- research_task
