构建你的第一个 CrewAI Agent

使用 CrewAI 框架创建协作式 AI Agent Crew 的分步指南

Build your First CrewAI Agents

如果你一直在探索 AI Agent 生态系统,你可能已经意识到协调的多 AI Agent 系统背后的潜力。CrewAI 是一个开源框架,专门设计用于简化这些协作式 Agent 网络的开发,无需典型的实现麻烦即可实现复杂的任务委托和执行。

本指南将逐步引导你从头开始创建你的第一个 Agent Crew,请遵循下面的最新视频教程。

你将学习如何:

  1. 使用 CrewAI 及其依赖项设置你的开发环境
  2. 使用我们的 CLI 工具构建新项目
  3. 通过基于 YAML 的定义配置你的 Agents 和任务
  4. 实现专用的工具用于网页搜索和其他功能
  5. 执行你的 Crew 并观察多 Agent 协作的实际运行

先决条件

在深入之前,请确保你的环境满足这些要求:

  • uv 包管理器:CrewAI 利用 Astral(Ruff 的创建者)的 uv 进行依赖管理。与传统的 pip 相比,这个超快速的包管理器显著提高了安装速度和可靠性。
  • Python:CrewAI 需要 Python >3.10<3.13。验证你的版本:
python3 --version

安装:设置你的环境

1. 安装 uv 包管理器

选择适合你的操作系统的相应方法:

macOS / Linux

curl -LsSf https://astral.sh/uv/install.sh | sh

Windows (PowerShell)

powershell -c "irm https://astral.sh/uv/install.ps1 | iex"

验证安装:

uv --version
注意:有关高级安装选项或故障排除,请参阅官方 uv 文档

2. 安装 CrewAI CLI

准备好 uv 后,安装 CrewAI 命令行界面:

uv tool install crewai

如果这是你第一次使用 uv tool,你可能会看到一个关于更新 PATH 的提示。请遵循说明(通常运行 uv tool update-shell),并在必要时重启终端。

验证你的安装:

uv tool list

你应该看到 crewai 及其版本号(例如,crewai v0.119.0)。

项目创建:构建你的第一个 Crew

CrewAI 提供了一个结构化的项目生成器,用于为你 Agent Crew 设置基础。导航到你的项目目录并运行:

crewai create crew latest-ai-development
latest-ai-development 替换为你项目的描述性名称。

CLI 将提示你:

  1. 选择一个 LLM 提供商:选择你偏好的大型语言模型提供商 (OpenAI, Anthropic, Gemini, Ollama 等)
  2. 选择一个模型:从提供商中选择一个特定模型 (例如,gpt-4o-mini)
  3. 输入 API 密钥:你可以现在或稍后添加这些密钥

生成的项目结构

CLI 会创建一个组织良好的目录结构:

latest-ai-development/
├── .env                  # Environment variables and API keys
├── .gitignore            # Pre-configured to prevent committing 
                          # sensitive data
├── pyproject.toml        # Project dependencies and metadata
├── README.md             # Basic project information
├── knowledge/            # Storage for knowledge files (PDFs, etc.)
└── src/                  # Main source code
    └── latest_ai_development/
        ├── config/       # YAML configuration files
        │   ├── agents.yaml
        │   └── tasks.yaml
        ├── tools/        # Custom tool implementations
        │   └── custom_tool.py
        ├── crew.py       # Crew class definition
        └── main.py       # Entry point

导航到你的项目目录:

cd latest-ai-development

配置

在这里,你将通过 YAML 配置文件定义你的 Crew 的 Agents 和任务。

1. API 密钥 (.env)

打开 .env 文件并添加你的 API 密钥:

MODEL=provider/your-preferred-model # e.g gemini/gemini-2.5-pro-preview-05-06
<PROVIDER>_API_KEY=your_preffered_provider_api_key
SERPER_API_KEY=your_serper_api_key  # For web search capability
安全注意:切勿将此文件提交到版本控制。生成的 .gitignore 已配置为排除它。

