-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathmain.py
More file actions
3243 lines (2838 loc) · 133 KB
/
main.py
File metadata and controls
3243 lines (2838 loc) · 133 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 os
import io
import re
import json
import uuid
import codecs
import httpx
import string
import secrets
import tomllib
import asyncio
from asyncio import Semaphore
import contextvars
from time import time
from urllib.parse import urlparse
from collections import defaultdict
from contextlib import asynccontextmanager, suppress
from datetime import datetime, timedelta, timezone
from typing import Dict, Union, Optional, List, Any
from pydantic import ValidationError, BaseModel, field_serializer
from starlette.responses import Response
from starlette.types import Scope, Receive, Send
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import StreamingResponse as StarletteStreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import StreamingResponse as FastAPIStreamingResponse
from fastapi import FastAPI, HTTPException, Depends, Request, Body, BackgroundTasks, UploadFile, File, Form, Query
from core.log_config import logger, trace_logger
from core.request import (
CODEX_CLI_VERSION,
CODEX_USER_AGENT,
apply_post_body_parameter_overrides,
force_codex_client_headers,
get_payload,
strip_unsupported_codex_payload_fields,
)
from core.response import fetch_response, fetch_response_stream
from core.models import RequestModel, ResponsesRequest, ImageGenerationRequest, ImageEditRequest, AudioTranscriptionRequest, ModerationRequest, TextToSpeechRequest, UnifiedRequest, EmbeddingRequest
from core.utils import (
get_proxy,
get_engine,
parse_rate_limit,
collect_openai_chat_completion_from_streaming_sse,
ThreadSafeCircularList,
provider_api_circular_list,
)
from routing import (
RoutingPlan,
build_api_key_models_map,
estimate_request_total_tokens,
get_right_order_providers,
select_provider_api_key_raw,
)
from upstream import (
UPSTREAM_NETWORK_ERRORS,
UpstreamRunner,
build_upstream_error_response,
)
from utils import (
safe_get,
load_config,
update_config,
post_all_models,
InMemoryRateLimiter,
error_handling_wrapper,
query_channel_key_stats,
)
from sqlalchemy import inspect, text
from sqlalchemy.sql import sqltypes
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, case, func, desc
from db import Base, RequestStat, ChannelStat, db_engine, async_session, DISABLE_DATABASE
DEFAULT_TIMEOUT = int(os.getenv("TIMEOUT", 100))
is_debug = bool(os.getenv("DEBUG", False))
logger.info("DISABLE_DATABASE: %s", DISABLE_DATABASE)
# 从 pyproject.toml 读取版本号
try:
with open('pyproject.toml', 'rb') as f:
data = tomllib.load(f)
VERSION = data['project']['version']
except Exception:
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)
# 检查并添加缺失的列 - 扩展此简易迁移以支持 SQLite 和 PostgreSQL
db_type = os.getenv("DB_TYPE", "sqlite").lower()
if db_type in ["sqlite", "postgres"]:
def check_and_add_columns(connection):
inspector = inspect(connection)
for table in [RequestStat, ChannelStat]:
table_name = table.__tablename__
existing_columns = {col['name'] for col in inspector.get_columns(table_name)}
for column_name, column in table.__table__.columns.items():
if column_name not in existing_columns:
# 适配 PostgreSQL 和 SQLite 的类型映射
col_type = column.type.compile(connection.dialect)
default = _get_default_sql(column.default) if db_type == "sqlite" else "" # PostgreSQL 的默认值处理更复杂,暂不处理
# 使用标准的 ALTER TABLE 语法
connection.execute(text(f'ALTER TABLE "{table_name}" ADD COLUMN "{column_name}" {col_type}{default}'))
logger.info(f"Added column '{column_name}' to table '{table_name}'.")
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 ""
def init_preference(all_config, preference_key, default_timeout=DEFAULT_TIMEOUT):
# 存储超时配置
preference_dict = {}
preferences = safe_get(all_config, "preferences", default={})
providers = safe_get(all_config, "providers", default=[])
if preferences:
if isinstance(preferences.get(preference_key), int):
preference_dict["default"] = preferences.get(preference_key)
else:
for model_name, timeout_value in preferences.get(preference_key, {"default": default_timeout}).items():
preference_dict[model_name] = timeout_value
if "default" not in preferences.get(preference_key, {}):
preference_dict["default"] = default_timeout
result = defaultdict(lambda: defaultdict(lambda: default_timeout))
for provider in providers:
provider_preference_settings = safe_get(provider, "preferences", preference_key, default={})
if provider_preference_settings:
for model_name, timeout_value in provider_preference_settings.items():
result[provider['provider']][model_name] = timeout_value
result["global"] = preference_dict
# print("result", json.dumps(result, indent=4))
return result
def _build_user_api_keys_rate_limit(config: dict, api_list: list[str]) -> defaultdict:
user_api_keys_rate_limit = defaultdict(ThreadSafeCircularList)
for api_index, api_key in enumerate(api_list):
user_api_keys_rate_limit[api_key] = ThreadSafeCircularList(
[api_key],
safe_get(config, "api_keys", api_index, "preferences", "rate_limit", default={"default": "999999/min"}),
"round_robin",
)
return user_api_keys_rate_limit
def _build_admin_api_keys(api_keys_db: list[dict]) -> list[str]:
admin_api_key = []
for item in api_keys_db:
if "admin" in item.get("role", ""):
admin_api_key.append(item.get("api"))
if admin_api_key:
return admin_api_key
if api_keys_db:
return [api_keys_db[0].get("api")]
from utils import yaml_error_message
if yaml_error_message:
raise HTTPException(
status_code=500,
detail={"error": yaml_error_message},
)
raise HTTPException(
status_code=500,
detail={"error": "No API key found in api.yaml"},
)
async def refresh_runtime_state(app: FastAPI) -> None:
config = getattr(app.state, "config", {}) or {}
api_keys_db = getattr(app.state, "api_keys_db", []) or []
api_list = getattr(app.state, "api_list", []) or []
app.state.user_api_keys_rate_limit = _build_user_api_keys_rate_limit(config, api_list)
app.state.global_rate_limit = parse_rate_limit(
safe_get(config, "preferences", "rate_limit", default="999999/min")
)
app.state.admin_api_key = _build_admin_api_keys(api_keys_db)
app.state.provider_timeouts = init_preference(config, "model_timeout", DEFAULT_TIMEOUT)
app.state.keepalive_interval = init_preference(config, "keepalive_interval", 99999)
app.state.models_list = build_api_key_models_map(config, api_list)
if not DISABLE_DATABASE:
app.state.paid_api_keys_states = {}
for paid_key in api_list:
await update_paid_api_keys_states(app, paid_key)
def get_runtime_api_list() -> list[str]:
runtime_api_list = getattr(app.state, "api_list", None)
if runtime_api_list:
return runtime_api_list
config = getattr(app.state, "config", {}) or {}
return [item.get("api") for item in config.get("api_keys", []) if item.get("api")]
def get_current_model_prices(model_name: str):
"""
根据当前配置偏好,返回指定模型的 prompt_price 和 completion_price(单位:$/M tokens)
"""
try:
model_price = safe_get(app.state.config, 'preferences', "model_price", default={})
price_str = next((model_price[k] for k in model_price.keys() if model_name and model_name.startswith(k)), model_price.get("default", "0.3,1"))
parts = [p.strip() for p in str(price_str).split(",")]
prompt_price = float(parts[0]) if len(parts) > 0 and parts[0] != "" else 0.3
completion_price = float(parts[1]) if len(parts) > 1 and parts[1] != "" else 1.0
return prompt_price, completion_price
except Exception:
return 0.3, 1.0
async def compute_total_cost_from_db(filter_api_key: Optional[str] = None, start_dt_obj: Optional[datetime] = None) -> float:
"""
直接从数据库历史记录累计成本:
sum((prompt_tokens*prompt_price + completion_tokens*completion_price)/1e6)
"""
if DISABLE_DATABASE:
return 0.0
async with async_session() as session:
expr = (func.coalesce(RequestStat.prompt_tokens, 0) * func.coalesce(RequestStat.prompt_price, 0.3) + func.coalesce(RequestStat.completion_tokens, 0) * func.coalesce(RequestStat.completion_price, 1.0)) / 1000000.0
query = select(func.coalesce(func.sum(expr), 0.0))
if filter_api_key:
query = query.where(RequestStat.api_key == filter_api_key)
if start_dt_obj:
query = query.where(RequestStat.timestamp >= start_dt_obj)
result = await session.execute(query)
total_cost = result.scalar_one() or 0.0
try:
total_cost = float(total_cost)
except Exception:
total_cost = 0.0
return total_cost
async def update_paid_api_keys_states(app, paid_key):
"""
更新付费API密钥的状态
参数:
app - FastAPI应用实例
check_index - API密钥在配置中的索引
paid_key - 需要更新状态的API密钥
"""
try:
check_index = app.state.api_list.index(paid_key)
except Exception:
raise HTTPException(
status_code=403,
detail={"error": "Invalid or missing API Key"}
)
credits = safe_get(app.state.config, 'api_keys', check_index, "preferences", "credits", default=-1)
created_at = safe_get(app.state.config, 'api_keys', check_index, "preferences", "created_at", default=datetime.now(timezone.utc) - timedelta(days=30))
created_at = created_at.astimezone(timezone.utc)
# 关键修改:总消耗改为从历史数据逐条累计当时价格
total_cost = await compute_total_cost_from_db(filter_api_key=paid_key, start_dt_obj=created_at)
if credits != -1:
# 仍返回聚合的 token 统计,供前端展示
all_tokens_info = await get_usage_data(filter_api_key=paid_key, start_dt_obj=created_at)
app.state.paid_api_keys_states[paid_key] = {
"credits": credits,
"created_at": created_at,
"all_tokens_info": all_tokens_info,
"total_cost": total_cost,
"enabled": True if total_cost <= credits else False
}
return credits, total_cost
# logger.info(f"app.state.paid_api_keys_states {paid_key}: {json.dumps({k: v.isoformat() if k == 'created_at' else v for k, v in app.state.paid_api_keys_states[paid_key].items()}, indent=4)}")
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时的代码
if not DISABLE_DATABASE:
await create_tables()
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)
# from ruamel.yaml.timestamp import TimeStamp
# def json_default(obj):
# if isinstance(obj, TimeStamp):
# return obj.isoformat()
# raise TypeError
# print("app.state.config", json.dumps(app.state.config, indent=4, ensure_ascii=False, default=json_default))
await refresh_runtime_state(app)
if app and not hasattr(app.state, 'client_manager'):
default_config = {
"headers": {
"User-Agent": "curl/7.68.0",
"Accept": "*/*",
"Accept-Encoding": "identity",
},
"http2": True,
"verify": True,
"follow_redirects": True
}
# 初始化客户端管理器
app.state.client_manager = ClientManager(pool_size=100)
await app.state.client_manager.init(default_config)
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
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(RequestValidationError)
# async def validation_exception_handler(request: Request, exc: RequestValidationError):
# error_messages = []
# for error in exc.errors():
# # 将字段路径转换为点分隔格式(例如 body.model -> model)
# field = ".".join(str(loc) for loc in error["loc"] if loc not in ("body", "query", "path"))
# error_type = error["type"]
# # 生成更友好的错误消息
# if error_type == "value_error.missing":
# msg = f"字段 '{field}' 是必填项"
# elif error_type == "type_error.integer":
# msg = f"字段 '{field}' 必须是整数类型"
# elif error_type == "type_error.str":
# msg = f"字段 '{field}' 必须是字符串类型"
# else:
# msg = error["msg"]
# error_messages.append({
# "field": field,
# "message": msg,
# "type": error_type
# })
# return JSONResponse(
# status_code=422,
# content={"detail": error_messages},
# )
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
if exc.status_code == 404:
token = await get_api_key(request)
logger.error(f"404 Error: {exc.detail} api_key: {token}")
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail},
)
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:
body_bytes = await request.body()
if not body_bytes:
return None
return await asyncio.to_thread(json.loads, body_bytes)
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, cooldown_period=0) -> 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=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] # 目标模型名称
cooldown_period = provider.get('preferences', {}).get('cooldown_period', self.cooldown_period)
# 检查该模型是否被排除
if not await self.is_model_excluded(provider_name, target_model, cooldown_period):
available_providers.append(provider)
return available_providers
# 根据数据库类型,动态创建信号量
# SQLite 需要严格的串行写入,而 PostgreSQL 可以处理高并发
if os.getenv("DB_TYPE", "sqlite").lower() == 'sqlite':
db_semaphore = Semaphore(1)
logger.info("Database semaphore configured for SQLite (1 concurrent writer).")
else: # For postgres
# 允许50个并发写入操作,这对于PostgreSQL来说是合理的
db_semaphore = Semaphore(50)
logger.info("Database semaphore configured for PostgreSQL (50 concurrent writers).")
async def update_stats(current_info):
if DISABLE_DATABASE:
return
# 在成功请求时,快照当前价格,写入数据库
try:
if current_info.get("success") and current_info.get("model"):
prompt_price, completion_price = get_current_model_prices(current_info["model"])
current_info["prompt_price"] = prompt_price
current_info["completion_price"] = completion_price
except Exception:
pass
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}
# 清洗字符串中的 NUL 字符,防止 PostgreSQL 报错
for key, value in filtered_info.items():
if isinstance(value, str):
filtered_info[key] = value.replace('\x00', '')
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()
check_key = current_info["api_key"]
if check_key and check_key in app.state.paid_api_keys_states and current_info["total_tokens"] > 0:
await update_paid_api_keys_states(app, check_key)
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, provider_api_key: str = None):
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,
provider_api_key=provider_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
self._sse_buffer = ""
# 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,
})
except Exception as e:
# 记录异常但不重新抛出,避免"Task exception was never retrieved"
logger.error(f"Error in streaming response: {type(e).__name__}: {str(e)}")
if is_debug:
import traceback
traceback.print_exc()
# 发送错误消息给客户端(如果可能)
try:
error_data = json.dumps({"error": f"Streaming error: {str(e)}"})
await send({
'type': 'http.response.body',
'body': f"data: {error_data}\n\n".encode('utf-8'),
'more_body': True,
})
except Exception as e:
logger.error(f"Error sending error message: {str(e)}")
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):
async for chunk in self.body_iterator:
if isinstance(chunk, str):
chunk = chunk.encode('utf-8')
if self.current_info.get("endpoint").endswith("/v1/audio/speech"):
yield chunk
continue
try:
text = chunk.decode("utf-8", errors="replace")
except Exception:
yield chunk
continue
if is_debug:
try:
logger.info(text.encode("utf-8").decode("unicode_escape"))
except Exception:
logger.info(text)
# Stream may contain multiple SSE lines per chunk, and/or partial lines.
self._sse_buffer += text
while "\n" in self._sse_buffer:
line, self._sse_buffer = self._sse_buffer.split("\n", 1)
line = line.rstrip("\r")
if not line or line.startswith(":") or line.startswith("event:"):
continue
data = None
if line.startswith("data:"):
data = line.removeprefix("data:").lstrip()
elif line.startswith("{") or line.startswith("["):
data = line
if not data:
continue
if data.startswith("[DONE]") or data.startswith("OK"):
continue
# Avoid parsing every delta event; only parse when usage is present.
if "\"usage\"" not in data:
continue
try:
resp = await asyncio.to_thread(json.loads, data)
except Exception:
continue
usage_obj = None
if isinstance(resp, dict):
usage_obj = resp.get("usage") or safe_get(resp, "response", "usage", default=None) or safe_get(resp, "message", "usage", default=None)
if not isinstance(usage_obj, dict):
continue
prompt_tokens = usage_obj.get("prompt_tokens")
completion_tokens = usage_obj.get("completion_tokens")
if prompt_tokens is None and "input_tokens" in usage_obj:
prompt_tokens = usage_obj.get("input_tokens")
if completion_tokens is None and "output_tokens" in usage_obj:
completion_tokens = usage_obj.get("output_tokens")
try:
prompt_tokens = int(prompt_tokens or 0)
except Exception:
prompt_tokens = 0
try:
completion_tokens = int(completion_tokens or 0)
except Exception:
completion_tokens = 0
total_tokens = usage_obj.get("total_tokens")
try:
total_tokens = int(total_tokens) if total_tokens is not None else (prompt_tokens + completion_tokens)
except Exception:
total_tokens = prompt_tokens + completion_tokens
self.current_info["prompt_tokens"] = prompt_tokens
self.current_info["completion_tokens"] = completion_tokens
self.current_info["total_tokens"] = total_tokens
yield chunk
async def close(self):
if not self._closed:
self._closed = True
if hasattr(self.body_iterator, 'aclose'):
await self.body_iterator.aclose()
async def get_api_key(request: Request):
token = None
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]
return token
def get_client_ip(request: Request) -> str:
"""
获取客户端真实 IP 地址,支持代理场景
优先级:X-Forwarded-For > X-Real-IP > CF-Connecting-IP > True-Client-IP > request.client.host
"""
# 1. X-Forwarded-For: 最常用的代理头,格式为 "client, proxy1, proxy2"
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
# 取第一个 IP(真实客户端 IP)
return forwarded_for.split(",")[0].strip()
# 2. X-Real-IP: nginx 常用
real_ip = request.headers.get("X-Real-IP")
if real_ip:
return real_ip.strip()
# 3. CF-Connecting-IP: Cloudflare 使用
cf_ip = request.headers.get("CF-Connecting-IP")
if cf_ip:
return cf_ip.strip()
# 4. True-Client-IP: 部分 CDN 使用
true_client_ip = request.headers.get("True-Client-IP")
if true_client_ip:
return true_client_ip.strip()
# 5. 回退到直连 IP
return request.client.host if request.client else "unknown"
async def monitor_disconnect(request: Request, disconnect_event: asyncio.Event) -> None:
try:
while not disconnect_event.is_set():
message = await request.receive()
if message.get("type") == "http.disconnect":
disconnect_event.set()
return
except asyncio.CancelledError:
return
except Exception:
disconnect_event.set()
class StatsMiddleware(BaseHTTPMiddleware):
def __init__(self, app):
super().__init__(app)
async def dispatch(self, request: Request, call_next):
# 如果是 OPTIONS 请求,直接放行,由 CORSMiddleware 处理
if request.method == "OPTIONS":
return await call_next(request)
start_time = time()
# 根据token决定是否启用道德审查
token = await get_api_key(request)
if not token:
return JSONResponse(
status_code=403,
content={"error": "Invalid or missing API Key"}
)
enable_moderation = False # 默认不开启道德审查
config = app.state.config
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)
api_index = None
# token不在api_list中,使用默认值(不开启)
if api_index is not None:
enable_moderation = safe_get(config, 'api_keys', api_index, "preferences", "ENABLE_MODERATION", default=False)
if not DISABLE_DATABASE:
check_api_key = safe_get(config, 'api_keys', api_index, "api")
# print("check_api_key", check_api_key)
# logger.info(f"app.state.paid_api_keys_states {check_api_key}: {json.dumps({k: v.isoformat() if k == 'created_at' else v for k, v in app.state.paid_api_keys_states[check_api_key].items()}, indent=4)}")
# print("app.state.paid_api_keys_states", safe_get(app.state.paid_api_keys_states, check_api_key, "enabled", default=None))
if safe_get(app.state.paid_api_keys_states, check_api_key, "enabled", default=None) is False and \
not request.url.path.startswith("/v1/token_usage"):
return JSONResponse(
status_code=429,
content={"error": "Balance is insufficient, please check your account."}
)
else:
return JSONResponse(
status_code=403,
content={"error": "Invalid or missing API Key"}
)
# 在 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": get_client_ip(request),
"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,
"total_tokens": 0
}
# 设置请求信息到上下文
current_request_info = request_info.set(request_info_data)
current_info = request_info.get()
disconnect_event: Optional[asyncio.Event] = None
disconnect_task: Optional[asyncio.Task] = None
try:
parsed_body = await parse_request_body(request)
if request.method == "POST" and "application/json" in request.headers.get("content-type", ""):
disconnect_event = asyncio.Event()
current_info["disconnect_event"] = disconnect_event
disconnect_task = asyncio.create_task(monitor_disconnect(request, disconnect_event))
if parsed_body and not request.url.path.startswith("/v1/api_config"):
request_model = await asyncio.to_thread(UnifiedRequest.model_validate, parsed_body)
request_model = request_model.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:
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 enable_moderation and moderated_content:
background_tasks_for_moderation = BackgroundTasks()
moderation_response = await self.moderate_content(moderated_content, api_index, background_tasks_for_moderation)
is_flagged = moderation_response.get('results', [{}])[0].get('flagged', False)
if is_flagged:
logger.error(f"Content did not pass the moral check: {moderated_content}")
process_time = time() - start_time
current_info["process_time"] = process_time
current_info["is_flagged"] = is_flagged
current_info["text"] = moderated_content # 仅在标记时记录文本
await update_stats(current_info)
return JSONResponse(
status_code=400,
content={"error": "Content did not pass the moral check, please modify and try again."}
)
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
except HTTPException:
# Let FastAPI's http_exception_handler format the response consistently.
raise
except ValidationError as e:
logger.error(f"API key: {token}, Invalid request body: {json.dumps(parsed_body, indent=2, ensure_ascii=False)}, errors: {e.errors()}")
content = await asyncio.to_thread(jsonable_encoder, {"detail": e.errors()})
return JSONResponse(
status_code=422,
content=content
)
except Exception as e:
if is_debug:
import traceback
traceback.print_exc()
logger.error(f"Error processing request: {str(e)}")
return JSONResponse(
status_code=500,
content={"error": f"Internal server error: {str(e)}"}
)
finally:
if disconnect_task is not None:
disconnect_task.cancel()
with suppress(asyncio.CancelledError):
await disconnect_task
# print("current_request_info", current_request_info)
request_info.reset(current_request_info)
async def moderate_content(self, content, api_index, background_tasks: BackgroundTasks):
moderation_request = ModerationRequest(input=content)
# 直接调用 moderations 函数
response = await moderations(moderation_request, background_tasks, 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)
@app.middleware("http")
async def ensure_config(request: Request, call_next):
if app and app.state.api_keys_db and not hasattr(app.state, "models_list"):
app.state.models_list = build_api_key_models_map(app.state.config, app.state.api_list)
return await call_next(request)
class ClientManager:
def __init__(self, pool_size=100):
self.pool_size = pool_size
self.clients = {} # {host_timeout_proxy: AsyncClient}
self._client_locks = defaultdict(asyncio.Lock)
async def init(self, default_config):
self.default_config = default_config
@asynccontextmanager
async def get_client(self, base_url, proxy=None, http2: Optional[bool] = None):
# 从base_url中提取主机名
parsed_url = urlparse(base_url)
host = parsed_url.netloc