# CrewAI 多智能体框架

## 概览

[CrewAI](https://github.com/crewAIInc/crewAI) 是一个用于编排 **角色扮演自治 AI 代理**的前沿框架，具有 **44K+ GitHub 星**。与单代理系统不同，CrewAI 允许你定义专业化的代理（研究员、作者、开发者、分析师……）作为一个“团队”协作完成复杂任务——每个代理都有自己的角色、目标、背景故事和工具包。

在 **Clore.ai**，CrewAI 可以部署在容器化环境中，成本低至 **每小时 $0.05–0.20**。虽然 CrewAI 本身受限于 CPU（它负责协调 API 调用），但将其与运行在同一 GPU 节点上的本地 Ollama 或 vLLM 服务器结合使用，可实现完全私有、支持离线的多代理系统。

**主要功能：**

* 👥 **多代理团队** — 使用角色、目标和背景故事定义代理设定
* 🎯 **任务委派** — 管理代理会自动将任务分配给合适的专家
* 🛠️ **工具生态** — 网页搜索、文件 I/O、代码执行、数据库访问、自定义工具
* 🔁 **顺序与并行** — 按顺序执行任务或同时运行相互独立的任务
* 🧠 **代理记忆** — 短期、长期、实体与上下文记忆类型
* 🔌 **与 LLM 无关** — 可与 OpenAI、Anthropic、Google、Ollama、Groq、Azure 等配合使用
* 📊 **CrewAI Studio** — 用于无代码构建团队的可视化界面（企业版）
* 🚀 **流水线** — 将多个团队串联以实现复杂的多阶段工作流

***

## 要求

CrewAI 是一个 Python 库。它在 CPU 上运行，仅需系统 Python 3.10+ 环境或 Docker。GPU 为可选，但可解锁强大的本地模型推理能力。

| 配置               | GPU             | 显存    | 系统内存  | 磁盘     | Clore.ai 价格     |
| ---------------- | --------------- | ----- | ----- | ------ | --------------- |
| **最小** （云端 API）  | 无 / 仅 CPU       | —     | 2 GB  | 10 GB  | 约 $0.03/小时（CPU） |
| **标准**           | 无 / 仅 CPU       | —     | 4 GB  | 20 GB  | 约 $0.05/小时      |
| **+ 本地 LLM（小型）** | RTX 3080        | 10 GB | 8 GB  | 40 GB  | 约 $0.15/小时      |
| **+ 本地 LLM（大型）** | RTX 3090 / 4090 | 24 GB | 16 GB | 60 GB  | $0.20–0.35/小时   |
| **+ 高质量本地 LLM**  | A100 40 GB      | 40 GB | 32 GB | 100 GB | 约 $0.80/小时      |

### API 密钥

CrewAI 可与大多数主流 LLM 提供商配合使用。你至少需要一个：

* **OpenAI** — GPT-4o（在复杂任务上具有最佳推理能力）
* **Anthropic** — Claude 3.5 Sonnet（非常适合以写作为主的团队）
* **Groq** — 免费额度，推理快速（Llama 3 70B）
* **Ollama** — 完全本地，不需要 API 密钥（参见 [GPU 加速](#gpu-acceleration))

***

## 快速开始

### 1. 租用 Clore.ai 服务器

登录到 [clore.ai](https://clore.ai):

* **仅 CPU** 如果使用云端 LLM API
* **RTX 3090/4090** 用于本地 Ollama 推理
* 已启用 SSH 访问
* CLI 使用不需要特殊端口（仅在使用 Web UI 时暴露端口）

### 2. 连接与准备

```bash
ssh root@<clore-server-ip> -p <ssh-port>

# 更新系统
apt-get update && apt-get upgrade -y

# 安装 Python 3.11（如果尚未安装）
apt-get install -y python3.11 python3.11-venv python3-pip
python3 --version   # 应为 3.10+

# 验证 Docker
docker --version
```

### 3. 选项 A — 直接 pip 安装（最快）

```bash
# 创建虚拟环境
python3 -m venv crewai-env
source crewai-env/bin/activate

# 安装包含所有工具的 CrewAI
pip install crewai crewai-tools

# 验证安装
python -c "import crewai; print(crewai.__version__)"
crewai --version
```

### 4. 选项 B — Docker 容器（推荐用于可重现性）

```bash
# 创建项目目录
mkdir my-crew && cd my-crew

# 编写 Dockerfile
cat > Dockerfile << 'EOF'
FROM python:3.11-slim

# 安装系统依赖项
RUN apt-get update && apt-get install -y \
    curl \
    git \
    && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 安装 CrewAI 和常用工具
RUN pip install --no-cache-dir \
    crewai \
    crewai-tools \
    langchain-openai \
    langchain-anthropic \
    python-dotenv

# 复制应用代码
COPY . .

# 默认命令
CMD ["python", "main.py"]
EOF

# 构建镜像
docker build -t my-crewai-app .
```

### 5. 创建你的第一个团队

```bash
# 使用 CLI 初始化一个新的 CrewAI 项目
source crewai-env/bin/activate
crewai create crew my-research-crew
cd my-research-crew

# 配置 API 密钥
cat > .env << 'EOF'
OPENAI_API_KEY=sk-...
# 或对于 Anthropic：
# ANTHROPIC_API_KEY=sk-ant-...
# 或对于 Ollama（无需密钥）：
# OPENAI_API_BASE=http://localhost:11434/v1
# OPENAI_API_KEY=ollama
EOF

# 安装项目依赖
crewai install

# 运行团队
crewai run
```

***

## 配置

### 项目结构（来自 `crewai create`)

```
my-research-crew/
├── .env                    # API 密钥与设置
├── pyproject.toml          # 依赖项
├── src/
│   └── my_research_crew/
│       ├── config/
│       │   ├── agents.yaml   # 代理定义
│       │   └── tasks.yaml    # 任务定义
│       ├── tools/
│       │   └── custom_tool.py  # 你的自定义工具
│       ├── crew.py           # 团队组装
│       └── main.py           # 入口点
```

### agents.yaml — 定义你的代理

```yaml
researcher:
  role: >
    高级研究分析师
  goal: >
    发现 {topic} 领域的前沿进展并综合可执行洞见
  backstory: >
    你是一名擅长从多样化来源发现并连接信息的专家研究员
    。你对可信度和相关性有敏锐的判断力。
  tools:
    - SerperDevTool
    - ScrapeWebsiteTool
  llm: gpt-4o                # 可按代理单独设置
  verbose: true
  max_iter: 15               # 最大推理迭代次数
  memory: true               # 启用代理记忆

writer:
  role: >
    专家级技术写作者
  goal: >
    将复杂研究转化为清晰、有吸引力且准确的内容
  backstory: >
    你撰写的解释能在不牺牲深度的前提下让复杂主题易于理解。
    你引用来源并以最大可读性来组织内容。
  llm: claude-3-5-sonnet-20241022
  verbose: true
```

### tasks.yaml — 定义任务

```yaml
research_task:
  description: >
    研究过去 6 个月内关于 {topic} 的最新进展。
    识别关键趋势、突破和其影响。
    汇编至少 10 个可信来源。
  expected_output: >
    一份按主题组织的详细研究报告，
    包括来源 URL 和出版日期。
  agent: researcher

writing_task:
  description: >
    使用研究报告，撰写一篇关于 {topic} 的综合博客文章。
    目标长度：1500–2000 字。包含标题、引言、主要章节，
    以及带有未来展望的结论。
  expected_output: >
    以 Markdown 格式输出一篇可发布的博客文章。
  agent: writer
  context:
    - research_task    # 写作任务接收研究者的输出
  output_file: output/blog_post.md
```

### crew\.py — 组装团队

```python
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool, ScrapeWebsiteTool

@CrewBase
class MyResearchCrew():
    """研究与写作团队"""
    agents_config = 'config/agents.yaml'
    tasks_config = 'config/tasks.yaml'

    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config['researcher'],
            tools=[SerperDevTool(), ScrapeWebsiteTool()],
            verbose=True
        )

    @agent
    def writer(self) -> Agent:
        return Agent(
            config=self.agents_config['writer'],
            verbose=True
        )

    @task
    def research_task(self) -> Task:
        return Task(config=self.tasks_config['research_task'])

    @task
    def writing_task(self) -> Task:
        return Task(
            config=self.tasks_config['writing_task'],
            output_file='output/blog_post.md'
        )

    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,  # 或 Process.hierarchical
            verbose=True,
            memory=True,
            max_rpm=10   # 限制 API 调用速率
        )
```

### 使用 Docker Compose 运行（含 Ollama）

```yaml
# docker-compose.yml
version: "3.8"

services:
  crewai:
    build: .
    volumes:
      - ./src:/app/src
      - ./output:/app/output
    environment:
      - OPENAI_API_BASE=http://ollama:11434/v1
      - OPENAI_API_KEY=ollama
      - OPENAI_MODEL_NAME=llama3.1:70b
      - SERPER_API_KEY=${SERPER_API_KEY}
    depends_on:
      - ollama

  ollama:
    image: ollama/ollama:latest
    volumes:
      - ollama_data:/root/.ollama
    ports:
      - "11434:11434"
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]

volumes:
  ollama_data:
```

```bash
# 启动服务栈
docker compose up -d ollama

# 拉取你的模型
docker compose exec ollama ollama pull llama3.1:70b

# 运行你的团队
docker compose run --rm crewai python src/my_research_crew/main.py
```

***

## GPU 加速

CrewAI 本身不使用 GPU —— 但它调用的 LLM 会使用。将 Ollama 或 vLLM 在同一 Clore 服务器上运行可以实现 GPU 加速的本地推理。

### Ollama 安装（为方便起见推荐）

```bash
# 在主机上安装 Ollama
curl -fsSL https://ollama.com/install.sh | sh

# 验证 GPU 检测
nvidia-smi
ollama run llama3:8b "Test"   # 应使用 GPU

# 为不同代理需求拉取模型
ollama pull llama3.1:8b          # 快速、轻量的推理
ollama pull llama3.1:70b         # 复杂推理（需要 A100+）
ollama pull codestral:latest     # 为代码代理专门优化
ollama pull nomic-embed-text     # 用于记忆 / RAG 嵌入

# 配置 CrewAI 使用 Ollama
export OPENAI_API_BASE=http://localhost:11434/v1
export OPENAI_API_KEY=ollama
export OPENAI_MODEL_NAME=llama3.1:8b
```

### 为每个代理配置 CrewAI 的 LLM

```python
from crewai import Agent, LLM

# 为特定代理使用 Ollama
local_llm = LLM(
    model="ollama/llama3.1:8b",
    base_url="http://localhost:11434"
)

# 为另一个代理使用云端 API（例如复杂推理）
cloud_llm = LLM(
    model="gpt-4o",
    api_key="sk-..."
)

researcher = Agent(
    role="Researcher",
    goal="Find information",
    backstory="Expert researcher",
    llm=local_llm    # 使用本地 GPU
)

strategist = Agent(
    role="Strategist",
    goal="Plan actions",
    backstory="Strategic thinker",
    llm=cloud_llm    # 使用云端 API
)
```

### 代理任务的模型推荐

| 任务类型      | 推荐模型             | 显存     | 注意事项    |
| --------- | ---------------- | ------ | ------- |
| 研究 + 网页搜索 | Llama 3.1 70B    | 40 GB  | 最佳本地推理  |
| 代码生成      | Codestral 22B    | 13 GB  | 代码专用    |
| 写作        | Llama 3.1 8B     | 6 GB   | 快速、质量良好 |
| 复杂编排      | GPT-4o（API）      | —      | 总体最佳    |
| 嵌入 / 记忆   | nomic-embed-text | < 1 GB | 记忆所需    |

> 参见 [Clore.ai 上的 Ollama](/guides/guides_v2-zh/yu-yan-mo-xing/ollama.md) 和 [Clore.ai 上的 vLLM](/guides/guides_v2-zh/yu-yan-mo-xing/vllm.md) 以获取完整的推理设置指南。

***

## 提示与最佳实践

### 成本优化

```bash
# 使用 CrewAI 内置使用情况跟踪来跟踪 LLM API 成本
# 将其添加到你的团队：
result = crew.kickoff(inputs={"topic": "AI agents"})
print(f"使用的总令牌数: {result.token_usage}")

# 对于简单任务使用更便宜的模型，对于复杂任务使用高端模型
# Ollama 上的 Llama 3.1 8B = $0 API 成本
# GPT-4o = 约 $0.005/1K 输入令牌

# 设置 max_iter 以防止代理失控
Agent(max_iter=10, max_execution_time=120)  # 2 分钟超时

# 在开发过程中缓存 LLM 响应
os.environ["CREWAI_DISABLE_CACHE"] = "false"
```

### 将团队作为持久服务运行

```bash
# 通过 FastAPI 端点提供团队服务
pip install fastapi uvicorn

cat > server.py << 'EOF'
from fastapi import FastAPI, BackgroundTasks
from my_research_crew.crew import MyResearchCrew
import asyncio

app = FastAPI()
results = {}

@app.post("/run/{topic}")
async def run_crew(topic: str, background_tasks: BackgroundTasks):
    job_id = f"job-{topic}-{len(results)}"
    background_tasks.add_task(execute_crew, job_id, topic)
    return {"job_id": job_id, "status": "started"}

async def execute_crew(job_id: str, topic: str):
    crew = MyResearchCrew().crew()
    result = crew.kickoff(inputs={"topic": topic})
    results[job_id] = str(result)

@app.get("/result/{job_id}")
async def get_result(job_id: str):
    return {"result": results.get(job_id, "pending")}

EOF

# 运行服务器
uvicorn server:app --host 0.0.0.0 --port 8080 &

# 触发一次团队运行
curl -X POST http://<clore-ip>:8080/run/quantum-computing
```

### 内置的有用 CrewAI 工具

```python
from crewai_tools import (
    SerperDevTool,        # 通过 Serper API 的 Google 搜索
    ScrapeWebsiteTool,    # 网页抓取
    FileReadTool,         # 读取本地文件
    FileWriterTool,       # 写入文件
    DirectoryReadTool,    # 列出目录内容
    CodeInterpreterTool,  # 执行 Python 代码
    GithubSearchTool,     # 搜索 GitHub 仓库
    YoutubeVideoSearchTool, # 搜索 YouTube
    PGSearchTool,         # 查询 PostgreSQL
)
```

### 实现人类在环（human-in-the-loop）

```python
# 在特定任务处请求人工输入
task = Task(
    description="Research {topic}",
    expected_output="Research report",
    agent=researcher,
    human_input=True    # 暂停并提示用户反馈
)
```

***

## # 使用固定种子以获得一致结果

### "openai.AuthenticationError" 即使密钥有效

```bash
# 检查你的 API 密钥是否已加载
python3 -c "import os; from dotenv import load_dotenv; load_dotenv(); print(os.getenv('OPENAI_API_KEY')[:10])"

# 如果使用 Ollama，请确保设置了以下项：
export OPENAI_API_BASE=http://localhost:11434/v1
export OPENAI_API_KEY=ollama
export OPENAI_MODEL_NAME=llama3.1:8b

# 验证 Ollama 是否可访问
curl http://localhost:11434/v1/models
```

### 代理卡在推理循环中

```bash
# 设置迭代的硬性上限
Agent(
    max_iter=10,            # 最大推理步数
    max_execution_time=300  # 5 分钟硬性超时
)

# 启用 verbose 以查看循环位置
Agent(verbose=True)

# 检查模型是否支持工具调用
# 一些较小的模型不支持；使用 llama3.1 或 mistral-nemo
```

### CrewAI 工具失败（SerperDevTool 403）

```bash
# SerperDevTool 需要从 serper.dev 获取免费的 API 密钥
export SERPER_API_KEY=your-serper-key

# 替代方案：使用 DuckDuckGo（无需 API 密钥）
from langchain_community.tools import DuckDuckGoSearchRun
from crewai import tool

@tool("DuckDuckGo Search")
def ddg_search(query: str) -> str:
    """使用 DuckDuckGo 搜索网页。"""
    return DuckDuckGoSearchRun().run(query)
```

### 内存错误（ChromaDB / 嵌入）

```bash
# CrewAI 记忆使用 ChromaDB 存储向量
# 如果失败，请检查磁盘空间和权限
df -h
ls -la ~/.local/share/crewai/

# 清除损坏的记忆
rm -rf ~/.local/share/crewai/

# 或者如果不需要可以禁用记忆
Crew(memory=False)

# 如果使用 Ollama 嵌入，请确保模型已被拉取
docker exec ollama ollama pull nomic-embed-text
```

### Docker 构建因 ARM/x86 不匹配而失败

```bash
# Clore.ai 服务器为 x86_64；请明确指定平台：
docker build --platform linux/amd64 -t my-crewai-app .

# 或在 docker-compose.yml 中：
services:
  crewai:
    platform: linux/amd64
    build: .
```

### 来自 LLM API 的速率限制

```bash
# 降低每分钟请求数
Crew(max_rpm=5)   # 每分钟 5 次请求

# 在 LLM 配置中添加重试逻辑
LLM(
    model="gpt-4o",
    max_retries=3,
    timeout=60
)
```

***

## 延伸阅读

* [CrewAI 官方文档](https://docs.crewai.com)
* [CrewAI GitHub 仓库](https://github.com/crewAIInc/crewAI)
* [CrewAI 工具文档](https://docs.crewai.com/concepts/tools)
* [CrewAI 示例仓库](https://github.com/crewAIInc/crewAI-examples)
* [在 Clore.ai 上运行 Ollama](/guides/guides_v2-zh/yu-yan-mo-xing/ollama.md)
* [在 Clore.ai 上运行 vLLM](/guides/guides_v2-zh/yu-yan-mo-xing/vllm.md)
* [Clore.ai GPU 对比](/guides/guides_v2-zh/ru-men/gpu-comparison.md)
* [CrewAI 社区 Discord](https://discord.com/invite/X4JWnZnxPb)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/ai-ping-tai-yu-zhi-neng-ti/crewai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
