Update api/utils.py
Browse files- api/utils.py +17 -39
api/utils.py
CHANGED
|
@@ -55,7 +55,6 @@ def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
|
| 55 |
|
| 56 |
# Process streaming response with headers from config.py
|
| 57 |
async def process_streaming_response(request: ChatRequest):
|
| 58 |
-
# Generate a unique ID for this request
|
| 59 |
request_id = f"chatcmpl-{uuid.uuid4()}"
|
| 60 |
logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")
|
| 61 |
|
|
@@ -63,24 +62,18 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 63 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
| 64 |
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
| 65 |
|
| 66 |
-
# Adjust headers_api_chat since referer_url is removed
|
| 67 |
headers_api_chat = get_headers_api_chat(BASE_URL)
|
| 68 |
|
|
|
|
| 69 |
if request.model == 'o1-preview':
|
| 70 |
delay_seconds = random.randint(1, 60)
|
| 71 |
-
logger.info(
|
| 72 |
-
f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' "
|
| 73 |
-
f"(Request ID: {request_id})"
|
| 74 |
-
)
|
| 75 |
await asyncio.sleep(delay_seconds)
|
| 76 |
|
| 77 |
-
# Fetch the h-value for the 'validated' field
|
| 78 |
h_value = await getHid()
|
| 79 |
if not h_value:
|
| 80 |
logger.error("Failed to retrieve h-value for validation.")
|
| 81 |
-
raise HTTPException(
|
| 82 |
-
status_code=500, detail="Validation failed due to missing h-value."
|
| 83 |
-
)
|
| 84 |
|
| 85 |
json_data = {
|
| 86 |
"agentMode": agent_mode,
|
|
@@ -89,13 +82,11 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 89 |
"clickedForceWebSearch": False,
|
| 90 |
"codeModelMode": True,
|
| 91 |
"githubToken": None,
|
| 92 |
-
"id":
|
| 93 |
"isChromeExt": False,
|
| 94 |
"isMicMode": False,
|
| 95 |
"maxTokens": request.max_tokens,
|
| 96 |
-
"messages": [
|
| 97 |
-
message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages
|
| 98 |
-
],
|
| 99 |
"mobileClient": False,
|
| 100 |
"playgroundTemperature": request.temperature,
|
| 101 |
"playgroundTopP": request.top_p,
|
|
@@ -104,24 +95,17 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 104 |
"userId": None,
|
| 105 |
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
| 106 |
"userSystemPrompt": None,
|
| 107 |
-
"validated": h_value,
|
| 108 |
"visitFromDelta": False,
|
| 109 |
"webSearchModePrompt": False,
|
| 110 |
-
"imageGenerationMode": False,
|
| 111 |
}
|
| 112 |
|
| 113 |
-
|
| 114 |
-
advertisement_added = False # Track if advertisement is added
|
| 115 |
|
| 116 |
async with httpx.AsyncClient() as client:
|
| 117 |
try:
|
| 118 |
-
async with client.stream(
|
| 119 |
-
"POST",
|
| 120 |
-
f"{BASE_URL}/api/chat",
|
| 121 |
-
headers=headers_api_chat,
|
| 122 |
-
json=json_data,
|
| 123 |
-
timeout=100,
|
| 124 |
-
) as response:
|
| 125 |
response.raise_for_status()
|
| 126 |
|
| 127 |
timestamp = int(datetime.now().timestamp())
|
|
@@ -131,39 +115,33 @@ async def process_streaming_response(request: ChatRequest):
|
|
| 131 |
if content.startswith("$@$v=undefined-rv1$@$"):
|
| 132 |
content = content[21:] # Remove unwanted prefix
|
| 133 |
|
| 134 |
-
# Remove blocked message if present
|
| 135 |
if BLOCKED_MESSAGE in content:
|
| 136 |
logger.info(f"Blocked message detected in response for Request ID {request_id}.")
|
| 137 |
content = content.replace(BLOCKED_MESSAGE, '').strip()
|
| 138 |
|
| 139 |
if not content:
|
| 140 |
-
continue # Skip
|
| 141 |
|
| 142 |
-
# Clean up the content
|
| 143 |
cleaned_content = strip_model_prefix(content, model_prefix)
|
| 144 |
|
| 145 |
-
#
|
| 146 |
-
response_content += cleaned_content
|
| 147 |
-
|
| 148 |
-
# Yield the cleaned chunk as part of the stream
|
| 149 |
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
| 150 |
|
| 151 |
-
#
|
| 152 |
if ADVERTISEMENT_TEXT and not advertisement_added:
|
| 153 |
-
|
|
|
|
| 154 |
advertisement_added = True
|
| 155 |
|
| 156 |
-
# Yield
|
| 157 |
-
yield f"data: {json.dumps(create_chat_completion_data(
|
| 158 |
-
|
| 159 |
-
# Add the final "done" marker
|
| 160 |
yield "data: [DONE]\n\n"
|
| 161 |
|
| 162 |
except httpx.HTTPStatusError as e:
|
| 163 |
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
| 164 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 165 |
except httpx.RequestError as e:
|
| 166 |
-
logger.error(f"
|
| 167 |
raise HTTPException(status_code=500, detail=str(e))
|
| 168 |
|
| 169 |
# Process non-streaming response with headers from config.py
|
|
|
|
| 55 |
|
| 56 |
# Process streaming response with headers from config.py
|
| 57 |
async def process_streaming_response(request: ChatRequest):
|
|
|
|
| 58 |
request_id = f"chatcmpl-{uuid.uuid4()}"
|
| 59 |
logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")
|
| 60 |
|
|
|
|
| 62 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
| 63 |
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
| 64 |
|
|
|
|
| 65 |
headers_api_chat = get_headers_api_chat(BASE_URL)
|
| 66 |
|
| 67 |
+
# Delay for 'o1-preview' model if necessary
|
| 68 |
if request.model == 'o1-preview':
|
| 69 |
delay_seconds = random.randint(1, 60)
|
| 70 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Request ID: {request_id})")
|
|
|
|
|
|
|
|
|
|
| 71 |
await asyncio.sleep(delay_seconds)
|
| 72 |
|
|
|
|
| 73 |
h_value = await getHid()
|
| 74 |
if not h_value:
|
| 75 |
logger.error("Failed to retrieve h-value for validation.")
|
| 76 |
+
raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")
|
|
|
|
|
|
|
| 77 |
|
| 78 |
json_data = {
|
| 79 |
"agentMode": agent_mode,
|
|
|
|
| 82 |
"clickedForceWebSearch": False,
|
| 83 |
"codeModelMode": True,
|
| 84 |
"githubToken": None,
|
| 85 |
+
"id": request_id,
|
| 86 |
"isChromeExt": False,
|
| 87 |
"isMicMode": False,
|
| 88 |
"maxTokens": request.max_tokens,
|
| 89 |
+
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
|
|
|
|
|
|
| 90 |
"mobileClient": False,
|
| 91 |
"playgroundTemperature": request.temperature,
|
| 92 |
"playgroundTopP": request.top_p,
|
|
|
|
| 95 |
"userId": None,
|
| 96 |
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
| 97 |
"userSystemPrompt": None,
|
| 98 |
+
"validated": h_value,
|
| 99 |
"visitFromDelta": False,
|
| 100 |
"webSearchModePrompt": False,
|
| 101 |
+
"imageGenerationMode": False,
|
| 102 |
}
|
| 103 |
|
| 104 |
+
advertisement_added = False # Track if advertisement is already added
|
|
|
|
| 105 |
|
| 106 |
async with httpx.AsyncClient() as client:
|
| 107 |
try:
|
| 108 |
+
async with client.stream("POST", f"{BASE_URL}/api/chat", headers=headers_api_chat, json=json_data, timeout=100) as response:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
response.raise_for_status()
|
| 110 |
|
| 111 |
timestamp = int(datetime.now().timestamp())
|
|
|
|
| 115 |
if content.startswith("$@$v=undefined-rv1$@$"):
|
| 116 |
content = content[21:] # Remove unwanted prefix
|
| 117 |
|
|
|
|
| 118 |
if BLOCKED_MESSAGE in content:
|
| 119 |
logger.info(f"Blocked message detected in response for Request ID {request_id}.")
|
| 120 |
content = content.replace(BLOCKED_MESSAGE, '').strip()
|
| 121 |
|
| 122 |
if not content:
|
| 123 |
+
continue # Skip empty content
|
| 124 |
|
|
|
|
| 125 |
cleaned_content = strip_model_prefix(content, model_prefix)
|
| 126 |
|
| 127 |
+
# Yield cleaned chunk as part of the stream
|
|
|
|
|
|
|
|
|
|
| 128 |
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
| 129 |
|
| 130 |
+
# Append advertisement as a separate chunk with a line break, if applicable
|
| 131 |
if ADVERTISEMENT_TEXT and not advertisement_added:
|
| 132 |
+
advertisement_with_line_break = "\n" + ADVERTISEMENT_TEXT
|
| 133 |
+
yield f"data: {json.dumps(create_chat_completion_data(advertisement_with_line_break, request.model, timestamp))}\n\n"
|
| 134 |
advertisement_added = True
|
| 135 |
|
| 136 |
+
# Yield final chunk indicating the end of the stream
|
| 137 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
|
|
|
|
|
|
| 138 |
yield "data: [DONE]\n\n"
|
| 139 |
|
| 140 |
except httpx.HTTPStatusError as e:
|
| 141 |
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
| 142 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
| 143 |
except httpx.RequestError as e:
|
| 144 |
+
logger.error(f"Request error occurred for Request ID {request_id}: {e}")
|
| 145 |
raise HTTPException(status_code=500, detail=str(e))
|
| 146 |
|
| 147 |
# Process non-streaming response with headers from config.py
|