# GPT4All 本地 LLM

## 概览

[GPT4All](https://github.com/nomic-ai/gpt4all) 由 Nomic AI 开发，是最受欢迎的开源本地大模型项目之一，拥有超过 **72,000 个 GitHub 星标**。它允许您在自己的硬件上完全离线运行大型语言模型——无需网络连接，也不会将数据发送给第三方。

GPT4All 最为人知的是其精美的桌面应用，但它也包含一个 **Python 库** (`gpt4all` 包）以及内置的 **兼容 OpenAI 的 API 服务器** 运行在端口 **4891**。在 Clore.ai 上，您可以在租用的 GPU 上将 GPT4All 部署在 Docker 容器中，通过 HTTP 提供服务，并将任何兼容 OpenAI 的客户端连接到它。

> **Docker 说明：** GPT4All 未为服务器组件发布官方 Docker 镜像。本指南使用带有 `gpt4all` Python 包 的自定义 Docker 设置。对于更适合生产的 Docker 替代方案，可运行 **相同的 GGUF 模型文件**，请参阅 [LocalAI 替代部分](#alternative-localai-docker-image) —— LocalAI 以 Docker 为先并支持相同的模型格式。

**主要功能：**

* 🔒 100% 离线 — 所有推理在本地运行
* 🤖 兼容 OpenAI 的 REST API（端口 4891）
* 📚 LocalDocs — 基于您自己的文档进行检索增强生成（RAG）
* 🧩 支持所有流行的 GGUF 模型格式
* 🐍 完整的 Python API，使用 `pip install gpt4all`
* 💬 精美的桌面界面（与服务器无关，但适合本地测试）

***

## 要求

### 硬件要求

| 方案          | GPU           | 显存    | 内存    | 存储         | Clore.ai 价格         |
| ----------- | ------------- | ----- | ----- | ---------- | ------------------- |
| **仅 CPU**   | 无             | —     | 16 GB | 50 GB SSD  | \~$0.02/小时（CPU 服务器） |
| **入门级 GPU** | RTX 3060 12GB | 12 GB | 16 GB | 50 GB SSD  | 约 $0.10/小时          |
| **推荐**      | 速度            | 24 GB | 32 GB | 100 GB SSD | \~$0.20/小时          |
| **高端**      | 512x512       | 24 GB | 64 GB | 200 GB SSD | \~$0.35/小时          |

> **注意：** GPT4All 的 GPU 支持在底层通过 llama.cpp 使用 CUDA。与 vLLM 不同，它确实 **工作方式：/api/generate** 需要特定的 CUDA 计算能力——通常 RTX 10xx 及更新型号可用。

### 模型显存需求（GGUF Q4\_K\_M）

| A100                  | 磁盘大小     | 显存      | 最小 GPU      |
| --------------------- | -------- | ------- | ----------- |
| Phi-3 Mini 3.8B       | \~2.4 GB | \~3 GB  | 按小时费率       |
| Mistral 7B Instruct   | \~4.1 GB | \~5 GB  | 按小时费率       |
| Llama 3.1 8B Instruct | \~4.7 GB | \~6 GB  | 按小时费率       |
| Llama 3 70B Instruct  | \~40 GB  | \~45 GB | 4 小时会话      |
| Mixtral 8x7B          | \~26 GB  | \~30 GB | 2× RTX 3090 |

***

## 快速开始

### 第 1 步 — 在 Clore.ai 上租用 GPU 服务器

1. 登录到 [clore.ai](https://clore.ai)
2. 筛选： **启用 Docker**, **GPU**：RTX 3090（用于 7B–13B 模型）
3. 使用镜像部署： `nvidia/cuda:12.1.0-runtime-ubuntu22.04`
4. 打开端口： **4891** （GPT4All API）， **22** （SSH）
5. 至少分配 **50 GB** 的磁盘空间

### 步骤 2 — 通过 SSH 连接

```bash
ssh -p <CLORE_SSH_PORT> root@<CLORE_SERVER_IP>

# 验证 GPU
nvidia-smi
# 应列出带有驱动版本的 GPU
```

### 第 3 步 — 构建 GPT4All Docker 镜像

由于没有官方的 GPT4All Docker 镜像，我们将构建一个：

```bash
mkdir -p /workspace/gpt4all-server && cd /workspace/gpt4all-server

cat > Dockerfile << 'EOF'
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04

ENV DEBIAN_FRONTEND=noninteractive
ENV PYTHONUNBUFFERED=1

# 安装 Python 和系统依赖
RUN apt-get update && apt-get install -y \
    python3.11 \
    python3.11-dev \
    python3-pip \
    curl \
    wget \
    git \
    libgomp1 \
    && rm -rf /var/lib/apt/lists/*

# 将 python3.11 设为默认
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 \
    && update-alternatives --install /usr/bin/python python python3.11 1

# 安装带有 CUDA 支持的 GPT4All
RUN pip install --upgrade pip && \
    pip install gpt4all>=2.8.0 fastapi uvicorn aiofiles pydantic

# 创建目录
RUN mkdir -p /models /workspace /app

WORKDIR /app

# 复制服务器脚本（将在运行时挂载或打包进去）
COPY server.py .

EXPOSE 4891

CMD ["python", "server.py"]
EOF
```

### 第 4 步 — 创建 API 服务器脚本

```bash
cat > /workspace/gpt4all-server/server.py << 'PYEOF'
#!/usr/bin/env python3
"""
GPT4All 兼容 OpenAI 的 API 服务器
运行在端口 4891（GPT4All 默认）
"""

批处理处理
import time
import json
import asyncio
from typing import Optional, List, Dict, Any
from pathlib import Path

from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import uvicorn
from gpt4all import GPT4All

# 配置
MODEL_NAME = os.environ.get("MODEL_NAME", "Mistral 7B Instruct v0.1 Q4_0")
MODEL_PATH = os.environ.get("MODEL_PATH", "/models")
API_HOST = os.environ.get("API_HOST", "0.0.0.0")
API_PORT = int(os.environ.get("API_PORT", "4891"))
DEVICE = os.environ.get("DEVICE", "gpu")  # 'gpu', 'cpu', 'metal'
N_CTX = int(os.environ.get("N_CTX", "4096"))

app = FastAPI(title="GPT4All API Server", version="1.0.0")

# 全局模型实例
model = None

def load_model():
    global model
    print(f"正在加载模型：{MODEL_NAME}")
    print(f"模型路径：{MODEL_PATH}")
    print(f"设备：{DEVICE}")
    model = GPT4All(
        model_name=MODEL_NAME,
        model_path=MODEL_PATH,
        device=DEVICE,
        n_ctx=N_CTX,
        allow_download=True,  # 如果不存在则从 GPT4All hub 下载
        verbose=True
    )
    print("模型加载成功！")

# --- Pydantic 模型 ---

class Message(BaseModel):
    role: str
    content: str

class ChatCompletionRequest(BaseModel):
    model: str
    messages: List[Message]
    temperature: float = 0.7
    max_tokens: int = 512
    top_p: float = 0.95
    top_k: int = 40
    stream: bool = False

class CompletionRequest(BaseModel):
    model: str
    prompt: str
    temperature: float = 0.7
    max_tokens: int = 512
    stream: bool = False

# --- API 路由 ---

@app.get("/health")
async def health():
    return {"status": "ok", "model": MODEL_NAME, "device": DEVICE}

@app.get("/v1/models")
async def list_models():
    return {
        "object": "list",
        "data": [{
            "id": MODEL_NAME,
            "object": "model",
            "created": int(time.time()),
            "owned_by": "gpt4all",
        }]
    }

@app.post("/v1/chat/completions")
async def chat_completions(request: ChatCompletionRequest):
    if model is None:
        raise HTTPException(status_code=503, detail="模型未加载")

    # 将消息格式化为单个提示
    prompt_parts = []
    for msg in request.messages:
        if msg.role == "system":
            prompt_parts.append(f"### System:\n{msg.content}")
        elif msg.role == "user":
            prompt_parts.append(f"### Human:\n{msg.content}")
        elif msg.role == "assistant":
            prompt_parts.append(f"### Assistant:\n{msg.content}")
    prompt_parts.append("### Assistant:")
    full_prompt = "\n\n".join(prompt_parts)

    with model.chat_session():
        response_text = model.generate(
            full_prompt,
            max_tokens=request.max_tokens,
            temp=request.temperature,
            top_p=request.top_p,
            top_k=request.top_k,
        )

    return {
        "id": f"chatcmpl-{int(time.time())}",
        "object": "chat.completion",
        "created": int(time.time()),
        "model": request.model,
        "choices": [{
            "index": 0,
            "message": {"role": "assistant", "content": response_text},
            "finish_reason": "stop"
        }],
        "usage": {
            "prompt_tokens": len(full_prompt.split()),
            "completion_tokens": len(response_text.split()),
            "total_tokens": len(full_prompt.split()) + len(response_text.split())
        }
    }

@app.post("/v1/completions")
async def completions(request: CompletionRequest):
    if model is None:
        raise HTTPException(status_code=503, detail="模型未加载")

    response_text = model.generate(
        request.prompt,
        max_tokens=request.max_tokens,
        temp=request.temperature,
    )

    return {
        "id": f"cmpl-{int(time.time())}",
        "object": "text_completion",
        "created": int(time.time()),
        "model": request.model,
        "choices": [{
            "text": response_text,
            "index": 0,
            "finish_reason": "stop"
        }]
    }

if __name__ == "__main__":
    load_model()
    uvicorn.run(app, host=API_HOST, port=API_PORT, log_level="info")
PYEOF
```

### 第 5 步 — 构建并运行

```bash
cd /workspace/gpt4all-server

# 构建 Docker 镜像
docker build -t gpt4all-server:latest .

# 先下载一个模型（可选 — 服务器也可以自动下载）
mkdir -p /workspace/models
wget -O /workspace/models/mistral-7b-instruct-v0.1.Q4_0.gguf \
  https://gpt4all.io/models/gguf/mistral-7b-instruct-v0.1.Q4_0.gguf

# 使用 GPU 支持运行
docker run -d \
  --name gpt4all-server \
  --gpus all \
  --restart unless-stopped \
  -p 4891:4891 \
  -v /workspace/models:/models \
  -v /workspace/gpt4all-server/server.py:/app/server.py \
  -e MODEL_NAME="mistral-7b-instruct-v0.1.Q4_0.gguf" \
  -e MODEL_PATH="/models" \
  -e DEVICE="gpu" \
  -e N_CTX="4096" \
  gpt4all-server:latest

# 跟随日志
docker logs -f gpt4all-server
```

### 第 6 步 — 测试 API

```bash
# 健康检查
curl http://localhost:4891/health

# 列出模型
curl http://localhost:4891/v1/models

# 聊天补全
curl http://localhost:4891/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mistral-7b-instruct-v0.1.Q4_0.gguf",
    "messages": [
      {"role": "user", "content": "法国的首都是什么？"}
    ],
    "temperature": 0.7,
    "max_tokens": 256
  }'
```

***

## 可选：LocalAI Docker 镜像

对于更健壮、适合生产的 Docker 部署且能运行 **相同的 GGUF 模型** 作为 GPT4All，推荐使用 LocalAI。它有官方 Docker 镜像、CUDA 支持且有持续维护：

```bash
# 拉取带有 CUDA 支持的 LocalAI
docker pull localai/localai:latest-aio-gpu-nvidia-cuda-12

# 创建模型目录并下载 GGUF 模型
mkdir -p /workspace/localai-models
wget -O /workspace/localai-models/mistral-7b.gguf \
  https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.1-GGUF/resolve/main/mistral-7b-instruct-v0.1.Q4_K_M.gguf

# 创建模型配置
cat > /workspace/localai-models/mistral-7b.yaml << 'EOF'
name: mistral-7b
parameters:
  model: mistral-7b.gguf
  temperature: 0.7
  top_p: 0.95
  top_k: 40
  max_tokens: 2048
context_size: 4096
f16: true
gpu_layers: 35
threads: 8
EOF

# 运行 LocalAI
docker run -d \
  --name localai \
  --gpus all \
  --restart unless-stopped \
  -p 8080:8080 \
  -v /workspace/localai-models:/build/models \
  -e DEBUG=true \
  localai/localai:latest-aio-gpu-nvidia-cuda-12

# 测试 LocalAI（相同的兼容 OpenAI 的 API）
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mistral-7b",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

***

## 配置

### GPT4All 服务器的环境变量

| 变量           | 默认值                      | 4s                             |
| ------------ | ------------------------ | ------------------------------ |
| `MODEL_NAME` | `mistral-7b-instruct...` | 模型文件名或 GPT4All hub 名称          |
| `MODEL_PATH` | `/models`                | 包含模型文件的目录                      |
| `DEVICE`     | `gpu`                    | `gpu`, `cpu`，或 `metal` （macOS） |
| `N_CTX`      | `4096`                   | 上下文窗口大小（标记数）                   |
| `API_HOST`   | `0.0.0.0`                | 绑定地址                           |
| `API_PORT`   | `4891`                   | API 服务器端口                      |

### Docker Compose 设置

```yaml
# /workspace/gpt4all-server/docker-compose.yml
version: '3.8'

services:
  gpt4all-server:
    build: .
    container_name: gpt4all-server
    restart: unless-stopped
    ports:
      - "4891:4891"
    volumes:
      - /workspace/models:/models
      - ./server.py:/app/server.py
    environment:
      - MODEL_NAME=mistral-7b-instruct-v0.1.Q4_0.gguf
      - MODEL_PATH=/models
      - DEVICE=gpu
      - N_CTX=4096
      - API_PORT=4891
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4891/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 120s
```

```bash
docker compose up -d
docker compose logs -f
```

***

## GPU 加速

### 验证 GPU 使用情况

GPT4All Python 库 在底层 使用 `llama.cpp` 与 CUDA 支持：

```bash
# 在模型加载后检查 GPU VRAM 使用情况
watch -n 2 nvidia-smi

# 在容器内检查 CUDA 是否可用
docker exec gpt4all-server python3 -c "
from gpt4all import GPT4All
devices = GPT4All.list_gpus()
print('可用 GPU：', devices)
"
```

### 选择 GPU 层数

该 `gpu_layers` （或 `n_gpu_layers`）参数控制模型有多少运行在 GPU 与 CPU 上：

```python
# 在 server.py 中 — 强制所有层到 GPU
model = GPT4All(
    model_name=MODEL_NAME,
    model_path=MODEL_PATH,
    device="gpu",
    n_ctx=N_CTX,
    # 通过以下方式传递额外的 llama.cpp 参数：
    # n_gpu_layers=99  # 所有层在 GPU 上
)
```

```bash
# 重新构建并重启以使用最大 GPU 层数
docker stop gpt4all-server && docker rm gpt4all-server
docker run -d \
  --name gpt4all-server \
  --gpus all \
  -p 4891:4891 \
  -v /workspace/models:/models \
  -e DEVICE=gpu \
  -e MODEL_NAME=mistral-7b-instruct-v0.1.Q4_0.gguf \
  gpt4all-server:latest
```

### CPU 回退模式

如果没有可用 GPU（例如，仅用于测试的 CPU-only Clore.ai 服务器）：

```bash
docker run -d \
  --name gpt4all-server-cpu \
  -p 4891:4891 \
  -v /workspace/models:/models \
  -e DEVICE=cpu \
  -e MODEL_NAME=Phi-3-mini-4k-instruct.Q4_0.gguf \
  gpt4all-server:latest
```

> ⚠️ CPU 推理 **比 GPU 慢 10–50 倍** 对于仅 CPU 的服务器，请使用小模型（Phi-3 Mini、TinyLlama），并预计 2–5 令牌/秒。

***

## 提示与最佳实践

### 📥 预下载模型

与其依赖启动时自动下载，不如预先下载模型以加快重启速度：

```bash
# 下载流行的 GPT4All 模型
mkdir -p /workspace/models

# Mistral 7B（最受欢迎，质量好）
wget -q -O /workspace/models/mistral-7b-instruct-v0.1.Q4_0.gguf \
  "https://gpt4all.io/models/gguf/mistral-7b-instruct-v0.1.Q4_0.gguf"

# Phi-3 Mini（最快、最小）
wget -q -O /workspace/models/Phi-3-mini-4k-instruct.Q4_0.gguf \
  "https://gpt4all.io/models/gguf/Phi-3-mini-4k-instruct.Q4_0.gguf"

# Llama 3（在 8B 规模中质量最佳）
wget -q -O /workspace/models/Meta-Llama-3-8B-Instruct.Q4_0.gguf \
  "https://gpt4all.io/models/gguf/Meta-Llama-3-8B-Instruct.Q4_0.gguf"

ls -lh /workspace/models/
```

### 🔌 与 Python 应用一起使用

```python
# 直接 Python 使用（不通过 Docker API）
from gpt4all import GPT4All

model = GPT4All(
    model_name="mistral-7b-instruct-v0.1.Q4_0.gguf",
    model_path="/workspace/models",
    device="gpu"
)

# 简单生成示例
with model.chat_session():
    response = model.generate("用通俗的语言解释 GPU 计算", max_tokens=200)
    print(response)

# 使用 OpenAI 客户端与 API 服务器
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:4891/v1",
    api_key="not-needed"
)

completion = client.chat.completions.create(
    model="mistral-7b-instruct-v0.1.Q4_0.gguf",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(completion.choices[0].message.content)
```

### 💰 在 Clore.ai 上的成本优化

```bash
# RTX 3090 每小时 $0.20 — 用于 7B 模型（性价比最高）
# 预计吞吐量：Mistral 7B Q4 约 ~40 令牌/秒
# 生成 100 万令牌的成本：~$0.005（相比 OpenAI 极其便宜）

# RTX 4090 每小时 $0.35 — 用于 13B 模型或对速度有要求时
# 预计吞吐量：Mistral 7B Q4 约 ~60 令牌/秒

# 对于批量处理：预加载模型，处理所有提示，然后关闭
docker run --rm \
  --gpus all \
  -v /workspace/models:/models \
  -v /workspace/prompts:/prompts \
  gpt4all-server:latest \
  python3 -c "
from gpt4all import GPT4All
import json

model = GPT4All('mistral-7b-instruct-v0.1.Q4_0.gguf', '/models', device='gpu')
prompts = open('/prompts/batch.txt').readlines()
if filename.endswith(('.jpg', '.png', '.jpeg')):
for p in prompts:
    with model.chat_session():
        results.append(model.generate(p.strip(), max_tokens=256))
json.dump(results, open('/prompts/results.json', 'w'))
print(f'处理了 {len(results)} 个提示')
"
```

***

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

### 模型无法加载 — 文件未找到

```bash
# 检查模型文件是否存在且名称正确
ls -lh /workspace/models/
docker exec gpt4all-server ls /models/

# GPT4All 对模型名称区分大小写
# 将 ls 输出中的精确文件名作为 MODEL_NAME 使用
docker stop gpt4all-server && docker rm gpt4all-server
docker run -d --gpus all -p 4891:4891 \
  -v /workspace/models:/models \
  -e MODEL_NAME=mistral-7b-instruct-v0.1.Q4_0.gguf \
  gpt4all-server:latest
```

### CUDA 错误：此架构没有内核镜像

```bash
# 您的 GPU 可能与该 CUDA 版本不兼容
# 检查 GPU 计算能力
nvidia-smi --query-gpu=compute_cap --format=csv,noheader

# 如果 < 6.0，则使用 CPU 模式
docker run -d --gpus all -p 4891:4891 \
  -v /workspace/models:/models \
  -e DEVICE=cpu \
  -e MODEL_NAME=Phi-3-mini-4k-instruct.Q4_0.gguf \
  gpt4all-server:latest
```

### API 返回 503 — 模型未加载

```bash
# 检查启动日志
docker logs gpt4all-server | head -50

# 模型加载可能需要 30–120 秒
# 等待并重试：
sleep 60 && curl http://localhost:4891/health

# 检查模型文件是否损坏
python3 -c "
from gpt4all import GPT4All
m = GPT4All('mistral-7b-instruct-v0.1.Q4_0.gguf', '/workspace/models')
print('模型正常：', m)
"
```

### 端口 4891 无法从外部访问

```bash
# 验证端口绑定
docker ps | grep 4891
# 应显示：0.0.0.0:4891->4891/tcp

# 检查 Clore.ai 是否有防火墙规则
# 在 Clore.ai 服务器设置中，确保端口 4891 已列为开放

# 在内部测试：
curl http://127.0.0.1:4891/health

# 注意：Clore.ai 会随机映射端口 — 使用服务器仪表板中显示的端口
```

***

## 延伸阅读

* [GPT4All GitHub](https://github.com/nomic-ai/gpt4all) — 主仓库
* [GPT4All Python 文档](https://docs.gpt4all.io/) — Python API 参考
* [GPT4All 模型浏览器](https://gpt4all.io/models/gguf/) — 浏览可用模型
* [LocalAI 文档](https://localai.io/) — 适合 Docker 的替代方案
* [Clore.ai 上的 Ollama](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/ollama) — 更简单的 Docker LLM 部署
* [Clore.ai 上的 vLLM](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/vllm) — 生产推理服务器
* [GPU 比较指南](https://docs.clore.ai/guides/guides_v2-zh/kuai-su-ru-men/gpu-comparison) — 选择合适的 Clore.ai GPU
* [TheBloke 在 HuggingFace](https://huggingface.co/TheBloke) — 数千个 GGUF 量化模型
* [GGUF 格式说明](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) — 模型格式文档

> 💡 **建议：** 如果您想要最简单的本地 LLM Docker 部署，请考虑 [Ollama](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/ollama) 作为替代 — 它有官方 Docker 镜像、内置 GPU 支持，并专为服务器端部署设计。GPT4All 的优势在于其精美的桌面 UI 和 LocalDocs（RAG）功能，这些在服务器模式下不可用。
