Update api/utils.py
Browse files- api/utils.py +48 -65
api/utils.py
CHANGED
@@ -16,7 +16,7 @@ from api.config import (
|
|
16 |
AGENT_MODE,
|
17 |
TRENDING_AGENT_MODE,
|
18 |
MODEL_PREFIXES,
|
19 |
-
MODEL_REFERERS
|
20 |
)
|
21 |
from api.models import ChatRequest
|
22 |
from api.logger import setup_logger
|
@@ -72,38 +72,18 @@ def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
|
72 |
return content[len(model_prefix):].strip()
|
73 |
return content
|
74 |
|
75 |
-
#
|
76 |
-
|
77 |
-
# Generate a unique ID for this request
|
78 |
-
request_id = f"chatcmpl-{uuid.uuid4()}"
|
79 |
-
logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")
|
80 |
-
|
81 |
agent_mode = AGENT_MODE.get(request.model, {})
|
82 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
83 |
-
|
84 |
-
|
85 |
-
# Adjust headers_api_chat since referer_url is removed
|
86 |
-
headers_api_chat = get_headers_api_chat(BASE_URL)
|
87 |
-
|
88 |
-
if request.model == 'o1-preview':
|
89 |
-
delay_seconds = random.randint(1, 60)
|
90 |
-
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Request ID: {request_id})")
|
91 |
-
await asyncio.sleep(delay_seconds)
|
92 |
-
|
93 |
-
# Fetch the h-value for the 'validated' field
|
94 |
-
h_value = await getHid()
|
95 |
-
if not h_value:
|
96 |
-
logger.error("Failed to retrieve h-value for validation.")
|
97 |
-
raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")
|
98 |
-
|
99 |
-
json_data = {
|
100 |
"agentMode": agent_mode,
|
101 |
"clickedAnswer2": False,
|
102 |
"clickedAnswer3": False,
|
103 |
"clickedForceWebSearch": False,
|
104 |
"codeModelMode": True,
|
105 |
"githubToken": None,
|
106 |
-
"id": None,
|
107 |
"isChromeExt": False,
|
108 |
"isMicMode": False,
|
109 |
"maxTokens": request.max_tokens,
|
@@ -116,10 +96,32 @@ async def process_streaming_response(request: ChatRequest):
|
|
116 |
"userId": None,
|
117 |
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
118 |
"userSystemPrompt": None,
|
119 |
-
"validated": h_value,
|
120 |
"visitFromDelta": False,
|
121 |
}
|
122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
async with httpx.AsyncClient() as client:
|
124 |
try:
|
125 |
async with client.stream(
|
@@ -138,7 +140,7 @@ async def process_streaming_response(request: ChatRequest):
|
|
138 |
content = content[21:]
|
139 |
# Remove the blocked message if present
|
140 |
if BLOCKED_MESSAGE in content:
|
141 |
-
logger.info(
|
142 |
content = content.replace(BLOCKED_MESSAGE, '').strip()
|
143 |
if not content:
|
144 |
continue # Skip if content is empty after removal
|
@@ -148,29 +150,29 @@ async def process_streaming_response(request: ChatRequest):
|
|
148 |
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
149 |
yield "data: [DONE]\n\n"
|
150 |
except httpx.HTTPStatusError as e:
|
151 |
-
logger.error(f"HTTP error occurred
|
152 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
153 |
except httpx.RequestError as e:
|
154 |
-
logger.error(f"Error occurred during request
|
155 |
raise HTTPException(status_code=500, detail=str(e))
|
156 |
|
157 |
# Process non-streaming response with headers from config.py
|
158 |
async def process_non_streaming_response(request: ChatRequest):
|
159 |
-
|
160 |
-
request_id = f"chatcmpl-{uuid.uuid4()}"
|
161 |
-
logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")
|
162 |
|
163 |
-
agent_mode = AGENT_MODE.get(request.model, {})
|
164 |
-
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
165 |
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
166 |
|
167 |
# Adjust headers_api_chat and headers_chat since referer_url is removed
|
168 |
headers_api_chat = get_headers_api_chat(BASE_URL)
|
169 |
-
headers_chat = get_headers_chat(
|
|
|
|
|
|
|
|
|
170 |
|
171 |
if request.model == 'o1-preview':
|
172 |
delay_seconds = random.randint(20, 60)
|
173 |
-
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview'
|
174 |
await asyncio.sleep(delay_seconds)
|
175 |
|
176 |
# Fetch the h-value for the 'validated' field
|
@@ -179,52 +181,33 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
179 |
logger.error("Failed to retrieve h-value for validation.")
|
180 |
raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")
|
181 |
|
182 |
-
json_data =
|
183 |
-
"agentMode": agent_mode,
|
184 |
-
"clickedAnswer2": False,
|
185 |
-
"clickedAnswer3": False,
|
186 |
-
"clickedForceWebSearch": False,
|
187 |
-
"codeModelMode": True,
|
188 |
-
"githubToken": None,
|
189 |
-
"id": None, # Using request_id instead of chat_id
|
190 |
-
"isChromeExt": False,
|
191 |
-
"isMicMode": False,
|
192 |
-
"maxTokens": request.max_tokens,
|
193 |
-
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
194 |
-
"mobileClient": False,
|
195 |
-
"playgroundTemperature": request.temperature,
|
196 |
-
"playgroundTopP": request.top_p,
|
197 |
-
"previewToken": None,
|
198 |
-
"trendingAgentMode": trending_agent_mode,
|
199 |
-
"userId": None,
|
200 |
-
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
201 |
-
"userSystemPrompt": None,
|
202 |
-
"validated": h_value, # Dynamically set the validated field
|
203 |
-
"visitFromDelta": False,
|
204 |
-
}
|
205 |
|
206 |
full_response = ""
|
207 |
async with httpx.AsyncClient() as client:
|
208 |
try:
|
209 |
async with client.stream(
|
210 |
-
method="POST",
|
|
|
|
|
|
|
211 |
) as response:
|
212 |
response.raise_for_status()
|
213 |
async for chunk in response.aiter_text():
|
214 |
full_response += chunk
|
215 |
except httpx.HTTPStatusError as e:
|
216 |
-
logger.error(f"HTTP error occurred
|
217 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
218 |
except httpx.RequestError as e:
|
219 |
-
logger.error(f"Error occurred during request
|
220 |
raise HTTPException(status_code=500, detail=str(e))
|
221 |
-
|
222 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
223 |
full_response = full_response[21:]
|
224 |
|
225 |
# Remove the blocked message if present
|
226 |
if BLOCKED_MESSAGE in full_response:
|
227 |
-
logger.info(
|
228 |
full_response = full_response.replace(BLOCKED_MESSAGE, '').strip()
|
229 |
if not full_response:
|
230 |
raise HTTPException(status_code=500, detail="Blocked message detected in response.")
|
@@ -244,4 +227,4 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
244 |
}
|
245 |
],
|
246 |
"usage": None,
|
247 |
-
}
|
|
|
16 |
AGENT_MODE,
|
17 |
TRENDING_AGENT_MODE,
|
18 |
MODEL_PREFIXES,
|
19 |
+
MODEL_REFERERS,
|
20 |
)
|
21 |
from api.models import ChatRequest
|
22 |
from api.logger import setup_logger
|
|
|
72 |
return content[len(model_prefix):].strip()
|
73 |
return content
|
74 |
|
75 |
+
# Helper function to build JSON data for the request
|
76 |
+
def build_json_data(request: ChatRequest, h_value: str, model_prefix: Optional[str]):
|
|
|
|
|
|
|
|
|
77 |
agent_mode = AGENT_MODE.get(request.model, {})
|
78 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
79 |
+
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
"agentMode": agent_mode,
|
81 |
"clickedAnswer2": False,
|
82 |
"clickedAnswer3": False,
|
83 |
"clickedForceWebSearch": False,
|
84 |
"codeModelMode": True,
|
85 |
"githubToken": None,
|
86 |
+
"id": None,
|
87 |
"isChromeExt": False,
|
88 |
"isMicMode": False,
|
89 |
"maxTokens": request.max_tokens,
|
|
|
96 |
"userId": None,
|
97 |
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
98 |
"userSystemPrompt": None,
|
99 |
+
"validated": h_value,
|
100 |
"visitFromDelta": False,
|
101 |
}
|
102 |
|
103 |
+
# Process streaming response with headers from config.py
|
104 |
+
async def process_streaming_response(request: ChatRequest):
|
105 |
+
logger.info(f"Processing request - Model: {request.model}")
|
106 |
+
|
107 |
+
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
108 |
+
|
109 |
+
# Adjust headers_api_chat since referer_url is removed
|
110 |
+
headers_api_chat = get_headers_api_chat(BASE_URL)
|
111 |
+
|
112 |
+
if request.model == 'o1-preview':
|
113 |
+
delay_seconds = random.randint(1, 60)
|
114 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview'")
|
115 |
+
await asyncio.sleep(delay_seconds)
|
116 |
+
|
117 |
+
# Fetch the h-value for the 'validated' field
|
118 |
+
h_value = await getHid()
|
119 |
+
if not h_value:
|
120 |
+
logger.error("Failed to retrieve h-value for validation.")
|
121 |
+
raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")
|
122 |
+
|
123 |
+
json_data = build_json_data(request, h_value, model_prefix)
|
124 |
+
|
125 |
async with httpx.AsyncClient() as client:
|
126 |
try:
|
127 |
async with client.stream(
|
|
|
140 |
content = content[21:]
|
141 |
# Remove the blocked message if present
|
142 |
if BLOCKED_MESSAGE in content:
|
143 |
+
logger.info("Blocked message detected in response.")
|
144 |
content = content.replace(BLOCKED_MESSAGE, '').strip()
|
145 |
if not content:
|
146 |
continue # Skip if content is empty after removal
|
|
|
150 |
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
151 |
yield "data: [DONE]\n\n"
|
152 |
except httpx.HTTPStatusError as e:
|
153 |
+
logger.error(f"HTTP error occurred: {e}")
|
154 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
155 |
except httpx.RequestError as e:
|
156 |
+
logger.error(f"Error occurred during request: {e}")
|
157 |
raise HTTPException(status_code=500, detail=str(e))
|
158 |
|
159 |
# Process non-streaming response with headers from config.py
|
160 |
async def process_non_streaming_response(request: ChatRequest):
|
161 |
+
logger.info(f"Processing request - Model: {request.model}")
|
|
|
|
|
162 |
|
|
|
|
|
163 |
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
164 |
|
165 |
# Adjust headers_api_chat and headers_chat since referer_url is removed
|
166 |
headers_api_chat = get_headers_api_chat(BASE_URL)
|
167 |
+
headers_chat = get_headers_chat(
|
168 |
+
BASE_URL,
|
169 |
+
next_action=str(uuid.uuid4()),
|
170 |
+
next_router_state_tree=json.dumps([""])
|
171 |
+
)
|
172 |
|
173 |
if request.model == 'o1-preview':
|
174 |
delay_seconds = random.randint(20, 60)
|
175 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview'")
|
176 |
await asyncio.sleep(delay_seconds)
|
177 |
|
178 |
# Fetch the h-value for the 'validated' field
|
|
|
181 |
logger.error("Failed to retrieve h-value for validation.")
|
182 |
raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")
|
183 |
|
184 |
+
json_data = build_json_data(request, h_value, model_prefix)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
|
186 |
full_response = ""
|
187 |
async with httpx.AsyncClient() as client:
|
188 |
try:
|
189 |
async with client.stream(
|
190 |
+
method="POST",
|
191 |
+
url=f"{BASE_URL}/api/chat",
|
192 |
+
headers=headers_api_chat,
|
193 |
+
json=json_data,
|
194 |
) as response:
|
195 |
response.raise_for_status()
|
196 |
async for chunk in response.aiter_text():
|
197 |
full_response += chunk
|
198 |
except httpx.HTTPStatusError as e:
|
199 |
+
logger.error(f"HTTP error occurred: {e}")
|
200 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
201 |
except httpx.RequestError as e:
|
202 |
+
logger.error(f"Error occurred during request: {e}")
|
203 |
raise HTTPException(status_code=500, detail=str(e))
|
204 |
+
|
205 |
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
206 |
full_response = full_response[21:]
|
207 |
|
208 |
# Remove the blocked message if present
|
209 |
if BLOCKED_MESSAGE in full_response:
|
210 |
+
logger.info("Blocked message detected in response.")
|
211 |
full_response = full_response.replace(BLOCKED_MESSAGE, '').strip()
|
212 |
if not full_response:
|
213 |
raise HTTPException(status_code=500, detail="Blocked message detected in response.")
|
|
|
227 |
}
|
228 |
],
|
229 |
"usage": None,
|
230 |
+
}
|