Niansuh commited on
Commit
86d7bd2
·
verified ·
1 Parent(s): e43189b

Update api/utils.py

Browse files
Files changed (1) hide show
  1. api/utils.py +14 -283
api/utils.py CHANGED
@@ -4,293 +4,24 @@ import uuid
4
  import asyncio
5
  import random
6
  import string
7
- import time
8
- import re
9
  from typing import Any, Dict, Optional
10
 
11
- import os
12
- import requests
13
  import httpx
14
  from fastapi import HTTPException
 
 
 
 
 
 
 
 
15
  from api.models import ChatRequest
16
  from api.logger import setup_logger
 
17
 
18
  logger = setup_logger(__name__)
19
 
20
- # Load environment variables
21
- from dotenv import load_dotenv
22
-
23
- load_dotenv()
24
-
25
- # Base URL
26
- BASE_URL = "https://www.blackbox.ai"
27
-
28
- APP_SECRET = os.getenv("APP_SECRET")
29
-
30
- # Allowed models (copy from your config.py)
31
- ALLOWED_MODELS = [
32
- {"id": "blackboxai", "name": "blackboxai"},
33
- {"id": "blackboxai-pro", "name": "blackboxai-pro"},
34
- {"id": "flux", "name": "flux"},
35
- {"id": "llama-3.1-8b", "name": "llama-3.1-8b"},
36
- {"id": "llama-3.1-70b", "name": "llama-3.1-70b"},
37
- {"id": "llama-3.1-405b", "name": "llama-3.1-405"},
38
- {"id": "gpt-4o", "name": "gpt-4o"},
39
- {"id": "gemini-pro", "name": "gemini-pro"},
40
- {"id": "gemini-1.5-flash", "name": "gemini-1.5-flash"},
41
- {"id": "claude-sonnet-3.5", "name": "claude-sonnet-3.5"},
42
- {"id": "PythonAgent", "name": "PythonAgent"},
43
- {"id": "JavaAgent", "name": "JavaAgent"},
44
- {"id": "JavaScriptAgent", "name": "JavaScriptAgent"},
45
- {"id": "HTMLAgent", "name": "HTMLAgent"},
46
- {"id": "GoogleCloudAgent", "name": "GoogleCloudAgent"},
47
- {"id": "AndroidDeveloper", "name": "AndroidDeveloper"},
48
- {"id": "SwiftDeveloper", "name": "SwiftDeveloper"},
49
- {"id": "Next.jsAgent", "name": "Next.jsAgent"},
50
- {"id": "MongoDBAgent", "name": "MongoDBAgent"},
51
- {"id": "PyTorchAgent", "name": "PyTorchAgent"},
52
- {"id": "ReactAgent", "name": "ReactAgent"},
53
- {"id": "XcodeAgent", "name": "XcodeAgent"},
54
- {"id": "AngularJSAgent", "name": "AngularJSAgent"},
55
- {"id": "HerokuAgent", "name": "HerokuAgent"},
56
- {"id": "GodotAgent", "name": "GodotAgent"},
57
- {"id": "GoAgent", "name": "GoAgent"},
58
- {"id": "GitlabAgent", "name": "GitlabAgent"},
59
- {"id": "GitAgent", "name": "GitAgent"},
60
- {"id": "RepoMap", "name": "RepoMap"},
61
- {"id": "gemini-1.5-pro-latest", "name": "gemini-pro"},
62
- {"id": "gemini-1.5-pro", "name": "gemini-1.5-pro"},
63
- {"id": "claude-3-5-sonnet-20240620", "name": "claude-sonnet-3.5"},
64
- {"id": "claude-3-5-sonnet", "name": "claude-sonnet-3.5"},
65
- {"id": "Niansuh", "name": "Niansuh"},
66
- {"id": "o1-preview", "name": "o1-preview"},
67
- {"id": "claude-3-5-sonnet-20241022", "name": "claude-3-5-sonnet-20241022"},
68
- {"id": "claude-3-5-sonnet-x", "name": "claude-3-5-sonnet-x"},
69
- # Added New Agents
70
- {"id": "FlaskAgent", "name": "FlaskAgent"},
71
- {"id": "FirebaseAgent", "name": "FirebaseAgent"},
72
- {"id": "FastAPIAgent", "name": "FastAPIAgent"},
73
- {"id": "ErlangAgent", "name": "ErlangAgent"},
74
- {"id": "ElectronAgent", "name": "ElectronAgent"},
75
- {"id": "DockerAgent", "name": "DockerAgent"},
76
- {"id": "DigitalOceanAgent", "name": "DigitalOceanAgent"},
77
- {"id": "BitbucketAgent", "name": "BitbucketAgent"},
78
- {"id": "AzureAgent", "name": "AzureAgent"},
79
- {"id": "FlutterAgent", "name": "FlutterAgent"},
80
- {"id": "YoutubeAgent", "name": "YoutubeAgent"},
81
- {"id": "builderAgent", "name": "builderAgent"},
82
- ]
83
-
84
- # Model mapping
85
- MODEL_MAPPING = {
86
- "blackboxai": "blackboxai",
87
- "blackboxai-pro": "blackboxai-pro",
88
- "flux": "flux",
89
- "ImageGeneration": "flux",
90
- "llama-3.1-8b": "llama-3.1-8b",
91
- "llama-3.1-70b": "llama-3.1-70b",
92
- "llama-3.1-405b": "llama-3.1-405",
93
- "gpt-4o": "gpt-4o",
94
- "gemini-pro": "gemini-pro",
95
- "gemini-1.5-flash": "gemini-1.5-flash",
96
- "claude-sonnet-3.5": "claude-sonnet-3.5",
97
- "PythonAgent": "PythonAgent",
98
- "JavaAgent": "JavaAgent",
99
- "JavaScriptAgent": "JavaScriptAgent",
100
- "HTMLAgent": "HTMLAgent",
101
- "GoogleCloudAgent": "GoogleCloudAgent",
102
- "AndroidDeveloper": "AndroidDeveloper",
103
- "SwiftDeveloper": "SwiftDeveloper",
104
- "Next.jsAgent": "Next.jsAgent",
105
- "MongoDBAgent": "MongoDBAgent",
106
- "PyTorchAgent": "PyTorchAgent",
107
- "ReactAgent": "ReactAgent",
108
- "XcodeAgent": "XcodeAgent",
109
- "AngularJSAgent": "AngularJSAgent",
110
- "HerokuAgent": "HerokuAgent",
111
- "GodotAgent": "GodotAgent",
112
- "GoAgent": "GoAgent",
113
- "GitlabAgent": "GitlabAgent",
114
- "GitAgent": "GitAgent",
115
- "RepoMap": "RepoMap",
116
- # Additional mappings
117
- "gemini-flash": "gemini-1.5-flash",
118
- "claude-3.5-sonnet": "claude-sonnet-3.5",
119
- "gemini-1.5-pro-latest": "gemini-pro",
120
- "gemini-1.5-pro": "gemini-1.5-pro",
121
- "claude-3-5-sonnet-20240620": "claude-sonnet-3.5",
122
- "claude-3-5-sonnet": "claude-sonnet-3.5",
123
- "Niansuh": "Niansuh",
124
- "o1-preview": "o1-preview",
125
- "claude-3-5-sonnet-20241022": "claude-3-5-sonnet-20241022",
126
- "claude-3-5-sonnet-x": "claude-3-5-sonnet-x",
127
- # Added New Agents
128
- "FlaskAgent": "FlaskAgent",
129
- "FirebaseAgent": "FirebaseAgent",
130
- "FastAPIAgent": "FastAPIAgent",
131
- "ErlangAgent": "ErlangAgent",
132
- "ElectronAgent": "ElectronAgent",
133
- "DockerAgent": "DockerAgent",
134
- "DigitalOceanAgent": "DigitalOceanAgent",
135
- "BitbucketAgent": "BitbucketAgent",
136
- "AzureAgent": "AzureAgent",
137
- "FlutterAgent": "FlutterAgent",
138
- "YoutubeAgent": "YoutubeAgent",
139
- "builderAgent": "builderAgent",
140
- }
141
-
142
- # Agent modes
143
- AGENT_MODE = {
144
- 'flux': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "flux"},
145
- 'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "Niansuh"},
146
- 'o1-preview': {'mode': True, 'id': "o1Dst8La8", 'name': "o1-preview"},
147
- 'claude-3-5-sonnet-20241022': {'mode': True, 'id': "Claude-Sonnet-3.5zO2HZSF", 'name': "claude-3-5-sonnet-20241022"},
148
- 'claude-3-5-sonnet-x': {'mode': True, 'id': "Claude-Sonnet-3.52022JE0UdQ3", 'name': "claude-3-5-sonnet-x"},
149
- }
150
-
151
- # Trending agent modes
152
- TRENDING_AGENT_MODE = {
153
- "blackboxai": {},
154
- "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
155
- "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
156
- 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
157
- 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"},
158
- 'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},
159
- 'PythonAgent': {'mode': True, 'id': "Python Agent"},
160
- 'JavaAgent': {'mode': True, 'id': "Java Agent"},
161
- 'JavaScriptAgent': {'mode': True, 'id': "JavaScript Agent"},
162
- 'HTMLAgent': {'mode': True, 'id': "HTML Agent"},
163
- 'GoogleCloudAgent': {'mode': True, 'id': "Google Cloud Agent"},
164
- 'AndroidDeveloper': {'mode': True, 'id': "Android Developer"},
165
- 'SwiftDeveloper': {'mode': True, 'id': "Swift Developer"},
166
- 'Next.jsAgent': {'mode': True, 'id': "Next.js Agent"},
167
- 'MongoDBAgent': {'mode': True, 'id': "MongoDB Agent"},
168
- 'PyTorchAgent': {'mode': True, 'id': "PyTorch Agent"},
169
- 'ReactAgent': {'mode': True, 'id': "React Agent"},
170
- 'XcodeAgent': {'mode': True, 'id': "Xcode Agent"},
171
- 'AngularJSAgent': {'mode': True, 'id': "AngularJS Agent"},
172
- 'HerokuAgent': {'mode': True, 'id': "HerokuAgent"},
173
- 'GodotAgent': {'mode': True, 'id': "GodotAgent"},
174
- 'GoAgent': {'mode': True, 'id': "GoAgent"},
175
- 'GitlabAgent': {'mode': True, 'id': "GitlabAgent"},
176
- 'GitAgent': {'mode': True, 'id': "GitAgent"},
177
- 'RepoMap': {'mode': True, 'id': "repomap"},
178
- # Added New Agents
179
- 'FlaskAgent': {'mode': True, 'id': "FlaskAgent"},
180
- 'FirebaseAgent': {'mode': True, 'id': "FirebaseAgent"},
181
- 'FastAPIAgent': {'mode': True, 'id': "FastAPIAgent"},
182
- 'ErlangAgent': {'mode': True, 'id': "ErlangAgent"},
183
- 'ElectronAgent': {'mode': True, 'id': "ElectronAgent"},
184
- 'DockerAgent': {'mode': True, 'id': "DockerAgent"},
185
- 'DigitalOceanAgent': {'mode': True, 'id': "DigitalOceanAgent"},
186
- 'BitbucketAgent': {'mode': True, 'id': "BitbucketAgent"},
187
- 'AzureAgent': {'mode': True, 'id': "AzureAgent"},
188
- 'FlutterAgent': {'mode': True, 'id': "FlutterAgent"},
189
- 'YoutubeAgent': {'mode': True, 'id': "YoutubeAgent"},
190
- 'builderAgent': {'mode': True, 'id': "builderAgent"},
191
- }
192
-
193
- # Model prefixes
194
- MODEL_PREFIXES = {
195
- 'gpt-4o': '@GPT-4o',
196
- 'gemini-pro': '@Gemini-PRO',
197
- 'PythonAgent': '@Python Agent',
198
- 'JavaAgent': '@Java Agent',
199
- 'JavaScriptAgent': '@JavaScript Agent',
200
- 'HTMLAgent': '@HTML Agent',
201
- 'GoogleCloudAgent': '@Google Cloud Agent',
202
- 'AndroidDeveloper': '@Android Developer',
203
- 'SwiftDeveloper': '@Swift Developer',
204
- 'Next.jsAgent': '@Next.js Agent',
205
- 'MongoDBAgent': '@MongoDB Agent',
206
- 'PyTorchAgent': '@PyTorch Agent',
207
- 'ReactAgent': '@React Agent',
208
- 'XcodeAgent': '@Xcode Agent',
209
- 'AngularJSAgent': '@AngularJS Agent',
210
- 'HerokuAgent': '@Heroku Agent',
211
- 'GodotAgent': '@Godot Agent',
212
- 'GoAgent': '@Go Agent',
213
- 'GitlabAgent': '@Gitlab Agent',
214
- 'GitAgent': '@Gitlab Agent',
215
- 'blackboxai-pro': '@BLACKBOXAI-PRO',
216
- 'flux': '@Image Generation',
217
- # Added New Agents
218
- 'FlaskAgent': '@Flask Agent',
219
- 'FirebaseAgent': '@Firebase Agent',
220
- 'FastAPIAgent': '@FastAPI Agent',
221
- 'ErlangAgent': '@Erlang Agent',
222
- 'ElectronAgent': '@Electron Agent',
223
- 'DockerAgent': '@Docker Agent',
224
- 'DigitalOceanAgent': '@DigitalOcean Agent',
225
- 'BitbucketAgent': '@Bitbucket Agent',
226
- 'AzureAgent': '@Azure Agent',
227
- 'FlutterAgent': '@Flutter Agent',
228
- 'YoutubeAgent': '@Youtube Agent',
229
- 'builderAgent': '@builder Agent',
230
- }
231
-
232
- # Cache variables for getHid function
233
- cached_hid = None
234
- cache_time = 0
235
- CACHE_DURATION = 36000 # 10 hours
236
-
237
- # Headers for HTTP requests
238
- headers = {
239
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
240
- 'AppleWebKit/537.36 (KHTML, like Gecko) '
241
- 'Chrome/130.0.0.0 Safari/537.36',
242
- 'Content-Type': 'application/json',
243
- }
244
-
245
- def getHid(force_refresh=False):
246
- global cached_hid, cache_time
247
- current_time = time.time()
248
-
249
- # Check if we need to refresh or cache is valid
250
- if not force_refresh and cached_hid and (current_time - cache_time) < CACHE_DURATION:
251
- logger.info(f"Using cached_hid: {cached_hid}")
252
- return cached_hid
253
-
254
- try:
255
- # Get initial HTML content
256
- response = requests.get(BASE_URL, headers=headers)
257
- response.raise_for_status()
258
- content = response.text
259
-
260
- # Use regex to find the specific static/chunks path
261
- pattern = r"static/chunks/app/layout-[a-zA-Z0-9]+\.js"
262
- match = re.search(pattern, content)
263
-
264
- if match:
265
- # Construct full URL of JS file
266
- js_path = match.group()
267
- full_url = f"{BASE_URL}/_next/{js_path}"
268
-
269
- # Get JS file content
270
- js_response = requests.get(full_url, headers=headers)
271
- js_response.raise_for_status()
272
-
273
- # Search for h-value in JS content
274
- h_pattern = r'h="([0-9a-f-]+)"'
275
- h_match = re.search(h_pattern, js_response.text)
276
-
277
- if h_match:
278
- h_value = h_match.group(1)
279
- logger.info(f"Found h-value: {h_value}")
280
- # Update cache
281
- cached_hid = h_value
282
- cache_time = current_time
283
- return h_value
284
- else:
285
- logger.error("h-value not found in JS content")
286
- return None
287
- else:
288
- logger.error("Specified JS file path not found in HTML content")
289
- return None
290
- except requests.exceptions.RequestException as e:
291
- logger.error(f"An error occurred: {e}")
292
- return None
293
-
294
  # Helper function to create a random alphanumeric chat ID
