> 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/yu-yan-mo-xing/litellm.md).

# LiteLLM AI 网关

在 Clore.ai GPU 上将 LiteLLM 部署为支持 100+ LLM 的 AI 网关代理

LiteLLM 是一个开源 AI 网关，为 100+ 个大语言模型提供商提供统一且兼容 OpenAI 的 API——包括 OpenAI、Anthropic、Azure、Bedrock、HuggingFace 以及本地托管模型。将其部署到 CLORE.AI，可通过单一端点路由、负载均衡并管理你所有的 LLM API 调用，并内置成本跟踪、速率限制和故障转移逻辑。

LiteLLM 的真正威力在规模化场景中体现：运行混合本地+云端栈的团队可以在不改动应用代码的情况下热切换模型。替换 `gpt-4o` 使用 `mistral-7b-local` 到配置中，重启——搞定。

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

## 服务器要求

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

{% hint style="info" %}
LiteLLM 本身是基于 CPU 的代理，不需要 GPU。不过，当你想在同一台机器上将本地模型（通过 Ollama、TGI、vLLM）与 LiteLLM 作为统一网关一起运行时，把它部署到 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 中用于端口 4000 的 http\_pub 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"
```

***

## 配置

### 虚拟密钥（按用户 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   # 每分钟 token 数
    rpm_limit: 1000     # 每分钟请求数
```

***

## 性能提示

### 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"
```

典型设置：在 Clore.ai 的 RTX 3090（$0.07–0.21/小时）上本地运行 Mistral 7B 或 Llama 3 8B，在那里处理 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.07–0.21/小时。可轻松处理约 50 req/min，并在复杂任务上使用 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 价格                       | 使用场景                                 |
| ---------- | -------------- | --------------------------------- | ------------------------------------ |
| 仅云端 API 代理 | 仅 CPU          | 约 $0.02/小时                        | 路由到 OpenAI、Anthropic、Gemini——不需要 GPU |
| 本地 vLLM 后端 | RTX 3090（24GB） | $0.07–0.21/小时                     | 使用 LiteLLM 作为前端的自托管 7B–13B 模型        |
| 本地 vLLM 后端 | RTX 4090（24GB） | $0.14–0.42/小时                     | 更高吞吐量的 7B–34B 本地模型                   |
| 本地 vLLM 后端 | A100 40GB      | [裸机](https://clore.ai/bare-metal) | 70B 模型，生产级本地服务                       |

{% hint style="info" %}
**最常见的设置：** 在你的 Clore.ai 托管的 vLLM/Ollama 实例前，运行 LiteLLM 作为统一代理。这样你就能获得提供商故障转移、速率限制、成本跟踪和兼容 OpenAI 的路由——同时让所有推理都保持本地且低成本。

**示例成本：** 在仅 CPU 的实例（$0.07–0.21/小时）上运行 LiteLLM 代理，并将其指向运行在 RTX 3090（$0.07–0.21/小时）上的 vLLM 服务器。对于一个具备故障转移、日志记录和速率限制的生产级自托管 LLM API，总成本为 $0.07–0.21/小时。
{% endhint %}

***

## 链接

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


---

# 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/yu-yan-mo-xing/litellm.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.
