# LibreChat 多提供商

## 概览

[LibreChat](https://github.com/danny-avila/LibreChat) 是一个增强的开源类 ChatGPT 界面，在 GitHub 上拥有 22K+ 星标。它忠实地重新构想了 ChatGPT 体验，同时添加了原版所缺乏的功能——在同一会话内切换多个提供者、会话分支/叉分、丰富的插件系统、具有视觉能力的文件上传，以及完整的代码解释器沙箱。

**为什么在 Clore.ai 上运行 LibreChat？**

* **在同一界面中的真正多提供者支持** — 会话中可在 GPT-4、Claude 3.5、Gemini Pro、Mistral 和本地 Ollama 模型之间切换。
* **应用无需 GPU** — LibreChat 是一个 Node.js 应用；只有在连接本地 LLM 后端进行推理时才需要计算资源。
* **经济实惠的自托管** — Clore.ai 的定价从每分钟几分之一美分起，是运行个人 AI 中心的理想选择。
* **持久对话** — 与仅在浏览器本地保存的解决方案不同，MongoDB 在服务器端存储你的完整聊天历史。
* **团队友好** — 支持多用户并提供各自的 API 密钥管理。

### 主要特性

| 特性    | 4s                                                      |
| ----- | ------------------------------------------------------- |
| 多提供者  | OpenAI、Anthropic、Google、Azure、Mistral、Ollama、OpenRouter |
| 会话分支  | 分叉并探索替代回复                                               |
| 插件    | Bing 搜索、Zapier、WolframAlpha、自定义工具                       |
| 文件上传  | 带有视觉分析的图像、PDF、文档                                        |
| 代码解释器 | 在隔离的沙箱中执行 Python                                        |
| 伪影    | 呈现 HTML、React 和 Markdown 输出                             |
| 预设    | 保存并共享自定义模型配置                                            |

***

## 要求

### 服务器规格

| 组件      | 最低     | 推荐                    | 注意事项              |
| ------- | ------ | --------------------- | ----------------- |
| **GPU** | 不需要    | RTX 3090（如果添加 Ollama） | 仅用于本地 LLM 推理      |
| **显存**  | —      | 24 GB                 | 通过 Ollama 用于本地模型  |
| **CPU** | 2 vCPU | 4 个 vCPU              | Node.js + MongoDB |
| **内存**  | 4 GB   | 8 GB                  | MongoDB 从更多内存中受益  |
| **存储**  | 20 GB  | 50+ GB                | 文件上传、本地时的模型缓存     |

### Clore.ai 价格参考

| 服务器类型                      | 大致费用            | 模型变体                        |
| -------------------------- | --------------- | --------------------------- |
| 以 CPU 为主（4 个 vCPU，8 GB 内存） | 约 $0.05–0.10/小时 | LibreChat + 外部 API 提供者      |
| RTX 3090（24 GB 显存）         | \~$0.20/小时      | LibreChat + Ollama 本地推理     |
| RTX 4090（24 GB 显存）         | \~$0.35/小时      | LibreChat + 更快的 Ollama/vLLM |
| A100 80 GB                 | \~$1.10/小时      | LibreChat + 大型 70B+ 模型      |

> 💡 **成本提示：** 如果你仅使用 LibreChat 将 API 调用路由到 OpenAI/Anthropic/Google，你只需为 Clore.ai 服务器计算付费（便宜），而不是为推理硬件付费。为可靠的 LibreChat 主机预算约 $0.05–0.15/小时。

### 先决条件

* 带 SSH 访问的 Clore.ai 服务器
* Docker + Docker Compose（Clore.ai 上预装）
* Git（Clore.ai 上预装）
* 至少一个 LLM API 密钥 **或** 一个本地 Ollama/vLLM 后端

***

## 快速开始

### 方法 1：Docker Compose（官方 — 推荐）

LibreChat 的官方部署使用 Docker Compose，配合 MongoDB 和 MeiliSearch 以实现完整功能。

**步骤 1：连接到你的 Clore.ai 服务器**

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

**第 2 步：克隆代码库**

```bash
git clone https://github.com/danny-avila/LibreChat.git
cd LibreChat
```

**第 3 步：配置环境**

```bash
cp .env.example .env
nano .env
```

至少设置：

```bash
# 在 .env 中 — 关键设置
MONGO_URI=mongodb://mongodb:27017/LibreChat
JWT_SECRET=your-random-64-char-secret-here
JWT_REFRESH_SECRET=another-random-64-char-secret-here
CREDS_KEY=your-random-32-char-key-here
CREDS_IV=your-random-16-char-iv-here

# API 密钥（添加你使用的那些）
OPENAI_API_KEY=sk-your-openai-key
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key
GOOGLE_KEY=your-google-gemini-key
```

快速生成密钥：

```bash
# 生成随机密钥
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

**第 4 步：启动堆栈**

```bash
docker compose up -d
```

这会启动：

* `LibreChat` — 主应用在端口 3080 上运行
* `MongoDB` — 会话和用户存储
* `MeiliSearch` — 快速的会话搜索

**第 5 步：验证并访问**

```bash
docker compose ps
docker compose logs librechat --tail 30
```

在浏览器中打开：

```
http://<your-clore-server-ip>:3080
```

在登录页面注册一个新账号。

***

### 方法 2：预构建 Docker 镜像（最快）

如果你想跳过从源码构建：

```bash
mkdir -p ~/librechat && cd ~/librechat

# 仅下载 docker-compose 文件
curl -o docker-compose.yml https://raw.githubusercontent.com/danny-avila/LibreChat/main/docker-compose.yml
curl -o .env https://raw.githubusercontent.com/danny-avila/LibreChat/main/.env.example

# 编辑配置
nano .env

# 启动
docker compose up -d
```

***

### 方法 3：单容器快速测试

用于无需 MongoDB 的快速概念验证（功能受限）：

```bash
docker run -d \
  --name librechat \
  --restart unless-stopped \
  -p 3080:3080 \
  -e OPENAI_API_KEY=sk-your-key \
  -e JWT_SECRET=your-jwt-secret-here \
  -e MONGO_URI=mongodb://host-gateway:27017/LibreChat \
  --add-host=host-gateway:host-gateway \
  ghcr.io/danny-avila/librechat-dev:latest
```

> ⚠️ 此方法需要一个单独的 MongoDB 实例。要完整设置请使用方法 1。

***

## 配置

### 添加 AI 提供者

编辑 `librechat.yaml` （在项目根目录创建）用于高级提供者配置：

```bash
cat > librechat.yaml << 'EOF'
version: 1.1.5
cache: true

endpoints:
  openAI:
    models:
      default: ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-3.5-turbo"]
      fetch: true

  anthropic:
    models:
      default: ["claude-opus-4-5", "claude-sonnet-4-5", "claude-3-haiku-20240307"]
      fetch: false

  google:
    models:
      default: ["gemini-1.5-pro", "gemini-1.5-flash", "gemini-pro"]
      fetch: false

  ollama:
    # 指向在同一 Clore.ai 服务器上运行的 Ollama
    baseURL: http://host-gateway:11434/v1
    apiKey: ollama
    models:
      default: ["llama3.2", "mistral", "codellama"]
      fetch: true

  custom:
    - name: "OpenRouter"
      apiKey: "${OPENROUTER_API_KEY}"
      baseURL: "https://openrouter.ai/api/v1"
      models:
        default: ["meta-llama/llama-3.1-8b-instruct:free"]
        fetch: true
      titleConvo: true
      titleModel: "meta-llama/llama-3.1-8b-instruct:free"
EOF
```

将此文件挂载到你的 `docker-compose.yml`:

```yaml
services:
  LibreChat：
    volumes:
      - ./librechat.yaml:/app/librechat.yaml
```

### 环境变量参考

| 变量                   | 4s                 | 示例                                  |
| -------------------- | ------------------ | ----------------------------------- |
| `MONGO_URI`          | MongoDB 连接字符串      | `mongodb://mongodb:27017/LibreChat` |
| `JWT_SECRET`         | JWT 签名密钥（64+ 字符）   | 随机十六进制字符串                           |
| `OPENAI_API_KEY`     | OpenAI 密钥          | `sk-...`                            |
| `ANTHROPIC_API_KEY`  | Anthropic 密钥       | `sk-ant-...`                        |
| `GOOGLE_KEY`         | Google Gemini 密钥   | `AI...`                             |
| `ALLOW_REGISTRATION` | 启用公开注册             | `true` / `false`                    |
| `ALLOW_EMAIL_LOGIN`  | 启用电子邮件/密码登录        | `true`                              |
| `DEBUG_LOGGING`      | 详细日志               | `true`                              |
| `SEARCH`             | 启用 MeiliSearch     | `true`                              |
| `MEILI_MASTER_KEY`   | MeiliSearch API 密钥 | 随机字符串                               |

### 限制注册

对于私人使用，在创建账户后禁用公开注册：

```bash
# 在 .env 中
ALLOW_REGISTRATION=false
```

然后重启： `docker compose restart LibreChat`

### 启用代码解释器

```bash
# 在 .env 中
CODE_INTERPRETER_ENABLED=true
```

代码解释器在隔离的 Docker 容器中运行 Python。确保可以访问 Docker 套接字。

### 文件上传配置

```bash
# 在 .env 中
# 最大文件大小（MB）
FILE_UPLOAD_SIZE_LIMIT=100

# 为视觉模型启用图像上传
VISION_ENABLED=true
```

***

## GPU 加速

LibreChat 并不 **工作方式：/api/generate** 直接使用 GPU — 它是一个路由层。GPU 加速适用于你连接到的任何本地推理后端。

### 连接 Ollama（同一服务器）

如果在同一 Clore.ai 服务器上运行 Ollama（参见 [Ollama 指南](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/ollama)):

