-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathapp.py
More file actions
1470 lines (1262 loc) · 51.7 KB
/
Copy pathapp.py
File metadata and controls
1470 lines (1262 loc) · 51.7 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
import asyncio
import time
import logging
from pathlib import Path
from contextlib import asynccontextmanager
from collections import deque
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
from fastapi.templating import Jinja2Templates
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel
import httpx
import secrets
# ============================================================
# 日志
# ============================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
)
logger = logging.getLogger("gateway")
# ============================================================
# 路径与常量
# ============================================================
import sys
if getattr(sys, 'frozen', False):
APP_DIR = Path(sys._MEIPASS)
DATA_DIR = Path(sys.executable).parent
else:
APP_DIR = Path(__file__).parent
DATA_DIR = Path(__file__).parent
DATA_FILE = DATA_DIR / "providers.json"
CONFIG_FILE = DATA_DIR / "config.json"
HISTORY_FILE = DATA_DIR / "history.jsonl"
USAGE_FILE = DATA_DIR / "usage.jsonl"
META_FILE = DATA_DIR / "models_meta.json"
ROUTERS_FILE = DATA_DIR / "routers.json"
ANNOUNCEMENT_FILE = DATA_DIR / "announcement.json"
APP_VERSION = "1.3.0"
MAX_HISTORY_DAYS = 30
MAX_USAGE_DAYS = 30
HISTORY_CLEANUP_INTERVAL = 6 * 3600
ONE_MILLION = 1048576
POLL_INTERVAL = 300
CIRCUIT_FAIL_THRESHOLD = 3
CIRCUIT_RECOVERY_SECONDS = 60
QUALITY_WINDOW = 20
# ============================================================
# 原子写入
# ============================================================
def atomic_write(path: Path, content: str):
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(content, encoding="utf-8")
tmp.replace(path)
# ============================================================
# 配置加载
# ============================================================
def load_config():
if CONFIG_FILE.exists():
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
data = {
"local_api_key": "sk-local-" + secrets.token_hex(16),
}
atomic_write(CONFIG_FILE, json.dumps(data, indent=2))
return data
def load_providers():
if DATA_FILE.exists():
return json.loads(DATA_FILE.read_text(encoding="utf-8"))
return []
def save_providers(data):
atomic_write(DATA_FILE, json.dumps(data, ensure_ascii=False, indent=2))
def load_meta():
default = {
"aliases": {},
"context_limits": {},
"non_chat_keywords": [],
"model_descriptions": {},
}
if META_FILE.exists():
default.update(json.loads(META_FILE.read_text(encoding="utf-8")))
return default
def load_routers():
if ROUTERS_FILE.exists():
try:
return json.loads(ROUTERS_FILE.read_text(encoding="utf-8"))
except:
pass
return {}
def save_routers():
ROUTERS_FILE.write_text(json.dumps(ROUTERS, indent=2, ensure_ascii=False), encoding="utf-8")
app_config = load_config()
LOCAL_API_KEY = app_config.get("local_api_key")
ROUTERS = load_routers()
meta = load_meta()
MODEL_ALIASES = meta.get("aliases", {})
CONTEXT_LIMITS = meta.get("context_limits", {})
NON_CHAT_KEYWORDS = meta.get("non_chat_keywords", [])
MODEL_DESCRIPTIONS = meta.get("model_descriptions", {})
# ============================================================
# 鉴权
# ============================================================
security = HTTPBearer(auto_error=False)
def verify_client(credentials: HTTPAuthorizationCredentials = Depends(security)):
"""客户端调用 /v1/* 的鉴权"""
if not credentials or credentials.credentials != LOCAL_API_KEY:
raise HTTPException(status_code=401, detail="Invalid or missing API Key")
return credentials
def verify_admin(credentials: HTTPAuthorizationCredentials = Depends(security)):
"""管理面板调用 /api/* 的鉴权,直接使用 local_api_key"""
if not credentials:
raise HTTPException(status_code=401, detail="Missing credentials")
if credentials.credentials != LOCAL_API_KEY:
raise HTTPException(status_code=401, detail="Invalid API key")
return credentials
# ============================================================
# 全局状态
# ============================================================
providers = load_providers()
health_status: dict = {}
model_details: dict = {}
model_quality: dict = {} # key -> {ok, fail, error, latencies: deque}
circuit_breaker: dict = {} # key -> {fails, open_until}
providers_lock = asyncio.Lock()
history_lock = asyncio.Lock()
usage_lock = asyncio.Lock()
http_client: httpx.AsyncClient | None = None
poll_task = None
last_poll_time: float = 0
last_check_time: float = time.time()
last_history_cleanup: float = 0
def mark_full_check():
"""记录一次完整检测的时间,用于重置自动轮询计时"""
global last_check_time
last_check_time = time.time()
# ============================================================
# 历史记录(异步文件 IO)
# ============================================================
def _append_history_sync(snapshot: dict):
line = json.dumps({"time": time.time(), "data": snapshot}, ensure_ascii=False) + "\n"
with open(HISTORY_FILE, "a", encoding="utf-8") as f:
f.write(line)
async def append_history(snapshot: dict):
await asyncio.to_thread(_append_history_sync, snapshot)
def _read_history_sync(hours: int):
if not HISTORY_FILE.exists():
return []
cutoff = time.time() - hours * 3600
records = []
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
for line in f:
try:
rec = json.loads(line.strip())
if rec["time"] >= cutoff:
records.append(rec)
except Exception:
pass
return records
async def read_history(hours: int = 24):
async with history_lock:
return await asyncio.to_thread(_read_history_sync, hours)
def _cleanup_history_sync():
if not HISTORY_FILE.exists():
return 0
cutoff = time.time() - MAX_HISTORY_DAYS * 86400
kept = []
removed = 0
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
for line in f:
try:
rec = json.loads(line.strip())
if rec["time"] >= cutoff:
kept.append(line if line.endswith("\n") else line + "\n")
else:
removed += 1
except Exception:
pass
if removed > 0:
atomic_write(HISTORY_FILE, "".join(kept))
return removed
async def maybe_cleanup_history():
global last_history_cleanup
now = time.time()
if now - last_history_cleanup < HISTORY_CLEANUP_INTERVAL:
return
last_history_cleanup = now
n = await asyncio.to_thread(_cleanup_history_sync)
if n:
logger.info("history cleanup: removed %d expired records", n)
un = await asyncio.to_thread(_cleanup_usage_sync)
if un:
logger.info("usage cleanup: removed %d expired records", un)
# ============================================================
# 消耗统计(异步文件 IO)
# ============================================================
def _append_usage_sync(record: dict):
line = json.dumps(record, ensure_ascii=False) + "\n"
with open(USAGE_FILE, "a", encoding="utf-8") as f:
f.write(line)
async def append_usage(record: dict):
await asyncio.to_thread(_append_usage_sync, record)
def _read_usage_sync(days: int):
if not USAGE_FILE.exists():
return []
cutoff = time.time() - days * 86400
records = []
with open(USAGE_FILE, "r", encoding="utf-8") as f:
for line in f:
try:
rec = json.loads(line.strip())
if rec.get("ts", 0) >= cutoff:
records.append(rec)
except Exception:
pass
return records
async def read_usage(days: int = 1):
async with usage_lock:
return await asyncio.to_thread(_read_usage_sync, days)
def _cleanup_usage_sync():
if not USAGE_FILE.exists():
return 0
cutoff = time.time() - MAX_USAGE_DAYS * 86400
kept = []
removed = 0
with open(USAGE_FILE, "r", encoding="utf-8") as f:
for line in f:
try:
rec = json.loads(line.strip())
if rec.get("ts", 0) >= cutoff:
kept.append(line if line.endswith("\n") else line + "\n")
else:
removed += 1
except Exception:
pass
if removed > 0:
atomic_write(USAGE_FILE, "".join(kept))
return removed
# ============================================================
# 模型工具函数
# ============================================================
def is_chat_model(model_id: str) -> bool:
lower = model_id.lower()
return not any(kw in lower for kw in NON_CHAT_KEYWORDS)
def is_free_model(model_info: dict) -> bool:
pricing = model_info.get("pricing", {})
prompt_price = pricing.get("prompt", "")
completion_price = pricing.get("completion", "")
try:
if float(prompt_price) == 0 and float(completion_price) == 0:
return True
except (ValueError, TypeError):
pass
return False
def is_free_by_name(model_id: str) -> bool:
lower = model_id.lower()
return ":free" in lower or "-free" in lower
def get_enabled_models(provider: dict) -> list[str]:
"""返回该 provider 未被禁用的模型列表"""
disabled = set(provider.get("disabled_models", []))
return [m for m in provider.get("models", []) if m not in disabled]
def get_context_length(model: str) -> int:
actual = MODEL_ALIASES.get(model, model)
ctx = CONTEXT_LIMITS.get(model) or CONTEXT_LIMITS.get(actual)
if ctx:
return ctx
return model_details.get(actual, {}).get("context_length") or 32768
def is_1m_model(model: str) -> bool:
ctx = get_context_length(model)
return bool(ctx) and ctx >= ONE_MILLION
def mask_key(key: str) -> str:
if not key:
return ""
if len(key) <= 12:
return "****"
return key[:6] + "****" + key[-4:]
# ============================================================
# 质量分(内存滑动窗口)
# ============================================================
def update_model_quality(key: str, info: dict):
q = model_quality.get(key)
if q is None:
q = {"ok": 0, "fail": 0, "error": 0, "latencies": deque(maxlen=QUALITY_WINDOW)}
model_quality[key] = q
st = info.get("status", "unknown")
if st == "ok":
q["ok"] += 1
lat = info.get("latency_ms")
if lat:
q["latencies"].append(lat)
elif st == "fail":
q["fail"] += 1
elif st == "error":
q["error"] += 1
def get_quality_score(key: str) -> float:
"""0~1 可用率,无数据返回 1.0(乐观)"""
q = model_quality.get(key)
if not q:
return 1.0
total = q["ok"] + q["fail"] + q["error"]
if total == 0:
return 1.0
return q["ok"] / total
def get_avg_latency(key: str):
q = model_quality.get(key)
if not q or not q["latencies"]:
return None
return sum(q["latencies"]) / len(q["latencies"])
# ============================================================
# 熔断
# ============================================================
def is_circuit_open(key: str) -> bool:
cb = circuit_breaker.get(key)
if not cb:
return False
return bool(cb.get("open_until")) and time.time() < cb["open_until"]
def record_fail(key: str):
cb = circuit_breaker.setdefault(key, {"fails": 0, "open_until": 0})
cb["fails"] += 1
if cb["fails"] >= CIRCUIT_FAIL_THRESHOLD:
cb["open_until"] = time.time() + CIRCUIT_RECOVERY_SECONDS
logger.warning("circuit opened: %s", key)
def record_success(key: str):
cb = circuit_breaker.get(key)
if cb:
cb["fails"] = 0
cb["open_until"] = 0
# ============================================================
# 探测
# ============================================================
async def check_model(base_url: str, api_key: str, model: str) -> dict:
actual_model = MODEL_ALIASES.get(model, model)
url = base_url.rstrip("/") + "/chat/completions"
payload = {
"model": actual_model,
"messages": [{"role": "user", "content": "hi"}],
"max_tokens": 5,
"stream": False,
}
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
start = time.time()
try:
resp = await http_client.post(url, json=payload, headers=headers, timeout=30)
latency = round((time.time() - start) * 1000)
if resp.status_code == 200:
usage = resp.json().get("usage", {})
return {
"status": "ok",
"code": resp.status_code,
"latency_ms": latency,
"prompt_tokens": usage.get("prompt_tokens", 0),
"completion_tokens": usage.get("completion_tokens", 0),
}
return {
"status": "fail",
"code": resp.status_code,
"latency_ms": latency,
"detail": resp.text[:200],
}
except Exception as e:
latency = round((time.time() - start) * 1000)
return {"status": "error", "latency_ms": latency, "detail": str(e)[:200]}
async def fetch_model_details(base_url: str, api_key: str) -> dict:
url = base_url.rstrip("/") + "/models"
headers = {"Authorization": f"Bearer {api_key}"}
try:
resp = await http_client.get(url, headers=headers, timeout=15)
if resp.status_code == 200:
data = resp.json()
model_list = data.get("data", data) if isinstance(data, dict) else data
details = {}
for m in model_list:
if isinstance(m, dict) and "id" in m:
pricing = m.get("pricing", {})
details[m["id"]] = {
"context_length": m.get("context_length"),
"prompt_price": pricing.get("prompt", ""),
"completion_price": pricing.get("completion", ""),
}
return details
except Exception:
logger.exception("fetch_model_details failed for %s", base_url)
return {}
async def fetch_models(base_url: str, api_key: str, free_only: bool = True) -> list[str]:
url = base_url.rstrip("/") + "/models"
headers = {"Authorization": f"Bearer {api_key}"}
try:
resp = await http_client.get(url, headers=headers, timeout=15)
if resp.status_code == 200:
data = resp.json()
model_list = data.get("data", data) if isinstance(data, dict) else data
if not isinstance(model_list, list):
return []
if free_only:
has_pricing = any(isinstance(m, dict) and m.get("pricing") for m in model_list)
if has_pricing:
free_by_api = [
m for m in model_list
if isinstance(m, dict) and "id" in m and is_free_model(m)
]
if free_by_api:
return [m["id"] for m in free_by_api if is_chat_model(m["id"])]
free_by_name = [
m["id"] for m in model_list
if isinstance(m, dict) and "id" in m
and is_free_by_name(m["id"]) and is_chat_model(m["id"])
]
if free_by_name:
return free_by_name
return [
m["id"] for m in model_list
if "id" in m and isinstance(m, dict) and is_chat_model(m["id"])
]
except Exception:
logger.exception("fetch_models failed for %s", base_url)
return []
# ============================================================
# 轮询
# ============================================================
async def poll_all():
global health_status, last_poll_time, last_check_time
# 首次拉取 model details
for p in list(providers):
try:
details = await fetch_model_details(p["base_url"], p["api_key"])
if details:
model_details.update(details)
except Exception:
logger.exception("initial model_details fetch failed: %s", p.get("name"))
while True:
try:
tasks = []
for p in list(providers):
for m in get_enabled_models(p):
tasks.append((p["name"], m, p["base_url"], p["api_key"]))
sem = asyncio.Semaphore(10)
async def limited_check(url, key, m):
async with sem:
return await check_model(url, key, m)
results = await asyncio.gather(
*[limited_check(url, key, m) for _, m, url, key in tasks],
return_exceptions=True,
)
new_status = {}
for (name, m, _, _), result in zip(tasks, results):
k = f"{name}||{m}"
if isinstance(result, Exception):
new_status[k] = {
"status": "error",
"detail": str(result)[:200],
"checked_at": time.time(),
}
else:
result["checked_at"] = time.time()
new_status[k] = result
update_model_quality(k, new_status[k])
health_status = new_status
last_poll_time = time.time()
last_check_time = last_poll_time
await append_history(new_status)
await maybe_cleanup_history()
ok_count = sum(1 for v in new_status.values() if v.get("status") == "ok")
logger.info("poll done: %d/%d ok", ok_count, len(new_status))
except Exception:
logger.exception("poll_all loop error")
# 等待到 last_check_time + POLL_INTERVAL;
# 若手动检测更新了 last_check_time,则顺延,避免短时间内重复轮询
while time.time() < last_check_time + POLL_INTERVAL:
await asyncio.sleep(5)
# ============================================================
# lifespan
# ============================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
global http_client, poll_task
http_client = httpx.AsyncClient(
timeout=httpx.Timeout(120.0, connect=10.0),
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
)
app.state.http = http_client
poll_task = asyncio.create_task(poll_all())
yield
if poll_task:
poll_task.cancel()
await http_client.aclose()
app = FastAPI(title="模型API网关", lifespan=lifespan)
templates = Jinja2Templates(directory=str(APP_DIR / "templates"))
templates.env.auto_reload = True
# ============================================================
# Pydantic 模型
# ============================================================
class ProviderIn(BaseModel):
name: str
base_url: str
api_key: str
models: list[str] = []
free_only: bool = True
class ProviderUpdate(BaseModel):
name: str | None = None
base_url: str | None = None
api_key: str | None = None
models: list[str] | None = None
free_only: bool | None = None
class ToggleModelIn(BaseModel):
model: str
enabled: bool
# ============================================================
# 模型选择
# ============================================================
def pick_available_models(model: str | None = None, force: bool = False) -> list[tuple[dict, str]]:
"""返回按质量排序的候选 (provider, model) 列表"""
raw = []
unhealthy_raw = []
# 1. 如果请求的是自定义路由组
if model in ROUTERS:
target_models = set(ROUTERS[model])
for p in providers:
for m in get_enabled_models(p):
if m in target_models:
k = f"{p['name']}||{m}"
if force:
raw.append((p, m, k))
continue
st = health_status.get(k, {}).get("status")
if not is_circuit_open(k) and st in ("ok", None, "unknown"):
raw.append((p, m, k))
else:
unhealthy_raw.append((p, m, k))
if not raw:
raw = unhealthy_raw
import random
random.shuffle(raw)
return [(p, m) for p, m, _ in raw]
# 3. 如果请求的是具体模型
for p in providers:
for m in get_enabled_models(p):
prefixed = f"{p['name']}-{m}"
if model and model != m and model != prefixed:
continue
k = f"{p['name']}||{m}"
if force:
raw.append((p, m, k))
continue
st = health_status.get(k, {}).get("status")
if not is_circuit_open(k) and st in ("ok", None, "unknown"):
raw.append((p, m, k))
else:
unhealthy_raw.append((p, m, k))
if not raw:
raw = unhealthy_raw
scored = [
(get_quality_score(k), get_avg_latency(k) or 1e9, p, m)
for p, m, k in raw
]
scored.sort(key=lambda x: (-x[0], x[1]))
return [(p, m) for _, _, p, m in scored]
def pick_available_model(model: str | None = None, force: bool = False):
cands = pick_available_models(model, force)
return cands[0] if cands else (None, None)
# ============================================================
# Hermes 工具名压缩 / 还原
# ============================================================
HERMES_MAP = [
("mcp_hermes_studio_use_hermes_studio_use_", "mcp_hsu_"),
("mcp_hermes_studio_devices_hermes_studio_lan_", "mcp_hsd_"),
("mcp_hermes_studio_api_hermes_studio_api_", "mcp_hsa_"),
]
def compress_hermes(obj: dict) -> dict:
s = json.dumps(obj, ensure_ascii=False)
for long, short in HERMES_MAP:
s = s.replace(long, short)
return json.loads(s)
def restore_hermes_text(text: str) -> str:
for long, short in HERMES_MAP:
text = text.replace(short, long)
return text
def merge_reasoning(obj: dict) -> dict:
"""将 reasoning_content 用 <think>...</think> 包裹后合并到 content"""
choices = obj.get("choices")
if not choices or not isinstance(choices, list):
return obj
for choice in choices:
target = choice.get("delta") or choice.get("message")
if not target or not isinstance(target, dict):
continue
rc = target.pop("reasoning_content", None)
if rc is None:
continue
wrapped = f"<think>{rc}</think>"
c = target.get("content")
if isinstance(c, str) and c:
target["content"] = c + wrapped
else:
target["content"] = wrapped
return obj
# ============================================================
# 回复语言跟随:根据用户消息语言决定回复语言
# ============================================================
LANG_HINTS = {
"zh": (
"\n\n【重要】请始终使用简体中文回答用户。"
"思考过程(reasoning)也请用中文。"
"代码、命令、文件名、专有名词、标识符等保持原样即可,不要翻译。"
),
"en": (
"\n\n[Important] Please always respond to the user in English. "
"The reasoning process should also be in English. "
"Keep code, commands, file names, proper nouns, and identifiers as-is; do not translate them."
),
}
def detect_user_lang(msgs: list) -> str:
"""检测用户最后一条文本消息的语言,返回 'zh' 或 'en'。
依据:CJK 字符数与拉丁字母数的比较,谁多跟随谁;
两者都为 0 时继续向前找;都找不到则默认 'zh'。"""
for m in reversed(msgs):
if not isinstance(m, dict) or m.get("role") != "user":
continue
c = m.get("content")
if isinstance(c, list):
# 多模态:拼接其中的 text 段
c = " ".join(
seg.get("text", "")
for seg in c
if isinstance(seg, dict) and seg.get("type") == "text"
)
if not isinstance(c, str):
continue
cjk = sum(1 for ch in c if "\u4e00" <= ch <= "\u9fff")
lat = sum(1 for ch in c if ch.isascii() and ch.isalpha())
if cjk == 0 and lat == 0:
continue
return "zh" if cjk >= lat else "en"
return "zh"
def ensure_lang_reply(body: dict) -> dict:
"""根据用户消息语言注入对应的回复语言提示。
- 已有 system 且为纯文本:在末尾追加指令(带判重,幂等)。
- 无 system:在最前面插入一条对应语言的 system。
- 多模态(数组) system 不动,避免破坏结构。"""
msgs = body.get("messages")
if not isinstance(msgs, list) or not msgs:
return body
lang = detect_user_lang(msgs)
hint = LANG_HINTS[lang]
first = msgs[0]
if isinstance(first, dict) and first.get("role") == "system":
c = first.get("content")
if isinstance(c, str) and "请始终使用简体中文" not in c and "always respond to the user in English" not in c:
first["content"] = c.rstrip() + hint
return body
sys_text = ("请使用简体中文回答。" + hint) if lang == "zh" else ("Please respond in English. " + hint)
msgs.insert(0, {"role": "system", "content": sys_text})
return body
# ============================================================
# 页面
# ============================================================
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
return templates.TemplateResponse(
request,
"index.html",
{
"local_api_key": LOCAL_API_KEY,
"app_version": APP_VERSION,
},
)
# ============================================================
# 管理接口(admin 鉴权)
# ============================================================
@app.get("/api/poll-status")
async def poll_status(_=Depends(verify_admin)):
return {
"last_poll_time": last_poll_time,
"total_models": sum(len(get_enabled_models(p)) for p in providers),
}
@app.get("/api/history")
async def get_history(hours: int = 24, _=Depends(verify_admin)):
return await read_history(hours)
@app.get("/api/stability")
async def get_stability(hours: int = 24, _=Depends(verify_admin)):
records = await read_history(hours)
model_stats: dict = {}
for rec in records:
for key, info in rec.get("data", {}).items():
if key not in model_stats:
model_stats[key] = {"ok": 0, "fail": 0, "error": 0, "total": 0, "latencies": []}
model_stats[key]["total"] += 1
st = info.get("status", "unknown")
if st == "ok":
model_stats[key]["ok"] += 1
if info.get("latency_ms"):
model_stats[key]["latencies"].append(info["latency_ms"])
elif st == "fail":
model_stats[key]["fail"] += 1
elif st == "error":
model_stats[key]["error"] += 1
allowed = set()
for p in providers:
for m in p.get("models", []):
k = f"{p['name']}||{m}"
allowed.add(k)
if k not in model_stats:
model_stats[k] = {"ok": 0, "fail": 0, "error": 0, "total": 0, "latencies": []}
model_stats = {k: v for k, v in model_stats.items() if k in allowed}
result = []
for key, s in model_stats.items():
name, model = key.split("||", 1)
avg_lat = sum(s["latencies"]) / len(s["latencies"]) if s["latencies"] else None
result.append({
"provider": name,
"model": model,
"checks": s["total"],
"ok": s["ok"],
"fail": s["fail"],
"error": s["error"],
"availability": round(s["ok"] / s["total"] * 100, 1) if s["total"] else 0,
"avg_latency_ms": round(avg_lat) if avg_lat else None,
"min_latency_ms": min(s["latencies"]) if s["latencies"] else None,
"max_latency_ms": max(s["latencies"]) if s["latencies"] else None,
"last_status": health_status.get(key, {}).get("status", "unknown"),
})
result.sort(key=lambda x: (-x["availability"], x["avg_latency_ms"] or 99999))
return result
@app.get("/api/usage")
async def get_usage(days: int = 1, _=Depends(verify_admin)):
days = max(1, min(days, MAX_USAGE_DAYS))
records = await read_usage(days)
total = {"pt": 0, "ct": 0, "tt": 0, "requests": 0}
by_day = {}
by_model = {}
for r in records:
ts = r.get("ts", 0)
day = time.strftime("%Y-%m-%d", time.localtime(ts))
pt = r.get("pt", 0) or 0
ct = r.get("ct", 0) or 0
tt = r.get("tt", 0) or (pt + ct)
m = r.get("model", "unknown")
p = r.get("provider", "unknown")
total["pt"] += pt
total["ct"] += ct
total["tt"] += tt
total["requests"] += 1
d = by_day.setdefault(day, {"pt": 0, "ct": 0, "tt": 0, "requests": 0})
d["pt"] += pt
d["ct"] += ct
d["tt"] += tt
d["requests"] += 1
mk = f"{p} · {m}"
mm = by_model.setdefault(mk, {"pt": 0, "ct": 0, "tt": 0, "requests": 0, "provider": p, "model": m})
mm["pt"] += pt
mm["ct"] += ct
mm["tt"] += tt
mm["requests"] += 1
by_day_list = [{"date": d, **v} for d, v in sorted(by_day.items())]
by_model_list = [
{"provider": v["provider"], "model": v["model"], "pt": v["pt"], "ct": v["ct"], "tt": v["tt"], "requests": v["requests"]}
for _, v in sorted(by_model.items(), key=lambda x: -x[1]["tt"])
]
return {"days": days, "total": total, "by_day": by_day_list, "by_model": by_model_list}
@app.get("/api/model-details")
async def get_model_details(_=Depends(verify_admin)):
merged = {}
# 1. 上游探测结果(键为上游模型 id / 原始名)
for k, v in model_details.items():
merged[k] = dict(v)
# 2. 对 providers 里每个模型(原始名),用别名归一化查 meta 兜底
# 解决魔搭等 provider 用别名形式(如 ZhipuAI/GLM-5.2)而 meta 里
# 只有规范化名(如 glm-5.2) 导致前端查不到上下文/描述的问题
for p in providers:
for m in p.get("models", []):
entry = merged.setdefault(m, {})
norm = MODEL_ALIASES.get(m, m)
meta_desc = MODEL_DESCRIPTIONS.get(norm, {})
if not entry.get("context_length"):
ctx = meta_desc.get("ctx") or CONTEXT_LIMITS.get(norm)
if ctx:
entry["context_length"] = ctx
if not entry.get("desc"):
desc = meta_desc.get("desc", "")
if desc:
entry["desc"] = desc
# 3. 对 meta 里规范化名也建条目(兼容以规范化名查询)
for k, v in MODEL_DESCRIPTIONS.items():
if k not in merged:
merged[k] = {}
# 上游 context_length 为 None/0/缺失时,用元数据覆盖
if not merged[k].get("context_length"):
merged[k]["context_length"] = v.get("ctx")
merged[k]["desc"] = v.get("desc", "")
return merged
@app.get("/api/context-limits")
async def get_context_limits(_=Depends(verify_admin)):
return {"ok": True, "data": CONTEXT_LIMITS}
class ContextLimitUpdate(BaseModel):
model: str
context_length: int
@app.put("/api/context-limits")
async def update_context_limit(req: ContextLimitUpdate, _=Depends(verify_admin)):
global CONTEXT_LIMITS, meta
meta = load_meta()
if "context_limits" not in meta:
meta["context_limits"] = {}
meta["context_limits"][req.model] = req.context_length
CONTEXT_LIMITS[req.model] = req.context_length
META_FILE.write_text(json.dumps(meta, indent=2, ensure_ascii=False), encoding="utf-8")
return {"ok": True}
@app.delete("/api/context-limits/{model}")
async def delete_context_limit(model: str, _=Depends(verify_admin)):
"""删除某条自定义上下文长度配置"""
global CONTEXT_LIMITS, meta
meta = load_meta()
if "context_limits" in meta and model in meta["context_limits"]:
del meta["context_limits"][model]
CONTEXT_LIMITS.pop(model, None)
META_FILE.write_text(json.dumps(meta, indent=2, ensure_ascii=False), encoding="utf-8")
return {"ok": True}
@app.get("/api/routers")
async def get_routers_api(_=Depends(verify_admin)):
return {"ok": True, "data": ROUTERS}
@app.post("/api/routers")
async def save_routers_api(request: Request, _=Depends(verify_admin)):
global ROUTERS
body = await request.json()
ROUTERS = body
save_routers()
return {"ok": True}
# ---------- 系统公告(Gitee 远程,本地兜底) ----------
DEFAULT_ANNOUNCEMENT_URL = "https://gitee.com/ywtc000/dongye/raw/master/announcement.md"
ANNOUNCEMENT_CACHE_FILE = DATA_DIR / "announcement_cache.json"
_announcement_cache = {"content": None, "ts": 0}
ANNOUNCEMENT_TTL = 300
@app.get("/api/announcement")
async def get_announcement(_=Depends(verify_admin)):
"""优先读 config.json 的 announcement_url(如 Gitee raw 链接)远程抓取;
未配置或抓取失败时回退到本地 announcement.json。远程结果缓存 5 分钟。"""
cfg = load_config()
url = cfg.get("announcement_url") or DEFAULT_ANNOUNCEMENT_URL
now = time.time()
if _announcement_cache["content"] is not None and now - _announcement_cache["ts"] < ANNOUNCEMENT_TTL:
return {"ok": True, "content": _announcement_cache["content"]}
# 远程抓取
try:
resp = await http_client.get(url, timeout=10, follow_redirects=True)
if resp.status_code == 200 and resp.text.strip():
content = resp.text
_announcement_cache["content"] = content
_announcement_cache["ts"] = now
# 持久化到本地缓存文件,断网时回退显示上次成功的内容
try:
atomic_write(ANNOUNCEMENT_CACHE_FILE, json.dumps({"content": content, "ts": now}, ensure_ascii=False))