---
title: "多模型共识：让 Claude Code 调用 DeepSeek、通义千问、KIMI 的完整配置教程"
author: deletexiumu
pubDatetime: 2026-01-27T10:00:00+08:00
featured: false
draft: false
tags:
  - Claude Code
  - 教程
description: "让 Claude Code 同时调用 DeepSeek、通义千问、KIMI，多模型共识的完整配置教程。"
---

> 记录于 2026-01-27，基于 LiteLLM 1.81.3 + PAL MCP Server + macOS

> **跨平台说明**：本教程基于 macOS 编写，但 **Linux 完全通用**，**Windows 用户请使用 WSL（Windows Subsystem for Linux）**。WSL 下的操作与 Linux 一致，只需将 launchd 自启动部分替换为 systemd 即可。如果你还没装 WSL，强烈建议先装一个，这是 Windows 下玩 AI 工具链的最佳方式。

## 前言

你是否想过，让 Claude 在回答问题时，能够同时咨询 DeepSeek、通义千问、KIMI 等多个 AI，然后综合它们的意见给出最终答案？

这就是「多模型共识」的魅力。

本教程将手把手教你配置这套系统，最终实现：
- 在 Claude Code 中一键调用国产大模型
- 使用 `consensus` 功能让多个模型讨论同一个问题
- 自动选择最合适的模型处理不同任务

## 架构概览

```
┌─────────────────────────────────────────────────────────────┐
│                      Claude Code                             │
│                          ↓                                   │
│              PAL MCP Server (模型编排层)                      │
│                          ↓                                   │
│              LiteLLM Proxy (API 聚合层)                       │
│                    ↓    ↓    ↓                               │
│     ┌──────────────┼────┼────┼──────────────┐               │
│     │              │    │    │              │               │
│  DeepSeek     通义千问   KIMI   ...更多模型                   │
│     │              │    │    │              │               │
│     └──────────────┴────┴────┴──────────────┘               │
└─────────────────────────────────────────────────────────────┘
```

**为什么需要两层？**

- **LiteLLM**: 将不同厂商的 API 统一成 OpenAI 兼容格式，提供单一访问入口
- **PAL MCP Server**: 在 LiteLLM 之上提供高级功能（共识讨论、智能选择、深度思考等）

---

## 目录

