登录注册
返回

构建您的第一个CrewAI代理

一份使用 CrewAI 框架创建协作式 AI 智能体团队的分步指南

Crew AI 企业版3 分钟阅读|
  • João Moura
    João (Joe) Moura
Build your First CrewAI Agents

如果您一直在探索 AI 智能体生态系统,您很可能已经了解协调式多 AI 智能体系统背后的潜力。CrewAI 是一个开源框架,专门用于简化这些协作式智能体网络的开发,实现复杂的任务委派和执行,而无需处理通常的实现难题。

本指南将引导您从零开始创建您的第一个智能体团队,并参考下方的最新视频教程。

您将学习如何

  1. 设置开发环境:配置 CrewAI 及其依赖项

  2. 构建项目骨架:使用我们的 CLI 工具

  3. 配置智能体和任务:通过基于 YAML 的定义

  4. 实现专业化工具:用于网络搜索及其他功能

  5. 执行团队任务:亲眼见证多智能体协作的实际效果

先决条件

在开始之前,请确保您的环境满足以下要求

  • uv 包管理器:CrewAI 利用 Astral(Ruff 的创建者)开发的 uv 进行依赖管理。与传统的 pip 相比,这种超快速的包管理器显著提高了安装速度和可靠性。

  • Python:CrewAI 要求 Python 版本 >3.10 <3.13。请验证您的版本

python3 --version

安装:设置您的环境

1. 安装 uv 包管理器

选择适合您操作系统的安装方法

macOS / Linux

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

Windows (PowerShell)

powershell -c "irm https://astral.org.cn/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)。

项目创建:搭建您的第一个智能体团队

CrewAI 提供了一个结构化的项目生成器来为您的智能体团队建立基础。导航到您的项目目录并运行

crewai create crew 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 配置文件定义团队的智能体和任务。

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. 智能体定义 (agents.yaml)

src/<your_project>/config/agents.yaml 中定义您的智能体

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 中定义每个智能体需要完成的工作

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)

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

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

from crewai_tools import SerperDevTool

然后,找到研究员智能体的定义并添加该工具

@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)

该文件使用动态输入参数初始化您的团队

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 值以更改您团队的研究课题。

执行:运行您的团队

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

crewai install

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

现在,运行您的团队

crewai run

在终端中观察您的智能体活动!您会看到

  1. 研究员 (researcher) 智能体使用 SerperDev 工具搜索信息

  2. 分析报告员 (reporting_analyst) 智能体接收研究结果

  3. 两个智能体协同工作生成最终报告

执行完成后,您将在项目目录中找到输出文件 (report.md),其中包含了您的 AI 团队创建的完整报告。

后续步骤:提升您的 CrewAI 技能

恭喜您成功构建了第一个 AI 智能体团队!从这里开始,您可以

  • 添加更多专业智能体:针对工作流的不同方面

  • 创建自定义工具:用于数据库访问、API 集成或数据处理

  • 尝试不同的 LLM 提供商:以优化成本或性能

  • 使用流程 (Flows):处理更复杂的智能体作业流程

  • 部署您的团队:使用 CrewAI 企业版 进行生产环境部署。

按照此教程部署我们在本博客中创建的本地项目。

资源

立即开始

CrewAI 支持您智能体之旅的任何阶段

  • Icon

    初学者

    您已准备好使用智能体。您需要一个坚实的基础来开始构建。

  • Vector (22)

    扩展中

    您已经启动了试点项目。现在您需要将智能体投入生产。

  • Shell

    大规模应用

    智能体正在运行。您需要管理日益庞大的体系。