Spaces:
Paused
Paused
Update api/utils.py
Browse files- api/utils.py +180 -169
api/utils.py
CHANGED
|
@@ -1,169 +1,180 @@
|
|
| 1 |
-
from datetime import datetime
|
| 2 |
-
from http.client import HTTPException
|
| 3 |
-
import json
|
| 4 |
-
from typing import Any, Dict, Optional
|
| 5 |
-
import uuid
|
| 6 |
-
|
| 7 |
-
import httpx
|
| 8 |
-
from api import validate
|
| 9 |
-
from api.config import MODEL_MAPPING, headers
|
| 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 |
-
|
| 21 |
-
def create_chat_completion_data(
|
| 22 |
-
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
| 23 |
-
) -> Dict[str, Any]:
|
| 24 |
-
return {
|
| 25 |
-
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 26 |
-
"object": "chat.completion.chunk",
|
| 27 |
-
"created": timestamp,
|
| 28 |
-
"model": model,
|
| 29 |
-
"choices": [
|
| 30 |
-
{
|
| 31 |
-
"index": 0,
|
| 32 |
-
"delta": {"content": content, "role": "assistant"},
|
| 33 |
-
"finish_reason": finish_reason,
|
| 34 |
-
}
|
| 35 |
-
],
|
| 36 |
-
"usage": None,
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 41 |
-
if credentials.credentials != APP_SECRET:
|
| 42 |
-
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
|
| 43 |
-
return credentials.credentials
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def message_to_dict(message):
|
| 47 |
-
if isinstance(message.content, str):
|
| 48 |
-
return {"role": message.role, "content": message.content}
|
| 49 |
-
elif isinstance(message.content, list) and len(message.content) == 2:
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from http.client import HTTPException
|
| 3 |
+
import json
|
| 4 |
+
from typing import Any, Dict, Optional
|
| 5 |
+
import uuid
|
| 6 |
+
|
| 7 |
+
import httpx
|
| 8 |
+
from api import validate
|
| 9 |
+
from api.config import MODEL_MAPPING, headers
|
| 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 |
+
|
| 21 |
+
def create_chat_completion_data(
|
| 22 |
+
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
| 23 |
+
) -> Dict[str, Any]:
|
| 24 |
+
return {
|
| 25 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 26 |
+
"object": "chat.completion.chunk",
|
| 27 |
+
"created": timestamp,
|
| 28 |
+
"model": model,
|
| 29 |
+
"choices": [
|
| 30 |
+
{
|
| 31 |
+
"index": 0,
|
| 32 |
+
"delta": {"content": content, "role": "assistant"},
|
| 33 |
+
"finish_reason": finish_reason,
|
| 34 |
+
}
|
| 35 |
+
],
|
| 36 |
+
"usage": None,
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 41 |
+
if credentials.credentials != APP_SECRET:
|
| 42 |
+
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
|
| 43 |
+
return credentials.credentials
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def message_to_dict(message):
|
| 47 |
+
if isinstance(message.content, str):
|
| 48 |
+
return {"role": message.role, "content": message.content}
|
| 49 |
+
elif isinstance(message.content, list) and len(message.content) == 2:
|
| 50 |
+
if "image_url" in message.content[1]:
|
| 51 |
+
return {
|
| 52 |
+
"role": message.role,
|
| 53 |
+
"content": message.content[0]["text"],
|
| 54 |
+
"data": {
|
| 55 |
+
"imageBase64": message.content[1]["image_url"]["url"],
|
| 56 |
+
"fileText": "",
|
| 57 |
+
"title": "snapshoot",
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
else:
|
| 61 |
+
return {
|
| 62 |
+
"role": message.role,
|
| 63 |
+
"content": message.content[0]["text"],
|
| 64 |
+
"data": {
|
| 65 |
+
"imageBase64": "",
|
| 66 |
+
"fileText": "",
|
| 67 |
+
"title": "snapshoot",
|
| 68 |
+
},
|
| 69 |
+
}
|
| 70 |
+
else:
|
| 71 |
+
return {"role": message.role, "content": message.content}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
async def process_streaming_response(request: ChatRequest):
|
| 75 |
+
json_data = {
|
| 76 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
| 77 |
+
"previewToken": None,
|
| 78 |
+
"userId": None,
|
| 79 |
+
"codeModelMode": True,
|
| 80 |
+
"agentMode": {},
|
| 81 |
+
"trendingAgentMode": {},
|
| 82 |
+
"isMicMode": False,
|
| 83 |
+
"userSystemPrompt": None,
|
| 84 |
+
"maxTokens": request.max_tokens,
|
| 85 |
+
"playgroundTopP": request.top_p,
|
| 86 |
+
"playgroundTemperature": request.temperature,
|
| 87 |
+
"isChromeExt": False,
|
| 88 |
+
"githubToken": None,
|
| 89 |
+
"clickedAnswer2": False,
|
| 90 |
+
"clickedAnswer3": False,
|
| 91 |
+
"clickedForceWebSearch": False,
|
| 92 |
+
"visitFromDelta": False,
|
| 93 |
+
"mobileClient": False,
|
| 94 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
| 95 |
+
"validated": validate.getHid()
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
async with httpx.AsyncClient() as client:
|
| 99 |
+
try:
|
| 100 |
+
async with client.stream(
|
| 101 |
+
"POST",
|
| 102 |
+
f"{BASE_URL}/api/chat",
|
| 103 |
+
headers=headers,
|
| 104 |
+
json=json_data,
|
| 105 |
+
timeout=100,
|
| 106 |
+
) as response:
|
| 107 |
+
response.raise_for_status()
|
| 108 |
+
async for line in response.aiter_lines():
|
| 109 |
+
timestamp = int(datetime.now().timestamp())
|
| 110 |
+
if line:
|
| 111 |
+
content = line + "\n"
|
| 112 |
+
if "https://www.blackbox.ai" in content:
|
| 113 |
+
validate.getHid(True)
|
| 114 |
+
content = "hid已刷新,重新对话即可\n"
|
| 115 |
+
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
|
| 116 |
+
break
|
| 117 |
+
if content.startswith("$@$v=undefined-rv1$@$"):
|
| 118 |
+
yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
|
| 119 |
+
else:
|
| 120 |
+
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
|
| 121 |
+
|
| 122 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
| 123 |
+
yield "data: [DONE]\n\n"
|
| 124 |
+
except httpx.HTTPStatusError as e:
|
| 125 |
+
logger.error(f"HTTP error occurred: {e}")
|
| 126 |
+
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 127 |
+
except httpx.RequestError as e:
|
| 128 |
+
logger.error(f"Error occurred during request: {e}")
|
| 129 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
async def process_non_streaming_response(request: ChatRequest):
|
| 133 |
+
json_data = {
|
| 134 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
| 135 |
+
"previewToken": None,
|
| 136 |
+
"userId": None,
|
| 137 |
+
"codeModelMode": True,
|
| 138 |
+
"agentMode": {},
|
| 139 |
+
"trendingAgentMode": {},
|
| 140 |
+
"isMicMode": False,
|
| 141 |
+
"userSystemPrompt": None,
|
| 142 |
+
"maxTokens": request.max_tokens,
|
| 143 |
+
"playgroundTopP": request.top_p,
|
| 144 |
+
"playgroundTemperature": request.temperature,
|
| 145 |
+
"isChromeExt": False,
|
| 146 |
+
"githubToken": None,
|
| 147 |
+
"clickedAnswer2": False,
|
| 148 |
+
"clickedAnswer3": False,
|
| 149 |
+
"clickedForceWebSearch": False,
|
| 150 |
+
"visitFromDelta": False,
|
| 151 |
+
"mobileClient": False,
|
| 152 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model),
|
| 153 |
+
"validated": validate.getHid()
|
| 154 |
+
}
|
| 155 |
+
full_response = ""
|
| 156 |
+
async with httpx.AsyncClient() as client:
|
| 157 |
+
async with client.stream(
|
| 158 |
+
method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
|
| 159 |
+
) as response:
|
| 160 |
+
async for chunk in response.aiter_text():
|
| 161 |
+
full_response += chunk
|
| 162 |
+
if "https://www.blackbox.ai" in full_response:
|
| 163 |
+
validate.getHid(True)
|
| 164 |
+
full_response = "hid已刷新,重新对话即可"
|
| 165 |
+
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
| 166 |
+
full_response = full_response[21:]
|
| 167 |
+
return {
|
| 168 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 169 |
+
"object": "chat.completion",
|
| 170 |
+
"created": int(datetime.now().timestamp()),
|
| 171 |
+
"model": request.model,
|
| 172 |
+
"choices": [
|
| 173 |
+
{
|
| 174 |
+
"index": 0,
|
| 175 |
+
"message": {"role": "assistant", "content": full_response},
|
| 176 |
+
"finish_reason": "stop",
|
| 177 |
+
}
|
| 178 |
+
],
|
| 179 |
+
"usage": None,
|
| 180 |
+
}
|