295
  def generate_chat_id(length: int = 7) -> str:
296
  characters = string.ascii_letters + string.digits
@@ -350,7 +81,7 @@ def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
350
  # Process streaming response
351
  async def process_streaming_response(request: ChatRequest):
352
  chat_id = generate_chat_id()
353
- referer_url = BASE_URL # MODEL_REFERERS are removed
354
  logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")
355
 
356
  agent_mode = AGENT_MODE.get(request.model, {})
@@ -385,7 +116,7 @@ async def process_streaming_response(request: ChatRequest):
385
  "userId": None,
386
  "userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
387
  "userSystemPrompt": None,
388
- "validated": getHid(),
389
  "visitFromDelta": False,
390
  }
391
 
@@ -404,7 +135,7 @@ async def process_streaming_response(request: ChatRequest):
404
  if line:
405
  content = line
406
  if "https://www.blackbox.ai" in content:
407
- getHid(True)
408
  content = "hid已刷新,重新对话即可\n"
409
  yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
410
  break
@@ -460,7 +191,7 @@ async def process_non_streaming_response(request: ChatRequest):
460
  "userId": None,
461
  "userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
462
  "userSystemPrompt": None,
463
- "validated": getHid(),
464
  "visitFromDelta": False,
465
  }
466
 
@@ -480,7 +211,7 @@ async def process_non_streaming_response(request: ChatRequest):
480
  logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
