Update api/utils.py
Browse files- api/utils.py +48 -94
api/utils.py
CHANGED
@@ -9,49 +9,25 @@ from typing import Any, Dict, Optional
|
|
9 |
import httpx
|
10 |
from fastapi import HTTPException
|
11 |
from api.config import (
|
12 |
-
|
|
|
13 |
get_headers_api_chat,
|
14 |
get_headers_chat,
|
15 |
BASE_URL,
|
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
|
23 |
|
24 |
logger = setup_logger(__name__)
|
25 |
|
26 |
-
#
|
27 |
def generate_chat_id(length: int = 7) -> str:
|
28 |
characters = string.ascii_letters + string.digits
|
29 |
-
return ''.join(random.
|
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
|
34 |
-
) -> Dict[str, Any]:
|
35 |
-
return {
|
36 |
-
"id": f"chatcmpl-{uuid.uuid4()}",
|
37 |
-
"object": "chat.completion.chunk",
|
38 |
-
"created": timestamp,
|
39 |
-
"model": model,
|
40 |
-
"choices": [
|
41 |
-
{
|
42 |
-
"index": 0,
|
43 |
-
"delta": {"content": content, "role": "assistant"},
|
44 |
-
"finish_reason": finish_reason,
|
45 |
-
}
|
46 |
-
],
|
47 |
-
"usage": None,
|
48 |
-
}
|
49 |
|
50 |
-
#
|
51 |
-
def message_to_dict(message
|
52 |
content = message.content if isinstance(message.content, str) else message.content[0]["text"]
|
53 |
-
if model_prefix:
|
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 |
# Ensure base64 images are always included for all models
|
57 |
return {
|
@@ -65,22 +41,16 @@ def message_to_dict(message, model_prefix: Optional[str] = None):
|
|
65 |
}
|
66 |
return {"role": message.role, "content": content}
|
67 |
|
68 |
-
#
|
69 |
-
def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
70 |
-
"""Remove the model prefix from the response content if present."""
|
71 |
-
if model_prefix and content.startswith(model_prefix):
|
72 |
-
logger.debug(f"Stripping prefix '{model_prefix}' from content.")
|
73 |
-
return content[len(model_prefix):].strip()
|
74 |
-
return content
|
75 |
|
76 |
-
# Function to get the correct referer URL
|
77 |
def get_referer_url(chat_id: str, model: str) -> str:
|
78 |
"""Generate the referer URL based on specific models listed in MODEL_REFERERS."""
|
79 |
if model in MODEL_REFERERS:
|
80 |
-
return f"{BASE_URL}
|
81 |
return BASE_URL
|
82 |
|
83 |
-
# Process streaming response with headers
|
84 |
async def process_streaming_response(request: ChatRequest):
|
85 |
chat_id = generate_chat_id()
|
86 |
referer_url = get_referer_url(chat_id, request.model)
|
@@ -88,37 +58,32 @@ async def process_streaming_response(request: ChatRequest):
|
|
88 |
|
89 |
agent_mode = AGENT_MODE.get(request.model, {})
|
90 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
91 |
-
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
92 |
|
93 |
headers_api_chat = get_headers_api_chat(referer_url)
|
94 |
|
95 |
-
if request.model == 'o1-preview':
|
96 |
-
delay_seconds = random.randint(1, 60)
|
97 |
-
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Chat ID: {chat_id})")
|
98 |
-
await asyncio.sleep(delay_seconds)
|
99 |
-
|
100 |
json_data = {
|
|
|
|
|
|
|
|
|
|
|
101 |
"agentMode": agent_mode,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
"clickedAnswer2": False,
|
103 |
"clickedAnswer3": False,
|
104 |
"clickedForceWebSearch": False,
|
105 |
-
"
|
106 |
-
"githubToken": None,
|
107 |
-
"id": chat_id,
|
108 |
-
"isChromeExt": False,
|
109 |
-
"isMicMode": False,
|
110 |
-
"maxTokens": request.max_tokens,
|
111 |
-
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
112 |
"mobileClient": False,
|
113 |
-
"
|
114 |
-
"
|
115 |
-
"previewToken": None,
|
116 |
-
"trendingAgentMode": trending_agent_mode,
|
117 |
-
"userId": None,
|
118 |
-
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
119 |
-
"userSystemPrompt": None,
|
120 |
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
121 |
-
"visitFromDelta": False,
|
122 |
}
|
123 |
|
124 |
async with httpx.AsyncClient() as client:
|
@@ -134,11 +99,9 @@ async def process_streaming_response(request: ChatRequest):
|
|
134 |
async for line in response.aiter_lines():
|
135 |
timestamp = int(datetime.now().timestamp())
|
136 |
if line:
|
137 |
-
content = line
|
138 |
-
if
|
139 |
-
|
140 |
-
cleaned_content = strip_model_prefix(content, model_prefix)
|
141 |
-
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
142 |
|
143 |
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
144 |
yield "data: [DONE]\n\n"
|
@@ -149,7 +112,7 @@ async def process_streaming_response(request: ChatRequest):
|
|
149 |
logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
|
150 |
raise HTTPException(status_code=500, detail=str(e))
|
151 |
|
152 |
-
# Process non-streaming response with headers
|
153 |
async def process_non_streaming_response(request: ChatRequest):
|
154 |
chat_id = generate_chat_id()
|
155 |
referer_url = get_referer_url(chat_id, request.model)
|
@@ -157,38 +120,33 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
157 |
|
158 |
agent_mode = AGENT_MODE.get(request.model, {})
|
159 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
160 |
-
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
161 |
|
162 |
headers_api_chat = get_headers_api_chat(referer_url)
|
163 |
headers_chat = get_headers_chat(referer_url, next_action=str(uuid.uuid4()), next_router_state_tree=json.dumps([""]))
|
164 |
|
165 |
-
if request.model == 'o1-preview':
|
166 |
-
delay_seconds = random.randint(20, 60)
|
167 |
-
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Chat ID: {chat_id})")
|
168 |
-
await asyncio.sleep(delay_seconds)
|
169 |
-
|
170 |
json_data = {
|
|
|
|
|
|
|
|
|
|
|
171 |
"agentMode": agent_mode,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
172 |
"clickedAnswer2": False,
|
173 |
"clickedAnswer3": False,
|
174 |
"clickedForceWebSearch": False,
|
175 |
-
"
|
176 |
-
"githubToken": None,
|
177 |
-
"id": chat_id,
|
178 |
-
"isChromeExt": False,
|
179 |
-
"isMicMode": False,
|
180 |
-
"maxTokens": request.max_tokens,
|
181 |
-
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
182 |
"mobileClient": False,
|
183 |
-
"
|
184 |
-
"
|
185 |
-
"previewToken": None,
|
186 |
-
"trendingAgentMode": trending_agent_mode,
|
187 |
-
"userId": None,
|
188 |
-
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
189 |
-
"userSystemPrompt": None,
|
190 |
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
191 |
-
"visitFromDelta": False,
|
192 |
}
|
193 |
|
194 |
full_response = ""
|
@@ -199,17 +157,13 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
199 |
) as response:
|
200 |
response.raise_for_status()
|
201 |
async for chunk in response.aiter_text():
|
202 |
-
full_response += chunk
|
203 |
except httpx.HTTPStatusError as e:
|
204 |
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
|
205 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
206 |
except httpx.RequestError as e:
|
207 |
logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
|
208 |
raise HTTPException(status_code=500, detail=str(e))
|
209 |
-
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
210 |
-
full_response = full_response[21:]
|
211 |
-
|
212 |
-
cleaned_full_response = strip_model_prefix(full_response, model_prefix)
|
213 |
|
214 |
return {
|
215 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
@@ -219,7 +173,7 @@ async def process_non_streaming_response(request: ChatRequest):
|
|
219 |
"choices": [
|
220 |
{
|
221 |
"index": 0,
|
222 |
-
"message": {"role": "assistant", "content":
|
223 |
"finish_reason": "stop",
|
224 |
}
|
225 |
],
|
|
|
9 |
import httpx
|
10 |
from fastapi import HTTPException
|
11 |
from api.config import (
|
12 |
+
AGENT_MODE,
|
13 |
+
TRENDING_AGENT_MODE,
|
14 |
get_headers_api_chat,
|
15 |
get_headers_chat,
|
16 |
BASE_URL,
|
|
|
|
|
|
|
|
|
17 |
)
|
18 |
from api.models import ChatRequest
|
19 |
from api.logger import setup_logger
|
20 |
|
21 |
logger = setup_logger(__name__)
|
22 |
|
23 |
+
# Updated message ID generator
|
24 |
def generate_chat_id(length: int = 7) -> str:
|
25 |
characters = string.ascii_letters + string.digits
|
26 |
+
return ''.join(random.choice(characters) for _ in range(length))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
# Updated message_to_dict function (removed model prefixes)
|
29 |
+
def message_to_dict(message):
|
30 |
content = message.content if isinstance(message.content, str) else message.content[0]["text"]
|
|
|
|
|
31 |
if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
|
32 |
# Ensure base64 images are always included for all models
|
33 |
return {
|
|
|
41 |
}
|
42 |
return {"role": message.role, "content": content}
|
43 |
|
44 |
+
# Removed strip_model_prefix function as per your requirement
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
# Function to get the correct referer URL
|
47 |
def get_referer_url(chat_id: str, model: str) -> str:
|
48 |
"""Generate the referer URL based on specific models listed in MODEL_REFERERS."""
|
49 |
if model in MODEL_REFERERS:
|
50 |
+
return f"{BASE_URL}{MODEL_REFERERS[model]}"
|
51 |
return BASE_URL
|
52 |
|
53 |
+
# Process streaming response with updated headers and data
|
54 |
async def process_streaming_response(request: ChatRequest):
|
55 |
chat_id = generate_chat_id()
|
56 |
referer_url = get_referer_url(chat_id, request.model)
|
|
|
58 |
|
59 |
agent_mode = AGENT_MODE.get(request.model, {})
|
60 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
|
|
61 |
|
62 |
headers_api_chat = get_headers_api_chat(referer_url)
|
63 |
|
|
|
|
|
|
|
|
|
|
|
64 |
json_data = {
|
65 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
66 |
+
"id": chat_id,
|
67 |
+
"previewToken": None,
|
68 |
+
"userId": None,
|
69 |
+
"codeModelMode": True,
|
70 |
"agentMode": agent_mode,
|
71 |
+
"trendingAgentMode": trending_agent_mode,
|
72 |
+
"isMicMode": False,
|
73 |
+
"userSystemPrompt": None,
|
74 |
+
"maxTokens": request.max_tokens,
|
75 |
+
"playgroundTopP": request.top_p,
|
76 |
+
"playgroundTemperature": request.temperature,
|
77 |
+
"isChromeExt": False,
|
78 |
+
"githubToken": None,
|
79 |
"clickedAnswer2": False,
|
80 |
"clickedAnswer3": False,
|
81 |
"clickedForceWebSearch": False,
|
82 |
+
"visitFromDelta": False,
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
"mobileClient": False,
|
84 |
+
"userSelectedModel": request.model if request.model in ["gpt-4o", "gemini-pro", "claude-sonnet-3.5", "blackboxai-pro"] else None,
|
85 |
+
"webSearchMode": False, # Adjust if needed
|
|
|
|
|
|
|
|
|
|
|
86 |
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
|
|
87 |
}
|
88 |
|
89 |
async with httpx.AsyncClient() as client:
|
|
|
99 |
async for line in response.aiter_lines():
|
100 |
timestamp = int(datetime.now().timestamp())
|
101 |
if line:
|
102 |
+
content = line.strip()
|
103 |
+
# Handle special cases if necessary
|
104 |
+
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
|
|
|
|
|
105 |
|
106 |
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
107 |
yield "data: [DONE]\n\n"
|
|
|
112 |
logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
|
113 |
raise HTTPException(status_code=500, detail=str(e))
|
114 |
|
115 |
+
# Process non-streaming response with updated headers and data
|
116 |
async def process_non_streaming_response(request: ChatRequest):
|
117 |
chat_id = generate_chat_id()
|
118 |
referer_url = get_referer_url(chat_id, request.model)
|
|
|
120 |
|
121 |
agent_mode = AGENT_MODE.get(request.model, {})
|
122 |
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
|
|
123 |
|
124 |
headers_api_chat = get_headers_api_chat(referer_url)
|
125 |
headers_chat = get_headers_chat(referer_url, next_action=str(uuid.uuid4()), next_router_state_tree=json.dumps([""]))
|
126 |
|
|
|
|
|
|
|
|
|
|
|
127 |
json_data = {
|
128 |
+
"messages": [message_to_dict(msg) for msg in request.messages],
|
129 |
+
"id": chat_id,
|
130 |
+
"previewToken": None,
|
131 |
+
"userId": None,
|
132 |
+
"codeModelMode": True,
|
133 |
"agentMode": agent_mode,
|
134 |
+
"trendingAgentMode": trending_agent_mode,
|
135 |
+
"isMicMode": False,
|
136 |
+
"userSystemPrompt": None,
|
137 |
+
"maxTokens": request.max_tokens,
|
138 |
+
"playgroundTopP": request.top_p,
|
139 |
+
"playgroundTemperature": request.temperature,
|
140 |
+
"isChromeExt": False,
|
141 |
+
"githubToken": None,
|
142 |
"clickedAnswer2": False,
|
143 |
"clickedAnswer3": False,
|
144 |
"clickedForceWebSearch": False,
|
145 |
+
"visitFromDelta": False,
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
"mobileClient": False,
|
147 |
+
"userSelectedModel": request.model if request.model in ["gpt-4o", "gemini-pro", "claude-sonnet-3.5", "blackboxai-pro"] else None,
|
148 |
+
"webSearchMode": False, # Adjust if needed
|
|
|
|
|
|
|
|
|
|
|
149 |
"validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
|
|
|
150 |
}
|
151 |
|
152 |
full_response = ""
|
|
|
157 |
) as response:
|
158 |
response.raise_for_status()
|
159 |
async for chunk in response.aiter_text():
|
160 |
+
full_response += chunk.strip()
|
161 |
except httpx.HTTPStatusError as e:
|
162 |
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
|
163 |
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
164 |
except httpx.RequestError as e:
|
165 |
logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
|
166 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
167 |
|
168 |
return {
|
169 |
"id": f"chatcmpl-{uuid.uuid4()}",
|
|
|
173 |
"choices": [
|
174 |
{
|
175 |
"index": 0,
|
176 |
+
"message": {"role": "assistant", "content": full_response},
|
177 |
"finish_reason": "stop",
|
178 |
}
|
179 |
],
|