1. [第一部分：安装 LiteLLM](#第一部分安装-litellm)
2. [第二部分：配置模型和 API Key](#第二部分配置模型和-api-key)
3. [第三部分：配置 PostgreSQL 数据库](#第三部分配置-postgresql-数据库)
4. [第四部分：配置开机自启动](#第四部分配置开机自启动)
5. [第五部分：配置 PAL MCP Server](#第五部分配置-pal-mcp-server)
6. [第六部分：验证和使用](#第六部分验证和使用)
7. [踩坑记录](#踩坑记录)
8. [常见问题](#常见问题)

---

## 第一部分：安装 LiteLLM

### 环境要求

- macOS (Apple Silicon 或 Intel)
- Python 3.10+（推荐 3.12，3.14 需要额外处理）
- PostgreSQL（用于 UI 登录，可选）

### 安装步骤

```bash
# 1. 安装 LiteLLM 及代理功能
pip3 install 'litellm[proxy]'

# 2. 安装 httpx socks 支持（如果系统配置了 SOCKS 代理）
pip3 install 'httpx[socks]'

# 3. 验证安装
litellm --version
```

---

## 第二部分：配置模型和 API Key

### 2.1 获取各平台 API Key

| 平台 | 获取地址 | 模型 |
|------|---------|------|
| DeepSeek | https://platform.deepseek.com/api_keys | deepseek-reasoner |
| 阿里云灵积 | https://dashscope.console.aliyun.com/apiKey | 通义千问 |
| Moonshot | https://platform.moonshot.cn/console/api-keys | KIMI K2 |

### 2.2 创建环境变量文件

**文件位置**: `~/.litellm.env`

```bash
# LiteLLM 环境变量配置

# DeepSeek API Key
export DEEPSEEK_API_KEY="sk-your-deepseek-key"

# 阿里云灵积 (DashScope) API Key
export DASHSCOPE_API_KEY="sk-your-dashscope-key"

# Moonshot (KIMI) API Key
export MOONSHOT_API_KEY="sk-your-moonshot-key"

# LiteLLM Master Key（自己设置一个密钥，用于 API 认证）
export LITELLM_MASTER_KEY="your-master-key-here"

# UI 登录凭据（可选，需要数据库支持）
export UI_USERNAME="admin"
export UI_PASSWORD="your-ui-password"

# PostgreSQL 数据库（可选，UI 登录需要）
export DATABASE_URL="postgresql://litellm:password@localhost:5432/litellm"
```

### 2.3 创建模型配置文件

**文件位置**: `~/.litellm_config.yaml`

```yaml
model_list:
  # DeepSeek 深度思考模型
  - model_name: deepseek-reasoner
    litellm_params:
      model: deepseek/deepseek-reasoner
      api_key: os.environ/DEEPSEEK_API_KEY
      api_base: https://api.deepseek.com

  # 阿里云通义千问思考模型
  - model_name: qwen3-max-thinking
    litellm_params:
      model: openai/qwen3-235b-a22b
      api_key: os.environ/DASHSCOPE_API_KEY
      api_base: https://dashscope.aliyuncs.com/compatible-mode/v1
      extra_body:
        enable_thinking: true

  # KIMI K2 思考模型
  - model_name: kimi-k2-thinking
    litellm_params:
      model: openai/kimi-k2-0711-preview
      api_key: os.environ/MOONSHOT_API_KEY
      api_base: https://api.moonshot.cn/v1

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
```

### 2.4 配置 Shell 自动加载

在 `~/.zshrc`（或 `~/.bashrc`）中添加：

```bash
# LiteLLM 环境变量
[ -f "$HOME/.litellm.env" ] && source "$HOME/.litellm.env"
```

然后重新加载：

```bash
source ~/.zshrc
```

### 2.5 测试启动

```bash
# 手动启动 LiteLLM（调试用）
litellm --config ~/.litellm_config.yaml --port 4000
```

访问 http://localhost:4000/v1/models 验证是否正常。

---

## 第三部分：配置 PostgreSQL 数据库

> **注意**: 如果你不需要 LiteLLM 的 Web UI 登录功能，可以跳过本部分。

LiteLLM 的 UI 登录功能需要 PostgreSQL 存储 session token。

### 3.1 创建数据库

```bash
# 使用 psql 连接到 PostgreSQL
psql -U postgres

# 创建数据库和用户
CREATE DATABASE litellm;
CREATE USER litellm WITH PASSWORD 'your-password';
GRANT ALL PRIVILEGES ON DATABASE litellm TO litellm;
ALTER DATABASE litellm OWNER TO litellm;
\q
```

### 3.2 安装并配置 Prisma

```bash
# 安装 prisma
pip3 install prisma

# 设置环境变量
export DATABASE_URL="postgresql://litellm:your-password@localhost:5432/litellm"

# 进入 litellm proxy 目录
cd $(python3 -c "import litellm; print(litellm.__path__[0])")/proxy

# 生成 Prisma 客户端
prisma generate

# 同步数据库 schema
prisma db push --accept-data-loss
```

---

## 第四部分：配置开机自启动

### 4.1 创建 Python 启动器

> **重要**: 如果你使用 Python 3.14，必须使用自定义启动器，因为 uvloop 与 Python 3.14 不兼容。

**文件位置**: `~/.litellm_launcher.py`

```python
#!/usr/bin/env python3
"""LiteLLM Proxy 启动器 - 兼容 Python 3.14"""
import os
import asyncio

CONFIG_FILE = os.path.expanduser("~/.litellm_config.yaml")

async def initialize():
    from litellm.proxy.proxy_server import proxy_config
    import litellm.proxy.proxy_server as proxy_server

    llm_router, llm_model_list, general_settings = await proxy_config.load_config(
        router=None,
        config_file_path=CONFIG_FILE,
    )

    proxy_server.llm_router = llm_router
    proxy_server.llm_model_list = llm_model_list
    proxy_server.general_settings = general_settings
    proxy_server.master_key = os.environ.get("LITELLM_MASTER_KEY")

    print(f"Loaded models: {[m.get('model_name') for m in llm_model_list or []]}")

asyncio.run(initialize())

from litellm.proxy.proxy_server import app
import uvicorn

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=4000, loop="asyncio")
```

### 4.2 创建启动脚本

**文件位置**: `~/.litellm_start.sh`

```bash
#!/bin/bash
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:$PATH"
source ~/.litellm.env
exec python3 ~/.litellm_launcher.py
```

```bash
chmod +x ~/.litellm_start.sh
```

### 4.3 创建 launchd 配置

**文件位置**: `~/Library/LaunchAgents/com.litellm.proxy.plist`

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.litellm.proxy</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>/Users/你的用户名/.litellm_start.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/你的用户名/.litellm.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/你的用户名/.litellm.error.log</string>
    <key>WorkingDirectory</key>
    <string>/Users/你的用户名</string>
</dict>
</plist>
```

> **注意**: 将 `你的用户名` 替换为实际用户名，可通过 `whoami` 命令获取。

### 4.4 加载服务

```bash
# 加载服务
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.litellm.proxy.plist

# 查看服务状态
launchctl list | grep litellm

# 卸载服务（需要时）
launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/com.litellm.proxy.plist
```

---

## 第五部分：配置 PAL MCP Server

PAL (Provider Abstraction Layer) 是一个 MCP 服务器，让 Claude Code 能够调用 LiteLLM 中配置的模型。

### 5.1 配置 MCP 服务器

**文件位置**: `~/.mcp.json`

```json
{
  "mcpServers": {
    "pal": {
      "command": "bash",
      "args": ["-c", "for p in $(which uvx 2>/dev/null) $HOME/.local/bin/uvx /opt/homebrew/bin/uvx /usr/local/bin/uvx uvx; do [ -x \"$p\" ] && exec \"$p\" --from git+https://github.com/BeehiveInnovations/pal-mcp-server.git pal-mcp-server; done; echo 'uvx not found' >&2; exit 1"],
      "env": {
        "PATH": "/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin:~/.local/bin",
        "CUSTOM_API_URL": "http://localhost:4000/v1",
        "CUSTOM_API_KEY": "你的-LITELLM_MASTER_KEY",
        "CUSTOM_MODEL_NAME": "deepseek-reasoner",
        "CUSTOM_MODELS_CONFIG_PATH": "~/.claude/pal_custom_models.json",
        "DISABLED_TOOLS": "analyze,refactor,testgen,secaudit,docgen,tracer",
        "DEFAULT_MODEL": "custom",
        "LOG_LEVEL": "INFO"
      }
    }
  }
}
```

### 5.2 配置自定义模型

**文件位置**: `~/.claude/pal_custom_models.json`

```json
{
  "models": [
    {
      "model_name": "deepseek-reasoner",
      "aliases": ["deepseek", "ds", "reasoner"],
      "description": "DeepSeek 推理模型，具有扩展思考能力",
      "context_window": 65536,
      "max_output_tokens": 8192,
      "supports_extended_thinking": true,
      "supports_json_mode": true,
      "supports_function_calling": true,
      "supports_images": false,
      "supports_temperature": true,
      "intelligence_score": 18
    },
    {
      "model_name": "qwen3-max-thinking",
      "aliases": ["qwen", "qwen3", "qwen-thinking"],
      "description": "Qwen3 Max 思考模型",
      "context_window": 131072,
      "max_output_tokens": 8192,
      "supports_extended_thinking": true,
      "supports_json_mode": true,
      "supports_function_calling": true,
      "supports_images": false,
      "supports_temperature": true,
      "intelligence_score": 17
    },
    {
      "model_name": "kimi-k2-thinking",
      "aliases": ["kimi", "k2", "moonshot"],
      "description": "Kimi K2 思考模型",
      "context_window": 131072,
      "max_output_tokens": 8192,
      "supports_extended_thinking": true,
      "supports_json_mode": true,
      "supports_function_calling": true,
      "supports_images": false,
      "supports_temperature": true,
      "intelligence_score": 17
    }
  ]
}
```

### 5.3 重要配置说明

| 配置项 | 说明 |
|--------|------|
| `CUSTOM_API_URL` | 必须指向 LiteLLM 的地址，以 `/v1` 结尾 |
| `CUSTOM_API_KEY` | 必须与 `LITELLM_MASTER_KEY` 一致 |
| `model_name` | 必须与 LiteLLM 配置中的模型名完全一致 |
| `aliases` | 简短别名，方便快速调用 |
| `intelligence_score` | 1-20 分，用于自动模式选择 |

---

## 第六部分：验证和使用

### 6.1 重启 Claude Code

配置完成后，必须重启 Claude Code 使 MCP 配置生效。

### 6.2 检查 MCP 连接状态

在 Claude Code 中输入 `/mcp`，应该能看到 `pal` 服务器已连接。

### 6.3 查看可用模型

使用 PAL 的 `listmodels` 工具：

![PAL 多模型支持列表结果](/blog/multi-model-consensus/PAL 多模型支持列表结果.png)

### 6.4 使用多模型共识

使用 PAL 的 `consensus` 工具，让多个模型讨论同一个问题：

![PAL 多模型共识调用结果](/blog/multi-model-consensus/PAL 多模型共识调用结果.png)

### 6.5 使用示例

```
# 使用简短别名调用模型
"用 deepseek 帮我分析这段代码"
"让 qwen 解释一下这个概念"
"让 kimi 生成一个方案"

# 使用共识功能
"用 consensus 讨论一下这个架构设计的优缺点"
```

---

## 踩坑记录

### 坑 1: Python 3.14 与 uvloop 不兼容

**错误信息:**
```
ImportError: cannot import name 'BaseDefaultEventLoopPolicy' from 'asyncio.events'
```

**解决方案:** 使用自定义启动器，指定 `loop="asyncio"` 而不是 uvloop。

### 坑 2: LiteLLM CLI 无法禁用 uvloop

**解决方案:** 创建 `~/.litellm_launcher.py`，直接使用 uvicorn 启动。

### 坑 3: uvicorn.run() 使用模块路径时配置丢失

**问题:** 使用字符串模块路径时，配置会在 fork 时丢失。

**解决方案:** 先加载配置，然后直接传入 app 对象：
```python
from litellm.proxy.proxy_server import app
uvicorn.run(app, host="0.0.0.0", port=4000, loop="asyncio")
```

### 坑 4: UI 登录接口使用表单数据

**错误:** 用 JSON 格式发送登录请求返回 `Invalid credentials`

**正确方式:**
```bash
curl -X POST http://localhost:4000/login \
  -d "username=admin&password=xxx"
```

### 坑 5: UI 登录需要 PostgreSQL

**解决方案:** 配置 PostgreSQL 并设置 `DATABASE_URL`。

### 坑 6: launchd 启动时环境变量问题

**解决方案:** 在启动脚本中显式设置 PATH 并 source 环境变量文件。

### 坑 7: PAL 不会自动获取模型列表

**原因:** PAL 需要知道模型的详细能力，而 `/models` API 不提供这些信息。

**解决方案:** 必须在 `pal_custom_models.json` 中手动定义每个模型。

---

## 常见问题

### Q: 服务启动后端口被占用？

```bash
lsof -ti:4000 | xargs kill -9
```

### Q: 数据库连接失败？

1. 检查 PostgreSQL 是否运行
2. 检查 `DATABASE_URL` 是否正确
3. 确保 Prisma 客户端已生成

### Q: PAL 无法连接？

1. 确保 LiteLLM 正在运行: `curl http://localhost:4000/v1/models`
2. 检查 `CUSTOM_API_KEY` 是否正确
3. 重启 Claude Code

### Q: 模型调用失败？

1. 检查对应的 API Key 是否正确
2. 查看 LiteLLM 日志: `tail -f ~/.litellm.error.log`

---

## 配置文件清单

| 文件 | 用途 |
|------|------|
| `~/.litellm.env` | 环境变量（API Key、数据库等） |
| `~/.litellm_config.yaml` | LiteLLM 模型配置 |
| `~/.litellm_launcher.py` | Python 启动器 |
| `~/.litellm_start.sh` | Bash 启动脚本 |
| `~/Library/LaunchAgents/com.litellm.proxy.plist` | launchd 自启动配置 |
| `~/.mcp.json` | MCP 服务器配置 |
| `~/.claude/pal_custom_models.json` | PAL 模型定义 |
| `~/.litellm.log` | 标准输出日志 |
| `~/.litellm.error.log` | 错误日志 |

---

## 参考链接

- [PAL MCP Server GitHub](https://github.com/BeehiveInnovations/pal-mcp-server)
- [LiteLLM 文档](https://docs.litellm.ai/)
- [DeepSeek 开放平台](https://platform.deepseek.com/)
- [阿里云灵积](https://dashscope.console.aliyun.com/)
- [Moonshot 开放平台](https://platform.moonshot.cn/)

---

*文档完成于 2026-01-27*

---

## 相关阅读

- [Claude Code 调用国内模型的缓存大坑：一个环境变量省 90% 的钱](/posts/claude-code-cache-pitfall/) — 配好多模型后，别忘了这个省钱技巧
- [Claude Code 完整安装与配置教程（支持国内模型）](/posts/claude-code-installation/) — 多模型配置的前置基础
- [AI Agent 多模型编排：让 Claude、DeepSeek、Gemini 各干各的活](/posts/ai-agent-multi-model-orchestration/) — 从共识配置进阶到多模型编排实战
