> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/ai-ping-tai-yu-zhi-neng-ti/crewai.md).

# CrewAI 多智能体框架

在 Clore.ai 上部署 CrewAI——使用任意 LLM 提供商编排角色扮演式自主 AI 智能体团队，以完成复杂的多步骤任务。

## 概览

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

在 **Clore.ai**，CrewAI 只需在 Docker 化环境中部署，成本低至 **$0.05–0.20/小时**。虽然 CrewAI 本身依赖 CPU（它负责协调 API 调用），但将它与同一 GPU 节点上的本地 Ollama 或 vLLM 服务器结合使用，你就能获得一个完全私有、可离线运行的多智能体系统。

**主要能力：**

* 👥 **多智能体团队** — 定义具备角色、目标和背景故事的智能体人格
* 🎯 **任务委派** — 管理智能体自动将任务分配给合适的专家
* 🛠️ **工具生态** — 网络搜索、文件读写、代码执行、数据库访问、自定义工具
* 🔁 **顺序与并行** — 按顺序执行任务，或同时运行彼此独立的任务
* 🧠 **智能体记忆** — 短期、长期、实体和上下文记忆类型
* 🔌 **与 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.05–0.19/小时                     |
| **+ 本地 LLM（大型）** | RTX 3090 / 4090 | 24 GB | 16 GB | 60 GB  | $0.07–0.21/小时                     |
| **+ 高质量本地 LLM**  | A100 40 GB      | 40 GB | 32 GB | 100 GB | [裸机](https://clore.ai/bare-metal) |

### 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 会使用。请在同一台 Clore 服务器上运行 Ollama 或 vLLM，以获得 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"总共使用的 token 数：{result.token_usage}")

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

# 设置 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 &

# 触发一次 crew 运行
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
```

### Agent 卡在推理循环中

```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 / embeddings）

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

# 清除损坏的内存
rm -rf ~/.local/share/crewai/

# 或者如果不需要则禁用内存
Crew(memory=False)

# 如果使用 Ollama embeddings，请确保已拉取模型
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-zhi-nan/gpu-comparison.md)
* [CrewAI 社区 Discord](https://discord.com/invite/X4JWnZnxPb)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