```bash
# 使用 GPU 支持启动 Ollama
docker run -d \
  --name ollama \
  --gpus all \
  --restart unless-stopped \
  -p 11434:11434 \
  -v ollama_models:/root/.ollama \
  ollama/ollama

# 拉取模型
docker exec ollama ollama pull llama3.2
docker exec ollama ollama pull codellama:13b

# 在 librechat.yaml 中设置：
# baseURL: http://172.17.0.1:11434/v1
```

### 连接 vLLM（高吞吐）

用于高并发部署（参见 [vLLM 指南](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/vllm)):

```bash
# 在 A100 Clore.ai 实例上启动 vLLM
docker run -d \
  --name vllm \
  --gpus all \
  --restart unless-stopped \
  -p 8000:8000 \
  -v hf_cache:/root/.cache/huggingface \
  -e HF_TOKEN=your-hf-token \
  vllm/vllm-openai:latest \
  --model meta-llama/Llama-3.1-70B-Instruct \
  --tensor-parallel-size 2 \
  --max-model-len 8192
```

在 `librechat.yaml`:

```yaml
  custom:
    - name: "Local vLLM"
      apiKey: "not-needed"
      baseURL: "http://172.17.0.1:8000/v1"
      models:
        default: ["meta-llama/Llama-3.1-70B-Instruct"]
        fetch: true
```

