Repository navigation
Expand file tree
/
Copy pathproxy_server.py
More file actions
1439 lines (1292 loc) · 69.7 KB
/
Copy pathproxy_server.py
File metadata and controls
1439 lines (1292 loc) · 69.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
#!/usr/bin/env python3
"""
Локальный OpenAI-совместимый прокси-сервер с ротацией ключей/эндпоинтов.
Запуск:
python proxy_server.py [--port 8818]
Использование:
OpenAI-совместимые приложения → http://localhost:8818/v1/chat/completions
Без API ключа (или с любым) — прокси сам подставляет ключи из пула.
Возможности:
- /v1/models — список моделей из active pool + все модели с эндпоинтов
- /v1/chat/completions — отправка с автоматической ротацией:
1. Находит модель в active pool (по имени или алиасу)
2. Берёт эндпоинты/ключи для этой модели (ротация round-robin)
3. При 429/402 → следующий ключ, затем следующий эндпоинт
4. Anthropic эндпоинты автоматически конвертируются в OpenAI формат
- Статистика обращений: /stats
- Управление пулом: /pool/add, /pool/remove, /pool/list
"""
import argparse
import asyncio
import json
import os
import sys
import time
from datetime import datetime
from typing import Any, Deque, Dict, List, Optional, Tuple
from collections import Counter, deque
import aiohttp
import ssl
from aiohttp import web, TCPConnector
from loguru import logger
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Трейс запросов прокси (ring buffer, последние 200 событий). TUI читает для
# панели «Трейс запросов»: попытки ключей со статусами, итог запроса.
TRACE: Deque[Dict[str, Any]] = deque(maxlen=200)
_trace_counter = 0
def push_trace(model: str, attempt: int, key_masked: str, endpoint: str,
status: int, detail: str = "") -> None:
"""Записать событие трейса запроса (попытка ключа)."""
global _trace_counter
_trace_counter += 1
TRACE.append({
"time": datetime.now().strftime("%H:%M:%S"),
"req_id": _trace_counter,
"model": model,
"attempt": attempt,
"key": key_masked,
"endpoint": endpoint,
"status": status, # 200/429/401/None
"detail": detail, # ✓/⚠/✗ + описание
})
def push_trace_summary(model: str, success: bool, attempts: int,
detail: str = "") -> None:
"""Записать итог запроса (после всех попыток)."""
global _trace_counter
_trace_counter += 1
TRACE.append({
"time": datetime.now().strftime("%H:%M:%S"),
"req_id": _trace_counter,
"model": model,
"attempt": -1, # маркер итога
"key": "",
"endpoint": "",
"status": 200 if success else 503,
"detail": ("✓ " if success else "✗ ") + detail,
"summary": True,
})
def get_trace(n: int = 50) -> List[Dict[str, Any]]:
"""Последние n событий трейса (для TUI)."""
return list(TRACE)[-n:]
def _mask_key(api_key: str) -> str:
"""Короткая безопасная маска ключа для логов и трейса."""
if len(api_key) < 12:
return api_key[:4] + "..."
return api_key[:8] + "..." + api_key[-4:]
def _upstream_url(endpoint: str, path: str) -> str:
"""Склеить base_url провайдера с OpenAI-compatible path.
В базе endpoint обычно уже нормализован до API-корня (`.../v1`), но
некоторые URL — только host (`https://api.minimaxi.com`) без `/v1`.
Также режем известный хвост, чтобы не получить `/chat/completions/...`.
"""
endpoint = (endpoint or "").rstrip("/")
path = path.strip("/")
for suffix in (
"/chat/completions", "/completions", "/embeddings", "/responses",
"/models", "/messages",
):
if endpoint.lower().endswith(suffix):
endpoint = endpoint[:-len(suffix)].rstrip("/")
break
# OpenAI-совместимые пути всегда под /v1/...
# host-only base like https://api.minimaxi.com → .../v1/chat/completions
el = endpoint.lower()
if path and not path.startswith("v1/") and not any(
el.endswith(s) for s in ("/v1", "/v1beta", "/v1alpha", "/openai/v1")
):
endpoint = endpoint + "/v1"
return f"{endpoint}/{path}"
async def _read_response(resp: aiohttp.ClientResponse) -> Tuple[Any, str]:
"""Прочитать JSON или текст ответа провайдера без падения на text/html."""
text = await resp.text()
if not text:
return {}, ""
try:
return json.loads(text), text
except Exception:
return {"raw": text}, text
from database import Database
from config import config
# ---------------------------------------------------------------------------
# Пул активных моделей/эндпоинтов
# ---------------------------------------------------------------------------
class ActivePool:
"""Управление пулом активных моделей и привязанных эндпоинтов/ключей."""
def __init__(self, db: Database):
self.db = db
self._lock = asyncio.Lock()
# model_name → [{"endpoint": url, "keys": [api_key,...], "platform": str}]
# Хранится в БД (active_pool table), кэшируется в памяти.
self._cache: Dict[str, List[Dict]] = {}
# Ротация: model → (endpoint_idx, key_idx)
self._rotation: Dict[str, List[int]] = {}
# Кулдаун: api_key → until_timestamp
self._cooldowns: Dict[str, float] = {}
self._cooldown_durations: Dict[str, int] = {} # адаптивный кулдаун: ключ → секунды
# Статистика: api_key → {"calls": N, "errors": N, "last_status": int}
self._stats: Dict[str, Dict] = {}
# Метод выбора ключа: 'round_robin' (по кругу) | 'sticky' (первый пока работает)
self._selection_mode: str = "round_robin"
self._load_cache()
def _load_cache(self):
"""Загрузить active pool из БД.
Источники с source='model' (модель добавлена явно в левую колонку) идут
ПЕРВЫМИ — приоритет при маршрутизации. source='endpoint' (правая
колонка) — fallback, используется только когда левые в кулдауне/недоступны.
"""
try:
with self.db._lock:
with self.db._get_connection() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS active_pool (
id INTEGER PRIMARY KEY AUTOINCREMENT,
model_name TEXT NOT NULL,
endpoint TEXT NOT NULL,
platform TEXT DEFAULT '',
api_keys TEXT DEFAULT '[]',
added_time DATETIME DEFAULT CURRENT_TIMESTAMP,
enabled BOOLEAN DEFAULT 1,
UNIQUE(model_name, endpoint)
)
""")
# Миграция колонок source/priority/zone (если старая схема)
try:
cols = [c[1] for c in conn.execute(
"PRAGMA table_info(active_pool)").fetchall()]
if "source" not in cols:
conn.execute("ALTER TABLE active_pool "
"ADD COLUMN source TEXT DEFAULT 'model'")
if "priority" not in cols:
conn.execute("ALTER TABLE active_pool "
"ADD COLUMN priority INTEGER DEFAULT 0")
if "zone" not in cols:
conn.execute("ALTER TABLE active_pool "
"ADD COLUMN zone TEXT DEFAULT 'model'")
except Exception:
pass
rows = conn.execute(
"SELECT model_name, endpoint, platform, api_keys, "
"enabled, source, priority, zone FROM active_pool "
"ORDER BY priority DESC"
).fetchall()
self._cache.clear()
for r in rows:
model = r[0]
endpoint = r[1]
platform = r[2]
keys = json.loads(r[3]) if r[3] else []
enabled = bool(r[4])
source = r[5] if len(r) > 5 and r[5] else "model"
priority = r[6] if len(r) > 6 and r[6] is not None else 0
zone = r[7] if len(r) > 7 and r[7] else "model"
if model not in self._cache:
self._cache[model] = []
self._cache[model].append({
"endpoint": endpoint,
"platform": platform,
"keys": keys,
"enabled": enabled,
"source": source,
"priority": priority,
"zone": zone,
})
# Сортировка: source='model' первыми + priority DESC (reorder)
for model in self._cache:
self._cache[model].sort(
key=lambda e: (0 if e.get("source") == "model" else 1,
-(e.get("priority", 0) or 0)))
except Exception as e:
logger.error(f"ActivePool load error: {e}")
def reorder_endpoint(self, endpoint: str, direction: str) -> None:
"""Изменить приоритет эндпоинта (up=выше, down=ниже). Выше = раньше
в маршрутизации (полезно для sticky + round-robin порядка)."""
delta = 1 if direction == "up" else -1
try:
with self.db._lock:
with self.db._get_connection() as conn:
conn.execute(
"UPDATE active_pool SET priority = "
"COALESCE(priority, 0) + ? WHERE endpoint=?",
(delta, endpoint))
conn.commit()
self._load_cache()
except Exception as e:
logger.error(f"reorder error: {e}")
def toggle_source(self, model: str, endpoint: str) -> None:
"""Вкл/выкл провайдера модели (enabled 0↔1)."""
try:
with self.db._lock:
with self.db._get_connection() as conn:
conn.execute(
"UPDATE active_pool SET enabled = "
"CASE WHEN enabled=1 THEN 0 ELSE 1 END "
"WHERE model_name=? AND endpoint=?",
(model, endpoint))
conn.commit()
self._load_cache()
except Exception as e:
logger.error(f"toggle_source error: {e}")
def remove_source(self, model: str, endpoint: str) -> None:
"""Удалить связь модель↔эндпоинт.
Пара попадает в pool_exclusions: resync_pool пересобирает active_pool
из pool_models/pool_endpoints, и без явного исключения удалённая пара
возвращалась бы через 5 минут. Повторное add_model/add_endpoint
снимает исключение.
"""
try:
with self.db._lock:
with self.db._get_connection() as conn:
self._ensure_desired_tables(conn)
conn.execute(
"DELETE FROM active_pool WHERE model_name=? AND endpoint=?",
(model, endpoint))
conn.execute(
"INSERT OR IGNORE INTO pool_exclusions "
"(model_name, endpoint) VALUES (?, ?)",
(model, endpoint))
conn.commit()
self._load_cache()
except Exception as e:
logger.error(f"remove_source error: {e}")
def model_sources(self, model: str) -> List[Dict]:
"""Провайдеры модели (из active_pool, zone=model): для UI правой таблицы.
endpoint, platform, priority, enabled, zone + счётчики ключей."""
out = []
try:
with self.db._lock:
with self.db._get_connection() as conn:
rows = conn.execute(
"SELECT endpoint, platform, priority, enabled, zone "
"FROM active_pool WHERE model_name=? "
"ORDER BY priority DESC", (model,)).fetchall()
# Ключи по статусам для каждого эндпоинта+модели
for r in rows:
ep, plat, prio, enbl, zone = r
kc = conn.execute(
"SELECT lk.status FROM key_models km "
"JOIN leaked_keys lk ON lk.id = km.key_id "
"WHERE km.model_name=? AND lk.base_url=?",
(model, ep)).fetchall()
n_keys = len(kc)
n_conf = sum(1 for k in kc if k[0] == "confirmed")
out.append({
"endpoint": ep, "platform": plat,
"priority": prio or 0,
"enabled": bool(enbl), "zone": zone or "model",
"keys": n_keys, "confirmed": n_conf,
})
except Exception as e:
logger.error(f"model_sources error: {e}")
return out
def reload(self):
self._load_cache()
def list_models(self) -> List[str]:
"""Все модели в пуле (включая алиасы)."""
return sorted(self._cache.keys())
def get_all_available_models(self) -> List[str]:
"""Модели, доступные через прокси = только active pool (то, что добавлено
в пул во вкладках Модели/Провайдеры). Раньше добавлялись ВСЕ confirmed
модели из БД → /v1/models показывал «кучу» того, что юзер не добавлял."""
return sorted(self._cache.keys())
@staticmethod
def _ensure_desired_tables(conn) -> None:
"""Создать pool_models/pool_endpoints/pool_exclusions, если их нет.
Прокси запускается и без TUI (он один создаёт эти таблицы), поэтому
handlers обязаны работать на чистой БД.
"""
conn.execute(
"CREATE TABLE IF NOT EXISTS pool_models "
"(id INTEGER PRIMARY KEY AUTOINCREMENT, "
"model_name TEXT NOT NULL UNIQUE, "
"added_time DATETIME DEFAULT CURRENT_TIMESTAMP)")
conn.execute(
"CREATE TABLE IF NOT EXISTS pool_endpoints "
"(id INTEGER PRIMARY KEY AUTOINCREMENT, "
"endpoint TEXT NOT NULL UNIQUE, "
"added_time DATETIME DEFAULT CURRENT_TIMESTAMP)")
conn.execute(
"CREATE TABLE IF NOT EXISTS pool_exclusions "
"(model_name TEXT NOT NULL, endpoint TEXT NOT NULL, "
"added_time DATETIME DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(model_name, endpoint))")
def add_model(self, model_name: str, endpoint: str = "",
platform: str = "", api_keys: List[str] = None) -> str:
"""Добавить модель в пул. Если endpoint пустой — берёт все доступные."""
if api_keys is None:
api_keys = []
# Если endpoint не указан — найти все эндпоинты с этой моделью
if not endpoint:
sources = self._find_endpoints_for_model(model_name)
else:
sources = [{"endpoint": endpoint, "platform": platform, "keys": api_keys}]
if not sources:
return f"Модель '{model_name}' не найдена ни на одном эндпоинте"
added = 0
with self.db._lock:
with self.db._get_connection() as conn:
self._ensure_desired_tables(conn)
# Желаемое состояние: resync_pool каждые 5 минут пересобирает
# active_pool именно из pool_models/pool_endpoints, поэтому без
# этой записи добавленное через API исчезало бы.
conn.execute(
"INSERT OR IGNORE INTO pool_models (model_name) VALUES (?)",
(model_name,))
conn.execute(
"DELETE FROM pool_exclusions WHERE model_name=?",
(model_name,))
for src in sources:
keys_json = json.dumps(src["keys"])
try:
conn.execute(
"INSERT OR IGNORE INTO active_pool "
"(model_name, endpoint, platform, api_keys, zone) "
"VALUES (?, ?, ?, ?, 'model')",
(model_name, src["endpoint"],
src.get("platform", ""), keys_json))
added += 1
except Exception:
pass
conn.commit()
self._load_cache()
return f"Добавлено: {model_name} ({added} эндпоинтов)"
def add_endpoint(self, endpoint: str, platform: str = "") -> str:
"""Добавить ВСЕ модели с эндпоинта в пул."""
# Найти все confirmed модели на этом эндпоинте
try:
with self.db._lock:
with self.db._get_connection() as conn:
rows = conn.execute(
"SELECT DISTINCT km.model_name, "
"GROUP_CONCAT(DISTINCT lk.api_key) as keys "
"FROM key_models km "
"JOIN leaked_keys lk ON lk.id = km.key_id "
"WHERE lk.base_url=? AND km.is_confirmed=1 "
"AND lk.status IN ('valid','confirmed') "
"GROUP BY km.model_name",
(endpoint,)).fetchall()
except Exception:
rows = []
if not rows:
# Попробовать без is_confirmed
try:
with self.db._lock:
with self.db._get_connection() as conn:
rows = conn.execute(
"SELECT DISTINCT km.model_name, "
"GROUP_CONCAT(DISTINCT lk.api_key) as keys "
"FROM key_models km "
"JOIN leaked_keys lk ON lk.id = km.key_id "
"WHERE lk.base_url=? "
"AND lk.status IN ('valid','confirmed') "
"GROUP BY km.model_name",
(endpoint,)).fetchall()
except Exception:
rows = []
if not rows:
return f"Не найдено моделей на {endpoint}"
added = 0
with self.db._lock:
with self.db._get_connection() as conn:
self._ensure_desired_tables(conn)
conn.execute(
"INSERT OR IGNORE INTO pool_endpoints (endpoint) VALUES (?)",
(endpoint,))
conn.execute(
"DELETE FROM pool_exclusions WHERE endpoint=?", (endpoint,))
for r in rows:
model = r[0]
keys = r[1].split(",") if r[1] else []
keys_json = json.dumps(keys)
try:
conn.execute(
"INSERT OR IGNORE INTO active_pool "
"(model_name, endpoint, platform, api_keys, zone) "
"VALUES (?, ?, ?, ?, 'endpoint')",
(model, endpoint, platform, keys_json))
added += 1
except Exception:
pass
conn.commit()
self._load_cache()
return f"Добавлено {added} моделей с {endpoint}"
def resync_pool(self) -> dict:
"""Привести active_pool к текущему состоянию key_models.
active_pool хранит снапшот api_keys, снятый в момент добавления:
новые confirmed-ключи не подхватывались, а модели, которые провайдер
перестал отдавать, оставались в /v1/models навсегда. Здесь пул
пересобирается из pool_models/pool_endpoints + key_models:
- ключи каждой пары (модель, эндпоинт) перечитываются из БД
(сначала confirmed+is_confirmed=1, иначе valid/quota);
- пара без единого живого ключа удаляется;
- пара, вернувшаяся к жизни, добавляется снова (pool_models/
pool_endpoints остаются желаемым состоянием пользователя);
- enabled/priority пользователя сохраняются.
Возвращает {'added', 'updated', 'removed'}.
"""
import json as _json
stats = {"added": 0, "updated": 0, "removed": 0}
try:
with self.db._lock:
with self.db._get_connection() as conn:
# До первого SELECT: на чистой БД (прокси без TUI) таблиц
# pool_models/pool_endpoints ещё нет, и запрос падал в
# «resync_pool error» с нулевым результатом.
self._ensure_desired_tables(conn)
explicit = {r[0] for r in conn.execute(
"SELECT model_name FROM pool_models").fetchall()}
endpoints = {r[0] for r in conn.execute(
"SELECT endpoint FROM pool_endpoints").fetchall()}
self._ensure_desired_tables(conn)
excluded = {(r[0], r[1]) for r in conn.execute(
"SELECT model_name, endpoint FROM pool_exclusions")}
prev = {
(r[0], r[1]): (int(r[2] or 1), int(r[3] or 0), r[4])
for r in conn.execute(
"SELECT model_name, endpoint, enabled, priority, "
"api_keys FROM active_pool").fetchall()
}
rows = conn.execute(
"SELECT km.model_name, lk.base_url, "
" GROUP_CONCAT(DISTINCT CASE WHEN lk.status='confirmed' "
" AND km.is_confirmed=1 THEN lk.api_key END), "
" GROUP_CONCAT(DISTINCT CASE WHEN lk.status IN "
" ('valid','confirmed','quota_exceeded') THEN lk.api_key END), "
" MAX(lk.platform) "
"FROM key_models km "
"JOIN leaked_keys lk ON lk.id = km.key_id "
"WHERE lk.base_url IS NOT NULL AND lk.base_url != '' "
"GROUP BY km.model_name, lk.base_url"
).fetchall()
desired = {}
for model, base_url, good, anyk, platform in rows:
if model not in explicit and base_url not in endpoints:
continue
if (model, base_url) in excluded:
continue
keys = [k for k in (good or "").split(",") if k] or \
[k for k in (anyk or "").split(",") if k]
if not keys:
continue
desired[(model, base_url)] = (keys, platform or "")
stale = [pair for pair in prev if pair not in desired]
for model, endpoint in stale:
conn.execute(
"DELETE FROM active_pool WHERE model_name=? "
"AND endpoint=?", (model, endpoint))
stats["removed"] += 1
for (model, endpoint), (keys, platform) in desired.items():
zone = "model" if model in explicit else "endpoint"
source = "model" if model in explicit else "endpoint"
keys_json = _json.dumps(keys)
if (model, endpoint) in prev:
old_enabled, old_priority, old_keys = prev[(model, endpoint)]
normalized_old = ""
try:
normalized_old = _json.dumps(_json.loads(old_keys or "[]"))
except Exception:
normalized_old = old_keys or ""
if normalized_old == keys_json:
continue
conn.execute(
"UPDATE active_pool SET api_keys=?, platform=?, "
"zone=?, source=? WHERE model_name=? AND endpoint=?",
(keys_json, platform, zone, source, model, endpoint))
stats["updated"] += 1
else:
old_enabled = 1
old_priority = 0
conn.execute(
"INSERT OR IGNORE INTO active_pool "
"(model_name, endpoint, platform, api_keys, enabled, "
" priority, source, zone) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(model, endpoint, platform, keys_json,
old_enabled, old_priority, source, zone))
stats["added"] += 1
conn.commit()
except Exception as e:
logger.error(f"resync_pool error: {e}")
return stats
self._load_cache()
return stats
def remove_model(self, model_name: str) -> str:
with self.db._lock:
with self.db._get_connection() as conn:
self._ensure_desired_tables(conn)
n = conn.execute(
"DELETE FROM active_pool WHERE model_name=?",
(model_name,)).rowcount
# Желаемое состояние тоже: иначе resync вернёт модель через 5 мин
conn.execute(
"DELETE FROM pool_models WHERE model_name=?", (model_name,))
conn.execute(
"DELETE FROM pool_exclusions WHERE model_name=?",
(model_name,))
conn.commit()
self._load_cache()
return f"Удалено: {n} записей для {model_name}"
def clear_pool(self) -> str:
with self.db._lock:
with self.db._get_connection() as conn:
self._ensure_desired_tables(conn)
conn.execute("DELETE FROM active_pool")
conn.execute("DELETE FROM pool_models")
conn.execute("DELETE FROM pool_endpoints")
conn.execute("DELETE FROM pool_exclusions")
conn.commit()
self._load_cache()
return "Пул очищен"
def _find_endpoints_for_model(self, model_name: str) -> List[Dict]:
"""Найти все эндпоинты где модель подтверждена.
ТОЛЬКО confirmed ключи (status='confirmed' AND is_confirmed=1). Valid-
ключи (is_confirmed=0) не подтверждались реальным запросом — к ним
запросы не шлём (они не ответят / дадут мусор).
"""
try:
with self.db._lock:
with self.db._get_connection() as conn:
rows = conn.execute(
"SELECT lk.base_url, lk.platform, lk.api_key "
"FROM key_models km "
"JOIN leaked_keys lk ON lk.id = km.key_id "
"WHERE km.model_name=? "
"AND lk.status='confirmed' AND km.is_confirmed=1",
(model_name,)).fetchall()
except Exception:
return []
endpoints: Dict[str, Dict] = {}
for r in rows:
url = r[0]
if url not in endpoints:
endpoints[url] = {"endpoint": url, "platform": r[1], "keys": []}
endpoints[url]["keys"].append(r[2])
return list(endpoints.values())
def _get_sources_for_model(self, model_name: str) -> List[Dict]:
"""Получить источники (endpoint+keys) для модели.
Раздельные зоны:
- Если модель в pool_models (добавлена явно) → только zone='model' источники
(крутит провайдеров). НЕ включает zone='endpoint'.
- Если только через pool_endpoints → только zone='endpoint' (крутит свои ключи).
- Ни там ни там → все confirmed (fallback).
"""
# Определить зону модели: есть ли она в pool_models / pool_endpoints
zone = self._model_zone(model_name)
pool_entries = self._cache.get(model_name, [])
sources = []
for entry in pool_entries:
# Фильтр по зоне (если зона известна)
if zone and entry.get("zone", "model") != zone:
continue
if not entry.get("enabled", True):
continue
keys = entry.get("keys", [])
if not keys:
src = self._find_endpoints_for_model(model_name)
for s in src:
if s["endpoint"] == entry["endpoint"]:
keys = s["keys"]
break
sources.append({
"endpoint": entry["endpoint"],
"platform": entry.get("platform", ""),
"keys": keys,
"source": entry.get("source", "model"),
})
# Если нет в пуле — найти автоматически (все confirmed)
if not sources:
sources = self._find_endpoints_for_model(model_name)
return sources
def _model_zone(self, model_name: str) -> str:
"""Зона модели: 'model' (в pool_models) | 'endpoint' (через провайдера) | '' (auto)."""
try:
with self.db._lock:
with self.db._get_connection() as conn:
in_models = conn.execute(
"SELECT 1 FROM pool_models WHERE model_name=? LIMIT 1",
(model_name,)).fetchone()
if in_models:
return "model"
in_eps = conn.execute(
"SELECT 1 FROM active_pool WHERE model_name=? "
"AND zone='endpoint' LIMIT 1",
(model_name,)).fetchone()
if in_eps:
return "endpoint"
except Exception:
pass
return ""
def _get_next_key(self, model_name: str, sources: List[Dict]
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
"""Получить следующий ключ — честный round-robin + кулдаун.
Ротация: каждый вызов возвращает СЛЕДУЮЩИЙ ключ (ep+key) по кругу,
равномерно распределяя нагрузку. Ключи в кулдауне пропускаются.
ПРИОРИТЕТ: источники source='model' (левая колонка) перебираются
первыми; source='endpoint' (правая) — fallback когда все model-ключи
в кулдауне. rot хранит позицию ОТДЕЛЬНО для model и endpoint, чтобы
восстановить приоритет после выхода из кулдауна.
Returns: (api_key, endpoint, platform) или (None, None, None)
"""
now = time.time()
# Очистить истекшие кулдауны + сбросить адаптивную длительность
expired = [k for k, t in self._cooldowns.items() if t < now]
for k in expired:
del self._cooldowns[k]
# Сбросить адаптивную длительность при истечении
self._cooldown_durations.pop(k, None)
# rot хранит ОДИН глобальный курсор по «плоскому» списку всех ключей.
# Но приоритет model: если есть model-ключи вне кулдауна — берём только
# их. Поэтому два курсора: model-only и all.
state = self._rotation.setdefault(model_name, {"model": 0, "all": 0})
total_sources = len(sources)
if total_sources == 0:
return None, None, None
has_model_src = any(s.get("source", "model") == "model"
for s in sources)
def _flat(only: Optional[str]):
"""Плоский список (api_key, endpoint, platform) для source=only.
Дедуп по api_key: ключ может встречаться и в source=model, и в
source=endpoint (если модель и провайдер добавлены одновременно).
Берём первое вхождение (приоритет model-источника сохранён сортировкой).
"""
seen = set()
out = []
for src in sources:
if only and src.get("source", "model") != only:
continue
for k in src["keys"]:
if k in seen:
continue
seen.add(k)
out.append((k, src["endpoint"], src.get("platform", "")))
return out
def _pick(flat, cursor):
"""Взять следующий не-в-кулдауне ключ.
round_robin: сдвинуть курсор на следующий (равномерное распределение).
sticky: курсор не двигать — всегда первый приоритетный, следующий
только когда все до него в кулдауне.
"""
if not flat:
return None, cursor
n = len(flat)
for off in range(n):
idx = (cursor + off) % n
k, ep, plat = flat[idx]
if k in self._cooldowns:
continue
if self._selection_mode == "sticky":
# Sticky: не двигаем курсор — приоритет порядка (reorder)
return (k, ep, plat), cursor
# round_robin: сдвинуть на следующий
return (k, ep, plat), (idx + 1) % n
return None, cursor
# 1) Приоритет: model-источники
if has_model_src:
flat_m = _flat("model")
r, state["model"] = _pick(flat_m, state["model"])
if r:
return r
# 2) Fallback: все источники
flat_all = _flat(None)
r, state["all"] = _pick(flat_all, state["all"])
return r if r else (None, None, None)
def _put_cooldown(self, api_key: str, seconds: float = 60):
"""Поставить ключ в кулдаун (429/quota)."""
self._cooldowns[api_key] = time.time() + seconds
def _record_stat(self, api_key: str, status: int):
"""Записать статистику."""
s = self._stats.setdefault(api_key, {"calls": 0, "errors": 0, "ok": 0})
s["calls"] += 1
s["last_status"] = status
if 200 <= status < 300:
s["ok"] += 1
else:
s["errors"] += 1
def get_stats(self) -> Dict[str, Any]:
# Агрегаты по всем ключам
total_calls = sum(s.get("calls", 0) for s in self._stats.values())
total_ok = sum(s.get("ok", 0) for s in self._stats.values())
total_err = sum(s.get("errors", 0) for s in self._stats.values())
return {
"pool_models": len(self._cache),
"pool_sources": sum(len(v) for v in self._cache.values()),
"cooldown_keys": len(self._cooldowns),
"total_calls": total_calls,
"total_ok": total_ok,
"total_errors": total_err,
"success_rate": (round(100 * total_ok / total_calls, 1)
if total_calls else 0),
"key_stats": dict(list(self._stats.items())[:50]),
}
# ---------------------------------------------------------------------------
# Конвертер Anthropic ↔ OpenAI
# ---------------------------------------------------------------------------
def anthropic_to_openai_request(body: Dict, model: str) -> Dict:
"""Конвертировать OpenAI chat/completions запрос → Anthropic /v1/messages."""
messages = body.get("messages", [])
system_msg = ""
filtered = []
for msg in messages:
if msg.get("role") == "system":
system_msg += msg.get("content", "") + "\n"
else:
filtered.append({
"role": msg.get("role", "user"),
"content": msg.get("content", ""),
})
return {
"model": model,
# Anthropic требует max_tokens и трактует как жёсткий лимит. Клиенты
# OpenAI часто не передают его → дефолт 100 обрезал ответы. 8192.
"max_tokens": body.get("max_tokens") or 8192,
"temperature": body.get("temperature", 0),
"system": system_msg.strip() if system_msg else None,
"messages": filtered,
}
def anthropic_to_openai_response(data: Dict, model: str) -> Dict:
"""Конвертировать ответ Anthropic → OpenAI format."""
content = ""
for block in data.get("content", []):
if isinstance(block, dict):
content += block.get("text", "")
usage = data.get("usage", {})
return {
"id": data.get("id", "chatcmpl-proxy"),
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": content},
"finish_reason": data.get("stop_reason", "stop"),
}],
"usage": {
"prompt_tokens": usage.get("input_tokens", 0),
"completion_tokens": usage.get("output_tokens", 0),
"total_tokens": (usage.get("input_tokens", 0)
+ usage.get("output_tokens", 0)),
},
}
def is_anthropic_endpoint(endpoint: str, platform: str = "") -> bool:
"""Определить, нужен ли Anthropic формат."""
return ("anthropic.com" in endpoint.lower()
or platform.lower() == "anthropic")
# ---------------------------------------------------------------------------
# Прокси-сервер
# ---------------------------------------------------------------------------
class ProxyServer:
"""OpenAI-совместимый прокси с ротацией ключей."""
def __init__(self, db: Database, port: int = 8818, host: str = "127.0.0.1"):
self.db = db
self.port = port
self.host = host # 127.0.0.1 (только локально) или 0.0.0.0 (внешний доступ)
self.pool = ActivePool(db)
self.session: Optional[aiohttp.ClientSession] = None
async def _get_session(self) -> aiohttp.ClientSession:
if self.session is None or self.session.closed:
timeout = aiohttp.ClientTimeout(total=120, connect=10)
connector = TCPConnector(
limit=20,
limit_per_host=10,
ssl=ssl.create_default_context(),
force_close=False,
use_dns_cache=True,
ttl_dns_cache=600,
keepalive_timeout=60,
enable_cleanup_closed=True,
resolver=aiohttp.resolver.ThreadedResolver(),
)
self.session = aiohttp.ClientSession(
connector=connector, timeout=timeout, trust_env=True
)
return self.session
async def handle_models(self, request: web.Request) -> web.Response:
"""GET /v1/models — список доступных моделей."""
models = self.pool.get_all_available_models()
data = {
"object": "list",
"data": [{"id": m, "object": "model",
"created": 0, "owned_by": "proxy"}
for m in models],
}
return web.json_response(data)
async def handle_chat(self, request: web.Request) -> web.StreamResponse:
"""POST /v1/chat/completions — отправка с ротацией."""
return await self._handle_openai_request(
request, upstream_path="chat/completions",
kind="chat", require_field="messages")
async def handle_completions(self, request: web.Request) -> web.StreamResponse:
"""POST /v1/completions — legacy completions endpoint."""
return await self._handle_openai_request(
request, upstream_path="completions",
kind="completion", require_field="prompt")
async def handle_embeddings(self, request: web.Request) -> web.StreamResponse:
"""POST /v1/embeddings — OpenAI-compatible embeddings endpoint."""
return await self._handle_openai_request(
request, upstream_path="embeddings",
kind="embedding", require_field="input")
async def _handle_openai_request(
self,
request: web.Request,
upstream_path: str,
kind: str,
require_field: str = "",
) -> web.StreamResponse:
"""Единая ротация для OpenAI-compatible endpoints.
Все параметры запроса передаются провайдеру как есть: temperature,
top_p, max_tokens/max_completion_tokens, tools, tool_choice, response_format,
stream_options и прочее. Прокси меняет только Authorization и, для
Anthropic chat, конвертирует формат.
"""
try:
body = await request.json()
except Exception:
return web.json_response(
{"error": {"message": "Invalid JSON"}}, status=400)
model = body.get("model", "")
if not model:
return web.json_response(
{"error": {"message": "Model not specified"}}, status=400)
# Ранняя валидация — не тратить попытку ключа на пустой запрос.
if require_field and require_field not in body:
return web.json_response(
{"error": {"message": f"{require_field} required"}}, status=400)
# Stream support
stream = bool(body.get("stream", False))
# Найти источники для модели
sources = self.pool._get_sources_for_model(model)
if not sources:
# Алиас: попробовать найти частичное совпадение
all_models = self.pool.get_all_available_models()
for m in all_models:
if model.lower() in m.lower():
sources = self.pool._get_sources_for_model(m)
model = m # используем точное имя
break
if not sources:
return web.json_response(
{"error": {"message": f"Model '{model}' not found in pool",
"type": "not_found"}}, status=404)
# Ротация: перебираем ключи/эндпоинты
tried = []
tried_counts: Counter = Counter() # число попыток по (key, endpoint)
# Лимит: 2× уникальных (key,endpoint) пар — достаточно для повторных
# попыток при transient-ошибках, но без бесконечного цикла.
unique_pairs = set()
for s in sources:
for k in s["keys"]:
unique_pairs.add((k, s["endpoint"]))
max_attempts = len(unique_pairs) * 2 if unique_pairs else 1
last_error: Dict[str, Any] = {}
for attempt in range(max_attempts):
api_key, endpoint, platform = self.pool._get_next_key(model, sources)
if not api_key:
break
# Анти-цикл: если уже пробовали эту (key,endpoint) пару 2+ раз — skip
pair = (api_key, endpoint)
if tried_counts[pair] >= 2:
# Поставить в кулдаун чтобы _get_next_key больше не вернул
self.pool._put_cooldown(api_key, seconds=30)
continue
masked = _mask_key(api_key)
tried.append(f"{masked}@{endpoint}")
tried_counts[pair] += 1
logger.info(
f"Proxy: {kind}/{model} attempt {attempt+1} -> {masked} @ {endpoint}")
# Определить формат запроса
is_anthropic = is_anthropic_endpoint(endpoint, platform)
if is_anthropic and kind == "chat":