-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathmain.py
2169 lines (1876 loc) · 85.8 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from log_config import logger
import copy
import httpx
import secrets
from time import time
from contextlib import asynccontextmanager
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, HTTPException, Depends, Request, APIRouter
from fastapi.responses import JSONResponse
from fastapi.responses import StreamingResponse as FastAPIStreamingResponse
from starlette.responses import StreamingResponse as StarletteStreamingResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.exceptions import RequestValidationError
from models import RequestModel, ImageGenerationRequest, AudioTranscriptionRequest, ModerationRequest, TextToSpeechRequest, UnifiedRequest, EmbeddingRequest
from request import get_payload
from response import fetch_response, fetch_response_stream
from utils import (
safe_get,
load_config,
save_api_yaml,
get_model_dict,
post_all_models,
circular_list_encoder,
error_handling_wrapper,
rate_limiter,
provider_api_circular_list,
ThreadSafeCircularList,
)
from collections import defaultdict
from typing import List, Dict, Union
from urllib.parse import urlparse
import os
import string
import json
DEFAULT_TIMEOUT = int(os.getenv("TIMEOUT", 100))
is_debug = bool(os.getenv("DEBUG", False))
# is_debug = False
from sqlalchemy import inspect, text
from sqlalchemy.sql import sqltypes
# 添加新的环境变量检查
DISABLE_DATABASE = os.getenv("DISABLE_DATABASE", "false").lower() == "true"
IS_VERCEL = os.path.dirname(os.path.abspath(__file__)).startswith('/var/task')
logger.info("IS_VERCEL: %s", IS_VERCEL)
logger.info("DISABLE_DATABASE: %s", DISABLE_DATABASE)
# 读取VERSION文件内容
try:
with open('VERSION', 'r') as f:
VERSION = f.read().strip()
except:
VERSION = 'unknown'
logger.info("VERSION: %s", VERSION)
async def create_tables():
if DISABLE_DATABASE:
return
async with db_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
# 检查并添加缺失的列
def check_and_add_columns(connection):
inspector = inspect(connection)
for table in [RequestStat, ChannelStat]:
table_name = table.__tablename__
existing_columns = {col['name']: col['type'] for col in inspector.get_columns(table_name)}
for column_name, column in table.__table__.columns.items():
if column_name not in existing_columns:
col_type = _map_sa_type_to_sql_type(column.type)
default = _get_default_sql(column.default)
connection.execute(text(f"ALTER TABLE {table_name} ADD COLUMN {column_name} {col_type}{default}"))
await conn.run_sync(check_and_add_columns)
def _map_sa_type_to_sql_type(sa_type):
type_map = {
sqltypes.Integer: "INTEGER",
sqltypes.String: "TEXT",
sqltypes.Float: "REAL",
sqltypes.Boolean: "BOOLEAN",
sqltypes.DateTime: "DATETIME",
sqltypes.Text: "TEXT"
}
return type_map.get(type(sa_type), "TEXT")
def _get_default_sql(default):
if default is None:
return ""
if isinstance(default.arg, bool):
return f" DEFAULT {str(default.arg).upper()}"
if isinstance(default.arg, (int, float)):
return f" DEFAULT {default.arg}"
if isinstance(default.arg, str):
return f" DEFAULT '{default.arg}'"
return ""
@asynccontextmanager
async def lifespan(app: FastAPI):
# print("Main app routes:")
# for route in app.routes:
# print(f"Route: {route.path}, methods: {route.methods}")
# print("\nFrontend router routes:")
# for route in frontend_router.routes:
# print(f"Route: {route.path}, methods: {route.methods}")
# 启动时的代码
if not DISABLE_DATABASE:
await create_tables()
yield
# 关闭时的代码
# await app.state.client.aclose()
if hasattr(app.state, 'client_manager'):
await app.state.client_manager.close()
app = FastAPI(lifespan=lifespan, debug=is_debug)
def generate_markdown_docs():
openapi_schema = app.openapi()
markdown = f"# {openapi_schema['info']['title']}\n\n"
markdown += f"Version: {openapi_schema['info']['version']}\n\n"
markdown += f"{openapi_schema['info'].get('description', '')}\n\n"
markdown += "## API Endpoints\n\n"
paths = openapi_schema['paths']
for path, path_info in paths.items():
for method, operation in path_info.items():
markdown += f"### {method.upper()} {path}\n\n"
markdown += f"{operation.get('summary', '')}\n\n"
markdown += f"{operation.get('description', '')}\n\n"
if 'parameters' in operation:
markdown += "Parameters:\n"
for param in operation['parameters']:
markdown += f"- {param['name']} ({param['in']}): {param.get('description', '')}\n"
markdown += "\n---\n\n"
return markdown
@app.get("/docs/markdown")
async def get_markdown_docs():
markdown = generate_markdown_docs()
return Response(
content=markdown,
media_type="text/markdown"
)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
if exc.status_code == 404:
logger.error(f"404 Error: {exc.detail}")
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail},
)
import uuid
import asyncio
import contextvars
request_info = contextvars.ContextVar('request_info', default={})
async def parse_request_body(request: Request):
if request.method == "POST" and "application/json" in request.headers.get("content-type", ""):
try:
return await request.json()
except json.JSONDecodeError:
return None
return None
class ChannelManager:
def __init__(self, cooldown_period=300):
self._excluded_models = defaultdict(lambda: None)
self.cooldown_period = cooldown_period
async def exclude_model(self, provider: str, model: str):
model_key = f"{provider}/{model}"
self._excluded_models[model_key] = datetime.now()
async def is_model_excluded(self, provider: str, model: str) -> bool:
model_key = f"{provider}/{model}"
excluded_time = self._excluded_models[model_key]
if not excluded_time:
return False
if datetime.now() - excluded_time > timedelta(seconds=self.cooldown_period):
del self._excluded_models[model_key]
return False
return True
async def get_available_providers(self, providers: list) -> list:
"""过滤出可用的providers,仅排除不可用的模型"""
available_providers = []
for provider in providers:
provider_name = provider['provider']
model_dict = provider['model'][0] # 获取唯一的模型字典
# source_model = list(model_dict.keys())[0] # 源模型名称
target_model = list(model_dict.values())[0] # 目标模型名称
# 检查该模型是否被排除
if not await self.is_model_excluded(provider_name, target_model):
available_providers.append(provider)
return available_providers
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import Column, Integer, String, Float, DateTime, select, Boolean, Text
from sqlalchemy.sql import func
# 定义数据库模型
Base = declarative_base()
class RequestStat(Base):
__tablename__ = 'request_stats'
id = Column(Integer, primary_key=True)
request_id = Column(String)
endpoint = Column(String)
client_ip = Column(String)
process_time = Column(Float)
first_response_time = Column(Float)
provider = Column(String)
model = Column(String)
# success = Column(Boolean, default=False)
api_key = Column(String)
is_flagged = Column(Boolean, default=False)
text = Column(Text)
prompt_tokens = Column(Integer, default=0)
completion_tokens = Column(Integer, default=0)
total_tokens = Column(Integer, default=0)
# cost = Column(Float, default=0)
timestamp = Column(DateTime(timezone=True), server_default=func.now())
class ChannelStat(Base):
__tablename__ = 'channel_stats'
id = Column(Integer, primary_key=True)
request_id = Column(String)
provider = Column(String)
model = Column(String)
api_key = Column(String)
success = Column(Boolean, default=False)
timestamp = Column(DateTime(timezone=True), server_default=func.now())
if not DISABLE_DATABASE:
# 获取数据库路径
db_path = os.getenv('DB_PATH', './data/stats.db')
# 确保 data 目录存在
data_dir = os.path.dirname(db_path)
os.makedirs(data_dir, exist_ok=True)
# 创建异步引擎和会话
# db_engine = create_async_engine('sqlite+aiosqlite:///' + db_path, echo=False)
db_engine = create_async_engine('sqlite+aiosqlite:///' + db_path, echo=is_debug)
async_session = sessionmaker(db_engine, class_=AsyncSession, expire_on_commit=False)
from starlette.types import Scope, Receive, Send
from starlette.responses import Response
from asyncio import Semaphore
# 创建一个信号量来控制数据库访问
db_semaphore = Semaphore(1) # 限制同时只有1个写入操作
async def update_stats(current_info):
if DISABLE_DATABASE:
return
try:
# 等待获取数据库访问权限
async with db_semaphore:
async with async_session() as session:
async with session.begin():
try:
columns = [column.key for column in RequestStat.__table__.columns]
filtered_info = {k: v for k, v in current_info.items() if k in columns}
new_request_stat = RequestStat(**filtered_info)
session.add(new_request_stat)
await session.commit()
except Exception as e:
await session.rollback()
logger.error(f"Error updating stats: {str(e)}")
if is_debug:
import traceback
traceback.print_exc()
except Exception as e:
logger.error(f"Error acquiring database lock: {str(e)}")
if is_debug:
import traceback
traceback.print_exc()
async def update_channel_stats(request_id, provider, model, api_key, success):
if DISABLE_DATABASE:
return
try:
async with db_semaphore:
async with async_session() as session:
async with session.begin():
try:
channel_stat = ChannelStat(
request_id=request_id,
provider=provider,
model=model,
api_key=api_key,
success=success,
)
session.add(channel_stat)
await session.commit()
except Exception as e:
await session.rollback()
logger.error(f"Error updating channel stats: {str(e)}")
if is_debug:
import traceback
traceback.print_exc()
except Exception as e:
logger.error(f"Error acquiring database lock: {str(e)}")
if is_debug:
import traceback
traceback.print_exc()
class LoggingStreamingResponse(Response):
def __init__(self, content, status_code=200, headers=None, media_type=None, current_info=None):
super().__init__(content=None, status_code=status_code, headers=headers, media_type=media_type)
self.body_iterator = content
self._closed = False
self.current_info = current_info
# Remove Content-Length header if it exists
if 'content-length' in self.headers:
del self.headers['content-length']
# Set Transfer-Encoding to chunked
self.headers['transfer-encoding'] = 'chunked'
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
await send({
'type': 'http.response.start',
'status': self.status_code,
'headers': self.raw_headers,
})
try:
async for chunk in self._logging_iterator():
await send({
'type': 'http.response.body',
'body': chunk,
'more_body': True,
})
finally:
await send({
'type': 'http.response.body',
'body': b'',
'more_body': False,
})
if hasattr(self.body_iterator, 'aclose') and not self._closed:
await self.body_iterator.aclose()
self._closed = True
process_time = time() - self.current_info["start_time"]
self.current_info["process_time"] = process_time
await update_stats(self.current_info)
async def _logging_iterator(self):
try:
async for chunk in self.body_iterator:
if isinstance(chunk, str):
chunk = chunk.encode('utf-8')
if self.current_info.get("endpoint") == "/v1/audio/speech":
yield chunk
continue
line = chunk.decode('utf-8')
if is_debug:
logger.info(f"{line.encode('utf-8').decode('unicode_escape')}")
if line.startswith("data:"):
line = line.lstrip("data: ")
if not line.startswith("[DONE]") and not line.startswith("OK"):
try:
resp: dict = json.loads(line)
input_tokens = safe_get(resp, "message", "usage", "input_tokens", default=0)
input_tokens = safe_get(resp, "usage", "prompt_tokens", default=0)
output_tokens = safe_get(resp, "usage", "completion_tokens", default=0)
total_tokens = input_tokens + output_tokens
self.current_info["prompt_tokens"] = input_tokens
self.current_info["completion_tokens"] = output_tokens
self.current_info["total_tokens"] = total_tokens
except Exception as e:
logger.error(f"Error parsing response: {str(e)}, line: {repr(line)}")
continue
yield chunk
except Exception as e:
raise
finally:
logger.debug("_logging_iterator finished")
async def close(self):
if not self._closed:
self._closed = True
if hasattr(self.body_iterator, 'aclose'):
await self.body_iterator.aclose()
class StatsMiddleware(BaseHTTPMiddleware):
def __init__(self, app):
super().__init__(app)
async def dispatch(self, request: Request, call_next):
start_time = time()
enable_moderation = False # 默认不开启道德审查
config = app.state.config
# 根据token决定是否启用道德审查
if request.headers.get("x-api-key"):
token = request.headers.get("x-api-key")
elif request.headers.get("Authorization"):
api_split_list = request.headers.get("Authorization").split(" ")
if len(api_split_list) > 1:
token = api_split_list[1]
else:
return JSONResponse(
status_code=403,
content={"error": "Invalid or missing API Key"}
)
else:
token = None
api_index = None
if token:
try:
api_list = app.state.api_list
api_index = api_list.index(token)
except ValueError:
# 如果 token 不在 api_list 中,检查是否以 api_list 中的任何一个开头
api_index = next((i for i, api in enumerate(api_list) if token.startswith(api)), None)
# token不在api_list中,使用默认值(不开启)
pass
if api_index is not None:
enable_moderation = safe_get(config, 'api_keys', api_index, "preferences", "ENABLE_MODERATION", default=False)
else:
return JSONResponse(
status_code=403,
content={"error": "Invalid or missing API Key"}
)
else:
# 如果token为None,检查全局设置
enable_moderation = config.get('ENABLE_MODERATION', False)
# 在 app.state 中存储此请求的信息
request_id = str(uuid.uuid4())
# 初始化请求信息
request_info_data = {
"request_id": request_id,
"start_time": start_time,
"endpoint": f"{request.method} {request.url.path}",
"client_ip": request.client.host,
"process_time": 0,
"first_response_time": -1,
"provider": None,
"model": None,
"success": False,
"api_key": token,
"is_flagged": False,
"text": None,
"prompt_tokens": 0,
"completion_tokens": 0,
# "cost": 0,
"total_tokens": 0
}
# 设置请求信息到上下文
current_request_info = request_info.set(request_info_data)
current_info = request_info.get()
parsed_body = await parse_request_body(request)
if parsed_body:
try:
request_model = UnifiedRequest.model_validate(parsed_body).data
if is_debug:
logger.info("request_model: %s", json.dumps(request_model.model_dump(exclude_unset=True), indent=2, ensure_ascii=False))
model = request_model.model
current_info["model"] = model
final_api_key = app.state.api_list[api_index]
try:
await app.state.user_api_keys_rate_limit[final_api_key].next(model)
except Exception as e:
return JSONResponse(
status_code=429,
content={"error": "Too many requests"}
)
moderated_content = None
if request_model.request_type == "chat":
moderated_content = request_model.get_last_text_message()
elif request_model.request_type == "image":
moderated_content = request_model.prompt
elif request_model.request_type == "tts":
moderated_content = request_model.input
elif request_model.request_type == "moderation":
pass
elif request_model.request_type == "embedding":
if isinstance(request_model.input, list) and len(request_model.input) > 0 and isinstance(request_model.input[0], str):
moderated_content = "\n".join(request_model.input)
else:
moderated_content = request_model.input
else:
logger.error(f"Unknown request type: {request_model.request_type}")
if moderated_content:
current_info["text"] = moderated_content
if enable_moderation and moderated_content:
moderation_response = await self.moderate_content(moderated_content, api_index)
is_flagged = moderation_response.get('results', [{}])[0].get('flagged', False)
if is_flagged:
logger.error(f"Content did not pass the moral check: %s", moderated_content)
process_time = time() - start_time
current_info["process_time"] = process_time
current_info["is_flagged"] = is_flagged
await update_stats(current_info)
return JSONResponse(
status_code=400,
content={"error": "Content did not pass the moral check, please modify and try again."}
)
except RequestValidationError:
logger.error(f"Invalid request body: {parsed_body}")
pass
except Exception as e:
if is_debug:
import traceback
traceback.print_exc()
logger.error(f"Error processing request or performing moral check: {str(e)}")
try:
response = await call_next(request)
if request.url.path.startswith("/v1") and not DISABLE_DATABASE:
if isinstance(response, (FastAPIStreamingResponse, StarletteStreamingResponse)) or type(response).__name__ == '_StreamingResponse':
response = LoggingStreamingResponse(
content=response.body_iterator,
status_code=response.status_code,
media_type=response.media_type,
headers=response.headers,
current_info=current_info,
)
elif hasattr(response, 'json'):
logger.info(f"Response: {await response.json()}")
else:
logger.info(f"Response: type={type(response).__name__}, status_code={response.status_code}, headers={response.headers}")
return response
finally:
# print("current_request_info", current_request_info)
request_info.reset(current_request_info)
async def moderate_content(self, content, api_index):
moderation_request = ModerationRequest(input=content)
# 直接调用 moderations 函数
response = await moderations(moderation_request, api_index)
# 读取流式响应的内容
moderation_result = b""
async for chunk in response.body_iterator:
if isinstance(chunk, str):
moderation_result += chunk.encode('utf-8')
else:
moderation_result += chunk
# 解码并解析 JSON
moderation_data = json.loads(moderation_result.decode('utf-8'))
return moderation_data
# 配置 CORS 中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有来源
allow_credentials=True,
allow_methods=["*"], # 允许所有 HTTP 方法
allow_headers=["*"], # 允许所有头部字段
)
app.add_middleware(StatsMiddleware)
class ClientManager:
def __init__(self, pool_size=100):
self.pool_size = pool_size
self.clients = {} # {host_timeout_proxy: AsyncClient}
async def init(self, default_config):
self.default_config = default_config
@asynccontextmanager
async def get_client(self, timeout_value, base_url, proxy=None):
# 直接获取或创建客户端,不使用锁
timeout_value = int(timeout_value)
# 从base_url中提取主机名
parsed_url = urlparse(base_url)
host = parsed_url.netloc
# 创建唯一的客户端键
client_key = f"{host}_{timeout_value}"
if proxy:
# 对代理URL进行规范化处理
proxy_normalized = proxy.replace('socks5h://', 'socks5://')
client_key += f"_{proxy_normalized}"
if client_key not in self.clients or IS_VERCEL:
timeout = httpx.Timeout(
connect=15.0,
read=timeout_value,
write=30.0,
pool=self.pool_size
)
limits = httpx.Limits(max_connections=self.pool_size)
client_config = {
**self.default_config,
"timeout": timeout,
"limits": limits
}
if proxy:
# 解析代理URL
parsed = urlparse(proxy)
scheme = parsed.scheme.rstrip('h')
if scheme == 'socks5':
try:
from httpx_socks import AsyncProxyTransport
proxy = proxy.replace('socks5h://', 'socks5://')
transport = AsyncProxyTransport.from_url(proxy)
client_config["transport"] = transport
# print("proxy", proxy)
except ImportError:
logger.error("httpx-socks package is required for SOCKS proxy support")
raise ImportError("Please install httpx-socks package for SOCKS proxy support: pip install httpx-socks")
else:
client_config["proxies"] = {
"http://": proxy,
"https://": proxy
}
self.clients[client_key] = httpx.AsyncClient(**client_config)
try:
yield self.clients[client_key]
except Exception as e:
if client_key in self.clients:
tmp_client = self.clients[client_key]
del self.clients[client_key] # 先删除引用
await tmp_client.aclose() # 然后关闭客户端
raise e
async def close(self):
for client in self.clients.values():
await client.aclose()
self.clients.clear()
@app.middleware("http")
async def ensure_config(request: Request, call_next):
if app and not hasattr(app.state, 'config'):
# logger.warning("Config not found, attempting to reload")
app.state.config, app.state.api_keys_db, app.state.api_list = await load_config(app)
if app.state.api_list:
app.state.user_api_keys_rate_limit = defaultdict(ThreadSafeCircularList)
for api_index, api_key in enumerate(app.state.api_list):
app.state.user_api_keys_rate_limit[api_key] = ThreadSafeCircularList(
[api_key],
safe_get(app.state.config, 'api_keys', api_index, "preferences", "rate_limit", default={"default": "999999/min"}),
"round_robin"
)
for item in app.state.api_keys_db:
if item.get("role") == "admin":
app.state.admin_api_key = item.get("api")
if not hasattr(app.state, "admin_api_key"):
if len(app.state.api_keys_db) >= 1:
app.state.admin_api_key = app.state.api_keys_db[0].get("api")
else:
from utils import yaml_error_message
if yaml_error_message:
return JSONResponse(
status_code=500,
content={"error": yaml_error_message}
)
else:
return JSONResponse(
status_code=500,
content={"error": "No admin API key found"}
)
if app and not hasattr(app.state, 'client_manager'):
default_config = {
"headers": {
"User-Agent": "curl/7.68.0",
"Accept": "*/*",
},
"http2": True,
"verify": True,
"follow_redirects": True
}
# 初始化客户端管理器
app.state.client_manager = ClientManager(pool_size=200)
await app.state.client_manager.init(default_config)
# 存储超时配置
app.state.timeouts = {}
if app.state.config and 'preferences' in app.state.config:
if isinstance(app.state.config['preferences'].get('model_timeout'), int):
app.state.timeouts["default"] = app.state.config['preferences'].get('model_timeout')
else:
for model_name, timeout_value in app.state.config['preferences'].get('model_timeout', {"default": DEFAULT_TIMEOUT}).items():
app.state.timeouts[model_name] = timeout_value
if "default" not in app.state.config['preferences'].get('model_timeout', {}):
app.state.timeouts["default"] = DEFAULT_TIMEOUT
app.state.provider_timeouts = defaultdict(lambda: defaultdict(lambda: DEFAULT_TIMEOUT))
for provider in app.state.config["providers"]:
# print("provider", provider)
provider_timeout_settings = safe_get(provider, "preferences", "model_timeout", default={})
# print("provider_timeout_settings", provider_timeout_settings)
if provider_timeout_settings:
for model_name, timeout_value in provider_timeout_settings.items():
app.state.provider_timeouts[provider['provider']][model_name] = timeout_value
app.state.provider_timeouts["global_time_out"] = app.state.timeouts
# provider_timeouts_dict = {
# provider: dict(timeouts)
# for provider, timeouts in app.state.provider_timeouts.items()
# }
# print("app.state.provider_timeouts", provider_timeouts_dict)
# print("ai" in app.state.provider_timeouts)
if app and not hasattr(app.state, "channel_manager"):
if app.state.config and 'preferences' in app.state.config:
COOLDOWN_PERIOD = app.state.config['preferences'].get('cooldown_period', 300)
else:
COOLDOWN_PERIOD = 300
app.state.channel_manager = ChannelManager(cooldown_period=COOLDOWN_PERIOD)
if app and not hasattr(app.state, "error_triggers"):
if app.state.config and 'preferences' in app.state.config:
ERROR_TRIGGERS = app.state.config['preferences'].get('error_triggers', [])
else:
ERROR_TRIGGERS = []
app.state.error_triggers = ERROR_TRIGGERS
if app and app.state.api_keys_db and not hasattr(app.state, "models_list"):
app.state.models_list = {}
for item in app.state.api_keys_db:
api_key_model_list = item.get("model", [])
for provider_rule in api_key_model_list:
provider_name = provider_rule.split("/")[0]
if provider_name.startswith("sk-") and provider_name in app.state.api_list:
models_list = []
try:
# 构建请求头
headers = {
"Authorization": f"Bearer {provider_name}"
}
# 发送GET请求获取模型列表
base_url = "http://127.0.0.1:8000/v1/models"
async with app.state.client_manager.get_client(1, base_url) as client:
response = await client.get(
base_url,
headers=headers
)
if response.status_code == 200:
models_data = response.json()
# 将获取到的模型添加到models_list
for model in models_data.get("data", []):
models_list.append(model["id"])
except Exception as e:
if str(e):
logger.error(f"获取模型列表失败: {str(e)}")
app.state.models_list[provider_name] = models_list
return await call_next(request)
def get_timeout_value(provider_timeouts, original_model):
timeout_value = None
original_model = original_model.lower()
if original_model in provider_timeouts:
timeout_value = provider_timeouts[original_model]
else:
# 尝试模糊匹配模型
for timeout_model in provider_timeouts:
if timeout_model != "default" and timeout_model in original_model:
timeout_value = provider_timeouts[timeout_model]
break
else:
# 如果模糊匹配失败,使用渠道的默认值
timeout_value = provider_timeouts.get("default")
return timeout_value
# 在 process_request 函数中更新成功和失败计数
async def process_request(request: Union[RequestModel, ImageGenerationRequest, AudioTranscriptionRequest, ModerationRequest, EmbeddingRequest], provider: Dict, endpoint=None, role=None):
url = provider['base_url']
parsed_url = urlparse(url)
# print("parsed_url", parsed_url)
engine = None
if parsed_url.path.endswith("/v1beta") or parsed_url.path.endswith("/v1"):
engine = "gemini"
elif parsed_url.netloc == 'aiplatform.googleapis.com':
engine = "vertex"
elif parsed_url.netloc.rstrip('/').endswith('openai.azure.com'):
engine = "azure"
elif parsed_url.netloc == 'api.cloudflare.com':
engine = "cloudflare"
elif parsed_url.netloc == 'api.anthropic.com' or parsed_url.path.endswith("v1/messages"):
engine = "claude"
elif parsed_url.netloc == 'api.cohere.com':
engine = "cohere"
request.stream = True
else:
engine = "gpt"
model_dict = get_model_dict(provider)
original_model = model_dict[request.model]
if "claude" not in original_model \
and "gpt" not in original_model \
and "deepseek" not in original_model \
and "o1" not in original_model \
and "o3" not in original_model \
and "gemini" not in original_model \
and "learnlm" not in original_model \
and "grok" not in original_model \
and parsed_url.netloc != 'api.cloudflare.com' \
and parsed_url.netloc != 'api.cohere.com':
engine = "openrouter"
if "claude" in original_model and engine == "vertex":
engine = "vertex-claude"
if "gemini" in original_model and engine == "vertex":
engine = "vertex-gemini"
if provider.get("engine"):
engine = provider["engine"]
if endpoint == "/v1/images/generations" or "stable-diffusion" in original_model:
engine = "dalle"
request.stream = False
if endpoint == "/v1/audio/transcriptions":
engine = "whisper"
request.stream = False
if endpoint == "/v1/moderations":
engine = "moderation"
request.stream = False
if endpoint == "/v1/embeddings":
engine = "embedding"
if endpoint == "/v1/audio/speech":
engine = "tts"
request.stream = False
channel_id = f"{provider['provider']}"
if engine != "moderation":
logger.info(f"provider: {channel_id:<11} model: {request.model:<22} engine: {engine} role: {role}")
url, headers, payload = await get_payload(request, engine, provider)
if is_debug:
logger.info(url)
logger.info(json.dumps(headers, indent=4, ensure_ascii=False))
if payload.get("file"):
pass
else:
logger.info(json.dumps(payload, indent=4, ensure_ascii=False))
current_info = request_info.get()
provider_timeouts = safe_get(app.state.provider_timeouts, channel_id, default=app.state.provider_timeouts["global_time_out"])
timeout_value = get_timeout_value(provider_timeouts, original_model)
if timeout_value is None:
timeout_value = get_timeout_value(app.state.provider_timeouts["global_time_out"], original_model)
if timeout_value is None:
timeout_value = app.state.timeouts.get("default", DEFAULT_TIMEOUT)
# print("timeout_value", timeout_value)
proxy = safe_get(provider, "preferences", "proxy", default=None)
# print("proxy", proxy)
try:
async with app.state.client_manager.get_client(timeout_value, url, proxy) as client:
if request.stream:
generator = fetch_response_stream(client, url, headers, payload, engine, original_model)
wrapped_generator, first_response_time = await error_handling_wrapper(generator, channel_id, engine, request.stream, app.state.error_triggers)
response = StarletteStreamingResponse(wrapped_generator, media_type="text/event-stream")
else:
generator = fetch_response(client, url, headers, payload, engine, original_model)
wrapped_generator, first_response_time = await error_handling_wrapper(generator, channel_id, engine, request.stream, app.state.error_triggers)
# 处理音频和其他二进制响应
if endpoint == "/v1/audio/speech":
if isinstance(wrapped_generator, bytes):
response = Response(content=wrapped_generator, media_type="audio/mpeg")
else:
first_element = await anext(wrapped_generator)
first_element = first_element.lstrip("data: ")
first_element = json.loads(first_element)
response = StarletteStreamingResponse(iter([json.dumps(first_element)]), media_type="application/json")
# 更新成功计数和首次响应时间
await update_channel_stats(current_info["request_id"], channel_id, request.model, current_info["api_key"], success=True)
current_info["first_response_time"] = first_response_time
current_info["success"] = True
current_info["provider"] = channel_id
return response
except (Exception, HTTPException, asyncio.CancelledError, httpx.ReadError, httpx.RemoteProtocolError, httpx.ReadTimeout, httpx.ConnectError) as e:
await update_channel_stats(current_info["request_id"], channel_id, request.model, current_info["api_key"], success=False)
raise e
def weighted_round_robin(weights):
provider_names = list(weights.keys())
current_weights = {name: 0 for name in provider_names}
num_selections = total_weight = sum(weights.values())
weighted_provider_list = []
for _ in range(num_selections):
max_ratio = -1
selected_letter = None
for name in provider_names:
current_weights[name] += weights[name]
ratio = current_weights[name] / weights[name]
if ratio > max_ratio:
max_ratio = ratio
selected_letter = name
weighted_provider_list.append(selected_letter)
current_weights[selected_letter] -= total_weight
return weighted_provider_list
import random
def lottery_scheduling(weights):
total_tickets = sum(weights.values())
selections = []
for _ in range(total_tickets):
ticket = random.randint(1, total_tickets)
cumulative = 0
for provider, weight in weights.items():
cumulative += weight
if ticket <= cumulative:
selections.append(provider)
break
return selections
async def get_provider_rules(model_rule, config, request_model):
provider_rules = []
if model_rule == "all":
# 如模型名为 all,则返回所有模型
for provider in config["providers"]:
model_dict = get_model_dict(provider)
for model in model_dict.keys():
provider_rules.append(provider["provider"] + "/" + model)
elif "/" in model_rule:
if model_rule.startswith("<") and model_rule.endswith(">"):
model_rule = model_rule[1:-1]
# 处理带斜杠的模型名
for provider in config['providers']:
model_dict = get_model_dict(provider)
if model_rule in model_dict.keys():
provider_rules.append(provider['provider'] + "/" + model_rule)
else:
provider_name = model_rule.split("/")[0]