### 本地模型的 GPU 大小建议

| 模型大小      | 最小显存  | 推荐的 Clore GPU | 大致费用       |
| --------- | ----- | ------------- | ---------- |
| 7–8B（Q4）  | 6 GB  | 速度            | \~$0.20/小时 |
| 13B（Q4）   | 10 GB | 速度            | \~$0.20/小时 |
| 34B（Q4）   | 24 GB | 512x512       | \~$0.35/小时 |
| 70B（Q4）   | 48 GB | 2× RTX 3090   | \~$0.40/小时 |
| 70B（FP16） | 80 GB | 4 小时会话        | \~$1.10/小时 |

***

## 提示与最佳实践

### 在 Clore.ai 上的成本管理

```bash
# 在停止服务器前快照你的配置
docker compose exec mongodb mongodump --out /tmp/backup
docker cp librechat-mongodb-1:/tmp/backup ./mongo-backup-$(date +%Y%m%d)

# 在不使用时停止所有容器
docker compose stop

# 或通过仪表板暂停 Clore.ai 实例将成本缩减到零
```

### 备份策略

```bash
# 自动每日备份脚本
cat > /root/backup-librechat.sh << 'EOF'
#!/bin/bash
cd ~/LibreChat
docker compose exec -T mongodb mongodump --archive | \
  gzip > ~/backups/librechat-$(date +%Y%m%d-%H%M).mongo.gz
# 仅保留最近 7 天
find ~/backups -name "*.mongo.gz" -mtime +7 -delete
EOF

chmod +x /root/backup-librechat.sh
# 添加到 crontab： 0 2 * * * /root/backup-librechat.sh
```

