# LocalAI

使用 LocalAI 运行自托管的兼容 OpenAI 的 API。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行： [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 服务器要求

| 参数   | 最低          | 推荐       |
| ---- | ----------- | -------- |
| 内存   | 8GB         | 16GB+    |
| 显存   | 6GB         | 8GB+     |
| 网络   | 200Mbps     | 500Mbps+ |
| 启动时间 | **5-10 分钟** | -        |

{% hint style="warning" %}
**重要：** LocalAI 在第一次启动时需要 5-10 分钟才能完全初始化。在此期间出现 HTTP 502 是正常的——服务正在下载并加载模型。
{% endhint %}

{% hint style="info" %}
LocalAI 非常轻量。要运行 LLM（7B 及以上模型），请选择具有 16GB+ 内存和 8GB+ 显存的服务器。
{% endhint %}

## 什么是 LocalAI？

LocalAI 提供：

* 可直接替换的 OpenAI API
* 支持多种模型格式
* 文本、图像、音频和嵌入生成
* 不需要 GPU（但使用 GPU 更快）

## 支持的模型

| 类型  | 格式         | 示例                |
| --- | ---------- | ----------------- |
| LLM | GGUF、GGML  | Llama、Mistral、Phi |
| 嵌入  | GGUF       | all-MiniLM、BGE    |
| 图像  | Diffusers  | SD 1.5、SDXL       |
| 音频  | Whisper    | 语音转文本             |
| TTS | Piper、Bark | 文本转语音             |

## 快速部署

**Docker 镜像：**

```
localai/localai:master-aio-gpu-nvidia-cuda-12
```

**端口：**

```
22/tcp
8080/http
```

**无需命令** - 服务器会自动启动。

### 验证是否正常运行

部署后，在以下位置查找您的 `http_pub` URL： **我的订单** 并测试：

```bash
# 检查服务是否就绪
curl https://your-http-pub.clorecloud.net/readyz

# 列出可用模型
curl https://your-http-pub.clorecloud.net/v1/models

# 获取版本
curl https://your-http-pub.clorecloud.net/version
```

{% hint style="warning" %}
如果收到 HTTP 502，请等待 5-10 分钟——LocalAI 初始化比其他服务要久。
{% endhint %}

## 预构建模型

LocalAI 搭载了若干开箱即可用的模型：

| 模型名称                       | 类型   | 4s          |
| -------------------------- | ---- | ----------- |
| `gpt-4`                    | 对话   | 通用用途的大型语言模型 |
| `gpt-4o`                   | 对话   | 通用用途的大型语言模型 |
| `gpt-4o-mini`              | 对话   | 更小、更快的 LLM  |
| `whisper-1`                | 语音识别 | 语音转文本       |
| `tts-1`                    | TTS  | 文本转语音       |
| `text-embedding-ada-002`   | 嵌入   | 384 维向量     |
| `jina-reranker-v1-base-en` | 重排序  | 文档重排序       |

{% hint style="info" %}
这些模型在启动后即可使用，无需额外配置。
{% endhint %}

## 访问您的服务

当部署在 CLORE.AI 上时，通过以下方式访问 LocalAI： `http_pub` URL：

```bash
# 聊天补全
curl https://your-http-pub.clorecloud.net/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "gpt-4",
        "messages": [{"role": "user", "content": "Hello!"}]
    }'
```

{% hint style="info" %}
全部 `localhost:8080` 下面的示例在通过 SSH 连接时可用。若需外部访问，请替换为你的 `https://your-http-pub.clorecloud.net/` URL。
{% endhint %}

## Docker 部署（替代）

```bash
docker run -d \
    --gpus all \
    -p 8080:8080 \
    -v /workspace/models:/models \
    -e THREADS=4 \
    -e CONTEXT_SIZE=4096 \
    localai/localai:master-aio-gpu-nvidia-cuda-12
```

## 下载模型

### 从模型库

LocalAI 内置了一个模型库：

```bash
# 列出可用模型
curl http://localhost:8080/models/available

# 从库中安装
curl http://localhost:8080/models/apply -d '{"id": "mistral-7b-instruct"}'
```

### 从 Hugging Face

```bash
mkdir -p /workspace/models

# Llama 3.1 8B GGUF
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \
    -O /workspace/models/llama-3.1-8b.gguf

# Mistral 7B GGUF
wget https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3-Q4_K_M.gguf \
    -O /workspace/models/mistral-7b.gguf
```

## 模型配置

为每个模型创建 YAML 配置：

**models/llama-3.1-8b.yaml：**

```yaml
name: llama-3.1-8b
backend: llama-cpp
parameters:
  model: llama-3.1-8b.gguf
  context_size: 4096
  threads: 8
  gpu_layers: 35
template:
  chat: |
    {{.Input}}
    ### 回应：
  completion: |
    {{.Input}}
```

## API 使用

### 聊天补全（兼容 OpenAI）

```python
import openai

# 若需外部访问，请使用你的 http_pub URL：
client = openai.OpenAI(
    base_url="https://your-http-pub.clorecloud.net/v1",
    api_key="not-needed"
)

# 或通过 SSH 隧道：
# client = openai.OpenAI(base_url="http://localhost:8080/v1", api_key="not-needed")

response = client.chat.completions.create(
    model="mistral-7b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "用简单词汇解释量子计算。"}
    ],
    temperature=0.7,
    max_tokens=500
)

print(response.choices[0].message.content)
```

### 流式传输

```python
stream = client.chat.completions.create(
    model="mistral-7b",
    messages=[{"role": "user", "content": "写一首关于 AI 的诗"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
```

### 嵌入

```python
response = client.embeddings.create(
    model="all-minilm",
    input="The quick brown fox jumps over the lazy dog"
)

embedding = response.data[0].embedding
print(f"Embedding dimension: {len(embedding)}")
```

### 图像生成

```python
response = client.images.generate(
    model="stablediffusion",
    prompt="a beautiful sunset over mountains",
    size="512x512",
    n=1
)

image_url = response.data[0].url
```

## cURL 示例

### 对话

```bash
curl https://your-http-pub.clorecloud.net/v1/chat/completions \
    -H "Content-Type: application/json" \
    -d '{
        "model": "mistral-7b",
        "messages": [{"role": "user", "content": "Hello!"}]
    }'
```

### 嵌入

```bash
curl https://your-http-pub.clorecloud.net/v1/embeddings \
    -H "Content-Type: application/json" \
    -d '{
        "model": "text-embedding-ada-002",
        "input": "Your text here"
    }'
```

响应：

```json
{
  "data": [{"embedding": [0.1, -0.2, ...], "index": 0}],
  "model": "text-embedding-ada-002",
  "usage": {"prompt_tokens": 4, "total_tokens": 4}
}
```

### 文本转语音（TTS）

```bash
curl https://your-http-pub.clorecloud.net/v1/audio/speech \
    -H "Content-Type: application/json" \
    -d '{
        "model": "tts-1",
        "input": "Hello, welcome to LocalAI!",
        "voice": "alloy"
    }' \
    --output speech.wav
```

可用的语音： `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`

### 语音转文本（STT）

```bash
curl https://your-http-pub.clorecloud.net/v1/audio/transcriptions \
    -F "file=@audio.mp3" \
    -F "model=whisper-1"
```

响应：

```json
{"text": "在此处填写转录文本..."}
```

### 重排序

按与查询相关性对文档重新排序：

```bash
curl https://your-http-pub.clorecloud.net/v1/rerank \
    -H "Content-Type: application/json" \
    -d '{
        "model": "jina-reranker-v1-base-en",
        "query": "什么是机器学习？",
        "documents": [
            "机器学习是人工智能的一个子集",
            "今天天气很好",
            "深度学习使用神经网络"
        ],
        "top_n": 2
    }'
```

响应：

```json
{
  "results": [
    {"index": 0, "relevance_score": 0.95},
    {"index": 2, "relevance_score": 0.82}
  ]
}
```

## 完整 API 参考

### 标准端点（兼容 OpenAI）

| 端点                         | 方法   | 4s     |
| -------------------------- | ---- | ------ |
| `/v1/models`               | GET  | 列出可用模型 |
| `/v1/chat/completions`     | POST | 聊天补全   |
| `/v1/completions`          | POST | 文本补全   |
| `/v1/embeddings`           | POST | 生成嵌入   |
| `/v1/audio/speech`         | POST | 文本转语音  |
| `/v1/audio/transcriptions` | POST | 语音转文本  |
| `/v1/images/generations`   | POST | 图像生成   |

### 附加端点

| 端点                  | 方法   | 4s            |
| ------------------- | ---- | ------------- |
| `/readyz`           | GET  | 就绪性检查         |
| `/healthz`          | GET  | 健康检查          |
| `/version`          | GET  | 获取 LocalAI 版本 |
| `/v1/rerank`        | POST | 文档重排序         |
| `/models/available` | GET  | 列出库中模型        |
| `/models/apply`     | POST | 从库安装模型        |
| `/swagger/`         | GET  | Swagger UI 文档 |
| `/metrics`          | GET  | Prometheus 指标 |

#### 获取版本

```bash
curl https://your-http-pub.clorecloud.net/version
```

响应：

```json
{"version": "v2.26.0"}
```

#### Swagger 文档

在浏览器中打开以获取交互式 API 文档：

```
https://your-http-pub.clorecloud.net/swagger/
```

## GPU 加速

### CUDA 后端

```yaml
# 在模型配置中
parameters:
  gpu_layers: 35  # 在 GPU 上的层数
  f16: true       # 使用 FP16
```

### 完全 GPU 卸载

```yaml
parameters:
  gpu_layers: 99  # 所有层在 GPU 上
  main_gpu: 0     # 主 GPU ID
```

## 多个模型

LocalAI 可以同时提供多个模型服务：

```
models/
├── llama-3.1-8b.yaml
├── llama-3.1-8b.gguf
├── mistral-7b.yaml
├── mistral-7b.gguf
├── whisper.yaml
└── whisper-base.bin
```

通过 API 调用中的模型名称访问每个模型。

## 性能调优

### 为速度优化

```yaml
parameters:
  threads: 8
  gpu_layers: 99
  batch_size: 512
  use_mmap: true
  use_mlock: true
```

### 为内存优化

```yaml
parameters:
  gpu_layers: 20  # 部分卸载
  context_size: 2048  # 较小的上下文
  batch_size: 256
```

## 基准测试

| A100            | GPU     | 每秒标记数 |
| --------------- | ------- | ----- |
| Llama 3.1 8B Q4 | 速度      | \~100 |
| Mistral 7B Q4   | 速度      | \~110 |
| Llama 3.1 8B Q4 | 512x512 | \~140 |
| Mixtral 8x7B Q4 | 2s      | \~60  |

*基准测试更新于 2026 年 1 月。*

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

### http\_pub URL 返回 HTTP 502

LocalAI 启动比其他服务要慢。请等待 **5-10 分钟** 然后重试：

```bash
# 检查就绪状态
curl https://your-http-pub.clorecloud.net/readyz

# 检查健康状态
curl https://your-http-pub.clorecloud.net/healthz
```

### 模型未加载

* 检查 YAML 中的文件路径
* 验证 GGUF 格式兼容性
* 检查可用显存

### 响应缓慢

* 增加 `gpu_layers`
* 启用 `use_mmap`
* 减少 `context_size`

### 内存不足

* 减少 `gpu_layers`
* 使用更小的量化（使用 Q4 而不是 Q8）
* 减少批量大小

### 图像生成问题

{% hint style="warning" %}
在某些 GPU 配置上，Stable Diffusion 可能存在 CUDA 兼容性问题。如果在图像生成时遇到 CUDA 错误，考虑改用专用的 Stable Diffusion 图像服务。
{% endhint %}

## 下载所有所需的检查点

典型 CLORE.AI 市场价格：

| GPU     | 显存   | 价格/天       | 适合     |
| ------- | ---- | ---------- | ------ |
| 按小时费率   | 12GB | $0.15–0.30 | 7B 模型  |
| 速度      | 24GB | $0.30–1.00 | 13B 模型 |
| 512x512 | 24GB | $0.50–2.00 | 快速推理   |
| 2s      | 40GB | $1.50–3.00 | 大型模型   |

*价格以美元/天计。费率因提供商而异——请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

## 使用以下方式支付

* [vLLM 推理](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/vllm) - 更高吞吐量
* [Ollama 指南](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/ollama) - 更简单的设置
* [使用 LangChain 的 RAG](https://docs.clore.ai/guides/guides_v2-zh/gao-ji/api-integration) - 构建应用程序


---

# 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/yu-yan-mo-xing/localai-openai-compatible.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.