481
  raise HTTPException(status_code=500, detail=str(e))
482
  if "https://www.blackbox.ai" in full_response:
483
- getHid(True)
484
  full_response = "hid已刷新,重新对话即可"
485
  if full_response.startswith("$@$v=undefined-rv1$@$"):
486
  full_response = full_response[21:]
 
4
  import asyncio
5
  import random
6
  import string
 
 
7
  from typing import Any, Dict, Optional
8
 
 
 
9
  import httpx
10
  from fastapi import HTTPException
11
+ from api.config import (
12
+ MODEL_MAPPING,
13
+ headers,
14
+ BASE_URL,
15
+ AGENT_MODE,
16
+ TRENDING_AGENT_MODE,
17
+ MODEL_PREFIXES
18
+ )
19
  from api.models import ChatRequest
20
  from api.logger import setup_logger
21
+ from api import validate
22
 
23
  logger = setup_logger(__name__)
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # Helper function to create a random alphanumeric chat ID
26
  def generate_chat_id(length: int = 7) -> str:
27
  characters = string.ascii_letters + string.digits
 
81
  # Process streaming response
82
  async def process_streaming_response(request: ChatRequest):
83
  chat_id = generate_chat_id()
84
+ referer_url = BASE_URL
85
  logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")
86
 
87
  agent_mode = AGENT_MODE.get(request.model, {})
 
116
  "userId": None,
117
  "userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
118
  "userSystemPrompt": None,
119
+ "validated": validate.getHid(),
120
  "visitFromDelta": False,
121
  }
122
 
 
135
  if line:
136
  content = line
137
  if "https://www.blackbox.ai" in content:
138
+ validate.getHid(True)
139
  content = "hid已刷新,重新对话即可\n"
140
  yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
141
  break
 
191
  "userId": None,
192
  "userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
193
  "userSystemPrompt": None,
194
+ "validated": validate.getHid(),
195
  "visitFromDelta": False,
196
  }
197
 
 
211
  logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
212
  raise HTTPException(status_code=500, detail=str(e))
213
  if "https://www.blackbox.ai" in full_response:
214
+ validate.getHid(True)
215
  full_response = "hid已刷新,重新对话即可"
216
  if full_response.startswith("$@$v=undefined-rv1$@$"):
217
  full_response = full_response[21:]