forked from yukkcat/gemini-business2api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1752 lines (1502 loc) · 71.1 KB
/
main.py
File metadata and controls
1752 lines (1502 loc) · 71.1 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
import json, time, os, asyncio, uuid, ssl, re, yaml, shutil, base64
from datetime import datetime, timezone, timedelta
from typing import List, Optional, Union, Dict, Any
from pathlib import Path
import logging
from dotenv import load_dotenv
import httpx
import aiofiles
from fastapi import FastAPI, HTTPException, Header, Request, Body, Form
from fastapi.responses import StreamingResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from util.streaming_parser import parse_json_array_stream_async
from collections import deque
from threading import Lock
# ---------- 数据目录配置 ----------
# 自动检测环境:HF Spaces Pro 使用 /data,本地使用 ./data
if os.path.exists("/data"):
DATA_DIR = "/data" # HF Pro 持久化存储
logger_prefix = "[HF-PRO]"
else:
DATA_DIR = "./data" # 本地持久化存储
logger_prefix = "[LOCAL]"
# 确保数据目录存在
os.makedirs(DATA_DIR, exist_ok=True)
# 统一的数据文件路径
ACCOUNTS_FILE = os.path.join(DATA_DIR, "accounts.json")
SETTINGS_FILE = os.path.join(DATA_DIR, "settings.yaml")
STATS_FILE = os.path.join(DATA_DIR, "stats.json")
IMAGE_DIR = os.path.join(DATA_DIR, "images")
# 确保图片目录存在
os.makedirs(IMAGE_DIR, exist_ok=True)
# 导入认证模块
from core.auth import verify_api_key
from core.session_auth import is_logged_in, login_user, logout_user, require_login, generate_session_secret
# 导入核心模块
from core.message import (
get_conversation_key,
parse_last_message,
build_full_context_text
)
from core.google_api import (
get_common_headers,
create_google_session,
upload_context_file,
get_session_file_metadata,
download_image_with_jwt,
save_image_to_hf
)
from core.account import (
AccountManager,
MultiAccountManager,
format_account_expiration,
load_multi_account_config,
load_accounts_from_source,
update_accounts_config as _update_accounts_config,
delete_account as _delete_account,
update_account_disabled_status as _update_account_disabled_status
)
# 导入 Uptime 追踪器
from core import uptime as uptime_tracker
# 导入配置管理和模板系统
from fastapi.templating import Jinja2Templates
from core.config import config_manager, config
from util.template_helpers import prepare_admin_template_data
# ---------- 日志配置 ----------
# 内存日志缓冲区 (保留最近 3000 条日志,重启后清空)
log_buffer = deque(maxlen=3000)
log_lock = Lock()
# 统计数据持久化
stats_lock = asyncio.Lock() # 改为异步锁
async def load_stats():
"""加载统计数据(异步)"""
try:
if os.path.exists(STATS_FILE):
async with aiofiles.open(STATS_FILE, 'r', encoding='utf-8') as f:
content = await f.read()
return json.loads(content)
except Exception:
pass
return {
"total_visitors": 0,
"total_requests": 0,
"request_timestamps": [], # 最近1小时的请求时间戳
"visitor_ips": {}, # {ip: timestamp} 记录访问IP和时间
"account_conversations": {} # {account_id: conversation_count} 账户对话次数
}
async def save_stats(stats):
"""保存统计数据(异步,避免阻塞事件循环)"""
try:
async with aiofiles.open(STATS_FILE, 'w', encoding='utf-8') as f:
await f.write(json.dumps(stats, ensure_ascii=False, indent=2))
except Exception as e:
logger.error(f"[STATS] 保存统计数据失败: {str(e)[:50]}")
# 初始化统计数据(需要在启动时异步加载)
global_stats = {
"total_visitors": 0,
"total_requests": 0,
"request_timestamps": [],
"visitor_ips": {},
"account_conversations": {}
}
class MemoryLogHandler(logging.Handler):
"""自定义日志处理器,将日志写入内存缓冲区"""
def emit(self, record):
log_entry = self.format(record)
# 转换为北京时间(UTC+8)
beijing_tz = timezone(timedelta(hours=8))
beijing_time = datetime.fromtimestamp(record.created, tz=beijing_tz)
with log_lock:
log_buffer.append({
"time": beijing_time.strftime("%Y-%m-%d %H:%M:%S"),
"level": record.levelname,
"message": record.getMessage()
})
# 配置日志
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger("gemini")
# 添加内存日志处理器
memory_handler = MemoryLogHandler()
memory_handler.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s", datefmt="%H:%M:%S"))
logger.addHandler(memory_handler)
# ---------- 配置管理(使用统一配置系统)----------
# 所有配置通过 config_manager 访问,优先级:环境变量 > YAML > 默认值
TIMEOUT_SECONDS = 600
API_KEY = config.basic.api_key
PATH_PREFIX = config.security.path_prefix
ADMIN_KEY = config.security.admin_key
PROXY = config.basic.proxy
BASE_URL = config.basic.base_url
SESSION_SECRET_KEY = config.security.session_secret_key
SESSION_EXPIRE_HOURS = config.session.expire_hours
# ---------- 公开展示配置 ----------
LOGO_URL = config.public_display.logo_url
CHAT_URL = config.public_display.chat_url
# ---------- 图片生成配置 ----------
IMAGE_GENERATION_ENABLED = config.image_generation.enabled
IMAGE_GENERATION_MODELS = config.image_generation.supported_models
# ---------- 重试配置 ----------
MAX_NEW_SESSION_TRIES = config.retry.max_new_session_tries
MAX_REQUEST_RETRIES = config.retry.max_request_retries
MAX_ACCOUNT_SWITCH_TRIES = config.retry.max_account_switch_tries
ACCOUNT_FAILURE_THRESHOLD = config.retry.account_failure_threshold
RATE_LIMIT_COOLDOWN_SECONDS = config.retry.rate_limit_cooldown_seconds
SESSION_CACHE_TTL_SECONDS = config.retry.session_cache_ttl_seconds
# ---------- 模型映射配置 ----------
MODEL_MAPPING = {
"gemini-auto": None,
"gemini-2.5-flash": "gemini-2.5-flash",
"gemini-2.5-pro": "gemini-2.5-pro",
"gemini-3-flash-preview": "gemini-3-flash-preview",
"gemini-3-pro-preview": "gemini-3-pro-preview"
}
# ---------- HTTP 客户端 ----------
http_client = httpx.AsyncClient(
proxy=PROXY or None,
verify=False,
http2=False,
timeout=httpx.Timeout(TIMEOUT_SECONDS, connect=60.0),
limits=httpx.Limits(
max_keepalive_connections=100, # 增加5倍:20 -> 100
max_connections=200 # 增加4倍:50 -> 200
)
)
# ---------- 工具函数 ----------
def get_base_url(request: Request) -> str:
"""获取完整的base URL(优先环境变量,否则从请求自动获取)"""
# 优先使用环境变量
if BASE_URL:
return BASE_URL.rstrip("/")
# 自动从请求获取(兼容反向代理)
forwarded_proto = request.headers.get("x-forwarded-proto", request.url.scheme)
forwarded_host = request.headers.get("x-forwarded-host", request.headers.get("host"))
return f"{forwarded_proto}://{forwarded_host}"
# ---------- 常量定义 ----------
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
# ---------- 多账户支持 ----------
# (AccountConfig, AccountManager, MultiAccountManager 已移至 core/account.py)
# ---------- 配置文件管理 ----------
# (配置管理函数已移至 core/account.py)
# 初始化多账户管理器
multi_account_mgr = load_multi_account_config(
http_client,
USER_AGENT,
ACCOUNT_FAILURE_THRESHOLD,
RATE_LIMIT_COOLDOWN_SECONDS,
SESSION_CACHE_TTL_SECONDS,
global_stats
)
# 验证必需的环境变量
if not ADMIN_KEY:
logger.error("[SYSTEM] 未配置 ADMIN_KEY 环境变量,请设置后重启")
import sys
sys.exit(1)
# 启动日志
if PATH_PREFIX:
logger.info(f"[SYSTEM] 路径前缀已配置: {PATH_PREFIX[:4]}****")
logger.info(f"[SYSTEM] API端点: /{PATH_PREFIX}/v1/chat/completions")
logger.info(f"[SYSTEM] 管理端点: /{PATH_PREFIX}/")
else:
logger.info("[SYSTEM] 未配置路径前缀,使用默认路径")
logger.info("[SYSTEM] API端点: /v1/chat/completions")
logger.info("[SYSTEM] 管理端点: /admin/")
logger.info("[SYSTEM] 公开端点: /public/log/html, /public/stats, /public/uptime/html")
logger.info(f"[SYSTEM] Session过期时间: {SESSION_EXPIRE_HOURS}小时")
logger.info("[SYSTEM] 系统初始化完成")
# ---------- JWT 管理 ----------
# (JWTManager已移至 core/jwt.py)
# ---------- Session & File 管理 ----------
# (Google API函数已移至 core/google_api.py)
# ---------- 消息处理逻辑 ----------
# (消息处理函数已移至 core/message.py)
# ---------- OpenAI 兼容接口 ----------
app = FastAPI(title="Gemini-Business OpenAI Gateway")
# ---------- 模板系统配置 ----------
templates = Jinja2Templates(directory="templates")
# 开发模式:支持热更新
if os.getenv("ENV") == "development":
templates.env.auto_reload = True
logger.info("[SYSTEM] 模板热更新已启用(开发模式)")
# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")
# ---------- Session 中间件配置 ----------
from starlette.middleware.sessions import SessionMiddleware
app.add_middleware(
SessionMiddleware,
secret_key=SESSION_SECRET_KEY,
max_age=SESSION_EXPIRE_HOURS * 3600, # 转换为秒
same_site="lax",
https_only=False # 本地开发可设为False,生产环境建议True
)
# ---------- Uptime 追踪中间件 ----------
@app.middleware("http")
async def track_uptime_middleware(request: Request, call_next):
"""追踪每个请求的成功/失败状态,用于 Uptime 监控"""
# 只追踪 API 请求(排除静态文件、管理端点等)
path = request.url.path
if path.startswith("/images/") or path.startswith("/public/") or path.startswith("/favicon"):
return await call_next(request)
start_time = time.time()
success = False
model = None
try:
response = await call_next(request)
success = response.status_code < 400
# 尝试从请求中提取模型信息
if hasattr(request.state, "model"):
model = request.state.model
# 记录 API 主服务状态
uptime_tracker.record_request("api_service", success)
# 如果有模型信息,记录模型状态
if model and model in uptime_tracker.SUPPORTED_MODELS:
uptime_tracker.record_request(model, success)
return response
except Exception as e:
# 请求失败 - 尝试提取模型信息(可能在异常前已设置)
if hasattr(request.state, "model"):
model = request.state.model
uptime_tracker.record_request("api_service", False)
if model and model in uptime_tracker.SUPPORTED_MODELS:
uptime_tracker.record_request(model, False)
raise
# ---------- 图片静态服务初始化 ----------
os.makedirs(IMAGE_DIR, exist_ok=True)
app.mount("/images", StaticFiles(directory=IMAGE_DIR), name="images")
if IMAGE_DIR == "/data/images":
logger.info(f"[SYSTEM] 图片静态服务已启用: /images/ -> {IMAGE_DIR} (HF Pro持久化)")
else:
logger.info(f"[SYSTEM] 图片静态服务已启用: /images/ -> {IMAGE_DIR} (本地持久化)")
# ---------- 后台任务启动 ----------
@app.on_event("startup")
async def startup_event():
"""应用启动时初始化后台任务"""
global global_stats
# 文件迁移逻辑:将根目录的旧文件迁移到 data 目录
old_accounts = "accounts.json"
if os.path.exists(old_accounts) and not os.path.exists(ACCOUNTS_FILE):
try:
shutil.copy(old_accounts, ACCOUNTS_FILE)
logger.info(f"{logger_prefix} 已迁移 {old_accounts} -> {ACCOUNTS_FILE}")
except Exception as e:
logger.warning(f"{logger_prefix} 文件迁移失败: {e}")
# 加载统计数据
global_stats = await load_stats()
logger.info(f"[SYSTEM] 统计数据已加载: {global_stats['total_requests']} 次请求, {global_stats['total_visitors']} 位访客")
# 启动缓存清理任务
asyncio.create_task(multi_account_mgr.start_background_cleanup())
logger.info("[SYSTEM] 后台缓存清理任务已启动(间隔: 5分钟)")
# 启动 Uptime 数据聚合任务
asyncio.create_task(uptime_tracker.uptime_aggregation_task())
logger.info("[SYSTEM] Uptime 数据聚合任务已启动(间隔: 240秒)")
# ---------- 日志脱敏函数 ----------
def get_sanitized_logs(limit: int = 100) -> list:
"""获取脱敏后的日志列表,按请求ID分组并提取关键事件"""
with log_lock:
logs = list(log_buffer)
# 按请求ID分组(支持两种格式:带[req_xxx]和不带的)
request_logs = {}
orphan_logs = [] # 没有request_id的日志(如选择账户)
for log in logs:
message = log["message"]
req_match = re.search(r'\[req_([a-z0-9]+)\]', message)
if req_match:
request_id = req_match.group(1)
if request_id not in request_logs:
request_logs[request_id] = []
request_logs[request_id].append(log)
else:
# 没有request_id的日志(如选择账户),暂存
orphan_logs.append(log)
# 将orphan_logs(如选择账户)关联到对应的请求
# 策略:将orphan日志关联到时间上最接近的后续请求
for orphan in orphan_logs:
orphan_time = orphan["time"]
# 找到时间上最接近且在orphan之后的请求
closest_request_id = None
min_time_diff = None
for request_id, req_logs in request_logs.items():
if req_logs:
first_log_time = req_logs[0]["time"]
# orphan应该在请求之前或同时
if first_log_time >= orphan_time:
if min_time_diff is None or first_log_time < min_time_diff:
min_time_diff = first_log_time
closest_request_id = request_id
# 如果找到最接近的请求,将orphan日志插入到该请求的日志列表开头
if closest_request_id:
request_logs[closest_request_id].insert(0, orphan)
# 为每个请求提取关键事件
sanitized = []
for request_id, req_logs in request_logs.items():
# 收集关键信息
model = None
message_count = None
retry_events = []
final_status = "in_progress"
duration = None
start_time = req_logs[0]["time"]
# 遍历该请求的所有日志
for log in req_logs:
message = log["message"]
# 提取模型名称和消息数量(开始对话)
if '收到请求:' in message and not model:
model_match = re.search(r'收到请求: ([^ |]+)', message)
if model_match:
model = model_match.group(1)
count_match = re.search(r'(\d+)条消息', message)
if count_match:
message_count = int(count_match.group(1))
# 提取重试事件(包括失败尝试、账户切换、选择账户)
# 注意:不提取"正在重试"日志,因为它和"失败 (尝试"是配套的
if any(keyword in message for keyword in ['切换账户', '选择账户', '失败 (尝试']):
retry_events.append({
"time": log["time"],
"message": message
})
# 提取响应完成(最高优先级 - 最终成功则忽略中间错误)
if '响应完成:' in message:
time_match = re.search(r'响应完成: ([\d.]+)秒', message)
if time_match:
duration = time_match.group(1) + 's'
final_status = "success"
# 检测非流式响应完成
if '非流式响应完成' in message:
final_status = "success"
# 检测失败状态(仅在非success状态下)
if final_status != "success" and (log['level'] == 'ERROR' or '失败' in message):
final_status = "error"
# 检测超时(仅在非success状态下)
if final_status != "success" and '超时' in message:
final_status = "timeout"
# 如果没有模型信息但有错误,仍然显示
if not model and final_status == "in_progress":
continue
# 构建关键事件列表
events = []
# 1. 开始对话
if model:
events.append({
"time": start_time,
"type": "start",
"content": f"{model} | {message_count}条消息" if message_count else model
})
else:
# 没有模型信息但有错误的情况
events.append({
"time": start_time,
"type": "start",
"content": "请求处理中"
})
# 2. 重试事件
failure_count = 0 # 失败重试计数
account_select_count = 0 # 账户选择计数
for i, retry in enumerate(retry_events):
msg = retry["message"]
# 识别不同类型的重试事件(按优先级匹配)
if '失败 (尝试' in msg:
# 创建会话失败
failure_count += 1
events.append({
"time": retry["time"],
"type": "retry",
"content": f"服务异常,正在重试({failure_count})"
})
elif '选择账户' in msg:
# 账户选择/切换
account_select_count += 1
# 检查下一条日志是否是"切换账户",如果是则跳过当前"选择账户"(避免重复)
next_is_switch = (i + 1 < len(retry_events) and '切换账户' in retry_events[i + 1]["message"])
if not next_is_switch:
if account_select_count == 1:
# 第一次选择:显示为"选择服务节点"
events.append({
"time": retry["time"],
"type": "select",
"content": "选择服务节点"
})
else:
# 第二次及以后:显示为"切换服务节点"
events.append({
"time": retry["time"],
"type": "switch",
"content": "切换服务节点"
})
elif '切换账户' in msg:
# 运行时切换账户(显示为"切换服务节点")
events.append({
"time": retry["time"],
"type": "switch",
"content": "切换服务节点"
})
# 3. 完成事件
if final_status == "success":
if duration:
events.append({
"time": req_logs[-1]["time"],
"type": "complete",
"status": "success",
"content": f"响应完成 | 耗时{duration}"
})
else:
events.append({
"time": req_logs[-1]["time"],
"type": "complete",
"status": "success",
"content": "响应完成"
})
elif final_status == "error":
events.append({
"time": req_logs[-1]["time"],
"type": "complete",
"status": "error",
"content": "请求失败"
})
elif final_status == "timeout":
events.append({
"time": req_logs[-1]["time"],
"type": "complete",
"status": "timeout",
"content": "请求超时"
})
sanitized.append({
"request_id": request_id,
"start_time": start_time,
"status": final_status,
"events": events
})
# 按时间排序并限制数量
sanitized.sort(key=lambda x: x["start_time"], reverse=True)
return sanitized[:limit]
class Message(BaseModel):
role: str
content: Union[str, List[Dict[str, Any]]]
class ChatRequest(BaseModel):
model: str = "gemini-auto"
messages: List[Message]
stream: bool = False
temperature: Optional[float] = 0.7
top_p: Optional[float] = 1.0
def create_chunk(id: str, created: int, model: str, delta: dict, finish_reason: Union[str, None]) -> str:
chunk = {
"id": id,
"object": "chat.completion.chunk",
"created": created,
"model": model,
"choices": [{
"index": 0,
"delta": delta,
"logprobs": None, # OpenAI 标准字段
"finish_reason": finish_reason
}],
"system_fingerprint": None # OpenAI 标准字段(可选)
}
return json.dumps(chunk)
# ---------- 辅助函数 ----------
def get_admin_template_data(request: Request):
"""获取管理页面模板数据(避免重复代码)"""
return prepare_admin_template_data(
request, multi_account_mgr, log_buffer, log_lock,
api_key=API_KEY, base_url=BASE_URL, proxy=PROXY,
logo_url=LOGO_URL, chat_url=CHAT_URL, path_prefix=PATH_PREFIX,
max_new_session_tries=MAX_NEW_SESSION_TRIES,
max_request_retries=MAX_REQUEST_RETRIES,
max_account_switch_tries=MAX_ACCOUNT_SWITCH_TRIES,
account_failure_threshold=ACCOUNT_FAILURE_THRESHOLD,
rate_limit_cooldown_seconds=RATE_LIMIT_COOLDOWN_SECONDS,
session_cache_ttl_seconds=SESSION_CACHE_TTL_SECONDS
)
# ---------- 路由定义 ----------
@app.get("/")
async def home(request: Request):
"""首页 - 根据PATH_PREFIX配置决定行为"""
if PATH_PREFIX:
# 如果设置了PATH_PREFIX(隐藏模式),首页返回404,不暴露任何信息
raise HTTPException(404, "Not Found")
else:
# 未设置PATH_PREFIX(公开模式),根据登录状态重定向
if is_logged_in(request):
template_data = get_admin_template_data(request)
return templates.TemplateResponse("admin/index.html", template_data)
else:
return RedirectResponse(url="/login", status_code=302)
# ---------- 登录/登出端点(支持可选PATH_PREFIX) ----------
# 不带PATH_PREFIX的登录端点
@app.get("/login")
async def admin_login_get(request: Request, error: str = None):
"""登录页面"""
return templates.TemplateResponse("auth/login.html", {"request": request, "error": error})
@app.post("/login")
async def admin_login_post(request: Request, admin_key: str = Form(...)):
"""处理登录表单提交"""
if admin_key == ADMIN_KEY:
login_user(request)
logger.info(f"[AUTH] 管理员登录成功")
return RedirectResponse(url="/", status_code=302)
else:
logger.warning(f"[AUTH] 登录失败 - 密钥错误")
return templates.TemplateResponse("auth/login.html", {"request": request, "error": "密钥错误,请重试"})
@app.post("/logout")
@require_login(redirect_to_login=False)
async def admin_logout(request: Request):
"""登出"""
logout_user(request)
logger.info(f"[AUTH] 管理员已登出")
return RedirectResponse(url="/login", status_code=302)
# 带PATH_PREFIX的登录端点(如果配置了PATH_PREFIX)
if PATH_PREFIX:
@app.get(f"/{PATH_PREFIX}/login")
async def admin_login_get_prefixed(request: Request, error: str = None):
"""登录页面(带前缀)"""
return templates.TemplateResponse("auth/login.html", {"request": request, "error": error})
@app.post(f"/{PATH_PREFIX}/login")
async def admin_login_post_prefixed(request: Request, admin_key: str = Form(...)):
"""处理登录表单提交(带前缀)"""
if admin_key == ADMIN_KEY:
login_user(request)
logger.info(f"[AUTH] 管理员登录成功")
return RedirectResponse(url=f"/{PATH_PREFIX}", status_code=302)
else:
logger.warning(f"[AUTH] 登录失败 - 密钥错误")
return templates.TemplateResponse("auth/login.html", {"request": request, "error": "密钥错误,请重试"})
@app.post(f"/{PATH_PREFIX}/logout")
@require_login(redirect_to_login=False)
async def admin_logout_prefixed(request: Request):
"""登出(带前缀)"""
logout_user(request)
logger.info(f"[AUTH] 管理员已登出")
return RedirectResponse(url=f"/{PATH_PREFIX}/login", status_code=302)
# ---------- 管理端点(需要登录) ----------
# 不带PATH_PREFIX的管理端点
@app.get("/admin")
@require_login()
async def admin_home_no_prefix(request: Request):
"""管理首页"""
template_data = get_admin_template_data(request)
return templates.TemplateResponse("admin/index.html", template_data)
# 带PATH_PREFIX的管理端点(如果配置了PATH_PREFIX)
if PATH_PREFIX:
@app.get(f"/{PATH_PREFIX}")
@require_login()
async def admin_home_prefixed(request: Request):
"""管理首页(带前缀)"""
return await admin_home_no_prefix(request=request)
# ---------- 管理API端点(需要登录) ----------
@app.get("/admin/health")
@require_login()
async def admin_health(request: Request):
return {"status": "ok", "time": datetime.utcnow().isoformat()}
@app.get("/admin/accounts")
@require_login()
async def admin_get_accounts(request: Request):
"""获取所有账户的状态信息"""
accounts_info = []
for account_id, account_manager in multi_account_mgr.accounts.items():
config = account_manager.config
remaining_hours = config.get_remaining_hours()
status, status_color, remaining_display = format_account_expiration(remaining_hours)
cooldown_seconds, cooldown_reason = account_manager.get_cooldown_info()
accounts_info.append({
"id": config.account_id,
"status": status,
"expires_at": config.expires_at or "未设置",
"remaining_hours": remaining_hours,
"remaining_display": remaining_display,
"is_available": account_manager.is_available,
"error_count": account_manager.error_count,
"disabled": config.disabled,
"cooldown_seconds": cooldown_seconds,
"cooldown_reason": cooldown_reason,
"conversation_count": account_manager.conversation_count
})
return {"total": len(accounts_info), "accounts": accounts_info}
@app.get("/admin/accounts-config")
@require_login()
async def admin_get_config(request: Request):
"""获取完整账户配置"""
try:
accounts_data = load_accounts_from_source()
return {"accounts": accounts_data}
except Exception as e:
logger.error(f"[CONFIG] 获取配置失败: {str(e)}")
raise HTTPException(500, f"获取失败: {str(e)}")
@app.put("/admin/accounts-config")
@require_login()
async def admin_update_config(request: Request, accounts_data: list = Body(...)):
"""更新整个账户配置"""
global multi_account_mgr
try:
multi_account_mgr = _update_accounts_config(
accounts_data, multi_account_mgr, http_client, USER_AGENT,
ACCOUNT_FAILURE_THRESHOLD, RATE_LIMIT_COOLDOWN_SECONDS,
SESSION_CACHE_TTL_SECONDS, global_stats
)
return {"status": "success", "message": "配置已更新", "account_count": len(multi_account_mgr.accounts)}
except Exception as e:
logger.error(f"[CONFIG] 更新配置失败: {str(e)}")
raise HTTPException(500, f"更新失败: {str(e)}")
@app.delete("/admin/accounts/{account_id}")
@require_login()
async def admin_delete_account(request: Request, account_id: str):
"""删除单个账户"""
global multi_account_mgr
try:
multi_account_mgr = _delete_account(
account_id, multi_account_mgr, http_client, USER_AGENT,
ACCOUNT_FAILURE_THRESHOLD, RATE_LIMIT_COOLDOWN_SECONDS,
SESSION_CACHE_TTL_SECONDS, global_stats
)
return {"status": "success", "message": f"账户 {account_id} 已删除", "account_count": len(multi_account_mgr.accounts)}
except Exception as e:
logger.error(f"[CONFIG] 删除账户失败: {str(e)}")
raise HTTPException(500, f"删除失败: {str(e)}")
@app.put("/admin/accounts/{account_id}/disable")
@require_login()
async def admin_disable_account(request: Request, account_id: str):
"""手动禁用账户"""
global multi_account_mgr
try:
multi_account_mgr = _update_account_disabled_status(
account_id, True, multi_account_mgr, http_client, USER_AGENT,
ACCOUNT_FAILURE_THRESHOLD, RATE_LIMIT_COOLDOWN_SECONDS,
SESSION_CACHE_TTL_SECONDS, global_stats
)
return {"status": "success", "message": f"账户 {account_id} 已禁用", "account_count": len(multi_account_mgr.accounts)}
except Exception as e:
logger.error(f"[CONFIG] 禁用账户失败: {str(e)}")
raise HTTPException(500, f"禁用失败: {str(e)}")
@app.put("/admin/accounts/{account_id}/enable")
@require_login()
async def admin_enable_account(request: Request, account_id: str):
"""启用账户(同时重置错误禁用状态)"""
global multi_account_mgr
try:
multi_account_mgr = _update_account_disabled_status(
account_id, False, multi_account_mgr, http_client, USER_AGENT,
ACCOUNT_FAILURE_THRESHOLD, RATE_LIMIT_COOLDOWN_SECONDS,
SESSION_CACHE_TTL_SECONDS, global_stats
)
# 重置运行时错误状态(允许手动恢复错误禁用的账户)
if account_id in multi_account_mgr.accounts:
account_mgr = multi_account_mgr.accounts[account_id]
account_mgr.is_available = True
account_mgr.error_count = 0
account_mgr.last_429_time = 0.0
logger.info(f"[CONFIG] 账户 {account_id} 错误状态已重置")
return {"status": "success", "message": f"账户 {account_id} 已启用", "account_count": len(multi_account_mgr.accounts)}
except Exception as e:
logger.error(f"[CONFIG] 启用账户失败: {str(e)}")
raise HTTPException(500, f"启用失败: {str(e)}")
# ---------- 系统设置 API ----------
@app.get("/admin/settings")
@require_login()
async def admin_get_settings(request: Request):
"""获取系统设置"""
# 返回当前配置(转换为字典格式)
return {
"basic": {
"api_key": config.basic.api_key,
"base_url": config.basic.base_url,
"proxy": config.basic.proxy
},
"image_generation": {
"enabled": config.image_generation.enabled,
"supported_models": config.image_generation.supported_models
},
"retry": {
"max_new_session_tries": config.retry.max_new_session_tries,
"max_request_retries": config.retry.max_request_retries,
"max_account_switch_tries": config.retry.max_account_switch_tries,
"account_failure_threshold": config.retry.account_failure_threshold,
"rate_limit_cooldown_seconds": config.retry.rate_limit_cooldown_seconds,
"session_cache_ttl_seconds": config.retry.session_cache_ttl_seconds
},
"public_display": {
"logo_url": config.public_display.logo_url,
"chat_url": config.public_display.chat_url
},
"session": {
"expire_hours": config.session.expire_hours
}
}
@app.put("/admin/settings")
@require_login()
async def admin_update_settings(request: Request, new_settings: dict = Body(...)):
"""更新系统设置"""
global API_KEY, PROXY, BASE_URL, LOGO_URL, CHAT_URL
global IMAGE_GENERATION_ENABLED, IMAGE_GENERATION_MODELS
global MAX_NEW_SESSION_TRIES, MAX_REQUEST_RETRIES, MAX_ACCOUNT_SWITCH_TRIES
global ACCOUNT_FAILURE_THRESHOLD, RATE_LIMIT_COOLDOWN_SECONDS, SESSION_CACHE_TTL_SECONDS
global SESSION_EXPIRE_HOURS, multi_account_mgr, http_client
try:
# 保存旧配置用于对比
old_proxy = PROXY
old_retry_config = {
"account_failure_threshold": ACCOUNT_FAILURE_THRESHOLD,
"rate_limit_cooldown_seconds": RATE_LIMIT_COOLDOWN_SECONDS,
"session_cache_ttl_seconds": SESSION_CACHE_TTL_SECONDS
}
# 保存到 YAML
config_manager.save_yaml(new_settings)
# 热更新配置
config_manager.reload()
# 更新全局变量(实时生效)
API_KEY = config.basic.api_key
PROXY = config.basic.proxy
BASE_URL = config.basic.base_url
LOGO_URL = config.public_display.logo_url
CHAT_URL = config.public_display.chat_url
IMAGE_GENERATION_ENABLED = config.image_generation.enabled
IMAGE_GENERATION_MODELS = config.image_generation.supported_models
MAX_NEW_SESSION_TRIES = config.retry.max_new_session_tries
MAX_REQUEST_RETRIES = config.retry.max_request_retries
MAX_ACCOUNT_SWITCH_TRIES = config.retry.max_account_switch_tries
ACCOUNT_FAILURE_THRESHOLD = config.retry.account_failure_threshold
RATE_LIMIT_COOLDOWN_SECONDS = config.retry.rate_limit_cooldown_seconds
SESSION_CACHE_TTL_SECONDS = config.retry.session_cache_ttl_seconds
SESSION_EXPIRE_HOURS = config.session.expire_hours
# 检查是否需要重建 HTTP 客户端(代理变化)
if old_proxy != PROXY:
logger.info(f"[CONFIG] 代理配置已变化,重建 HTTP 客户端")
await http_client.aclose() # 关闭旧客户端
http_client = httpx.AsyncClient(
proxy=PROXY or None,
verify=False,
http2=False,
timeout=httpx.Timeout(TIMEOUT_SECONDS, connect=60.0),
limits=httpx.Limits(
max_keepalive_connections=100,
max_connections=200
)
)
# 更新所有账户的 http_client 引用
multi_account_mgr.update_http_client(http_client)
# 检查是否需要更新账户管理器配置(重试策略变化)
retry_changed = (
old_retry_config["account_failure_threshold"] != ACCOUNT_FAILURE_THRESHOLD or
old_retry_config["rate_limit_cooldown_seconds"] != RATE_LIMIT_COOLDOWN_SECONDS or
old_retry_config["session_cache_ttl_seconds"] != SESSION_CACHE_TTL_SECONDS
)
if retry_changed:
logger.info(f"[CONFIG] 重试策略已变化,更新账户管理器配置")
# 更新所有账户管理器的配置
multi_account_mgr.cache_ttl = SESSION_CACHE_TTL_SECONDS
for account_id, account_mgr in multi_account_mgr.accounts.items():
account_mgr.account_failure_threshold = ACCOUNT_FAILURE_THRESHOLD
account_mgr.rate_limit_cooldown_seconds = RATE_LIMIT_COOLDOWN_SECONDS
logger.info(f"[CONFIG] 系统设置已更新并实时生效")
return {"status": "success", "message": "设置已保存并实时生效!"}
except Exception as e:
logger.error(f"[CONFIG] 更新设置失败: {str(e)}")
raise HTTPException(500, f"更新失败: {str(e)}")
@app.get("/admin/log")
@require_login()
async def admin_get_logs(
request: Request,
limit: int = 1500,
level: str = None,
search: str = None,
start_time: str = None,
end_time: str = None
):
with log_lock:
logs = list(log_buffer)
stats_by_level = {}
error_logs = []
chat_count = 0
for log in logs:
level_name = log.get("level", "INFO")
stats_by_level[level_name] = stats_by_level.get(level_name, 0) + 1
if level_name in ["ERROR", "CRITICAL"]:
error_logs.append(log)
if "收到请求" in log.get("message", ""):
chat_count += 1
if level:
level = level.upper()
logs = [log for log in logs if log["level"] == level]
if search:
logs = [log for log in logs if search.lower() in log["message"].lower()]
if start_time:
logs = [log for log in logs if log["time"] >= start_time]
if end_time:
logs = [log for log in logs if log["time"] <= end_time]
limit = min(limit, 3000)
filtered_logs = logs[-limit:]
return {
"total": len(filtered_logs),
"limit": limit,
"filters": {"level": level, "search": search, "start_time": start_time, "end_time": end_time},
"logs": filtered_logs,
"stats": {
"memory": {"total": len(log_buffer), "by_level": stats_by_level, "capacity": log_buffer.maxlen},
"errors": {"count": len(error_logs), "recent": error_logs[-10:]},
"chat_count": chat_count
}
}
@app.delete("/admin/log")
@require_login()
async def admin_clear_logs(request: Request, confirm: str = None):
if confirm != "yes":
raise HTTPException(400, "需要 confirm=yes 参数确认清空操作")
with log_lock:
cleared_count = len(log_buffer)
log_buffer.clear()
logger.info("[LOG] 日志已清空")
return {"status": "success", "message": "已清空内存日志", "cleared_count": cleared_count}
@app.get("/admin/log/html")
@require_login()
async def admin_logs_html_route(request: Request):
"""返回美化的 HTML 日志查看界面"""
return templates.TemplateResponse("admin/logs.html", {"request": request})
# 带PATH_PREFIX的管理API端点(如果配置了PATH_PREFIX)
if PATH_PREFIX:
@app.get(f"/{PATH_PREFIX}/health")
@require_login()
async def admin_health_prefixed(request: Request):
return await admin_health(request=request)
@app.get(f"/{PATH_PREFIX}/accounts")
@require_login()
async def admin_get_accounts_prefixed(request: Request):
return await admin_get_accounts(request=request)
@app.get(f"/{PATH_PREFIX}/accounts-config")
@require_login()
async def admin_get_config_prefixed(request: Request):
return await admin_get_config(request=request)