# LiteLLM AI 网关

LiteLLM 是一个开源的 AI 网关，为 100+ 个语言模型提供商（包括 OpenAI、Anthropic、Azure、Bedrock、HuggingFace 以及本地托管模型）提供统一的兼容 OpenAI 的 API。在 CLORE.AI 上部署它可以通过单一端点路由、负载均衡并管理所有 LLM API 调用，并内置费用跟踪、速率限制和回退逻辑。

LiteLLM 的真正能力在于大规模场景：运行混合本地+云堆栈的团队可以在不改动应用代码的情况下热插拔模型。将 `gpt-4o` 替换为 `mistral-7b-local` 在配置中，重启 —— 完成。

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

## 服务器要求

| 参数       | 最低要求     | 推荐配置       |
| -------- | -------- | ---------- |
| 内存（RAM）  | 4 GB     | 8 GB+      |
| 显存（VRAM） | 不适用（仅代理） | 不适用        |
| 磁盘       | 10 GB    | 20 GB+     |
| GPU      | 不需要      | 可选（用于本地模型） |

{% hint style="info" %}
LiteLLM 本身是基于 CPU 的代理，不需要 GPU。但是，当您希望在同一台机器上与 LiteLLM 一起运行本地模型（通过 Ollama、TGI、vLLM）时，在 CLORE.AI 的 GPU 服务器上部署是有意义的。
{% endhint %}

## 在 CLORE.AI 上快速部署

**Docker 镜像：** `ghcr.io/berriai/litellm:main-latest`

**端口：** `22/tcp`, `4000/http`

**环境变量：**

| 变量                   | 示例                 | 描述                 |
| -------------------- | ------------------ | ------------------ |
| `OPENAI_API_KEY`     | `sk-xxx...`        | OpenAI API 密钥      |
| `ANTHROPIC_API_KEY`  | `sk-ant-xxx...`    | Anthropic API 密钥   |
| `AZURE_API_KEY`      | `xxx...`           | Azure OpenAI 密钥    |
| `LITELLM_MASTER_KEY` | `sk-my-master-key` | 代理的主认证密钥           |
| `DATABASE_URL`       | `postgresql://...` | 用于费用跟踪的 PostgreSQL |
| `STORE_MODEL_IN_DB`  | `True`             | 将模型配置持久化到数据库       |

## 逐步设置

### 1. 在 CLORE.AI 上租用服务器

LiteLLM 即使在仅 CPU 的服务器上也能很好运行。前往 [CLORE.AI 市场](https://clore.ai/marketplace) 并筛选：

* 用于纯代理设置的最低价 CPU 服务器
* 如果您也想运行本地模型，则选择 GPU 服务器（RTX 3090+）

### 2. SSH 登录到您的服务器

```bash
ssh -p <PORT> root@<SERVER_IP>
```

### 3. 创建配置文件

LiteLLM 使用 YAML 配置文件来定义模型：

```bash
mkdir -p /root/litellm
cat > /root/litellm/config.yaml << 'EOF'
model_list:
  # OpenAI 模型
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: "os.environ/OPENAI_API_KEY"

  - model_name: gpt-4o-mini
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: "os.environ/OPENAI_API_KEY"

  # Anthropic 模型
  - model_name: claude-3-5-sonnet
    litellm_params:
      model: anthropic/claude-3-5-sonnet-20241022
      api_key: "os.environ/ANTHROPIC_API_KEY"

  # 通过 TGI 的本地模型（在同一服务器上，端口 8080）
  - model_name: mistral-7b-local
    litellm_params:
      model: openai/mistralai/Mistral-7B-Instruct-v0.3
      api_base: "http://localhost:8080/v1"
      api_key: "none"

  # 负载均衡器：路由到多个端点
  - model_name: fast-model
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: "os.environ/OPENAI_API_KEY"
    model_info:
      mode: chat

litellm_settings:
  drop_params: True
  set_verbose: False
  num_retries: 3
  request_timeout: 60

general_settings:
  master_key: "sk-my-secret-master-key"  # 请更改此项！
  alerting: []
EOF
```

### 4. 启动 LiteLLM

**基础启动：**

```bash
docker run -d \
  --name litellm \
  --network host \
  -v /root/litellm/config.yaml:/app/config.yaml \
  -e OPENAI_API_KEY=sk-your-openai-key \
  -e ANTHROPIC_API_KEY=sk-ant-your-anthropic-key \
  -e LITELLM_MASTER_KEY=sk-my-secret-master-key \
  ghcr.io/berriai/litellm:main-latest \
  --config /app/config.yaml \
  --port 4000 \
  --host 0.0.0.0
```

**使用 PostgreSQL 进行费用跟踪：**

首先，启动一个 PostgreSQL 容器：

```bash
docker run -d \
  --name postgres \
  -e POSTGRES_PASSWORD=litellm_pass \
  -e POSTGRES_DB=litellm \
  -p 5432:5432 \
  postgres:15

# 然后用数据库启动 LiteLLM
docker run -d \
  --name litellm \
  -p 4000:4000 \
  -v /root/litellm/config.yaml:/app/config.yaml \
  -e OPENAI_API_KEY=sk-your-openai-key \
  -e ANTHROPIC_API_KEY=sk-ant-your-anthropic-key \
  -e LITELLM_MASTER_KEY=sk-my-secret-master-key \
  -e DATABASE_URL="postgresql://postgres:litellm_pass@localhost:5432/litellm" \
  --network host \
  ghcr.io/berriai/litellm:main-latest \
  --config /app/config.yaml \
  --port 4000 \
  --host 0.0.0.0
```

**使用 Docker Compose（推荐）：**

```bash
cat > /root/litellm/docker-compose.yml << 'EOF'
version: "3.8"
services:
  litellm:
    image: ghcr.io/berriai/litellm:main-latest
    ports:
      - "4000:4000"
    volumes:
      - ./config.yaml:/app/config.yaml
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
      - LITELLM_MASTER_KEY=sk-my-secret-master-key
      - DATABASE_URL=postgresql://postgres:litellm_pass@db:5432/litellm
    command: --config /app/config.yaml --port 4000 --host 0.0.0.0
    depends_on:
      - db

  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: litellm_pass
      POSTGRES_DB: litellm
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:
EOF

cd /root/litellm && docker compose up -d
```

### 5. 验证服务器

```bash
# 检查健康状态
curl http://localhost:4000/health

# 列出可用模型
curl http://localhost:4000/v1/models \
  -H "Authorization: Bearer sk-my-secret-master-key"
```

### 6. 通过 CLORE.AI HTTP 代理访问

您的 CLORE.AI http\_pub（用于端口 4000）URL：

```
https://<order-id>-4000.clore.ai/v1
```

将此用作您的 `api_base` 在任何兼容 OpenAI 的客户端中使用。

***

## 使用示例

### 示例 1：通过代理的直接 API 调用

```bash
curl http://localhost:4000/v1/chat/completions \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-my-secret-master-key" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      {"role": "user", "content": "德国的首都是什么？"}
    ]
  }'
```

### 示例 2：使用 LiteLLM 代理的 OpenAI Python SDK

```python
from openai import OpenAI

# 只需更改 base_url 和 api_key —— 其余完全相同
client = OpenAI(
    base_url="http://localhost:4000/v1",
    api_key="sk-my-secret-master-key",
)

# 使用配置中的任意模型
response = client.chat.completions.create(
    model="gpt-4o-mini",  # 或 "claude-3-5-sonnet", "mistral-7b-local"
    messages=[{"role": "user", "content": "总结 GPU 计算的好处。"}],
)
print(response.choices[0].message.content)

# 在不改代码的情况下切换模型
response2 = client.chat.completions.create(
    model="claude-3-5-sonnet",
    messages=[{"role": "user", "content": "相同的问题，不同的模型。"}],
)
print(response2.choices[0].message.content)
```

### 示例 3：LiteLLM Python SDK（直接）

```python
import litellm

# 直接使用，不通过代理
response = litellm.completion(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "你好！"}],
    api_key="your-openai-key",
)

# 或通过您的代理路由
response = litellm.completion(
    model="openai/gpt-4o-mini",
    messages=[{"role": "user", "content": "你好！"}],
    api_base="http://localhost:4000",
    api_key="sk-my-secret-master-key",
)
```

### 示例 4：回退配置

配置模型之间的自动回退：

```yaml
# 在 config.yaml 中
model_list:
  - model_name: smart-fallback
    litellm_params:
      model: gpt-4o
      api_key: "os.environ/OPENAI_API_KEY"

router_settings:
  routing_strategy: least-busy
  model_group_alias:
    "gpt-4-fallback":
      - "gpt-4o"
      - "claude-3-5-sonnet"
      - "mistral-7b-local"
  num_retries: 3
  fallbacks:
    - gpt-4o:
        - claude-3-5-sonnet
        - mistral-7b-local
```

### 示例 5：费用跟踪仪表盘

启用 PostgreSQL 后，访问支出分析：

```bash
# 按用户获取支出
curl http://localhost:4000/global/spend/users \
  -H "Authorization: Bearer sk-my-secret-master-key"

# 按模型获取支出
curl http://localhost:4000/global/spend/models \
  -H "Authorization: Bearer sk-my-secret-master-key"

# 生成支出报告
curl "http://localhost:4000/global/spend?start_date=2024-01-01&end_date=2024-12-31" \
  -H "Authorization: Bearer sk-my-secret-master-key"
```

***

## invokeai.yaml 配置文件

### 虚拟密钥（每用户 API 密钥）

为不同用户创建具有速率限制和预算的独立密钥：

```bash
# 创建带预算的密钥
curl http://localhost:4000/key/generate \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-my-secret-master-key" \
  -d '{
    "models": ["gpt-4o-mini", "claude-3-5-sonnet"],
    "duration": "30d",
    "max_budget": 10.0,
    "metadata": {"user_id": "user_123"}
  }'
```

### 负载均衡

```yaml
model_list:
  # 在多个 OpenAI API 密钥之间轮询
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: sk-key-1
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_key: sk-key-2

router_settings:
  routing_strategy: least-busy  # 或：simple-shuffle、latency-based-routing
```

### 缓存

```yaml
litellm_settings:
  cache: True
  cache_params:
    type: redis
    host: localhost
    port: 6379
    ttl: 3600  # 1 小时
```

### 速率限制

```yaml
general_settings:
  default_team_settings:
    tpm_limit: 100000   # 每分钟令牌数
    rpm_limit: 1000     # 每分钟请求数
```

***

## 1. 使用 SDXL-Turbo 或 SDXL-Lightning 以实现快速生成

### 1. 为重复提示启用缓存

对于具有常见问题的 RAG 或聊天机器人应用，Redis 缓存可降低 30–70% 的成本，并在缓存命中时将 P50 延迟降至 <5ms：

```yaml
litellm_settings:
  cache: True
  cache_params:
    type: redis
    host: localhost
    port: 6379
```

### 2. 使用异步请求

```python
import asyncio
import litellm

async def batch_complete(prompts):
    tasks = [
        litellm.acompletion(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": p}],
        )
        for p in prompts
    ]
    return await asyncio.gather(*tasks)

results = asyncio.run(batch_complete(["Hello", "World", "Test"]))
```

### 3. 本地模型路由

将廉价/简单的请求路由到 Clore.ai GPU 上的本地模型，将复杂请求交给 GPT-4：

```yaml
model_list:
  - model_name: smart-router
    litellm_params:
      model: openai/gpt-4o
      api_key: "os.environ/OPENAI_API_KEY"
```

典型设置：在本地运行 Mistral 7B 或 Llama 3 8B（在 Clore.ai 的 RTX 3090 上，$0.10–0.15/小时），在那里处理 80% 的流量，然后将复杂任务升级到 GPT-4o。与仅使用云相比，通常能节省 3–5 倍的成本。

### 4. 设置超时和重试

```yaml
litellm_settings:
  request_timeout: 30
  num_retries: 3
  retry_after: 5
```

***

## Clore.ai 的 GPU 建议

LiteLLM 本身不需要 GPU —— 它是一个代理。只有在您在其旁边共同部署本地推理时，GPU 的选择才重要。

| 本地模型                            | GPU                | 为什么                                   |
| ------------------------------- | ------------------ | ------------------------------------- |
| Mistral 7B / Llama 3 8B（bf16）   | **RTX 3090** 24 GB | 可轻松适配，约 200 tok/s 吞吐量                 |
| Mixtral 8×7B 或 Llama 3 70B（AWQ） | **RTX 4090** 24 GB | 比 3090 更快的内存带宽；可容纳 70B AWQ 的 4-bit 模型 |
| Llama 3 70B（bf16）或多模型服务         | **A100 80 GB**     | 同时运行多个 7–13B 模型；使用 HBM2e 以实现低延迟       |

**单人开发者推荐堆栈：** RTX 3090 + Mistral 7B + LiteLLM 网关。在 Clore.ai 上总成本约 $0.12/小时。可轻松处理约 50 次请求/分钟，并在复杂任务时回退到 GPT-4o。

**团队 / 生产堆栈：** A100 80GB，运行 Llama 3 70B + LiteLLM + PostgreSQL。可服务 20+ 并发用户，完整费用跟踪，对大多数请求实现零云 LLM 支出。

***

## 故障排除

### 问题："找不到模型"

确保请求中的模型名称与 `config.yaml`:

```bash
curl http://localhost:4000/v1/models -H "Authorization: Bearer sk-my-secret-master-key"
```

### 问题："认证失败"

检查您的 `LITELLM_MASTER_KEY` 环境变量并将其用作 Bearer 令牌。

### 问题：配置更改未生效

在更改配置后重启容器：

```bash
docker restart litellm
```

### 问题：首次请求延迟高

LiteLLM 在启动时加载模型配置。前几次请求在建立连接时可能会较慢。

### 问题：数据库连接错误

```bash
# 检查 PostgreSQL 是否在运行
docker logs postgres

# 验证连接字符串格式
DATABASE_URL="postgresql://user:password@host:5432/dbname"
```

### 问题：来自提供商的 429 速率限制错误

配置回退：

```yaml
litellm_settings:
  num_retries: 5
  fallbacks:
    - gpt-4o: [claude-3-5-sonnet]
```

***

## Clore.ai 的 GPU 建议

LiteLLM 是一个 API 网关/代理 —— 它本身不做推理。GPU 的选择取决于您是路由到云 API 还是本地模型。

| 设置         | GPU       | Clore.ai 价格 | 在 Clore.ai 上的预估费用                     |
| ---------- | --------- | ----------- | ------------------------------------- |
| 仅云 API 代理  | 仅 CPU     | ≈$0.02/小时   | 路由到 OpenAI、Anthropic、Gemini —— 无需 GPU |
| 本地 vLLM 后端 | 生产        | \~$0.12/小时  | 自托管的 7B–13B 模型，LiteLLM 作为前端           |
| 本地 vLLM 后端 | 大规模       | \~$0.70/小时  | 更高吞吐量的 7B–34B 本地模型                    |
| 本地 vLLM 后端 | A100 40GB | \~$1.20/小时  | 70B 模型，生产级本地服务                        |

{% hint style="info" %}
**最常见的设置：** 在 Clore.ai 托管的 vLLM/Ollama 实例前运行 LiteLLM 作为统一代理。这为您提供提供商回退、速率限制、费用跟踪和兼容 OpenAI 的路由，同时将所有推理保持在本地以降低成本。

**示例成本：** 在仅 CPU 实例上运行 LiteLLM 代理（~~$0.02/小时）并将其指向在 RTX 3090 上的 vLLM 服务器（~~$0.12/小时）。具有回退、日志记录和速率限制的可用于生产的自托管 LLM API 总成本约 $0.14/小时。
{% endhint %}

***

## 文档

* [GitHub](https://github.com/BerriAI/litellm)
* [文档](https://docs.litellm.ai)
* [Clore.ai GPU 建议](https://github.com/BerriAI/litellm/pkgs/container/litellm)
* [支持的提供商](https://docs.litellm.ai/docs/providers)
* [CLORE.AI 市场](https://clore.ai/marketplace)


---

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