> 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/gpt4all.md).

# GPT4All 本地 LLM

在 Clore.ai 上部署 GPT4All——使用兼容 OpenAI 的 API 服务器通过 Docker 运行隐私优先的本地 LLM，支持 GGUF 模型，并可选择启用 CUDA 加速以获得最高性能。

## 概览

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

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

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

**主要特性：**

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

***

## 需求

### 硬件要求

| 层级          | GPU           | 显存    | 内存    | 存储         | Clore.ai 价格         |
| ----------- | ------------- | ----- | ----- | ---------- | ------------------- |
| **仅 CPU**   | 无             | —     | 16 GB | 50 GB SSD  | 约 $0.02/小时（CPU 服务器） |
| **入门级 GPU** | RTX 3060 12GB | 12 GB | 16 GB | 50 GB SSD  | $0.03–0.07/小时       |
| **推荐**      | RTX 3090      | 24 GB | 32 GB | 100 GB SSD | $0.07–0.21/小时       |
| **高端**      | RTX 4090      | 24 GB | 64 GB | 200 GB SSD | $0.14–0.42/小时       |

> **注意：** GPT4All 的 GPU 支持底层通过 llama.cpp 使用 CUDA。与 vLLM 不同，它并不 **不** 要求特定的 CUDA 计算能力——RTX 10xx 及更新的显卡通常都可以。

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

| 模型                    | 磁盘占用     | 显存      | 最低 GPU      |
| --------------------- | -------- | ------- | ----------- |
| Phi-3 Mini 3.8B       | \~2.4 GB | \~3 GB  | RTX 3060    |
| Mistral 7B Instruct   | \~4.1 GB | \~5 GB  | RTX 3060    |
| Llama 3.1 8B Instruct | \~4.7 GB | \~6 GB  | RTX 3060    |
| Llama 3 70B Instruct  | 约 40 GB  | \~45 GB | A100 80GB   |
| 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.8.1-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.8.1-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 os
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"### 系统：\n{msg.content}")
        elif msg.role == "user":
            prompt_parts.append(f"### 用户：\n{msg.content}")
        elif msg.role == "assistant":
            prompt_parts.append(f"### 助手：\n{msg.content}")
    prompt_parts.append("### 助手：")
    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": "你好！"}]
  }'
```

***

## 配置

### GPT4All 服务器环境变量

| 变量           | 默认值                      | 描述                             |
| ------------ | ------------------------ | ------------------------------ |
| `MODEL_NAME` | `mistral-7b-instruct...` | 模型文件名或 GPT4All hub 名称          |
| `MODEL_PATH` | `/models`                | 包含模型文件的目录                      |
| `DEVICE`     | `gpu`                    | `gpu`, `cpu`，或 `metal` （macOS） |
| `N_CTX`      | `4096`                   | 上下文窗口大小（tokens）                |
| `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 显存占用
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 的 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 推理是 **慢 10–50 倍** 比 GPU。对于仅 CPU 的服务器，请使用小模型（Phi-3 Mini、TinyLlama），并预期每秒 2–5 个 token。

***

## 提示与最佳实践

### 📥 预先下载模型

不要依赖启动时自动下载，预先下载模型以便更快重启：

```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("Explain GPU computing in simple terms", max_tokens=200)
    打印(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.07–0.21 —— 用于 7B 模型（最划算）
# 预期吞吐量：Mistral 7B Q4 约 40 token/秒
# 每生成 100 万 token 的成本：约 $0.005（与 OpenAI 相比极其便宜）

# RTX 4090 每小时 $0.14–0.42 —— 用于 13B 模型或在速度很重要时
# 预期吞吐量：Mistral 7B Q4 约 60 token/秒

# 对于批处理：预加载模型，处理所有提示，然后关闭
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()
results = []
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](/guides/guides_v2-zh/yu-yan-mo-xing/ollama.md) — 更容易的 Docker LLM 部署
* [Clore.ai 上的 vLLM](/guides/guides_v2-zh/yu-yan-mo-xing/vllm.md) — 生产级推理服务器
* [GPU 比较指南](/guides/guides_v2-zh/ru-men-zhi-nan/gpu-comparison.md) — 选择合适的 Clore.ai GPU
* [HuggingFace 上的 TheBloke](https://huggingface.co/TheBloke) — 数千种 GGUF 量化模型
* [GGUF 格式说明](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) — 模型格式文档

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


---

# 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/gpt4all.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.
