Update api/utils.py
Browse files- api/utils.py +52 -77
api/utils.py
CHANGED
|
@@ -1,27 +1,21 @@
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
|
|
|
| 2 |
import json
|
| 3 |
-
import uuid
|
| 4 |
from typing import Any, Dict, Optional
|
|
|
|
| 5 |
|
| 6 |
import httpx
|
| 7 |
-
from
|
| 8 |
-
from fastapi
|
| 9 |
-
|
| 10 |
-
from . import
|
| 11 |
-
from .
|
| 12 |
-
MODEL_MAPPING,
|
| 13 |
-
AGENT_MODE,
|
| 14 |
-
TRENDING_AGENT_MODE,
|
| 15 |
-
MODEL_PREFIXES,
|
| 16 |
-
BASE_URL,
|
| 17 |
-
APP_SECRET,
|
| 18 |
-
)
|
| 19 |
-
from .models import ChatRequest
|
| 20 |
-
from .logger import setup_logger
|
| 21 |
|
| 22 |
logger = setup_logger(__name__)
|
| 23 |
-
security = HTTPBearer()
|
| 24 |
|
|
|
|
| 25 |
|
| 26 |
def create_chat_completion_data(
|
| 27 |
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
|
@@ -41,39 +35,37 @@ def create_chat_completion_data(
|
|
| 41 |
"usage": None,
|
| 42 |
}
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
if credentials.credentials != APP_SECRET:
|
| 47 |
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
|
| 48 |
return credentials.credentials
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
content = f"{model_prefix} {content}"
|
| 55 |
-
if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
|
| 56 |
return {
|
| 57 |
"role": message.role,
|
| 58 |
-
"content": content,
|
| 59 |
"data": {
|
| 60 |
-
"imageBase64": message.content[1]
|
| 61 |
"fileText": "",
|
| 62 |
"title": "snapshot",
|
| 63 |
},
|
| 64 |
}
|
| 65 |
-
|
| 66 |
-
|
| 67 |
|
| 68 |
-
async def process_streaming_response(request: ChatRequest):
|
| 69 |
-
|
| 70 |
json_data = {
|
| 71 |
-
"messages": [message_to_dict(msg
|
| 72 |
"previewToken": None,
|
| 73 |
"userId": None,
|
| 74 |
"codeModelMode": True,
|
| 75 |
-
"agentMode":
|
| 76 |
-
"trendingAgentMode":
|
| 77 |
"isMicMode": False,
|
| 78 |
"userSystemPrompt": None,
|
| 79 |
"maxTokens": request.max_tokens,
|
|
@@ -86,17 +78,8 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 86 |
"clickedForceWebSearch": False,
|
| 87 |
"visitFromDelta": False,
|
| 88 |
"mobileClient": False,
|
| 89 |
-
"userSelectedModel":
|
| 90 |
-
"validated": validate.
|
| 91 |
-
}
|
| 92 |
-
|
| 93 |
-
headers = {
|
| 94 |
-
"Content-Type": "application/json",
|
| 95 |
-
"User-Agent": (
|
| 96 |
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 97 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 98 |
-
"Chrome/91.0.4472.124 Safari/537.36"
|
| 99 |
-
),
|
| 100 |
}
|
| 101 |
|
| 102 |
async with httpx.AsyncClient() as client:
|
|
@@ -112,17 +95,18 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 112 |
async for line in response.aiter_lines():
|
| 113 |
timestamp = int(datetime.now().timestamp())
|
| 114 |
if line:
|
| 115 |
-
content = line
|
| 116 |
if "https://www.blackbox.ai" in content:
|
| 117 |
-
validate.
|
| 118 |
-
content = "
|
| 119 |
-
yield f"data: {json.dumps(create_chat_completion_data(content,
|
| 120 |
break
|
| 121 |
if content.startswith("$@$v=undefined-rv1$@$"):
|
| 122 |
-
|
| 123 |
-
|
|
|
|
| 124 |
|
| 125 |
-
yield f"data: {json.dumps(create_chat_completion_data('',
|
| 126 |
yield "data: [DONE]\n\n"
|
| 127 |
except httpx.HTTPStatusError as e:
|
| 128 |
logger.error(f"HTTP error occurred: {e}")
|
|
@@ -131,16 +115,15 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 131 |
logger.error(f"Error occurred during request: {e}")
|
| 132 |
raise HTTPException(status_code=500, detail=str(e))
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
| 137 |
json_data = {
|
| 138 |
-
"messages": [message_to_dict(msg
|
| 139 |
"previewToken": None,
|
| 140 |
"userId": None,
|
| 141 |
"codeModelMode": True,
|
| 142 |
-
"agentMode":
|
| 143 |
-
"trendingAgentMode":
|
| 144 |
"isMicMode": False,
|
| 145 |
"userSystemPrompt": None,
|
| 146 |
"maxTokens": request.max_tokens,
|
|
@@ -153,43 +136,35 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 153 |
"clickedForceWebSearch": False,
|
| 154 |
"visitFromDelta": False,
|
| 155 |
"mobileClient": False,
|
| 156 |
-
"userSelectedModel":
|
| 157 |
-
"validated": validate.
|
| 158 |
-
}
|
| 159 |
-
|
| 160 |
-
headers = {
|
| 161 |
-
"Content-Type": "application/json",
|
| 162 |
-
"User-Agent": (
|
| 163 |
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 164 |
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 165 |
-
"Chrome/91.0.4472.124 Safari/537.36"
|
| 166 |
-
),
|
| 167 |
}
|
| 168 |
-
|
| 169 |
full_response = ""
|
| 170 |
async with httpx.AsyncClient() as client:
|
| 171 |
try:
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
| 175 |
except httpx.HTTPStatusError as e:
|
| 176 |
logger.error(f"HTTP error occurred: {e}")
|
| 177 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 178 |
except httpx.RequestError as e:
|
| 179 |
logger.error(f"Error occurred during request: {e}")
|
| 180 |
raise HTTPException(status_code=500, detail=str(e))
|
| 181 |
-
|
| 182 |
if "https://www.blackbox.ai" in full_response:
|
| 183 |
-
validate.
|
| 184 |
-
full_response = "
|
| 185 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
| 186 |
full_response = full_response[21:]
|
| 187 |
-
|
| 188 |
return {
|
| 189 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 190 |
"object": "chat.completion",
|
| 191 |
"created": int(datetime.now().timestamp()),
|
| 192 |
-
"model":
|
| 193 |
"choices": [
|
| 194 |
{
|
| 195 |
"index": 0,
|
|
|
|
| 1 |
+
# api/utils.py
|
| 2 |
+
|
| 3 |
from datetime import datetime
|
| 4 |
+
from http.client import HTTPException
|
| 5 |
import json
|
|
|
|
| 6 |
from typing import Any, Dict, Optional
|
| 7 |
+
import uuid
|
| 8 |
|
| 9 |
import httpx
|
| 10 |
+
from api.config import MODEL_MAPPING, headers, BASE_URL, validate, model_prefixes
|
| 11 |
+
from fastapi import Depends
|
| 12 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 13 |
+
from api.models import ChatRequest
|
| 14 |
+
from api.logger import setup_logger
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
logger = setup_logger(__name__)
|
|
|
|
| 17 |
|
| 18 |
+
from api.config import resolve_model
|
| 19 |
|
| 20 |
def create_chat_completion_data(
|
| 21 |
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
|
|
|
| 35 |
"usage": None,
|
| 36 |
}
|
| 37 |
|
| 38 |
+
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
|
| 39 |
+
from api.config import APP_SECRET
|
| 40 |
if credentials.credentials != APP_SECRET:
|
| 41 |
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
|
| 42 |
return credentials.credentials
|
| 43 |
|
| 44 |
+
def message_to_dict(message):
|
| 45 |
+
if isinstance(message.content, str):
|
| 46 |
+
return {"role": message.role, "content": message.content}
|
| 47 |
+
elif isinstance(message.content, list) and len(message.content) == 2:
|
|
|
|
|
|
|
| 48 |
return {
|
| 49 |
"role": message.role,
|
| 50 |
+
"content": message.content[0].get("text", ""),
|
| 51 |
"data": {
|
| 52 |
+
"imageBase64": message.content[1].get("image_url", {}).get("url", ""),
|
| 53 |
"fileText": "",
|
| 54 |
"title": "snapshot",
|
| 55 |
},
|
| 56 |
}
|
| 57 |
+
else:
|
| 58 |
+
return {"role": message.role, "content": message.content}
|
| 59 |
|
| 60 |
+
async def process_streaming_response(request: ChatRequest, resolved_model: str):
|
| 61 |
+
from api.config import validate
|
| 62 |
json_data = {
|
| 63 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
| 64 |
"previewToken": None,
|
| 65 |
"userId": None,
|
| 66 |
"codeModelMode": True,
|
| 67 |
+
"agentMode": {}, # Adjust if agentMode is needed
|
| 68 |
+
"trendingAgentMode": {}, # Adjust if trendingAgentMode is needed
|
| 69 |
"isMicMode": False,
|
| 70 |
"userSystemPrompt": None,
|
| 71 |
"maxTokens": request.max_tokens,
|
|
|
|
| 78 |
"clickedForceWebSearch": False,
|
| 79 |
"visitFromDelta": False,
|
| 80 |
"mobileClient": False,
|
| 81 |
+
"userSelectedModel": resolved_model,
|
| 82 |
+
"validated": validate.getHid()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
}
|
| 84 |
|
| 85 |
async with httpx.AsyncClient() as client:
|
|
|
|
| 95 |
async for line in response.aiter_lines():
|
| 96 |
timestamp = int(datetime.now().timestamp())
|
| 97 |
if line:
|
| 98 |
+
content = line + "\n"
|
| 99 |
if "https://www.blackbox.ai" in content:
|
| 100 |
+
validate.getHid(True)
|
| 101 |
+
content = "hid已刷新,重新对话即可\n"
|
| 102 |
+
yield f"data: {json.dumps(create_chat_completion_data(content, resolved_model, timestamp))}\n\n"
|
| 103 |
break
|
| 104 |
if content.startswith("$@$v=undefined-rv1$@$"):
|
| 105 |
+
yield f"data: {json.dumps(create_chat_completion_data(content[21:], resolved_model, timestamp))}\n\n"
|
| 106 |
+
else:
|
| 107 |
+
yield f"data: {json.dumps(create_chat_completion_data(content, resolved_model, timestamp))}\n\n"
|
| 108 |
|
| 109 |
+
yield f"data: {json.dumps(create_chat_completion_data('', resolved_model, timestamp, 'stop'))}\n\n"
|
| 110 |
yield "data: [DONE]\n\n"
|
| 111 |
except httpx.HTTPStatusError as e:
|
| 112 |
logger.error(f"HTTP error occurred: {e}")
|
|
|
|
| 115 |
logger.error(f"Error occurred during request: {e}")
|
| 116 |
raise HTTPException(status_code=500, detail=str(e))
|
| 117 |
|
| 118 |
+
async def process_non_streaming_response(request: ChatRequest, resolved_model: str):
|
| 119 |
+
from api.config import validate
|
|
|
|
| 120 |
json_data = {
|
| 121 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
| 122 |
"previewToken": None,
|
| 123 |
"userId": None,
|
| 124 |
"codeModelMode": True,
|
| 125 |
+
"agentMode": {}, # Adjust if agentMode is needed
|
| 126 |
+
"trendingAgentMode": {}, # Adjust if trendingAgentMode is needed
|
| 127 |
"isMicMode": False,
|
| 128 |
"userSystemPrompt": None,
|
| 129 |
"maxTokens": request.max_tokens,
|
|
|
|
| 136 |
"clickedForceWebSearch": False,
|
| 137 |
"visitFromDelta": False,
|
| 138 |
"mobileClient": False,
|
| 139 |
+
"userSelectedModel": resolved_model,
|
| 140 |
+
"validated": validate.getHid()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
}
|
|
|
|
| 142 |
full_response = ""
|
| 143 |
async with httpx.AsyncClient() as client:
|
| 144 |
try:
|
| 145 |
+
async with client.stream(
|
| 146 |
+
method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
|
| 147 |
+
) as response:
|
| 148 |
+
response.raise_for_status()
|
| 149 |
+
async for chunk in response.aiter_text():
|
| 150 |
+
full_response += chunk
|
| 151 |
except httpx.HTTPStatusError as e:
|
| 152 |
logger.error(f"HTTP error occurred: {e}")
|
| 153 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 154 |
except httpx.RequestError as e:
|
| 155 |
logger.error(f"Error occurred during request: {e}")
|
| 156 |
raise HTTPException(status_code=500, detail=str(e))
|
| 157 |
+
|
| 158 |
if "https://www.blackbox.ai" in full_response:
|
| 159 |
+
validate.getHid(True)
|
| 160 |
+
full_response = "hid已刷新,重新对话即可"
|
| 161 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
| 162 |
full_response = full_response[21:]
|
|
|
|
| 163 |
return {
|
| 164 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 165 |
"object": "chat.completion",
|
| 166 |
"created": int(datetime.now().timestamp()),
|
| 167 |
+
"model": resolved_model,
|
| 168 |
"choices": [
|
| 169 |
{
|
| 170 |
"index": 0,
|