2. Agent 定义 (agents.yaml)

src/<your_project>/config/agents.yaml 中定义你的智能 Agents:

researcher:
  role: '{topic} Senior Data Researcher'
  goal: 'Uncover cutting-edge developments in {topic} with comprehensive research'
  backstory: 'You are a seasoned researcher with expertise in identifying emerging trends. Your specialty is finding information that others miss, particularly in technical domains.'

reporting_analyst:
  role: '{topic} Reporting Analyst'
  goal: 'Create detailed, actionable reports based on {topic} research data'
  backstory: 'You are a meticulous analyst with a talent for transforming raw research into coherent narratives. Your reports are known for their clarity and strategic insights.'
动态变量:注意 {topic} 占位符。这些在运行时会被你的 main.py 文件中的值动态替换。

3. 任务定义 (tasks.yaml)

src/<your_project>/config/tasks.yaml 中定义每个 Agent 需要完成的任务:

research_task:
  description: >
    Conduct thorough research about {topic}. Focus on:
    1. Latest developments (make sure to find information from {current_year})
    2. Key players and their contributions
    3. Technical innovations and breakthroughs
    4. Challenges and limitations
    5. Future directions
  expected_output: >
    A list with 10 bullet points covering the most significant findings about {topic},
    with emphasis on technical details relevant to developers.
  agent: researcher

reporting_task:
  description: >
    Review the research findings and create a comprehensive report on {topic}.
    Expand each bullet point with supporting evidence, technical explanations,
    and implementation considerations.
  expected_output: >
    A fully fledged technical report with sections covering each major aspect of {topic}.
    Include code examples where relevant. Format as markdown without code block indicators.
  agent: reporting_analyst
  output_file: report.md  # Automatically saves output to this file

4. 工具集成 (crew.py)

Agents 通常需要专用的工具来与外部系统交互。让我们为我们的研究员 Agent 添加一个网页搜索功能:

首先,在 crew.py 的顶部导入工具:

from crewai_tools import SerperDevTool

然后,找到研究员 Agent 的定义并添加工具:

@agent
def researcher(self) -> Agent:
    return Agent(
        config=self.agents_config['researcher'],
        tools=[SerperDevTool()],  # Enable web search capability
        verbose=True,
        llm=self.openai_llm
    )

5. 入口点 (main.py)

此文件使用动态输入参数初始化你的 Crew:

from datetime import datetime

# Variables that will be interpolated in your YAML configurations
inputs = {
    'topic': 'Open source AI agent frameworks',
    'current_year': str(datetime.now().year)
}

# Initialize and run the crew
LatestAiDevelopment().crew().kickoff(inputs=inputs)
自定义提示:调整 topic 值以更改你的 Crew 的研究主题。

执行:运行你的 Crew

配置完成后,安装项目依赖项:

crewai install

此命令使用 uv 安装并锁定 pyproject.toml 中定义的所有依赖项。

现在,执行你的 Crew:

crewai run

观察你的终端,Agents 将开始工作!你将看到:

  1. 研究员 Agent 使用 SerperDev 工具搜索信息
  2. 报告分析师 Agent 接收研究结果
  3. 两个 Agents 协同工作以生成最终报告

执行完成后,你会在项目目录中找到输出文件(report.md),其中包含由你的 AI Crew 创建的综合报告。

下一步:扩展你的 CrewAI 技能

祝贺你构建了第一个 AI Agent Crew!在此基础上,你可以:

  • 为工作流的不同方面添加更多专用的 Agents
  • 创建自定义工具用于数据库访问、API 集成或数据处理
  • 尝试不同的 LLM 提供商以优化成本或能力
  • 使用 Flows 处理更复杂的 Agent 流程
  • 使用 CrewAI 企业版 部署你的 Crew 到生产环境。

请按照本教程将我们在此博客中刚刚创建的本地项目部署到 CrewAI 企业版。

资源


有问题或想分享你的 CrewAI 项目?加入我们的社区论坛或在 LinkedInX 上标记我们!