🐛 Bug: Fix bug in total time calculation
Browse files✨ Feature: Add support for storing the number ofinput and output tokens to the database.
📖 Docs: Update documentation
💻 Code: Refactor code: Use UUID for each request
- .gitignore +1 -0
- README.md +11 -0
- README_CN.md +11 -0
- main.py +208 -38
- models.py +13 -13
- response.py +1 -2
.gitignore
CHANGED
|
@@ -11,3 +11,4 @@ node_modules
|
|
| 11 |
*.png
|
| 12 |
*.db
|
| 13 |
.aider*
|
|
|
|
|
|
| 11 |
*.png
|
| 12 |
*.db
|
| 13 |
.aider*
|
| 14 |
+
.idea
|
README.md
CHANGED
|
@@ -126,6 +126,17 @@ api_keys:
|
|
| 126 |
AUTO_RETRY: true
|
| 127 |
```
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
## Environment Variables
|
| 130 |
|
| 131 |
- CONFIG_URL: The download address of the configuration file, it can be a local file or a remote file, optional
|
|
|
|
| 126 |
AUTO_RETRY: true
|
| 127 |
```
|
| 128 |
|
| 129 |
+
If you do not want to set available channels for each `api` one by one in `api_keys`, `uni-api` supports setting the `api key` to be able to use all models. The configuration is as follows:
|
| 130 |
+
|
| 131 |
+
```yaml
|
| 132 |
+
# ... providers configuration unchanged ...
|
| 133 |
+
api_keys:
|
| 134 |
+
- api: sk-LjjI60Yf0JFWxfgRmXqFWyGtWUd9GZnmi3KlvowmRWpWpQRo # API Key, users need an API key to request uni-api, required
|
| 135 |
+
model: # The model that can be used with this API Key, required
|
| 136 |
+
- * # Can use all models in all channels set under providers, no need to add available channels one by one.
|
| 137 |
+
# ... other configurations unchanged ...
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
## Environment Variables
|
| 141 |
|
| 142 |
- CONFIG_URL: The download address of the configuration file, it can be a local file or a remote file, optional
|
README_CN.md
CHANGED
|
@@ -126,6 +126,17 @@ api_keys:
|
|
| 126 |
AUTO_RETRY: true
|
| 127 |
```
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
## 环境变量
|
| 130 |
|
| 131 |
- CONFIG_URL: 配置文件的下载地址,可以是本地文件,也可以是远程文件,选填
|
|
|
|
| 126 |
AUTO_RETRY: true
|
| 127 |
```
|
| 128 |
|
| 129 |
+
如果你不想在 `api_keys` 里面给每个 `api` 一个个设置可用渠道,`uni-api` 支持将 `api key` 设置为可以使用所有模型,配置如下:
|
| 130 |
+
|
| 131 |
+
```yaml
|
| 132 |
+
# ... providers 配置不变 ...
|
| 133 |
+
api_keys:
|
| 134 |
+
- api: sk-LjjI60Yf0JFWxfgRmXqFWyGtWUd9GZnmi3KlvowmRWpWpQRo # API Key,用户请求 uni-api 需要 API key,必填
|
| 135 |
+
model: # 该 API Key 可以使用的模型,必填
|
| 136 |
+
- * # 可以使用 providers 下面设置的所有渠道里面的所有模型,不需要一个个添加可用渠道。
|
| 137 |
+
# ... 其他配置不变 ...
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
## 环境变量
|
| 141 |
|
| 142 |
- CONFIG_URL: 配置文件的下载地址,可以是本地文件,也可以是远程文件,选填
|
main.py
CHANGED
|
@@ -5,6 +5,7 @@ import httpx
|
|
| 5 |
import secrets
|
| 6 |
import time as time_module
|
| 7 |
from contextlib import asynccontextmanager
|
|
|
|
| 8 |
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
from fastapi import FastAPI, HTTPException, Depends, Request
|
|
@@ -26,6 +27,7 @@ import string
|
|
| 26 |
import json
|
| 27 |
|
| 28 |
is_debug = bool(os.getenv("DEBUG", False))
|
|
|
|
| 29 |
|
| 30 |
from sqlalchemy import inspect, text
|
| 31 |
from sqlalchemy.sql import sqltypes
|
|
@@ -106,11 +108,12 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
|
| 106 |
content={"message": exc.detail},
|
| 107 |
)
|
| 108 |
|
|
|
|
|
|
|
| 109 |
import asyncio
|
| 110 |
from time import time
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
import json
|
| 114 |
|
| 115 |
async def parse_request_body(request: Request):
|
| 116 |
if request.method == "POST" and "application/json" in request.headers.get("content-type", ""):
|
|
@@ -131,23 +134,31 @@ Base = declarative_base()
|
|
| 131 |
class RequestStat(Base):
|
| 132 |
__tablename__ = 'request_stats'
|
| 133 |
id = Column(Integer, primary_key=True)
|
|
|
|
| 134 |
endpoint = Column(String)
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
| 138 |
model = Column(String)
|
|
|
|
|
|
|
| 139 |
is_flagged = Column(Boolean, default=False)
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
timestamp = Column(DateTime(timezone=True), server_default=func.now())
|
| 142 |
|
| 143 |
class ChannelStat(Base):
|
| 144 |
__tablename__ = 'channel_stats'
|
| 145 |
id = Column(Integer, primary_key=True)
|
|
|
|
| 146 |
provider = Column(String)
|
| 147 |
model = Column(String)
|
| 148 |
api_key = Column(String)
|
| 149 |
-
success = Column(Boolean)
|
| 150 |
-
first_response_time = Column(Float) # 新增: 记录首次响应时间
|
| 151 |
timestamp = Column(DateTime(timezone=True), server_default=func.now())
|
| 152 |
|
| 153 |
# 获取数据库路径
|
|
@@ -162,6 +173,123 @@ os.makedirs(data_dir, exist_ok=True)
|
|
| 162 |
engine = create_async_engine('sqlite+aiosqlite:///' + db_path, echo=is_debug)
|
| 163 |
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
class StatsMiddleware(BaseHTTPMiddleware):
|
| 166 |
def __init__(self, app):
|
| 167 |
super().__init__(app)
|
|
@@ -169,12 +297,6 @@ class StatsMiddleware(BaseHTTPMiddleware):
|
|
| 169 |
async def dispatch(self, request: Request, call_next):
|
| 170 |
start_time = time()
|
| 171 |
|
| 172 |
-
endpoint = f"{request.method} {request.url.path}"
|
| 173 |
-
client_ip = request.client.host
|
| 174 |
-
|
| 175 |
-
model = "unknown"
|
| 176 |
-
is_flagged = False
|
| 177 |
-
moderated_content = ""
|
| 178 |
enable_moderation = False # 默认不开启道德审查
|
| 179 |
|
| 180 |
config = app.state.config
|
|
@@ -197,16 +319,47 @@ class StatsMiddleware(BaseHTTPMiddleware):
|
|
| 197 |
# 如果token为None,检查全局设置
|
| 198 |
enable_moderation = config.get('ENABLE_MODERATION', False)
|
| 199 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
parsed_body = await parse_request_body(request)
|
| 201 |
if parsed_body:
|
| 202 |
try:
|
| 203 |
request_model = UnifiedRequest.model_validate(parsed_body).data
|
| 204 |
model = request_model.model
|
|
|
|
| 205 |
|
| 206 |
if request_model.request_type == "chat":
|
| 207 |
moderated_content = request_model.get_last_text_message()
|
| 208 |
elif request_model.request_type == "image":
|
| 209 |
moderated_content = request_model.prompt
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
if enable_moderation and moderated_content:
|
| 212 |
moderation_response = await self.moderate_content(moderated_content, token)
|
|
@@ -217,12 +370,15 @@ class StatsMiddleware(BaseHTTPMiddleware):
|
|
| 217 |
if is_flagged:
|
| 218 |
logger.error(f"Content did not pass the moral check: %s", moderated_content)
|
| 219 |
process_time = time() - start_time
|
| 220 |
-
|
|
|
|
|
|
|
| 221 |
return JSONResponse(
|
| 222 |
status_code=400,
|
| 223 |
content={"error": "Content did not pass the moral check, please modify and try again."}
|
| 224 |
)
|
| 225 |
except RequestValidationError:
|
|
|
|
| 226 |
pass
|
| 227 |
except Exception as e:
|
| 228 |
if is_debug:
|
|
@@ -231,43 +387,51 @@ class StatsMiddleware(BaseHTTPMiddleware):
|
|
| 231 |
|
| 232 |
logger.error(f"处理请求或进行道德检查时出错: {str(e)}")
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
-
async def update_stats(self,
|
|
|
|
| 243 |
async with async_session() as session:
|
| 244 |
async with session.begin():
|
| 245 |
try:
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
token=token,
|
| 250 |
-
total_time=process_time,
|
| 251 |
-
model=model,
|
| 252 |
-
is_flagged=is_flagged,
|
| 253 |
-
moderated_content=moderated_content
|
| 254 |
-
)
|
| 255 |
session.add(new_request_stat)
|
| 256 |
await session.commit()
|
| 257 |
except Exception as e:
|
| 258 |
await session.rollback()
|
| 259 |
logger.error(f"Error updating stats: {str(e)}")
|
| 260 |
|
| 261 |
-
async def update_channel_stats(self, provider, model, api_key, success
|
| 262 |
async with async_session() as session:
|
| 263 |
async with session.begin():
|
| 264 |
try:
|
| 265 |
channel_stat = ChannelStat(
|
|
|
|
| 266 |
provider=provider,
|
| 267 |
model=model,
|
| 268 |
api_key=api_key,
|
| 269 |
success=success,
|
| 270 |
-
first_response_time=first_response_time
|
| 271 |
)
|
| 272 |
session.add(channel_stat)
|
| 273 |
await session.commit()
|
|
@@ -357,6 +521,7 @@ async def process_request(request: Union[RequestModel, ImageGenerationRequest, A
|
|
| 357 |
pass
|
| 358 |
else:
|
| 359 |
logger.info(json.dumps(payload, indent=4, ensure_ascii=False))
|
|
|
|
| 360 |
try:
|
| 361 |
if request.stream:
|
| 362 |
model = provider['model'][request.model]
|
|
@@ -372,12 +537,14 @@ async def process_request(request: Union[RequestModel, ImageGenerationRequest, A
|
|
| 372 |
response = JSONResponse(first_element)
|
| 373 |
|
| 374 |
# 更新成功计数和首次响应时间
|
| 375 |
-
await app.middleware_stack.app.update_channel_stats(provider['provider'], request.model, token, success=True
|
|
|
|
|
|
|
|
|
|
| 376 |
|
| 377 |
return response
|
| 378 |
except (Exception, HTTPException, asyncio.CancelledError, httpx.ReadError, httpx.RemoteProtocolError) as e:
|
| 379 |
-
|
| 380 |
-
await app.middleware_stack.app.update_channel_stats(provider['provider'], request.model, token, success=False, first_response_time=-1)
|
| 381 |
|
| 382 |
raise e
|
| 383 |
|
|
@@ -550,6 +717,10 @@ class ModelRequestHandler:
|
|
| 550 |
else:
|
| 551 |
raise HTTPException(status_code=500, detail=f"Error: Current provider response failed: {error_message}")
|
| 552 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
raise HTTPException(status_code=status_code, detail=f"All {request.model} error: {error_message}")
|
| 554 |
|
| 555 |
model_handler = ModelRequestHandler()
|
|
@@ -647,7 +818,6 @@ def verify_admin_api_key(credentials: HTTPAuthorizationCredentials = Depends(sec
|
|
| 647 |
|
| 648 |
@app.post("/v1/chat/completions", dependencies=[Depends(rate_limit_dependency)])
|
| 649 |
async def request_model(request: RequestModel, token: str = Depends(verify_api_key)):
|
| 650 |
-
# logger.info(f"Request received: {request}")
|
| 651 |
return await model_handler.request_model(request, token)
|
| 652 |
|
| 653 |
@app.options("/v1/chat/completions", dependencies=[Depends(rate_limit_dependency)])
|
|
|
|
| 5 |
import secrets
|
| 6 |
import time as time_module
|
| 7 |
from contextlib import asynccontextmanager
|
| 8 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 9 |
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from fastapi import FastAPI, HTTPException, Depends, Request
|
|
|
|
| 27 |
import json
|
| 28 |
|
| 29 |
is_debug = bool(os.getenv("DEBUG", False))
|
| 30 |
+
# is_debug = False
|
| 31 |
|
| 32 |
from sqlalchemy import inspect, text
|
| 33 |
from sqlalchemy.sql import sqltypes
|
|
|
|
| 108 |
content={"message": exc.detail},
|
| 109 |
)
|
| 110 |
|
| 111 |
+
import uuid
|
| 112 |
+
import json
|
| 113 |
import asyncio
|
| 114 |
from time import time
|
| 115 |
+
import contextvars
|
| 116 |
+
request_info = contextvars.ContextVar('request_info', default={})
|
|
|
|
| 117 |
|
| 118 |
async def parse_request_body(request: Request):
|
| 119 |
if request.method == "POST" and "application/json" in request.headers.get("content-type", ""):
|
|
|
|
| 134 |
class RequestStat(Base):
|
| 135 |
__tablename__ = 'request_stats'
|
| 136 |
id = Column(Integer, primary_key=True)
|
| 137 |
+
request_id = Column(String)
|
| 138 |
endpoint = Column(String)
|
| 139 |
+
client_ip = Column(String)
|
| 140 |
+
process_time = Column(Float)
|
| 141 |
+
first_response_time = Column(Float)
|
| 142 |
+
provider = Column(String)
|
| 143 |
model = Column(String)
|
| 144 |
+
# success = Column(Boolean, default=False)
|
| 145 |
+
api_key = Column(String)
|
| 146 |
is_flagged = Column(Boolean, default=False)
|
| 147 |
+
text = Column(Text)
|
| 148 |
+
prompt_tokens = Column(Integer, default=0)
|
| 149 |
+
completion_tokens = Column(Integer, default=0)
|
| 150 |
+
total_tokens = Column(Integer, default=0)
|
| 151 |
+
# cost = Column(Float, default=0)
|
| 152 |
timestamp = Column(DateTime(timezone=True), server_default=func.now())
|
| 153 |
|
| 154 |
class ChannelStat(Base):
|
| 155 |
__tablename__ = 'channel_stats'
|
| 156 |
id = Column(Integer, primary_key=True)
|
| 157 |
+
request_id = Column(String)
|
| 158 |
provider = Column(String)
|
| 159 |
model = Column(String)
|
| 160 |
api_key = Column(String)
|
| 161 |
+
success = Column(Boolean, default=False)
|
|
|
|
| 162 |
timestamp = Column(DateTime(timezone=True), server_default=func.now())
|
| 163 |
|
| 164 |
# 获取数据库路径
|
|
|
|
| 173 |
engine = create_async_engine('sqlite+aiosqlite:///' + db_path, echo=is_debug)
|
| 174 |
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
| 175 |
|
| 176 |
+
from starlette.types import Scope, Receive, Send
|
| 177 |
+
from starlette.responses import Response
|
| 178 |
+
|
| 179 |
+
from decimal import Decimal, getcontext
|
| 180 |
+
|
| 181 |
+
# 设置全局精度
|
| 182 |
+
getcontext().prec = 17 # 设置为17是为了确保15位小数的精度
|
| 183 |
+
|
| 184 |
+
def calculate_cost(model: str, input_tokens: int, output_tokens: int) -> Decimal:
|
| 185 |
+
costs = {
|
| 186 |
+
"gpt-4": {"input": Decimal('5.0') / Decimal('1000000'), "output": Decimal('15.0') / Decimal('1000000')},
|
| 187 |
+
"claude-3-sonnet": {"input": Decimal('3.0') / Decimal('1000000'), "output": Decimal('15.0') / Decimal('1000000')}
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
if model not in costs:
|
| 191 |
+
logger.error(f"Unknown model: {model}")
|
| 192 |
+
return 0
|
| 193 |
+
|
| 194 |
+
model_costs = costs[model]
|
| 195 |
+
input_cost = Decimal(input_tokens) * model_costs["input"]
|
| 196 |
+
output_cost = Decimal(output_tokens) * model_costs["output"]
|
| 197 |
+
total_cost = input_cost + output_cost
|
| 198 |
+
|
| 199 |
+
# 返回精确到15位小数的结果
|
| 200 |
+
return total_cost.quantize(Decimal('0.000000000000001'))
|
| 201 |
+
|
| 202 |
+
class LoggingStreamingResponse(Response):
|
| 203 |
+
def __init__(self, content, status_code=200, headers=None, media_type=None, current_info=None):
|
| 204 |
+
super().__init__(content=None, status_code=status_code, headers=headers, media_type=media_type)
|
| 205 |
+
self.body_iterator = content
|
| 206 |
+
self._closed = False
|
| 207 |
+
self.current_info = current_info
|
| 208 |
+
|
| 209 |
+
# Remove Content-Length header if it exists
|
| 210 |
+
if 'content-length' in self.headers:
|
| 211 |
+
del self.headers['content-length']
|
| 212 |
+
# Set Transfer-Encoding to chunked
|
| 213 |
+
self.headers['transfer-encoding'] = 'chunked'
|
| 214 |
+
|
| 215 |
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
| 216 |
+
await send({
|
| 217 |
+
'type': 'http.response.start',
|
| 218 |
+
'status': self.status_code,
|
| 219 |
+
'headers': self.raw_headers,
|
| 220 |
+
})
|
| 221 |
+
|
| 222 |
+
try:
|
| 223 |
+
async for chunk in self._logging_iterator():
|
| 224 |
+
await send({
|
| 225 |
+
'type': 'http.response.body',
|
| 226 |
+
'body': chunk,
|
| 227 |
+
'more_body': True,
|
| 228 |
+
})
|
| 229 |
+
finally:
|
| 230 |
+
await send({
|
| 231 |
+
'type': 'http.response.body',
|
| 232 |
+
'body': b'',
|
| 233 |
+
'more_body': False,
|
| 234 |
+
})
|
| 235 |
+
if hasattr(self.body_iterator, 'aclose') and not self._closed:
|
| 236 |
+
await self.body_iterator.aclose()
|
| 237 |
+
self._closed = True
|
| 238 |
+
|
| 239 |
+
process_time = time() - self.current_info["start_time"]
|
| 240 |
+
self.current_info["process_time"] = process_time
|
| 241 |
+
await self.update_stats()
|
| 242 |
+
|
| 243 |
+
async def update_stats(self):
|
| 244 |
+
# 这里添加更新数据库的逻辑
|
| 245 |
+
# print("current_info2")
|
| 246 |
+
async with async_session() as session:
|
| 247 |
+
async with session.begin():
|
| 248 |
+
try:
|
| 249 |
+
columns = [column.key for column in RequestStat.__table__.columns]
|
| 250 |
+
filtered_info = {k: v for k, v in self.current_info.items() if k in columns}
|
| 251 |
+
new_request_stat = RequestStat(**filtered_info)
|
| 252 |
+
session.add(new_request_stat)
|
| 253 |
+
await session.commit()
|
| 254 |
+
except Exception as e:
|
| 255 |
+
await session.rollback()
|
| 256 |
+
logger.error(f"Error updating stats: {str(e)}")
|
| 257 |
+
|
| 258 |
+
async def _logging_iterator(self):
|
| 259 |
+
try:
|
| 260 |
+
async for chunk in self.body_iterator:
|
| 261 |
+
if isinstance(chunk, str):
|
| 262 |
+
chunk = chunk.encode('utf-8')
|
| 263 |
+
line = chunk.decode()
|
| 264 |
+
if is_debug:
|
| 265 |
+
logger.info(f"{line}")
|
| 266 |
+
if line.startswith("data:"):
|
| 267 |
+
line = line.lstrip("data: ")
|
| 268 |
+
if not line.startswith("[DONE]"):
|
| 269 |
+
resp: dict = json.loads(line)
|
| 270 |
+
input_tokens = safe_get(resp, "message", "usage", "input_tokens", default=0)
|
| 271 |
+
input_tokens = safe_get(resp, "usage", "prompt_tokens", default=0)
|
| 272 |
+
output_tokens = safe_get(resp, "usage", "completion_tokens", default=0)
|
| 273 |
+
total_tokens = input_tokens + output_tokens
|
| 274 |
+
|
| 275 |
+
model = self.current_info.get("model", "")
|
| 276 |
+
# total_cost = calculate_cost(model, input_tokens, output_tokens)
|
| 277 |
+
self.current_info["prompt_tokens"] = input_tokens
|
| 278 |
+
self.current_info["completion_tokens"] = output_tokens
|
| 279 |
+
self.current_info["total_tokens"] = total_tokens
|
| 280 |
+
# self.current_info["cost"] = total_cost
|
| 281 |
+
yield chunk
|
| 282 |
+
except Exception as e:
|
| 283 |
+
raise
|
| 284 |
+
finally:
|
| 285 |
+
logger.debug("_logging_iterator finished")
|
| 286 |
+
|
| 287 |
+
async def close(self):
|
| 288 |
+
if not self._closed:
|
| 289 |
+
self._closed = True
|
| 290 |
+
if hasattr(self.body_iterator, 'aclose'):
|
| 291 |
+
await self.body_iterator.aclose()
|
| 292 |
+
|
| 293 |
class StatsMiddleware(BaseHTTPMiddleware):
|
| 294 |
def __init__(self, app):
|
| 295 |
super().__init__(app)
|
|
|
|
| 297 |
async def dispatch(self, request: Request, call_next):
|
| 298 |
start_time = time()
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
enable_moderation = False # 默认不开启道德审查
|
| 301 |
|
| 302 |
config = app.state.config
|
|
|
|
| 319 |
# 如果token为None,检查全局设置
|
| 320 |
enable_moderation = config.get('ENABLE_MODERATION', False)
|
| 321 |
|
| 322 |
+
# 在 app.state 中存储此请求的信息
|
| 323 |
+
request_id = str(uuid.uuid4())
|
| 324 |
+
|
| 325 |
+
# 初始化请求信息
|
| 326 |
+
request_info_data = {
|
| 327 |
+
"request_id": request_id,
|
| 328 |
+
"start_time": start_time,
|
| 329 |
+
"endpoint": f"{request.method} {request.url.path}",
|
| 330 |
+
"client_ip": request.client.host,
|
| 331 |
+
"process_time": 0,
|
| 332 |
+
"first_response_time": -1,
|
| 333 |
+
"provider": None,
|
| 334 |
+
"model": None,
|
| 335 |
+
"success": False,
|
| 336 |
+
"api_key": token,
|
| 337 |
+
"is_flagged": False,
|
| 338 |
+
"text": None,
|
| 339 |
+
"prompt_tokens": 0,
|
| 340 |
+
"completion_tokens": 0,
|
| 341 |
+
# "cost": 0,
|
| 342 |
+
"total_tokens": 0
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
# 设置请求信息到上下文
|
| 346 |
+
current_request_info = request_info.set(request_info_data)
|
| 347 |
+
current_info = request_info.get()
|
| 348 |
+
|
| 349 |
parsed_body = await parse_request_body(request)
|
| 350 |
if parsed_body:
|
| 351 |
try:
|
| 352 |
request_model = UnifiedRequest.model_validate(parsed_body).data
|
| 353 |
model = request_model.model
|
| 354 |
+
current_info["model"] = model
|
| 355 |
|
| 356 |
if request_model.request_type == "chat":
|
| 357 |
moderated_content = request_model.get_last_text_message()
|
| 358 |
elif request_model.request_type == "image":
|
| 359 |
moderated_content = request_model.prompt
|
| 360 |
+
if moderated_content:
|
| 361 |
+
current_info["text"] = moderated_content
|
| 362 |
+
|
| 363 |
|
| 364 |
if enable_moderation and moderated_content:
|
| 365 |
moderation_response = await self.moderate_content(moderated_content, token)
|
|
|
|
| 370 |
if is_flagged:
|
| 371 |
logger.error(f"Content did not pass the moral check: %s", moderated_content)
|
| 372 |
process_time = time() - start_time
|
| 373 |
+
current_info["process_time"] = process_time
|
| 374 |
+
current_info["is_flagged"] = is_flagged
|
| 375 |
+
await self.update_stats(current_info)
|
| 376 |
return JSONResponse(
|
| 377 |
status_code=400,
|
| 378 |
content={"error": "Content did not pass the moral check, please modify and try again."}
|
| 379 |
)
|
| 380 |
except RequestValidationError:
|
| 381 |
+
logger.error(f"Invalid request body: {parsed_body}")
|
| 382 |
pass
|
| 383 |
except Exception as e:
|
| 384 |
if is_debug:
|
|
|
|
| 387 |
|
| 388 |
logger.error(f"处理请求或进行道德检查时出错: {str(e)}")
|
| 389 |
|
| 390 |
+
try:
|
| 391 |
+
response = await call_next(request)
|
| 392 |
+
|
| 393 |
+
if isinstance(response, StreamingResponse):
|
| 394 |
+
response = LoggingStreamingResponse(
|
| 395 |
+
content=response.body_iterator,
|
| 396 |
+
status_code=response.status_code,
|
| 397 |
+
media_type=response.media_type,
|
| 398 |
+
headers=response.headers,
|
| 399 |
+
current_info=current_info,
|
| 400 |
+
)
|
| 401 |
+
elif hasattr(response, 'json'):
|
| 402 |
+
logger.info(f"Response: {await response.json()}")
|
| 403 |
+
else:
|
| 404 |
+
logger.info(f"Response: type={type(response).__name__}, status_code={response.status_code}, headers={response.headers}")
|
| 405 |
|
| 406 |
+
return response
|
| 407 |
+
finally:
|
| 408 |
+
# print("current_request_info", current_request_info)
|
| 409 |
+
request_info.reset(current_request_info)
|
| 410 |
|
| 411 |
+
async def update_stats(self, current_info):
|
| 412 |
+
# 这里添加更新数据库的逻辑
|
| 413 |
async with async_session() as session:
|
| 414 |
async with session.begin():
|
| 415 |
try:
|
| 416 |
+
columns = [column.key for column in RequestStat.__table__.columns]
|
| 417 |
+
filtered_info = {k: v for k, v in current_info.items() if k in columns}
|
| 418 |
+
new_request_stat = RequestStat(**filtered_info)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
session.add(new_request_stat)
|
| 420 |
await session.commit()
|
| 421 |
except Exception as e:
|
| 422 |
await session.rollback()
|
| 423 |
logger.error(f"Error updating stats: {str(e)}")
|
| 424 |
|
| 425 |
+
async def update_channel_stats(self, request_id, provider, model, api_key, success):
|
| 426 |
async with async_session() as session:
|
| 427 |
async with session.begin():
|
| 428 |
try:
|
| 429 |
channel_stat = ChannelStat(
|
| 430 |
+
request_id=request_id,
|
| 431 |
provider=provider,
|
| 432 |
model=model,
|
| 433 |
api_key=api_key,
|
| 434 |
success=success,
|
|
|
|
| 435 |
)
|
| 436 |
session.add(channel_stat)
|
| 437 |
await session.commit()
|
|
|
|
| 521 |
pass
|
| 522 |
else:
|
| 523 |
logger.info(json.dumps(payload, indent=4, ensure_ascii=False))
|
| 524 |
+
current_info = request_info.get()
|
| 525 |
try:
|
| 526 |
if request.stream:
|
| 527 |
model = provider['model'][request.model]
|
|
|
|
| 537 |
response = JSONResponse(first_element)
|
| 538 |
|
| 539 |
# 更新成功计数和首次响应时间
|
| 540 |
+
await app.middleware_stack.app.update_channel_stats(current_info["request_id"], provider['provider'], request.model, token, success=True)
|
| 541 |
+
current_info["first_response_time"] = first_response_time
|
| 542 |
+
current_info["success"] = True
|
| 543 |
+
current_info["provider"] = provider['provider']
|
| 544 |
|
| 545 |
return response
|
| 546 |
except (Exception, HTTPException, asyncio.CancelledError, httpx.ReadError, httpx.RemoteProtocolError) as e:
|
| 547 |
+
await app.middleware_stack.app.update_channel_stats(current_info["request_id"], provider['provider'], request.model, token, success=False)
|
|
|
|
| 548 |
|
| 549 |
raise e
|
| 550 |
|
|
|
|
| 717 |
else:
|
| 718 |
raise HTTPException(status_code=500, detail=f"Error: Current provider response failed: {error_message}")
|
| 719 |
|
| 720 |
+
current_info = request_info.get()
|
| 721 |
+
current_info["first_response_time"] = -1
|
| 722 |
+
current_info["success"] = False
|
| 723 |
+
current_info["provider"] = None
|
| 724 |
raise HTTPException(status_code=status_code, detail=f"All {request.model} error: {error_message}")
|
| 725 |
|
| 726 |
model_handler = ModelRequestHandler()
|
|
|
|
| 818 |
|
| 819 |
@app.post("/v1/chat/completions", dependencies=[Depends(rate_limit_dependency)])
|
| 820 |
async def request_model(request: RequestModel, token: str = Depends(verify_api_key)):
|
|
|
|
| 821 |
return await model_handler.request_model(request, token)
|
| 822 |
|
| 823 |
@app.options("/v1/chat/completions", dependencies=[Depends(rate_limit_dependency)])
|
models.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
from io import IOBase
|
| 2 |
from pydantic import BaseModel, Field, model_validator
|
| 3 |
from typing import List, Dict, Optional, Union, Tuple, Literal
|
|
|
|
| 4 |
|
| 5 |
class FunctionParameter(BaseModel):
|
| 6 |
type: str
|
|
@@ -57,8 +58,10 @@ class ToolChoice(BaseModel):
|
|
| 57 |
type: str
|
| 58 |
function: Optional[FunctionChoice] = None
|
| 59 |
|
| 60 |
-
class
|
| 61 |
-
request_type: Literal["chat"
|
|
|
|
|
|
|
| 62 |
model: str
|
| 63 |
messages: List[Message]
|
| 64 |
logprobs: Optional[bool] = None
|
|
@@ -86,16 +89,14 @@ class RequestModel(BaseModel):
|
|
| 86 |
return item.text
|
| 87 |
return ""
|
| 88 |
|
| 89 |
-
class ImageGenerationRequest(
|
| 90 |
-
request_type: Literal["image"] = "image"
|
| 91 |
prompt: str
|
| 92 |
model: Optional[str] = "dall-e-3"
|
| 93 |
n: Optional[int] = 1
|
| 94 |
size: Optional[str] = "1024x1024"
|
| 95 |
stream: bool = False
|
| 96 |
|
| 97 |
-
class AudioTranscriptionRequest(
|
| 98 |
-
request_type: Literal["audio"] = "audio"
|
| 99 |
file: Tuple[str, IOBase, str]
|
| 100 |
model: str
|
| 101 |
language: Optional[str] = None
|
|
@@ -107,31 +108,30 @@ class AudioTranscriptionRequest(BaseModel):
|
|
| 107 |
class Config:
|
| 108 |
arbitrary_types_allowed = True
|
| 109 |
|
| 110 |
-
class ModerationRequest(
|
| 111 |
-
request_type: Literal["moderation"] = "moderation"
|
| 112 |
input: str
|
| 113 |
model: Optional[str] = "text-moderation-latest"
|
| 114 |
stream: bool = False
|
| 115 |
|
| 116 |
class UnifiedRequest(BaseModel):
|
| 117 |
-
data: Union[RequestModel, ImageGenerationRequest, AudioTranscriptionRequest, ModerationRequest]
|
| 118 |
|
| 119 |
@model_validator(mode='before')
|
| 120 |
@classmethod
|
| 121 |
def set_request_type(cls, values):
|
| 122 |
if isinstance(values, dict):
|
| 123 |
if "messages" in values:
|
| 124 |
-
values["request_type"] = "chat"
|
| 125 |
values["data"] = RequestModel(**values)
|
|
|
|
| 126 |
elif "prompt" in values:
|
| 127 |
-
values["request_type"] = "image"
|
| 128 |
values["data"] = ImageGenerationRequest(**values)
|
|
|
|
| 129 |
elif "file" in values:
|
| 130 |
-
values["request_type"] = "audio"
|
| 131 |
values["data"] = AudioTranscriptionRequest(**values)
|
|
|
|
| 132 |
elif "input" in values:
|
| 133 |
-
values["request_type"] = "moderation"
|
| 134 |
values["data"] = ModerationRequest(**values)
|
|
|
|
| 135 |
else:
|
| 136 |
raise ValueError("无法确定请求类型")
|
| 137 |
return values
|
|
|
|
| 1 |
from io import IOBase
|
| 2 |
from pydantic import BaseModel, Field, model_validator
|
| 3 |
from typing import List, Dict, Optional, Union, Tuple, Literal
|
| 4 |
+
from log_config import logger
|
| 5 |
|
| 6 |
class FunctionParameter(BaseModel):
|
| 7 |
type: str
|
|
|
|
| 58 |
type: str
|
| 59 |
function: Optional[FunctionChoice] = None
|
| 60 |
|
| 61 |
+
class BaseRequest(BaseModel):
|
| 62 |
+
request_type: Optional[Literal["chat", "image", "audio", "moderation"]] = Field(default=None, exclude=True)
|
| 63 |
+
|
| 64 |
+
class RequestModel(BaseRequest):
|
| 65 |
model: str
|
| 66 |
messages: List[Message]
|
| 67 |
logprobs: Optional[bool] = None
|
|
|
|
| 89 |
return item.text
|
| 90 |
return ""
|
| 91 |
|
| 92 |
+
class ImageGenerationRequest(BaseRequest):
|
|
|
|
| 93 |
prompt: str
|
| 94 |
model: Optional[str] = "dall-e-3"
|
| 95 |
n: Optional[int] = 1
|
| 96 |
size: Optional[str] = "1024x1024"
|
| 97 |
stream: bool = False
|
| 98 |
|
| 99 |
+
class AudioTranscriptionRequest(BaseRequest):
|
|
|
|
| 100 |
file: Tuple[str, IOBase, str]
|
| 101 |
model: str
|
| 102 |
language: Optional[str] = None
|
|
|
|
| 108 |
class Config:
|
| 109 |
arbitrary_types_allowed = True
|
| 110 |
|
| 111 |
+
class ModerationRequest(BaseRequest):
|
|
|
|
| 112 |
input: str
|
| 113 |
model: Optional[str] = "text-moderation-latest"
|
| 114 |
stream: bool = False
|
| 115 |
|
| 116 |
class UnifiedRequest(BaseModel):
|
| 117 |
+
data: Union[RequestModel, ImageGenerationRequest, AudioTranscriptionRequest, ModerationRequest]
|
| 118 |
|
| 119 |
@model_validator(mode='before')
|
| 120 |
@classmethod
|
| 121 |
def set_request_type(cls, values):
|
| 122 |
if isinstance(values, dict):
|
| 123 |
if "messages" in values:
|
|
|
|
| 124 |
values["data"] = RequestModel(**values)
|
| 125 |
+
values["data"].request_type = "chat"
|
| 126 |
elif "prompt" in values:
|
|
|
|
| 127 |
values["data"] = ImageGenerationRequest(**values)
|
| 128 |
+
values["data"].request_type = "image"
|
| 129 |
elif "file" in values:
|
|
|
|
| 130 |
values["data"] = AudioTranscriptionRequest(**values)
|
| 131 |
+
values["data"].request_type = "audio"
|
| 132 |
elif "input" in values:
|
|
|
|
| 133 |
values["data"] = ModerationRequest(**values)
|
| 134 |
+
values["data"].request_type = "moderation"
|
| 135 |
else:
|
| 136 |
raise ValueError("无法确定请求类型")
|
| 137 |
return values
|
response.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import json
|
| 2 |
import httpx
|
| 3 |
from datetime import datetime
|
| 4 |
-
from io import BytesIO
|
| 5 |
|
| 6 |
from log_config import logger
|
| 7 |
|
|
@@ -32,7 +31,7 @@ async def generate_sse_response(timestamp, model, content=None, tools_id=None, f
|
|
| 32 |
sample_data["choices"][0]["delta"] = {"role": role, "content": ""}
|
| 33 |
if total_tokens:
|
| 34 |
total_tokens = prompt_tokens + completion_tokens
|
| 35 |
-
sample_data["usage"] = {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens,"total_tokens": total_tokens}
|
| 36 |
sample_data["choices"] = []
|
| 37 |
json_data = json.dumps(sample_data, ensure_ascii=False)
|
| 38 |
|
|
|
|
| 1 |
import json
|
| 2 |
import httpx
|
| 3 |
from datetime import datetime
|
|
|
|
| 4 |
|
| 5 |
from log_config import logger
|
| 6 |
|
|
|
|
| 31 |
sample_data["choices"][0]["delta"] = {"role": role, "content": ""}
|
| 32 |
if total_tokens:
|
| 33 |
total_tokens = prompt_tokens + completion_tokens
|
| 34 |
+
sample_data["usage"] = {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": total_tokens}
|
| 35 |
sample_data["choices"] = []
|
| 36 |
json_data = json.dumps(sample_data, ensure_ascii=False)
|
| 37 |
|