Update api/utils.py
Browse files- api/utils.py +26 -53
api/utils.py
CHANGED
|
@@ -6,40 +6,29 @@ import uuid
|
|
| 6 |
|
| 7 |
import httpx
|
| 8 |
from api import validate
|
| 9 |
-
from api.config import
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
AGENT_MODE,
|
| 13 |
-
TRENDING_AGENT_MODE,
|
| 14 |
-
MODEL_PREFIXES,
|
| 15 |
-
APP_SECRET,
|
| 16 |
-
BASE_URL,
|
| 17 |
-
)
|
| 18 |
-
from fastapi import Depends, HTTPException
|
| 19 |
-
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 20 |
|
|
|
|
| 21 |
from api.models import ChatRequest
|
|
|
|
| 22 |
from api.logger import setup_logger
|
| 23 |
|
| 24 |
logger = setup_logger(__name__)
|
| 25 |
|
| 26 |
-
# Initialize HTTPBearer for security
|
| 27 |
-
security = HTTPBearer()
|
| 28 |
-
|
| 29 |
def create_chat_completion_data(
|
| 30 |
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
| 31 |
) -> Dict[str, Any]:
|
| 32 |
-
prefix = MODEL_PREFIXES.get(model, "")
|
| 33 |
-
full_content = f"{prefix} {content}" if prefix else content
|
| 34 |
return {
|
| 35 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 36 |
"object": "chat.completion.chunk",
|
| 37 |
"created": timestamp,
|
| 38 |
-
"model":
|
| 39 |
"choices": [
|
| 40 |
{
|
| 41 |
"index": 0,
|
| 42 |
-
"delta": {"content":
|
| 43 |
"finish_reason": finish_reason,
|
| 44 |
}
|
| 45 |
],
|
|
@@ -52,34 +41,28 @@ def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(securi
|
|
| 52 |
return credentials.credentials
|
| 53 |
|
| 54 |
def message_to_dict(message):
|
| 55 |
-
prefix = MODEL_PREFIXES.get(message.model, "") if hasattr(message, 'model') else ""
|
| 56 |
-
|
| 57 |
if isinstance(message.content, str):
|
| 58 |
-
|
| 59 |
elif isinstance(message.content, list) and len(message.content) == 2:
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
"imageBase64": message.content[1]["image_url"]["url"],
|
| 69 |
-
"fileText": "",
|
| 70 |
-
"title": "snapshot",
|
| 71 |
}
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
async def process_streaming_response(request: ChatRequest):
|
| 76 |
agent_mode = AGENT_MODE.get(request.model, {})
|
| 77 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
| 78 |
-
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
| 79 |
|
| 80 |
-
# Log reduced information
|
| 81 |
logger.info(
|
| 82 |
-
f"Streaming request for model: '{
|
| 83 |
f"agent mode: {agent_mode}, trending agent mode: {trending_agent_mode}"
|
| 84 |
)
|
| 85 |
|
|
@@ -103,8 +86,7 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 103 |
"visitFromDelta": False,
|
| 104 |
"mobileClient": False,
|
| 105 |
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
| 106 |
-
"validated": validate.getHid()
|
| 107 |
-
# "modelPrefix": model_prefix, # This line has been removed
|
| 108 |
}
|
| 109 |
|
| 110 |
async with httpx.AsyncClient() as client:
|
|
@@ -143,11 +125,10 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 143 |
async def process_non_streaming_response(request: ChatRequest):
|
| 144 |
agent_mode = AGENT_MODE.get(request.model, {})
|
| 145 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
| 146 |
-
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
| 147 |
|
| 148 |
-
# Log reduced information
|
| 149 |
logger.info(
|
| 150 |
-
f"Non-streaming request for model: '{
|
| 151 |
f"agent mode: {agent_mode}, trending agent mode: {trending_agent_mode}"
|
| 152 |
)
|
| 153 |
|
|
@@ -171,8 +152,7 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 171 |
"visitFromDelta": False,
|
| 172 |
"mobileClient": False,
|
| 173 |
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
| 174 |
-
"validated": validate.getHid()
|
| 175 |
-
# "modelPrefix": model_prefix, # This line has been removed
|
| 176 |
}
|
| 177 |
|
| 178 |
full_response = ""
|
|
@@ -182,23 +162,16 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 182 |
) as response:
|
| 183 |
async for chunk in response.aiter_text():
|
| 184 |
full_response += chunk
|
| 185 |
-
|
| 186 |
if "https://www.blackbox.ai" in full_response:
|
| 187 |
validate.getHid(True)
|
| 188 |
full_response = "hid已刷新,重新对话即可"
|
| 189 |
-
|
| 190 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
| 191 |
full_response = full_response[21:]
|
| 192 |
-
|
| 193 |
-
# Prepend model prefix to the final response content
|
| 194 |
-
if model_prefix:
|
| 195 |
-
full_response = f"{model_prefix} {full_response}"
|
| 196 |
-
|
| 197 |
return {
|
| 198 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 199 |
"object": "chat.completion",
|
| 200 |
"created": int(datetime.now().timestamp()),
|
| 201 |
-
"model":
|
| 202 |
"choices": [
|
| 203 |
{
|
| 204 |
"index": 0,
|
|
@@ -207,4 +180,4 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 207 |
}
|
| 208 |
],
|
| 209 |
"usage": None,
|
| 210 |
-
}
|
|
|
|
| 6 |
|
| 7 |
import httpx
|
| 8 |
from api import validate
|
| 9 |
+
from api.config import MODEL_MAPPING, headers, AGENT_MODE, TRENDING_AGENT_MODE
|
| 10 |
+
from fastapi import Depends, security
|
| 11 |
+
from fastapi.security import HTTPAuthorizationCredentials
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
from api.config import APP_SECRET, BASE_URL
|
| 14 |
from api.models import ChatRequest
|
| 15 |
+
|
| 16 |
from api.logger import setup_logger
|
| 17 |
|
| 18 |
logger = setup_logger(__name__)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
| 20 |
def create_chat_completion_data(
|
| 21 |
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
| 22 |
) -> Dict[str, Any]:
|
|
|
|
|
|
|
| 23 |
return {
|
| 24 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 25 |
"object": "chat.completion.chunk",
|
| 26 |
"created": timestamp,
|
| 27 |
+
"model": model,
|
| 28 |
"choices": [
|
| 29 |
{
|
| 30 |
"index": 0,
|
| 31 |
+
"delta": {"content": content, "role": "assistant"},
|
| 32 |
"finish_reason": finish_reason,
|
| 33 |
}
|
| 34 |
],
|
|
|
|
| 41 |
return credentials.credentials
|
| 42 |
|
| 43 |
def message_to_dict(message):
|
|
|
|
|
|
|
| 44 |
if isinstance(message.content, str):
|
| 45 |
+
return {"role": message.role, "content": message.content}
|
| 46 |
elif isinstance(message.content, list) and len(message.content) == 2:
|
| 47 |
+
return {
|
| 48 |
+
"role": message.role,
|
| 49 |
+
"content": message.content[0]["text"],
|
| 50 |
+
"data": {
|
| 51 |
+
"imageBase64": message.content[1]["image_url"]["url"],
|
| 52 |
+
"fileText": "",
|
| 53 |
+
"title": "snapshot",
|
| 54 |
+
},
|
|
|
|
|
|
|
|
|
|
| 55 |
}
|
| 56 |
+
else:
|
| 57 |
+
return {"role": message.role, "content": message.content}
|
| 58 |
|
| 59 |
async def process_streaming_response(request: ChatRequest):
|
| 60 |
agent_mode = AGENT_MODE.get(request.model, {})
|
| 61 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
|
|
|
| 62 |
|
| 63 |
+
# Log reduced information
|
| 64 |
logger.info(
|
| 65 |
+
f"Streaming request for model: '{request.model}', "
|
| 66 |
f"agent mode: {agent_mode}, trending agent mode: {trending_agent_mode}"
|
| 67 |
)
|
| 68 |
|
|
|
|
| 86 |
"visitFromDelta": False,
|
| 87 |
"mobileClient": False,
|
| 88 |
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
| 89 |
+
"validated": validate.getHid()
|
|
|
|
| 90 |
}
|
| 91 |
|
| 92 |
async with httpx.AsyncClient() as client:
|
|
|
|
| 125 |
async def process_non_streaming_response(request: ChatRequest):
|
| 126 |
agent_mode = AGENT_MODE.get(request.model, {})
|
| 127 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
|
|
|
| 128 |
|
| 129 |
+
# Log reduced information
|
| 130 |
logger.info(
|
| 131 |
+
f"Non-streaming request for model: '{request.model}', "
|
| 132 |
f"agent mode: {agent_mode}, trending agent mode: {trending_agent_mode}"
|
| 133 |
)
|
| 134 |
|
|
|
|
| 152 |
"visitFromDelta": False,
|
| 153 |
"mobileClient": False,
|
| 154 |
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
| 155 |
+
"validated": validate.getHid()
|
|
|
|
| 156 |
}
|
| 157 |
|
| 158 |
full_response = ""
|
|
|
|
| 162 |
) as response:
|
| 163 |
async for chunk in response.aiter_text():
|
| 164 |
full_response += chunk
|
|
|
|
| 165 |
if "https://www.blackbox.ai" in full_response:
|
| 166 |
validate.getHid(True)
|
| 167 |
full_response = "hid已刷新,重新对话即可"
|
|
|
|
| 168 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
| 169 |
full_response = full_response[21:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
return {
|
| 171 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 172 |
"object": "chat.completion",
|
| 173 |
"created": int(datetime.now().timestamp()),
|
| 174 |
+
"model": request.model,
|
| 175 |
"choices": [
|
| 176 |
{
|
| 177 |
"index": 0,
|
|
|
|
| 180 |
}
|
| 181 |
],
|
| 182 |
"usage": None,
|
| 183 |
+
}
|