Files
docker-configs/router/README.md
Will Song 568dcc45e4 Fix router failover and add Discord bot
- Remove duplicate claude_api provider to fix automatic failover
- Enhance error detection with HTTP status codes and more indicators
- Add comprehensive README documentation with manual switching
- Implement Discord bot with Claude Code CLI integration
- Support /terminal and /claude commands with AI-powered responses

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-16 21:35:52 -05:00

314 lines
6.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Claude API Router
智能的Claude API路由器提供自动故障转移和负载均衡功能。当主要API服务遇到限制或错误时自动切换到备用提供商。
## 🚀 功能特性
- **自动故障转移**: 检测到速率限制或错误时自动切换API提供商
- **多提供商支持**: 支持Claude Pro、DeepSeek、Kimi
- **手动切换**: 支持手动强制切换到指定提供商
- **健康检查**: 自动监控和恢复主要提供商
- **完全兼容**: 与Anthropic Claude API完全兼容
- **流式响应**: 支持流式和非流式响应
## 📋 支持的提供商
按优先级排序:
1. **Claude Pro** - 最高优先级,首选提供商
2. **DeepSeek** - OpenAI兼容的备用提供商
3. **Kimi** - OpenAI兼容的备用提供商
## 🛠️ 安装和配置
### 1. 环境要求
```bash
cd router
pip install -r requirements.txt
```
### 2. 配置API密钥
`/home/will/docker/tokens.txt` 文件中添加以下令牌:
```txt
claude_api_key=your_claude_api_key_here
deepseek_api_key=your_deepseek_api_key_here
kimi_api_key=your_kimi_api_key_here
```
或者设置环境变量:
```bash
export CLAUDE_API_KEY="your_claude_api_key"
export DEEPSEEK_API_KEY="your_deepseek_api_key"
export KIMI_API_KEY="your_kimi_api_key"
```
### 3. 启动服务
```bash
# 开发模式
python app.py
# 生产模式 (使用Docker Compose)
docker-compose up -d
```
服务将在 `http://localhost:8000` 启动。
## 🔧 手动切换提供商
### API端点
```http
POST /v1/switch-provider
Content-Type: application/json
{
"provider": "provider_name"
}
```
### 可用的提供商名称
- `claude_pro` - Claude Pro提供商 (默认)
- `deepseek` - DeepSeek提供商
- `kimi` - Kimi提供商
### 使用示例
#### curl命令
```bash
# 切换到DeepSeek
curl -X POST http://localhost:8000/v1/switch-provider \
-H "Content-Type: application/json" \
-d '{"provider": "deepseek"}'
# 切换到Kimi
curl -X POST http://localhost:8000/v1/switch-provider \
-H "Content-Type: application/json" \
-d '{"provider": "kimi"}'
# 切换回Claude Pro
curl -X POST http://localhost:8000/v1/switch-provider \
-H "Content-Type: application/json" \
-d '{"provider": "claude_pro"}'
```
#### Python脚本
```python
import requests
def switch_provider(provider_name):
"""切换API提供商"""
url = "http://localhost:8000/v1/switch-provider"
data = {"provider": provider_name}
response = requests.post(url, json=data)
if response.status_code == 200:
result = response.json()
print(f"成功切换到: {result['current_provider']}")
return True
else:
print(f"切换失败: {response.text}")
return False
# 使用示例
switch_provider("deepseek")
switch_provider("kimi")
switch_provider("claude_pro")
```
### 查看当前状态
```bash
# 查看当前使用的提供商
curl http://localhost:8000/v1/health
# 响应示例
{
"status": "healthy",
"current_provider": "claude_pro",
"providers": {
"claude_pro": "available",
"deepseek": "unknown",
"kimi": "unknown"
}
}
```
## 🔄 自动故障转移
路由器会自动检测以下错误并进行故障转移:
- 速率限制 (Rate limit exceeded)
- 使用配额超额 (Usage limit exceeded)
- HTTP 429错误
- 每日/月度限制达到
- 网络连接错误
### 故障转移流程
1. 检测到故障转移触发条件
2. 自动切换到下一个优先级提供商
3. 重试请求
4. 记录切换日志
5. 定期尝试恢复到主要提供商
## 🩺 健康检查和自动恢复
- **自动检查频率**: 每小时的前5分钟
- **检查内容**: 向Claude Pro发送测试请求
- **自动恢复**: 如果Claude Pro恢复可用自动切换回去
## 🔌 API兼容性
路由器完全兼容Anthropic Claude API支持
- 所有Claude模型 (claude-3-sonnet, claude-3-opus等)
- 流式和非流式响应
- 系统消息和用户消息
- 所有API参数 (max_tokens, temperature等)
### 使用示例
```python
import requests
# 标准Claude API调用
url = "http://localhost:8000/v1/messages"
headers = {
"Content-Type": "application/json",
"x-api-key": "your_claude_api_key"
}
data = {
"model": "claude-3-sonnet-20240229",
"max_tokens": 1000,
"messages": [
{"role": "user", "content": "Hello, Claude!"}
]
}
response = requests.post(url, headers=headers, json=data)
print(response.json())
```
## 🐛 故障排除
### 常见问题
#### 1. 自动切换不工作
**问题**: 遇到限制时不自动切换
**解决方案**:
```bash
# 手动切换到备用提供商
curl -X POST http://localhost:8000/v1/switch-provider \
-H "Content-Type: application/json" \
-d '{"provider": "deepseek"}'
```
#### 2. API密钥错误
**问题**: 提示API密钥无效
**解决方案**:
1. 检查 `tokens.txt` 文件中的密钥格式
2. 确保密钥没有多余的空格或换行
3. 验证密钥是否有效
#### 3. 服务无法启动
**问题**: 路由器启动失败
**解决方案**:
```bash
# 检查日志
docker-compose logs router
# 手动启动调试
cd router
python app.py
```
### 调试模式
启用详细日志:
```python
import logging
logging.basicConfig(level=logging.DEBUG)
```
## 📊 监控和日志
### 日志级别
- `INFO`: 正常操作日志
- `WARNING`: 提供商切换警告
- `ERROR`: 错误和故障转移事件
### 关键日志信息
- 提供商切换事件
- API请求失败
- 健康检查结果
- 自动恢复操作
## ⚙️ 高级配置
### 自定义故障转移条件
编辑 `app.py` 中的 `should_failover` 方法:
```python
def should_failover(self, error_message: str) -> bool:
# 添加自定义错误检测条件
custom_indicators = [
"your_custom_error",
"specific_provider_error"
]
return any(indicator in error_message.lower()
for indicator in custom_indicators)
```
### 调整健康检查频率
修改 `app.py` 中的定时任务:
```python
# 每30分钟检查一次
@scheduler.cron("*/30 * * * *")
async def health_check_claude_pro():
# ... 健康检查逻辑
```
## 🤝 SillyTavern集成
在SillyTavern中使用此路由器
1. **API URL**: `http://localhost:8000/v1/messages`
2. **API Key**: 使用你的Claude API密钥
3. **模型**: 选择任何Claude模型
路由器会自动处理故障转移对SillyTavern完全透明。
## 📄 许可证
MIT License
## 🆘 获取帮助
如果遇到问题:
1. 检查日志文件
2. 验证API密钥配置
3. 尝试手动切换提供商
4. 查看健康检查状态
需要进一步帮助请查看代码注释或联系开发者。