### 从备份恢复

```bash
# 恢复 MongoDB 转储
gunzip < ~/backups/librechat-20240101-0200.mongo.gz | \
  docker compose exec -T mongodb mongorestore --archive
```

### 保护 LibreChat

* 始终为以下项设置强且唯一的值： `JWT_SECRET` 和 `CREDS_KEY`
* 在首次创建用户后禁用注册： `ALLOW_REGISTRATION=false`
* 在生产环境中使用带 HTTPS 的反向代理（nginx/Caddy）
* 定期更新 Docker 镜像： `docker compose pull && docker compose up -d`

### Nginx 反向代理（可选）

```bash
cat > /etc/nginx/sites-available/librechat << 'EOF'
server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://localhost:3080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        client_max_body_size 100M;
    }
}
EOF
ln -s /etc/nginx/sites-available/librechat /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx
```

***

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

### 端口 3080 无法访问

```bash
# 检查容器是否在运行
docker compose ps

# 检查端口绑定
ss -tlnp | grep 3080

# 查看应用日志
docker compose logs librechat --tail 50 -f

# 检查 Clore.ai 防火墙 — 确保端口 3080 在你的端口映射中
```

### MongoDB 连接被拒绝

```bash
# 检查 MongoDB 状态
docker compose ps mongodb
docker compose logs mongodb --tail 20

# 验证 .env 中的 MONGO_URI 是否与服务名匹配
# 应为： mongodb://mongodb:27017/LibreChat（而非 localhost）

# 手动测试连接
docker compose exec LibreChat node -e "
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI)
  .then(() => console.log('Connected!'))
  .catch(e => console.error(e));
"
```

### JWT / 身份验证错误

```bash
# 在 .env 中重新生成密钥
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

# 更新 JWT_SECRET 和 JWT_REFRESH_SECRET
# 然后重启： docker compose restart LibreChat
```

### Ollama 模型未出现

```bash
# 在 LibreChat 容器中测试 Ollama API
docker compose exec LibreChat \
  curl -s http://172.17.0.1:11434/v1/models | python3 -m json.tool

# 确保 Ollama 监听的是 0.0.0.0，而不仅仅是 localhost
docker exec ollama ollama serve  # 检查启动日志中的绑定地址
```

### 磁盘空间不足

```bash
# 检查磁盘使用情况
df -h
docker system df

# 清理 Docker 资源
docker system prune -f
docker volume prune -f  # 警告：会删除未使用的卷

# 检查 LibreChat 上传目录
du -sh ~/LibreChat/client/public/uploads
```

### 更新到最新版本

```bash
cd ~/LibreChat
git pull origin main
docker compose pull
docker compose up -d --build
```

***

## 延伸阅读

* [LibreChat 文档](https://docs.librechat.ai) — 完整的配置参考
* [LibreChat GitHub](https://github.com/danny-avila/LibreChat) — 源码、问题、更新日志
* [LibreChat Docker Hub](https://ghcr.io/danny-avila/librechat-dev) — 镜像标签
* [在 Clore.ai 上运行 Ollama](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/ollama) — 本地 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) — 选择合适的 GPU 等级
* [LibreChat 配置文件参考](https://docs.librechat.ai/install/configuration/librechat_yaml.html) — `librechat.yaml` schema
