-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathmain.py
More file actions
2681 lines (2276 loc) · 113 KB
/
main.py
File metadata and controls
2681 lines (2276 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, Request, Response, Depends, WebSocket, WebSocketDisconnect, HTTPException, Cookie
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from sqlalchemy import desc
import httpx
import json
import time
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
import asyncio
import logging
# 配置统一的日志系统
import os
DEBUG_MODE = os.getenv('DEBUG_MODE', 'false').lower() == 'true'
logging.basicConfig(
level=logging.DEBUG if DEBUG_MODE else logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def debug_print(*args, **kwargs):
"""统一的DEBUG输出函数,只在DEBUG_MODE启用时输出"""
if DEBUG_MODE:
print(*args, **kwargs)
from database import (
get_db, APIRecord, PlatformConfig, ModelConfig, RoutingConfig, RoutingScene, SystemConfig,
ClaudeCodeServer, UserAuth, LoginSession, hash_password, verify_password, generate_session_token
)
from multi_platform_service import multi_platform_service
app = FastAPI(title="API Hook System")
# 静态文件服务
app.mount("/static", StaticFiles(directory="."), name="static")
# 默认配置
default_config = {
"local_path": "api/v1/claude-code",
"target_url": "https://dashscope.aliyuncs.com/api/v2/apps/claude-code-proxy",
"use_multi_platform": True, # 是否使用多平台转发
"current_work_mode": "claude_code" # 当前工作模式: claude_code, global_direct, smart_routing
}
# 全局配置(从数据库加载)
config_data = default_config.copy()
# 系统启动时间
system_start_time = time.time()
def load_system_config():
"""从数据库加载系统配置"""
global config_data
logger.info("🔄 [Config] 开始从数据库加载系统配置...")
try:
from sqlalchemy.orm import Session
db = next(get_db())
# 加载当前工作模式
work_mode_config = db.query(SystemConfig).filter(
SystemConfig.config_key == "current_work_mode"
).first()
if work_mode_config:
old_mode = config_data["current_work_mode"]
config_data["current_work_mode"] = work_mode_config.config_value
logger.info(f"📂 [Config] 从数据库加载工作模式: {old_mode} -> {work_mode_config.config_value}")
else:
# 如果数据库中没有配置,保存默认配置
save_system_config("current_work_mode", config_data["current_work_mode"])
logger.info(f"💾 [Config] 数据库无配置,保存默认工作模式: {config_data['current_work_mode']}")
logger.info(f"✅ [Config] 配置加载完成,当前工作模式: {config_data['current_work_mode']}")
db.close()
except Exception as e:
logger.error(f"⚠️ [Config] 加载系统配置失败,使用默认配置: {e}")
def save_system_config(key: str, value: str):
"""保存系统配置到数据库"""
logger.info(f"💾 [Config] 开始保存系统配置: {key} = {value}")
try:
from sqlalchemy.orm import Session
db = next(get_db())
existing_config = db.query(SystemConfig).filter(
SystemConfig.config_key == key
).first()
if existing_config:
old_value = existing_config.config_value
existing_config.config_value = value
existing_config.updated_at = datetime.utcnow()
logger.info(f"🔄 [Config] 更新配置: {key} = {old_value} -> {value}")
else:
new_config = SystemConfig(
config_key=key,
config_value=value,
config_type="string",
description=f"系统配置: {key}"
)
db.add(new_config)
logger.info(f"➕ [Config] 新增配置: {key} = {value}")
db.commit()
db.close()
logger.info(f"✅ [Config] 系统配置已保存: {key} = {value}")
except Exception as e:
logger.error(f"❌ [Config] 保存系统配置失败: {e}")
# 在应用启动时加载配置
load_system_config()
# WebSocket连接管理
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def broadcast(self, message: dict):
for connection in self.active_connections:
try:
await connection.send_text(json.dumps(message))
except:
# 连接已断开,移除连接
self.active_connections.remove(connection)
manager = ConnectionManager()
# 认证相关函数
def get_current_session(request: Request, db: Session = Depends(get_db)) -> Optional[LoginSession]:
"""获取当前会话"""
session_token = request.cookies.get("session_token")
if not session_token:
return None
session = db.query(LoginSession).filter(
LoginSession.session_token == session_token,
LoginSession.expires_at > datetime.utcnow()
).first()
return session
def require_auth(request: Request, db: Session = Depends(get_db)):
"""需要认证的依赖"""
session = get_current_session(request, db)
if not session:
raise HTTPException(status_code=401, detail="未登录或会话已过期")
return session
def check_first_login(db: Session = Depends(get_db)) -> bool:
"""检查是否首次登录"""
user = db.query(UserAuth).first()
return user.is_first_login if user else True
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request, db: Session = Depends(get_db)):
# 检查是否已登录
session = get_current_session(request, db)
if not session:
return RedirectResponse(url="/login", status_code=302)
# 检查是否首次登录,需要修改密码
if check_first_login(db):
return RedirectResponse(url="/change-password?first=true", status_code=302)
with open("index.html", "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read())
@app.get("/login", response_class=HTMLResponse)
async def login_page():
"""登录页面"""
login_html = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - Claude Code Hook</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
<div class="bg-white rounded-lg shadow-xl w-full max-w-md p-8">
<div class="text-center mb-8">
<h1 class="text-2xl font-bold text-gray-900 mb-2">Claude Code Hook</h1>
<p class="text-gray-600">请输入密码登录系统</p>
</div>
<form id="login-form" class="space-y-6">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">密码</label>
<input type="password" id="password" required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="请输入密码">
</div>
<button type="submit"
class="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition-colors">
登录
</button>
</form>
<div id="error-message" class="mt-4 text-red-600 text-sm hidden"></div>
<div class="mt-8 text-center text-sm text-gray-500">
<p>首次登录默认密码: <code class="bg-gray-100 px-1 rounded">admin</code></p>
<p>登录后将要求修改密码</p>
</div>
</div>
<script>
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const password = document.getElementById('password').value;
const errorDiv = document.getElementById('error-message');
try {
const response = await fetch('/_api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ password })
});
const result = await response.json();
if (response.ok) {
// 登录成功,跳转到主页
window.location.href = '/';
} else {
errorDiv.textContent = result.detail || '登录失败';
errorDiv.classList.remove('hidden');
}
} catch (error) {
errorDiv.textContent = '网络错误,请重试';
errorDiv.classList.remove('hidden');
}
});
</script>
</body>
</html>
"""
return HTMLResponse(content=login_html)
@app.get("/change-password", response_class=HTMLResponse)
async def change_password_page(first: Optional[str] = None):
"""修改密码页面"""
is_first = first == "true"
title = "首次登录 - 修改密码" if is_first else "修改密码"
description = "首次登录需要修改默认密码" if is_first else "请输入新密码"
change_password_html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title} - Claude Code Hook</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
<div class="bg-white rounded-lg shadow-xl w-full max-w-md p-8">
<div class="text-center mb-8">
<h1 class="text-2xl font-bold text-gray-900 mb-2">{title}</h1>
<p class="text-gray-600">{description}</p>
</div>
<form id="change-password-form" class="space-y-6">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">当前密码</label>
<input type="password" id="current-password" required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="请输入当前密码">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">新密码</label>
<input type="password" id="new-password" required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="请输入新密码(至少6位)" minlength="6">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">确认新密码</label>
<input type="password" id="confirm-password" required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="请再次输入新密码">
</div>
<button type="submit"
class="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition-colors">
修改密码
</button>
</form>
<div id="error-message" class="mt-4 text-red-600 text-sm hidden"></div>
<div id="success-message" class="mt-4 text-green-600 text-sm hidden"></div>
</div>
<script>
document.getElementById('change-password-form').addEventListener('submit', async function(e) {{
e.preventDefault();
const currentPassword = document.getElementById('current-password').value;
const newPassword = document.getElementById('new-password').value;
const confirmPassword = document.getElementById('confirm-password').value;
const errorDiv = document.getElementById('error-message');
const successDiv = document.getElementById('success-message');
errorDiv.classList.add('hidden');
successDiv.classList.add('hidden');
if (newPassword !== confirmPassword) {{
errorDiv.textContent = '两次输入的密码不一致';
errorDiv.classList.remove('hidden');
return;
}}
if (newPassword.length < 6) {{
errorDiv.textContent = '新密码至少需要6位';
errorDiv.classList.remove('hidden');
return;
}}
try {{
const response = await fetch('/_api/change-password', {{
method: 'POST',
headers: {{ 'Content-Type': 'application/json' }},
body: JSON.stringify({{
current_password: currentPassword,
new_password: newPassword
}})
}});
const result = await response.json();
if (response.ok) {{
successDiv.textContent = '密码修改成功,即将跳转到主页...';
successDiv.classList.remove('hidden');
setTimeout(function() {{ window.location.href = '/'; }}, 2000);
}} else {{
errorDiv.textContent = result.detail || '修改密码失败';
errorDiv.classList.remove('hidden');
}}
}} catch (error) {{
errorDiv.textContent = '网络错误,请重试';
errorDiv.classList.remove('hidden');
}}
}});
</script>
</body>
</html>"""
return HTMLResponse(content=change_password_html)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
# 处理来自前端的消息
message = json.loads(data)
if message.get("type") == "ping":
await websocket.send_text(json.dumps({"type": "pong"}))
except WebSocketDisconnect:
manager.disconnect(websocket)
# 认证API端点
@app.post("/_api/login")
async def login(request: Request, db: Session = Depends(get_db)):
"""用户登录"""
data = await request.json()
password = data.get("password")
if not password:
raise HTTPException(status_code=400, detail="密码不能为空")
# 查找用户
user = db.query(UserAuth).first()
if not user:
raise HTTPException(status_code=401, detail="用户不存在")
# 验证密码
if not verify_password(password, user.password_hash, user.salt):
raise HTTPException(status_code=401, detail="密码错误")
# 创建会话
session_token = generate_session_token()
expires_at = datetime.utcnow() + timedelta(days=7) # 7天有效期
session = LoginSession(
session_token=session_token,
expires_at=expires_at
)
db.add(session)
# 更新最后登录时间
user.last_login = datetime.utcnow()
db.commit()
# 设置Cookie
response = JSONResponse({"message": "登录成功"})
response.set_cookie(
key="session_token",
value=session_token,
max_age=7 * 24 * 60 * 60, # 7天
httponly=True,
secure=False, # 开发环境设为False,生产环境应设为True
samesite="lax"
)
return response
@app.post("/_api/change-password")
async def change_password(request: Request, db: Session = Depends(get_db)):
"""修改密码"""
data = await request.json()
current_password = data.get("current_password")
new_password = data.get("new_password")
if not current_password or not new_password:
raise HTTPException(status_code=400, detail="当前密码和新密码不能为空")
if len(new_password) < 6:
raise HTTPException(status_code=400, detail="新密码至少需要6位")
# 查找用户
user = db.query(UserAuth).first()
if not user:
raise HTTPException(status_code=401, detail="用户不存在")
# 验证当前密码
if not verify_password(current_password, user.password_hash, user.salt):
raise HTTPException(status_code=401, detail="当前密码错误")
# 更新密码
new_hash, new_salt = hash_password(new_password)
user.password_hash = new_hash
user.salt = new_salt
user.is_first_login = False # 标记已不是首次登录
user.updated_at = datetime.utcnow()
db.commit()
return {"message": "密码修改成功"}
@app.post("/_api/logout")
async def logout(request: Request, db: Session = Depends(get_db)):
"""用户登出"""
session_token = request.cookies.get("session_token")
if session_token:
# 删除会话记录
db.query(LoginSession).filter(
LoginSession.session_token == session_token
).delete()
db.commit()
response = JSONResponse({"message": "登出成功"})
response.delete_cookie("session_token")
return response
@app.get("/control/config")
async def get_config(session: LoginSession = Depends(require_auth)):
logger.info(f"📋 [Config] 前端请求获取配置,当前工作模式: {config_data.get('current_work_mode')}")
return config_data
@app.post("/control/config")
async def update_config(request: Request, session: LoginSession = Depends(require_auth)):
global config_data
new_config = await request.json()
logger.info(f"🔄 [Config] 收到配置更新请求: {json.dumps(new_config, ensure_ascii=False)}")
# 如果工作模式发生变化,持久化到数据库
if "current_work_mode" in new_config and new_config["current_work_mode"] != config_data.get("current_work_mode"):
old_mode = config_data.get("current_work_mode")
save_system_config("current_work_mode", new_config["current_work_mode"])
logger.info(f"🔄 [Config] 工作模式切换: {old_mode} -> {new_config['current_work_mode']}")
config_data.update(new_config)
await manager.broadcast({"type": "config_updated", "config": config_data})
logger.info(f"✅ [Config] 配置更新完成并广播: {json.dumps(config_data, ensure_ascii=False)}")
return {"message": "配置已更新", "config": config_data}
@app.post("/control/clear-records")
async def clear_records(session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
try:
db.query(APIRecord).delete()
db.commit()
return {"message": "记录已清空"}
except Exception as e:
return JSONResponse(status_code=500, content={"error": f"清空记录失败: {str(e)}"})
@app.get("/control/debug-status")
async def get_debug_status(session: LoginSession = Depends(require_auth)):
"""获取后端DEBUG模式状态"""
return {"debug_mode": DEBUG_MODE}
# 多平台API端点
@app.get("/_api/platforms")
async def get_platforms(session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""获取所有平台配置"""
platforms = db.query(PlatformConfig).all()
return [
{
"id": platform.id,
"platform_type": platform.platform_type,
"api_key": platform.api_key or "", # 不再隐藏,直接显示完整API Key
"base_url": platform.base_url,
"enabled": platform.enabled,
"timeout": platform.timeout
}
for platform in platforms
]
@app.post("/_api/platforms")
async def create_or_update_platform(request: Request, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""创建或更新平台配置"""
try:
data = await request.json()
platform_type = data.get("platform_type")
# 查找已存在的配置
existing = db.query(PlatformConfig).filter(
PlatformConfig.platform_type == platform_type
).first()
if existing:
# 更新现有配置
if data.get("api_key"):
existing.api_key = data["api_key"]
if data.get("base_url"):
existing.base_url = data["base_url"]
if "enabled" in data:
existing.enabled = data["enabled"]
if data.get("timeout"):
existing.timeout = data["timeout"]
else:
# 创建新配置
new_platform = PlatformConfig(
platform_type=platform_type,
api_key=data.get("api_key", ""),
base_url=data.get("base_url", ""),
enabled=data.get("enabled", True),
timeout=data.get("timeout", 30)
)
db.add(new_platform)
db.commit()
# 重新初始化多平台服务
await multi_platform_service.initialize(db)
return {"message": "平台配置已保存"}
except Exception as e:
return JSONResponse(status_code=500, content={"error": f"保存平台配置失败: {str(e)}"})
@app.get("/_api/models")
async def get_models(session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""获取所有可用模型"""
import logging
logger = logging.getLogger(__name__)
logger.info("🔍 [API] 收到获取模型列表请求")
try:
models = await multi_platform_service.get_available_models(db)
logger.info(f"✅ [API] 成功返回 {len(models)} 个模型")
return models
except Exception as e:
logger.error(f"❌ [API] 获取模型列表失败: {e}")
return JSONResponse(status_code=500, content={"error": f"获取模型列表失败: {str(e)}"})
@app.get("/_api/models/from-db")
async def get_models_from_db(session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""从数据库获取模型信息(用于配置恢复)"""
try:
model_configs = db.query(ModelConfig).filter(ModelConfig.enabled == True).all()
models = []
for config in model_configs:
models.append({
"id": config.model_id,
"name": config.model_name or config.model_id,
"platform": config.platform_type,
"description": config.description or "",
"enabled": config.enabled
})
return models
except Exception as e:
import logging
logger = logging.getLogger(__name__)
logger.error(f"获取数据库模型列表失败: {e}")
return JSONResponse(status_code=500, content={"error": f"获取数据库模型列表失败: {str(e)}"})
@app.post("/_api/models/refresh")
async def refresh_models(request: Request, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""刷新模型列表"""
import logging
logger = logging.getLogger(__name__)
logger.info("🔄 [API] 收到刷新模型列表请求")
try:
data = await request.json()
platform_type = data.get("platform_type")
logger.info(f"🎯 [API] 刷新平台: {platform_type if platform_type else '所有平台'}")
await multi_platform_service.refresh_models(db, platform_type)
logger.info("✅ [API] 模型列表刷新完成")
return {"message": "模型列表已刷新"}
except Exception as e:
logger.error(f"❌ [API] 刷新模型列表失败: {e}")
return JSONResponse(status_code=500, content={"error": f"刷新模型列表失败: {str(e)}"})
@app.get("/_api/platforms/test")
async def test_platform_connections(session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""测试平台连接"""
try:
results = await multi_platform_service.test_platform_connections(db)
return results
except Exception as e:
return JSONResponse(status_code=500, content={"error": f"测试连接失败: {str(e)}"})
@app.post("/_api/platforms/test-single")
async def test_single_platform(request: Request, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""测试单个平台连接"""
import logging
logger = logging.getLogger(__name__)
try:
data = await request.json()
platform_type = data.get("platform_type")
test_message = data.get("test_message", "你好")
logger.info(f"🧪 [API] 测试单个平台: {platform_type}")
if not platform_type:
return JSONResponse(status_code=400, content={"error": "缺少platform_type参数"})
# 重新初始化服务以加载最新配置
await multi_platform_service.initialize(db)
# 测试连接
results = await multi_platform_service.test_platform_connections(db)
platform_success = results.get(platform_type, False)
if platform_success:
# 如果连接成功,尝试发送测试消息
try:
# 这里可以进一步测试实际的API调用
logger.info(f"✅ [API] {platform_type} 连接测试成功")
return {"success": True, "message": f"{platform_type} 连接成功"}
except Exception as test_error:
logger.error(f"❌ [API] {platform_type} 测试消息发送失败: {test_error}")
return {"success": False, "error": f"连接成功但测试消息失败: {str(test_error)}"}
else:
logger.error(f"❌ [API] {platform_type} 连接失败")
return {"success": False, "error": f"{platform_type} 连接失败"}
except Exception as e:
logger.error(f"❌ [API] 测试单个平台出错: {e}")
return JSONResponse(status_code=500, content={"error": f"测试失败: {str(e)}"})
@app.get("/_api/routing")
async def get_routing_config(session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""获取路由配置"""
try:
# 确保多平台服务已初始化
if not multi_platform_service.initialized:
await multi_platform_service.initialize(db)
# 获取当前激活的配置
active_config = db.query(RoutingConfig).filter(
RoutingConfig.is_active == True
).first()
# 获取所有配置类型
all_configs = db.query(RoutingConfig).all()
configs_by_type = {}
for config in all_configs:
config_data = {}
if config.config_data:
try:
config_data = json.loads(config.config_data)
except json.JSONDecodeError:
continue
# 如果是智能路由配置,从RoutingScene表中获取最新的场景配置
if config.config_type == "smart_routing":
scenes = db.query(RoutingScene).filter(
RoutingScene.routing_config_id == config.id
).order_by(RoutingScene.priority).all()
scene_list = []
for scene in scenes:
try:
models = json.loads(scene.models) if scene.models else []
scene_data = {
"name": scene.scene_name,
"description": scene.scene_description,
"models": models,
"enabled": scene.enabled,
"priority": scene.priority
}
# 标记默认场景
if scene.scene_name == "默认对话":
scene_data["is_default"] = True
scene_list.append(scene_data)
except json.JSONDecodeError:
continue
config_data["scenes"] = scene_list
configs_by_type[config.config_type] = {
"id": config.id,
"name": config.config_name,
"type": config.config_type,
"data": config_data,
"is_active": config.is_active
}
# 使用主配置系统的工作模式,而不是路由管理器的模式
current_mode = config_data.get("current_work_mode", "claude_code")
logger.info(f"📋 [Config] 路由配置API返回当前工作模式: {current_mode}")
return {
"current_mode": current_mode,
"active_config": configs_by_type.get(active_config.config_type) if active_config else None,
"all_configs": configs_by_type
}
except Exception as e:
return JSONResponse(status_code=500, content={"error": f"获取路由配置失败: {str(e)}"})
@app.post("/_api/routing")
async def update_routing_config(request: Request, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""更新路由配置"""
try:
data = await request.json()
config_name = data.get("config_name")
config_type = data.get("config_type")
config_data = data.get("config_data", {})
# 查找现有配置
existing = db.query(RoutingConfig).filter(
RoutingConfig.config_name == config_name
).first()
# 只有在保存成功后才将其他配置设为非激活状态
if existing:
existing.config_type = config_type
existing.config_data = json.dumps(config_data)
existing.is_active = True
config_id = existing.id
else:
new_config = RoutingConfig(
config_name=config_name,
config_type=config_type,
config_data=json.dumps(config_data),
is_active=True
)
db.add(new_config)
db.flush() # 获取生成的ID
config_id = new_config.id
# 如果是智能路由配置,保存场景到数据库
if config_type == "smart_routing" and "scenes" in config_data:
print(f"🔧 [Backend] 开始处理智能路由场景配置,config_id: {config_id}")
# 删除现有场景
deleted_count = db.query(RoutingScene).filter(
RoutingScene.routing_config_id == config_id
).delete()
print(f"🗑️ [Backend] 删除了 {deleted_count} 个现有场景")
# 添加默认场景(如果不存在)
scenes = config_data.get("scenes", [])
print(f"📋 [Backend] 收到 {len(scenes)} 个场景配置")
default_scene_exists = any(scene.get("name") == "默认对话" and scene.get("is_default") for scene in scenes)
print(f"🔍 [Backend] 默认场景是否存在: {default_scene_exists}")
if not default_scene_exists:
# 在列表开头插入默认场景
default_scene = {
"name": "默认对话",
"description": "当系统无法识别具体场景时使用的默认对话模式",
"models": ["qwen-plus"],
"enabled": True,
"priority": 0,
"is_default": True
}
scenes.insert(0, default_scene)
# 调整其他场景的优先级
for i, scene in enumerate(scenes[1:], 1):
scene["priority"] = i
# 更新config_data
config_data["scenes"] = scenes
if existing:
existing.config_data = json.dumps(config_data)
else:
new_config.config_data = json.dumps(config_data)
# 保存场景到RoutingScene表
print(f"💾 [Backend] 开始保存 {len(scenes)} 个场景到数据库")
for i, scene in enumerate(scenes):
scene_record = RoutingScene(
routing_config_id=config_id,
scene_name=scene["name"],
scene_description=scene["description"],
models=json.dumps(scene["models"]),
priority=scene.get("priority", 0),
enabled=scene.get("enabled", True)
)
db.add(scene_record)
print(f"✅ [Backend] 添加场景 {i+1}: {scene['name']}")
else:
print(f"⏭️ [Backend] 跳过场景保存,config_type: {config_type}, has_scenes: {'scenes' in config_data if config_data else False}")
# 先提交当前配置的更改
db.commit()
# 成功保存后,将其他配置设为非激活状态
db.query(RoutingConfig).filter(
RoutingConfig.id != config_id
).update({"is_active": False})
db.commit()
# 重新初始化多平台服务
await multi_platform_service.initialize(db)
return {"message": "路由配置已保存"}
except Exception as e:
return JSONResponse(status_code=500, content={"error": f"保存路由配置失败: {str(e)}"})
@app.get("/_api/records")
async def get_records(limit: int = 100, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
records = db.query(APIRecord).order_by(desc(APIRecord.timestamp)).limit(limit).all()
return [
{
"id": record.id,
"method": record.method,
"path": record.path,
"timestamp": record.timestamp.isoformat(),
"response_status": record.response_status,
"duration_ms": record.duration_ms,
"user_key_id": record.user_key_id,
"target_platform": record.target_platform,
"target_model": record.target_model,
"token_usage": {
"input_tokens": record.input_tokens or 0,
"output_tokens": record.output_tokens or 0,
"total_tokens": record.total_tokens or 0
} if (record.input_tokens or 0) + (record.output_tokens or 0) > 0 else None
}
for record in records
]
@app.get("/_api/records/{record_id}")
async def get_record_detail(record_id: int, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
from database import UserKey
record = db.query(APIRecord).filter(APIRecord.id == record_id).first()
if not record:
return JSONResponse(status_code=404, content={"message": "记录未找到"})
# 获取Token使用量(优先使用数据库字段,fallback到解析)
if record.input_tokens is not None or record.output_tokens is not None or record.total_tokens is not None:
token_info = {
"input_tokens": record.input_tokens or 0,
"output_tokens": record.output_tokens or 0,
"total_tokens": record.total_tokens or 0
}
else:
# 如果数据库字段为空,回退到解析response_body
token_info = parse_token_usage(record.response_body)
# 获取关联的KEY信息
key_info = None
if record.user_key_id:
user_key = db.query(UserKey).filter(UserKey.id == record.user_key_id).first()
if user_key:
key_info = {
"id": user_key.id,
"key_name": user_key.key_name,
"api_key": user_key.api_key[-8:] + "..." if len(user_key.api_key) > 8 else user_key.api_key # 只显示后8位
}
return {
"id": record.id,
"method": record.method,
"path": record.path,
"headers": json.loads(record.headers) if record.headers else {},
"body": record.body,
"response_status": record.response_status,
"response_headers": json.loads(record.response_headers) if record.response_headers else {},
"response_body": record.response_body,
"timestamp": record.timestamp.isoformat(),
"duration_ms": record.duration_ms,
"target_platform": record.target_platform,
"target_model": record.target_model,
"platform_base_url": record.platform_base_url,
"processed_prompt": record.processed_prompt,
"processed_headers": record.processed_headers,
"model_raw_headers": record.model_raw_headers,
"model_raw_response": record.model_raw_response,
"routing_scene": record.routing_scene,
"user_key_id": record.user_key_id,
"key_info": key_info,
"token_usage": token_info
}
# ==================== Claude Code 服务器管理 API ====================
@app.get("/_api/claude-code-servers")
async def get_claude_code_servers(session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""获取所有Claude Code服务器配置"""
servers = db.query(ClaudeCodeServer).order_by(ClaudeCodeServer.priority, ClaudeCodeServer.id).all()
return [
{
"id": server.id,
"name": server.name,
"url": server.url,
"api_key": server.api_key,
"timeout": server.timeout,
"priority": server.priority,
"enabled": server.enabled,
"created_at": server.created_at.isoformat(),
"updated_at": server.updated_at.isoformat()
}
for server in servers
]
@app.post("/_api/claude-code-servers")
async def create_claude_code_server(request: Request, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""创建新的Claude Code服务器配置"""
try:
data = await request.json()
name = data.get("name", "").strip()
url = data.get("url", "").strip()
api_key = data.get("api_key", "").strip()
timeout = data.get("timeout", 600)
priority = data.get("priority", 0)
enabled = data.get("enabled", True)
if not name:
return JSONResponse(status_code=400, content={"error": "服务器名称不能为空"})
if not url:
return JSONResponse(status_code=400, content={"error": "服务器地址不能为空"})
# 检查名称是否重复
existing_server = db.query(ClaudeCodeServer).filter(ClaudeCodeServer.name == name).first()
if existing_server:
return JSONResponse(status_code=400, content={"error": "服务器名称已存在"})
# 创建新服务器配置
new_server = ClaudeCodeServer(
name=name,
url=url,
api_key=api_key,
timeout=timeout,
priority=priority,
enabled=enabled
)
db.add(new_server)
db.commit()
db.refresh(new_server)
return {
"id": new_server.id,
"name": new_server.name,
"url": new_server.url,
"api_key": new_server.api_key,
"timeout": new_server.timeout,
"priority": new_server.priority,
"enabled": new_server.enabled,
"created_at": new_server.created_at.isoformat(),
"updated_at": new_server.updated_at.isoformat()
}
except Exception as e:
return JSONResponse(status_code=500, content={"error": f"创建服务器配置失败: {str(e)}"})
@app.put("/_api/claude-code-servers/{server_id}")
async def update_claude_code_server(server_id: int, request: Request, session: LoginSession = Depends(require_auth), db: Session = Depends(get_db)):
"""更新Claude Code服务器配置"""
try:
server = db.query(ClaudeCodeServer).filter(ClaudeCodeServer.id == server_id).first()
if not server: