Update api/utils.py
Browse files- api/utils.py +40 -16
api/utils.py
CHANGED
@@ -55,6 +55,7 @@ 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 |
request_id = f"chatcmpl-{uuid.uuid4()}"
|
59 |
logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")
|
60 |
|
@@ -62,18 +63,24 @@ async def process_streaming_response(request: ChatRequest):
|
|
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(
|
|
|
|
|
|
|
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(
|
|
|
|
|
77 |
|
78 |
json_data = {
|
79 |
"agentMode": agent_mode,
|
@@ -82,11 +89,13 @@ async def process_streaming_response(request: ChatRequest):
|
|
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": [
|
|
|
|
|
90 |
"mobileClient": False,
|
91 |
"playgroundTemperature": request.temperature,
|
92 |
"playgroundTopP": request.top_p,
|
@@ -95,17 +104,24 @@ async def process_streaming_response(request: ChatRequest):
|
|
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 |
-
|
|
|
105 |
|
106 |
async with httpx.AsyncClient() as client:
|
107 |
try:
|
108 |
-
async with client.stream(
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
response.raise_for_status()
|
110 |
|
111 |
timestamp = int(datetime.now().timestamp())
|
@@ -115,34 +131,42 @@ async def process_streaming_response(request: ChatRequest):
|
|
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
|
124 |
|
|
|
125 |
cleaned_content = strip_model_prefix(content, model_prefix)
|
126 |
|
127 |
-
#
|
|
|
|
|
|
|
128 |
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
129 |
|
130 |
-
#
|
131 |
if ADVERTISEMENT_TEXT and not advertisement_added:
|
132 |
-
|
133 |
advertisement_added = True
|
134 |
|
135 |
-
#
|
136 |
-
yield f"data: {json.dumps(create_chat_completion_data(
|
|
|
|
|
137 |
yield "data: [DONE]\n\n"
|
138 |
|
139 |
except httpx.HTTPStatusError as e:
|
140 |
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
141 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
142 |
except httpx.RequestError as e:
|
143 |
-
logger.error(f"
|
144 |
raise HTTPException(status_code=500, detail=str(e))
|
145 |
|
|
|
146 |
# Process non-streaming response with headers from config.py
|
147 |
async def process_non_streaming_response(request: ChatRequest):
|
148 |
request_id = f"chatcmpl-{uuid.uuid4()}"
|
|
|
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 |
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 |
"clickedForceWebSearch": False,
|
90 |
"codeModelMode": True,
|
91 |
"githubToken": None,
|
92 |
+
"id": None, # Using request_id instead of chat_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 |
"userId": None,
|
105 |
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
106 |
"userSystemPrompt": None,
|
107 |
+
"validated": h_value, # Dynamically set the validated field
|
108 |
"visitFromDelta": False,
|
109 |
"webSearchModePrompt": False,
|
110 |
+
"imageGenerationMode": False, # Added this line
|
111 |
}
|
112 |
|
113 |
+
response_content = "" # Variable to hold the full response content
|
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 |
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 if content is empty after removal
|
141 |
|
142 |
+
# Clean up the content
|
143 |
cleaned_content = strip_model_prefix(content, model_prefix)
|
144 |
|
145 |
+
# Add the chunk to the full response content
|
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 |
+
# After all chunks are processed, append the advertisement text at the end if it's not already included
|
152 |
if ADVERTISEMENT_TEXT and not advertisement_added:
|
153 |
+
response_content += "\n\n" + ADVERTISEMENT_TEXT # Line break added here
|
154 |
advertisement_added = True
|
155 |
|
156 |
+
# Now yield the final chunk with the advertisement text appended at the end
|
157 |
+
yield f"data: {json.dumps(create_chat_completion_data(response_content, request.model, timestamp, 'stop'))}\n\n"
|
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"Error occurred during request for Request ID {request_id}: {e}")
|
167 |
raise HTTPException(status_code=500, detail=str(e))
|
168 |
|
169 |
+
|
170 |
# Process non-streaming response with headers from config.py
|
171 |
async def process_non_streaming_response(request: ChatRequest):
|
172 |
request_id = f"chatcmpl-{uuid.uuid4()}"
|