Update api/utils.py
Browse files- api/utils.py +59 -44
api/utils.py
CHANGED
|
@@ -4,7 +4,7 @@ import uuid
|
|
| 4 |
import asyncio
|
| 5 |
import random
|
| 6 |
import string
|
| 7 |
-
import
|
| 8 |
from typing import Any, Dict, Optional
|
| 9 |
|
| 10 |
import httpx
|
|
@@ -28,6 +28,9 @@ logger = setup_logger(__name__)
|
|
| 28 |
# Define the blocked message
|
| 29 |
BLOCKED_MESSAGE = "Generated by BLACKBOX.AI, try unlimited chat https://www.blackbox.ai"
|
| 30 |
|
|
|
|
|
|
|
|
|
|
| 31 |
# Helper function to create chat completion data
|
| 32 |
def create_chat_completion_data(
|
| 33 |
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
|
@@ -81,18 +84,6 @@ def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
|
| 81 |
return content[len(model_prefix):].strip()
|
| 82 |
return content
|
| 83 |
|
| 84 |
-
# Helper function to remove content starting with N\n\n$~~~$ and ending with $~~~$
|
| 85 |
-
def remove_enclosed_content(message: str) -> str:
|
| 86 |
-
"""
|
| 87 |
-
Remove content that starts with N\n\n$~~~$ and ends with $~~~$ from the message.
|
| 88 |
-
If no such content is found, return the original message.
|
| 89 |
-
"""
|
| 90 |
-
pattern = r'N\n\n\$\~\~\~\$(.*?)\$\~\~\~\$'
|
| 91 |
-
match = re.search(pattern, message, re.DOTALL)
|
| 92 |
-
if match:
|
| 93 |
-
return message[:match.start()] + message[match.end():]
|
| 94 |
-
return message
|
| 95 |
-
|
| 96 |
# Process streaming response with headers from config.py
|
| 97 |
async def process_streaming_response(request: ChatRequest):
|
| 98 |
# Generate a unique ID for this request
|
|
@@ -108,14 +99,19 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 108 |
|
| 109 |
if request.model == 'o1-preview':
|
| 110 |
delay_seconds = random.randint(1, 60)
|
| 111 |
-
logger.info(
|
|
|
|
|
|
|
|
|
|
| 112 |
await asyncio.sleep(delay_seconds)
|
| 113 |
|
| 114 |
# Fetch the h-value for the 'validated' field
|
| 115 |
h_value = await getHid()
|
| 116 |
if not h_value:
|
| 117 |
logger.error("Failed to retrieve h-value for validation.")
|
| 118 |
-
raise HTTPException(
|
|
|
|
|
|
|
| 119 |
|
| 120 |
json_data = {
|
| 121 |
"agentMode": agent_mode,
|
|
@@ -128,7 +124,9 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 128 |
"isChromeExt": False,
|
| 129 |
"isMicMode": False,
|
| 130 |
"maxTokens": request.max_tokens,
|
| 131 |
-
"messages": [
|
|
|
|
|
|
|
| 132 |
"mobileClient": False,
|
| 133 |
"playgroundTemperature": request.temperature,
|
| 134 |
"playgroundTopP": request.top_p,
|
|
@@ -146,7 +144,11 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 146 |
async with httpx.AsyncClient() as client:
|
| 147 |
try:
|
| 148 |
async with client.stream(
|
| 149 |
-
"POST",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
) as response:
|
| 151 |
response.raise_for_status()
|
| 152 |
async for chunk in response.aiter_text():
|
|
@@ -157,22 +159,29 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 157 |
content = content[21:]
|
| 158 |
# Remove the blocked message if present
|
| 159 |
if BLOCKED_MESSAGE in content:
|
| 160 |
-
logger.info(
|
|
|
|
|
|
|
| 161 |
content = content.replace(BLOCKED_MESSAGE, '').strip()
|
| 162 |
if not content:
|
| 163 |
continue # Skip if content is empty after removal
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
| 167 |
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
| 168 |
|
| 169 |
-
yield f"data: {json.dumps(create_chat_completion_data('
|
| 170 |
yield "data: [DONE]\n\n"
|
| 171 |
except httpx.HTTPStatusError as e:
|
| 172 |
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
| 173 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 174 |
except httpx.RequestError as e:
|
| 175 |
-
logger.error(
|
|
|
|
|
|
|
| 176 |
raise HTTPException(status_code=500, detail=str(e))
|
| 177 |
|
| 178 |
# Process non-streaming response with headers from config.py
|
|
@@ -195,14 +204,19 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 195 |
|
| 196 |
if request.model == 'o1-preview':
|
| 197 |
delay_seconds = random.randint(20, 60)
|
| 198 |
-
logger.info(
|
|
|
|
|
|
|
|
|
|
| 199 |
await asyncio.sleep(delay_seconds)
|
| 200 |
|
| 201 |
# Fetch the h-value for the 'validated' field
|
| 202 |
h_value = await getHid()
|
| 203 |
if not h_value:
|
| 204 |
logger.error("Failed to retrieve h-value for validation.")
|
| 205 |
-
raise HTTPException(
|
|
|
|
|
|
|
| 206 |
|
| 207 |
json_data = {
|
| 208 |
"agentMode": agent_mode,
|
|
@@ -215,7 +229,9 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 215 |
"isChromeExt": False,
|
| 216 |
"isMicMode": False,
|
| 217 |
"maxTokens": request.max_tokens,
|
| 218 |
-
"messages": [
|
|
|
|
|
|
|
| 219 |
"mobileClient": False,
|
| 220 |
"playgroundTemperature": request.temperature,
|
| 221 |
"playgroundTopP": request.top_p,
|
|
@@ -230,26 +246,27 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 230 |
"imageGenerationMode": False, # Added this line
|
| 231 |
}
|
| 232 |
|
|
|
|
| 233 |
async with httpx.AsyncClient() as client:
|
| 234 |
try:
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
return {"choices": [{"text": cleaned_content}], "model": request.model}
|
| 245 |
except httpx.HTTPStatusError as e:
|
| 246 |
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
| 247 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 248 |
except httpx.RequestError as e:
|
| 249 |
-
logger.error(
|
|
|
|
|
|
|
| 250 |
raise HTTPException(status_code=500, detail=str(e))
|
| 251 |
|
| 252 |
-
|
| 253 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
| 254 |
full_response = full_response[21:]
|
| 255 |
|
|
@@ -264,14 +281,12 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
| 264 |
status_code=500, detail="Blocked message detected in response."
|
| 265 |
)
|
| 266 |
|
| 267 |
-
# Remove content between special tags
|
| 268 |
-
full_response = remove_message_between_special_tags(full_response)
|
| 269 |
-
|
| 270 |
-
# Remove search results but keep the links intact
|
| 271 |
-
full_response = remove_search_results(full_response)
|
| 272 |
-
|
| 273 |
cleaned_full_response = strip_model_prefix(full_response, model_prefix)
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
return {
|
| 276 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 277 |
"object": "chat.completion",
|
|
|
|
| 4 |
import asyncio
|
| 5 |
import random
|
| 6 |
import string
|
| 7 |
+
import os
|
| 8 |
from typing import Any, Dict, Optional
|
| 9 |
|
| 10 |
import httpx
|
|
|
|
| 28 |
# Define the blocked message
|
| 29 |
BLOCKED_MESSAGE = "Generated by BLACKBOX.AI, try unlimited chat https://www.blackbox.ai"
|
| 30 |
|
| 31 |
+
# Fetch the advertisement text from environment variable
|
| 32 |
+
ADVERTISEMENT_TEXT = os.getenv("ADVERTISEMENT_TEXT", "")
|
| 33 |
+
|
| 34 |
# Helper function to create chat completion data
|
| 35 |
def create_chat_completion_data(
|
| 36 |
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
|
|
|
| 84 |
return content[len(model_prefix):].strip()
|
| 85 |
return content
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# Process streaming response with headers from config.py
|
| 88 |
async def process_streaming_response(request: ChatRequest):
|
| 89 |
# Generate a unique ID for this request
|
|
|
|
| 99 |
|
| 100 |
if request.model == 'o1-preview':
|
| 101 |
delay_seconds = random.randint(1, 60)
|
| 102 |
+
logger.info(
|
| 103 |
+
f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' "
|
| 104 |
+
f"(Request ID: {request_id})"
|
| 105 |
+
)
|
| 106 |
await asyncio.sleep(delay_seconds)
|
| 107 |
|
| 108 |
# Fetch the h-value for the 'validated' field
|
| 109 |
h_value = await getHid()
|
| 110 |
if not h_value:
|
| 111 |
logger.error("Failed to retrieve h-value for validation.")
|
| 112 |
+
raise HTTPException(
|
| 113 |
+
status_code=500, detail="Validation failed due to missing h-value."
|
| 114 |
+
)
|
| 115 |
|
| 116 |
json_data = {
|
| 117 |
"agentMode": agent_mode,
|
|
|
|
| 124 |
"isChromeExt": False,
|
| 125 |
"isMicMode": False,
|
| 126 |
"maxTokens": request.max_tokens,
|
| 127 |
+
"messages": [
|
| 128 |
+
message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages
|
| 129 |
+
],
|
| 130 |
"mobileClient": False,
|
| 131 |
"playgroundTemperature": request.temperature,
|
| 132 |
"playgroundTopP": request.top_p,
|
|
|
|
| 144 |
async with httpx.AsyncClient() as client:
|
| 145 |
try:
|
| 146 |
async with client.stream(
|
| 147 |
+
"POST",
|
| 148 |
+
f"{BASE_URL}/api/chat",
|
| 149 |
+
headers=headers_api_chat,
|
| 150 |
+
json=json_data,
|
| 151 |
+
timeout=100,
|
| 152 |
) as response:
|
| 153 |
response.raise_for_status()
|
| 154 |
async for chunk in response.aiter_text():
|
|
|
|
| 159 |
content = content[21:]
|
| 160 |
# Remove the blocked message if present
|
| 161 |
if BLOCKED_MESSAGE in content:
|
| 162 |
+
logger.info(
|
| 163 |
+
f"Blocked message detected in response for Request ID {request_id}."
|
| 164 |
+
)
|
| 165 |
content = content.replace(BLOCKED_MESSAGE, '').strip()
|
| 166 |
if not content:
|
| 167 |
continue # Skip if content is empty after removal
|
| 168 |
+
cleaned_content = strip_model_prefix(content, model_prefix)
|
| 169 |
+
|
| 170 |
+
# Append advertisement text
|
| 171 |
+
if ADVERTISEMENT_TEXT:
|
| 172 |
+
cleaned_content += "\n\n" + ADVERTISEMENT_TEXT
|
| 173 |
+
|
| 174 |
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
| 175 |
|
| 176 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
| 177 |
yield "data: [DONE]\n\n"
|
| 178 |
except httpx.HTTPStatusError as e:
|
| 179 |
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
| 180 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 181 |
except httpx.RequestError as e:
|
| 182 |
+
logger.error(
|
| 183 |
+
f"Error occurred during request for Request ID {request_id}: {e}"
|
| 184 |
+
)
|
| 185 |
raise HTTPException(status_code=500, detail=str(e))
|
| 186 |
|
| 187 |
# Process non-streaming response with headers from config.py
|
|
|
|
| 204 |
|
| 205 |
if request.model == 'o1-preview':
|
| 206 |
delay_seconds = random.randint(20, 60)
|
| 207 |
+
logger.info(
|
| 208 |
+
f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' "
|
| 209 |
+
f"(Request ID: {request_id})"
|
| 210 |
+
)
|
| 211 |
await asyncio.sleep(delay_seconds)
|
| 212 |
|
| 213 |
# Fetch the h-value for the 'validated' field
|
| 214 |
h_value = await getHid()
|
| 215 |
if not h_value:
|
| 216 |
logger.error("Failed to retrieve h-value for validation.")
|
| 217 |
+
raise HTTPException(
|
| 218 |
+
status_code=500, detail="Validation failed due to missing h-value."
|
| 219 |
+
)
|
| 220 |
|
| 221 |
json_data = {
|
| 222 |
"agentMode": agent_mode,
|
|
|
|
| 229 |
"isChromeExt": False,
|
| 230 |
"isMicMode": False,
|
| 231 |
"maxTokens": request.max_tokens,
|
| 232 |
+
"messages": [
|
| 233 |
+
message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages
|
| 234 |
+
],
|
| 235 |
"mobileClient": False,
|
| 236 |
"playgroundTemperature": request.temperature,
|
| 237 |
"playgroundTopP": request.top_p,
|
|
|
|
| 246 |
"imageGenerationMode": False, # Added this line
|
| 247 |
}
|
| 248 |
|
| 249 |
+
full_response = ""
|
| 250 |
async with httpx.AsyncClient() as client:
|
| 251 |
try:
|
| 252 |
+
async with client.stream(
|
| 253 |
+
method="POST",
|
| 254 |
+
url=f"{BASE_URL}/api/chat",
|
| 255 |
+
headers=headers_api_chat,
|
| 256 |
+
json=json_data,
|
| 257 |
+
) as response:
|
| 258 |
+
response.raise_for_status()
|
| 259 |
+
async for chunk in response.aiter_text():
|
| 260 |
+
full_response += chunk
|
|
|
|
| 261 |
except httpx.HTTPStatusError as e:
|
| 262 |
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
| 263 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 264 |
except httpx.RequestError as e:
|
| 265 |
+
logger.error(
|
| 266 |
+
f"Error occurred during request for Request ID {request_id}: {e}"
|
| 267 |
+
)
|
| 268 |
raise HTTPException(status_code=500, detail=str(e))
|
| 269 |
|
|
|
|
| 270 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
| 271 |
full_response = full_response[21:]
|
| 272 |
|
|
|
|
| 281 |
status_code=500, detail="Blocked message detected in response."
|
| 282 |
)
|
| 283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
cleaned_full_response = strip_model_prefix(full_response, model_prefix)
|
| 285 |
|
| 286 |
+
# Append the advertisement text if available
|
| 287 |
+
if ADVERTISEMENT_TEXT:
|
| 288 |
+
cleaned_full_response += "\n\n" + ADVERTISEMENT_TEXT
|
| 289 |
+
|
| 290 |
return {
|
| 291 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
| 292 |
"object": "chat.completion",
|