Niansuh commited on
Commit
aaae064
1 Parent(s): 5640f9d

Upload 15 files

Browse files
Files changed (7) hide show
  1. .github/workflows/docker-deploy.yml +1 -1
  2. Dockerfile +1 -1
  3. api/config.py +259 -259
  4. api/utils.py +247 -247
  5. api/validate.py +41 -40
  6. main.py +5 -5
  7. requirements.txt +5 -5
.github/workflows/docker-deploy.yml CHANGED
@@ -36,7 +36,7 @@ jobs:
36
  with:
37
  context: . # The context is the root of your repository
38
  push: true # Automatically push the image after building
39
- tags: ${{ secrets.DOCKER_USERNAME }}/blackboxv2:v7 # Replace 'your-app-name' with your desired Docker image name
40
 
41
  # Step 5: Log out of Docker Hub
42
  - name: Log out of Docker Hub
 
36
  with:
37
  context: . # The context is the root of your repository
38
  push: true # Automatically push the image after building
39
+ tags: ${{ secrets.DOCKER_USERNAME }}/blackboxv2:v100 # Replace 'your-app-name' with your desired Docker image name
40
 
41
  # Step 5: Log out of Docker Hub
42
  - name: Log out of Docker Hub
Dockerfile CHANGED
@@ -26,4 +26,4 @@ COPY . .
26
  EXPOSE 8001
27
 
28
  # Command to run the FastAPI app with Uvicorn
29
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
 
26
  EXPOSE 8001
27
 
28
  # Command to run the FastAPI app with Uvicorn
29
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
api/config.py CHANGED
@@ -1,259 +1,259 @@
1
- import os
2
- from dotenv import load_dotenv
3
-
4
- load_dotenv()
5
-
6
- # Base URL and Common Headers
7
- BASE_URL = "https://www.blackbox.ai"
8
- common_headers = {
9
- 'accept': '*/*',
10
- 'accept-language': 'en-US,en;q=0.9',
11
- 'cache-control': 'no-cache',
12
- 'origin': BASE_URL,
13
- 'pragma': 'no-cache',
14
- 'priority': 'u=1, i',
15
- 'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
16
- 'sec-ch-ua-arch': '"x86"',
17
- 'sec-ch-ua-bitness': '"64"',
18
- 'sec-ch-ua-full-version': '"131.0.6778.69"',
19
- 'sec-ch-ua-full-version-list': '"Google Chrome";v="131.0.6778.69", "Chromium";v="131.0.6778.69", "Not_A Brand";v="24.0.0.0"',
20
- 'sec-ch-ua-mobile': '?0',
21
- 'sec-ch-ua-platform': '"Windows"',
22
- 'sec-ch-ua-platform-version': '"19.0.0"',
23
- 'sec-fetch-dest': 'empty',
24
- 'sec-fetch-mode': 'cors',
25
- 'sec-fetch-site': 'same-origin',
26
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
27
- }
28
-
29
-
30
- # Header Configurations for Specific API Calls
31
- def get_headers_api_chat(referer_url):
32
- return {**common_headers, 'Content-Type': 'application/json', 'Referer': referer_url}
33
-
34
- def get_headers_chat(chat_url, next_action, next_router_state_tree):
35
- return {
36
- **common_headers,
37
- 'Accept': 'text/x-component',
38
- 'Content-Type': 'text/plain;charset=UTF-8',
39
- 'Referer': chat_url,
40
- 'next-action': next_action,
41
- 'next-router-state-tree': next_router_state_tree,
42
- 'next-url': '/',
43
- }
44
-
45
-
46
- APP_SECRET = os.getenv("APP_SECRET")
47
-
48
- ALLOWED_MODELS = [
49
- {"id": "blackboxai", "name": "blackboxai"},
50
- {"id": "blackboxai-pro", "name": "blackboxai-pro"},
51
- {"id": "flux", "name": "flux"},
52
- {"id": "llama-3.1-8b", "name": "llama-3.1-8b"},
53
- {"id": "llama-3.1-70b", "name": "llama-3.1-70b"},
54
- {"id": "llama-3.1-405b", "name": "llama-3.1-405"},
55
- {"id": "gpt-4o", "name": "gpt-4o"},
56
- {"id": "gemini-pro", "name": "gemini-pro"},
57
- {"id": "gemini-1.5-flash", "name": "gemini-1.5-flash"},
58
- {"id": "claude-sonnet-3.5", "name": "claude-sonnet-3.5"},
59
- {"id": "PythonAgent", "name": "PythonAgent"},
60
- {"id": "JavaAgent", "name": "JavaAgent"},
61
- {"id": "JavaScriptAgent", "name": "JavaScriptAgent"},
62
- {"id": "HTMLAgent", "name": "HTMLAgent"},
63
- {"id": "GoogleCloudAgent", "name": "GoogleCloudAgent"},
64
- {"id": "AndroidDeveloper", "name": "AndroidDeveloper"},
65
- {"id": "SwiftDeveloper", "name": "SwiftDeveloper"},
66
- {"id": "Next.jsAgent", "name": "Next.jsAgent"},
67
- {"id": "MongoDBAgent", "name": "MongoDBAgent"},
68
- {"id": "PyTorchAgent", "name": "PyTorchAgent"},
69
- {"id": "ReactAgent", "name": "ReactAgent"},
70
- {"id": "XcodeAgent", "name": "XcodeAgent"},
71
- {"id": "AngularJSAgent", "name": "AngularJSAgent"},
72
- {"id": "HerokuAgent", "name": "HerokuAgent"},
73
- {"id": "GodotAgent", "name": "GodotAgent"},
74
- {"id": "GoAgent", "name": "GoAgent"},
75
- {"id": "GitlabAgent", "name": "GitlabAgent"},
76
- {"id": "GitAgent", "name": "GitAgent"},
77
- {"id": "RepoMap", "name": "RepoMap"},
78
- {"id": "gemini-1.5-pro-latest", "name": "gemini-pro"},
79
- {"id": "gemini-1.5-pro", "name": "gemini-1.5-pro"},
80
- {"id": "claude-3-5-sonnet-20240620", "name": "claude-sonnet-3.5"},
81
- {"id": "claude-3-5-sonnet", "name": "claude-sonnet-3.5"},
82
- {"id": "Niansuh", "name": "Niansuh"},
83
- {"id": "o1-preview", "name": "o1-preview"},
84
- {"id": "claude-3-5-sonnet-20241022", "name": "claude-3-5-sonnet-20241022"},
85
- {"id": "claude-3-5-sonnet-x", "name": "claude-3-5-sonnet-x"},
86
-
87
- # Added New Agents
88
- {"id": "FlaskAgent", "name": "FlaskAgent"},
89
- {"id": "FirebaseAgent", "name": "FirebaseAgent"},
90
- {"id": "FastAPIAgent", "name": "FastAPIAgent"},
91
- {"id": "ErlangAgent", "name": "ErlangAgent"},
92
- {"id": "ElectronAgent", "name": "ElectronAgent"},
93
- {"id": "DockerAgent", "name": "DockerAgent"},
94
- {"id": "DigitalOceanAgent", "name": "DigitalOceanAgent"},
95
- {"id": "BitbucketAgent", "name": "BitbucketAgent"},
96
- {"id": "AzureAgent", "name": "AzureAgent"},
97
- {"id": "FlutterAgent", "name": "FlutterAgent"},
98
- {"id": "YoutubeAgent", "name": "YoutubeAgent"},
99
- {"id": "builderAgent", "name": "builderAgent"},
100
- ]
101
-
102
- MODEL_MAPPING = {
103
- "blackboxai": "blackboxai",
104
- "blackboxai-pro": "blackboxai-pro",
105
- "flux": "flux",
106
- "ImageGeneration": "flux",
107
- "llama-3.1-8b": "llama-3.1-8b",
108
- "llama-3.1-70b": "llama-3.1-70b",
109
- "llama-3.1-405b": "llama-3.1-405",
110
- "gpt-4o": "gpt-4o",
111
- "gemini-pro": "gemini-pro",
112
- "gemini-1.5-flash": "gemini-1.5-flash",
113
- "claude-sonnet-3.5": "claude-sonnet-3.5",
114
- "PythonAgent": "PythonAgent",
115
- "JavaAgent": "JavaAgent",
116
- "JavaScriptAgent": "JavaScriptAgent",
117
- "HTMLAgent": "HTMLAgent",
118
- "GoogleCloudAgent": "GoogleCloudAgent",
119
- "AndroidDeveloper": "AndroidDeveloper",
120
- "SwiftDeveloper": "SwiftDeveloper",
121
- "Next.jsAgent": "Next.jsAgent",
122
- "MongoDBAgent": "MongoDBAgent",
123
- "PyTorchAgent": "PyTorchAgent",
124
- "ReactAgent": "ReactAgent",
125
- "XcodeAgent": "XcodeAgent",
126
- "AngularJSAgent": "AngularJSAgent",
127
- "HerokuAgent": "HerokuAgent",
128
- "GodotAgent": "GodotAgent",
129
- "GoAgent": "GoAgent",
130
- "GitlabAgent": "GitlabAgent",
131
- "GitAgent": "GitAgent",
132
- "RepoMap": "RepoMap",
133
- # Additional mappings
134
- "gemini-flash": "gemini-1.5-flash",
135
- "claude-3.5-sonnet": "claude-sonnet-3.5",
136
- "gemini-1.5-pro-latest": "gemini-pro",
137
- "gemini-1.5-pro": "gemini-1.5-pro",
138
- "claude-3-5-sonnet-20240620": "claude-sonnet-3.5",
139
- "claude-3-5-sonnet": "claude-sonnet-3.5",
140
- "Niansuh": "Niansuh",
141
- "o1-preview": "o1-preview",
142
- "claude-3-5-sonnet-20241022": "claude-3-5-sonnet-20241022",
143
- "claude-3-5-sonnet-x": "claude-3-5-sonnet-x",
144
-
145
- # Added New Agents
146
- "FlaskAgent": "FlaskAgent",
147
- "FirebaseAgent": "FirebaseAgent",
148
- "FastAPIAgent": "FastAPIAgent",
149
- "ErlangAgent": "ErlangAgent",
150
- "ElectronAgent": "ElectronAgent",
151
- "DockerAgent": "DockerAgent",
152
- "DigitalOceanAgent": "DigitalOceanAgent",
153
- "BitbucketAgent": "BitbucketAgent",
154
- "AzureAgent": "AzureAgent",
155
- "FlutterAgent": "FlutterAgent",
156
- "YoutubeAgent": "YoutubeAgent",
157
- "builderAgent": "builderAgent",
158
- }
159
-
160
- # Agent modes
161
- AGENT_MODE = {
162
- 'flux': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "flux"},
163
- 'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "Niansuh"},
164
- 'o1-preview': {'mode': True, 'id': "o1Dst8La8", 'name': "o1-preview"},
165
- 'claude-3-5-sonnet-20241022': {'mode': True, 'id': "Claude-Sonnet-3.5zO2HZSF", 'name': "claude-3-5-sonnet-20241022"},
166
- 'claude-3-5-sonnet-x': {'mode': True, 'id': "Claude-Sonnet-3.52022JE0UdQ3", 'name': "claude-3-5-sonnet-x"},
167
- }
168
-
169
- TRENDING_AGENT_MODE = {
170
- "blackboxai": {},
171
- "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
172
- "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
173
- 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
174
- 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"},
175
- 'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},
176
- 'PythonAgent': {'mode': True, 'id': "Python Agent"},
177
- 'JavaAgent': {'mode': True, 'id': "Java Agent"},
178
- 'JavaScriptAgent': {'mode': True, 'id': "JavaScript Agent"},
179
- 'HTMLAgent': {'mode': True, 'id': "HTML Agent"},
180
- 'GoogleCloudAgent': {'mode': True, 'id': "Google Cloud Agent"},
181
- 'AndroidDeveloper': {'mode': True, 'id': "Android Developer"},
182
- 'SwiftDeveloper': {'mode': True, 'id': "Swift Developer"},
183
- 'Next.jsAgent': {'mode': True, 'id': "Next.js Agent"},
184
- 'MongoDBAgent': {'mode': True, 'id': "MongoDB Agent"},
185
- 'PyTorchAgent': {'mode': True, 'id': "PyTorch Agent"},
186
- 'ReactAgent': {'mode': True, 'id': "React Agent"},
187
- 'XcodeAgent': {'mode': True, 'id': "Xcode Agent"},
188
- 'AngularJSAgent': {'mode': True, 'id': "AngularJS Agent"},
189
- 'HerokuAgent': {'mode': True, 'id': "HerokuAgent"},
190
- 'GodotAgent': {'mode': True, 'id': "GodotAgent"},
191
- 'GoAgent': {'mode': True, 'id': "GoAgent"},
192
- 'GitlabAgent': {'mode': True, 'id': "GitlabAgent"},
193
- 'GitAgent': {'mode': True, 'id': "GitAgent"},
194
- 'RepoMap': {'mode': True, 'id': "repomap"},
195
-
196
- # Added New Agents
197
- 'FlaskAgent': {'mode': True, 'id': "FlaskAgent"},
198
- 'FirebaseAgent': {'mode': True, 'id': "FirebaseAgent"},
199
- 'FastAPIAgent': {'mode': True, 'id': "FastAPIAgent"},
200
- 'ErlangAgent': {'mode': True, 'id': "ErlangAgent"},
201
- 'ElectronAgent': {'mode': True, 'id': "ElectronAgent"},
202
- 'DockerAgent': {'mode': True, 'id': "DockerAgent"},
203
- 'DigitalOceanAgent': {'mode': True, 'id': "DigitalOceanAgent"},
204
- 'BitbucketAgent': {'mode': True, 'id': "BitbucketAgent"},
205
- 'AzureAgent': {'mode': True, 'id': "AzureAgent"},
206
- 'FlutterAgent': {'mode': True, 'id': "FlutterAgent"},
207
- 'YoutubeAgent': {'mode': True, 'id': "YoutubeAgent"},
208
- 'builderAgent': {'mode': True, 'id': "builderAgent"},
209
- }
210
-
211
- # Model prefixes
212
- MODEL_PREFIXES = {
213
- 'gpt-4o': '@GPT-4o',
214
- 'gemini-pro': '@Gemini-PRO',
215
- 'claude-sonnet-3.5': '@Claude-Sonnet-3.5',
216
- 'PythonAgent': '@Python Agent',
217
- 'JavaAgent': '@Java Agent',
218
- 'JavaScriptAgent': '@JavaScript Agent',
219
- 'HTMLAgent': '@HTML Agent',
220
- 'GoogleCloudAgent': '@Google Cloud Agent',
221
- 'AndroidDeveloper': '@Android Developer',
222
- 'SwiftDeveloper': '@Swift Developer',
223
- 'Next.jsAgent': '@Next.js Agent',
224
- 'MongoDBAgent': '@MongoDB Agent',
225
- 'PyTorchAgent': '@PyTorch Agent',
226
- 'ReactAgent': '@React Agent',
227
- 'XcodeAgent': '@Xcode Agent',
228
- 'AngularJSAgent': '@AngularJS Agent',
229
- 'HerokuAgent': '@Heroku Agent',
230
- 'GodotAgent': '@Godot Agent',
231
- 'GoAgent': '@Go Agent',
232
- 'GitlabAgent': '@Gitlab Agent',
233
- 'GitAgent': '@Git Agent',
234
- 'blackboxai-pro': '@BLACKBOXAI-PRO',
235
- 'flux': '@Image Generation',
236
-
237
- # Added New Agents
238
- 'FlaskAgent': '@Flask Agent',
239
- 'FirebaseAgent': '@Firebase Agent',
240
- 'FastAPIAgent': '@FastAPI Agent',
241
- 'ErlangAgent': '@Erlang Agent',
242
- 'ElectronAgent': '@Electron Agent',
243
- 'DockerAgent': '@Docker Agent',
244
- 'DigitalOceanAgent': '@DigitalOcean Agent',
245
- 'BitbucketAgent': '@Bitbucket Agent',
246
- 'AzureAgent': '@Azure Agent',
247
- 'FlutterAgent': '@Flutter Agent',
248
- 'YoutubeAgent': '@Youtube Agent',
249
- 'builderAgent': '@builder Agent',
250
- }
251
-
252
- # Model referers
253
- MODEL_REFERERS = {
254
- "blackboxai": "/?model=blackboxai",
255
- "gpt-4o": "/?model=gpt-4o",
256
- "gemini-pro": "/?model=gemini-pro",
257
- "claude-sonnet-3.5": "/?model=claude-sonnet-3.5",
258
- # Add any additional referers if necessary
259
- }
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv()
5
+
6
+ # Base URL and Common Headers
7
+ BASE_URL = "https://www.blackbox.ai"
8
+ common_headers = {
9
+ 'accept': '*/*',
10
+ 'accept-language': 'en-US,en;q=0.9',
11
+ 'cache-control': 'no-cache',
12
+ 'origin': BASE_URL,
13
+ 'pragma': 'no-cache',
14
+ 'priority': 'u=1, i',
15
+ 'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
16
+ 'sec-ch-ua-arch': '"x86"',
17
+ 'sec-ch-ua-bitness': '"64"',
18
+ 'sec-ch-ua-full-version': '"131.0.6778.69"',
19
+ 'sec-ch-ua-full-version-list': '"Google Chrome";v="131.0.6778.69", "Chromium";v="131.0.6778.69", "Not_A Brand";v="24.0.0.0"',
20
+ 'sec-ch-ua-mobile': '?0',
21
+ 'sec-ch-ua-platform': '"Windows"',
22
+ 'sec-ch-ua-platform-version': '"19.0.0"',
23
+ 'sec-fetch-dest': 'empty',
24
+ 'sec-fetch-mode': 'cors',
25
+ 'sec-fetch-site': 'same-origin',
26
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
27
+ }
28
+
29
+ # Header Configurations for Specific API Calls
30
+ def get_headers_api_chat(referer_url):
31
+ return {**common_headers, 'Content-Type': 'application/json', 'Referer': referer_url}
32
+
33
+ def get_headers_chat(chat_url, next_action, next_router_state_tree):
34
+ return {
35
+ **common_headers,
36
+ 'Accept': 'text/x-component',
37
+ 'Content-Type': 'text/plain;charset=UTF-8',
38
+ 'Referer': chat_url,
39
+ 'next-action': next_action,
40
+ 'next-router-state-tree': next_router_state_tree,
41
+ 'next-url': '/',
42
+ }
43
+
44
+ APP_SECRET = os.getenv("APP_SECRET")
45
+
46
+ ALLOWED_MODELS = [
47
+ {"id": "blackboxai", "name": "blackboxai"},
48
+ {"id": "blackboxai-pro", "name": "blackboxai-pro"},
49
+ {"id": "flux", "name": "flux"},
50
+ {"id": "llama-3.1-8b", "name": "llama-3.1-8b"},
51
+ {"id": "llama-3.1-70b", "name": "llama-3.1-70b"},
52
+ {"id": "llama-3.1-405b", "name": "llama-3.1-405"},
53
+ {"id": "gpt-4o", "name": "gpt-4o"},
54
+ {"id": "gpt-4o-2024-05-13", "name": "gpt-4o"},
55
+ {"id": "gemini-pro", "name": "gemini-pro"},
56
+ {"id": "gemini-1.5-flash", "name": "gemini-1.5-flash"},
57
+ {"id": "claude-sonnet-3.5", "name": "claude-sonnet-3.5"},
58
+ {"id": "PythonAgent", "name": "python"},
59
+ {"id": "JavaAgent", "name": "java"},
60
+ {"id": "JavaScriptAgent", "name": "javascript"},
61
+ {"id": "HTMLAgent", "name": "html"},
62
+ {"id": "GoogleCloudAgent", "name": "googlecloud"},
63
+ {"id": "AndroidDeveloper", "name": "androiddeveloper"},
64
+ {"id": "SwiftDeveloper", "name": "swiftdeveloper"},
65
+ {"id": "Next.jsAgent", "name": "next.js"},
66
+ {"id": "MongoDBAgent", "name": "mongodb"},
67
+ {"id": "PyTorchAgent", "name": "pytorch"},
68
+ {"id": "ReactAgent", "name": "react"},
69
+ {"id": "XcodeAgent", "name": "xcode"},
70
+ {"id": "AngularJSAgent", "name": "angularjs"},
71
+ {"id": "HerokuAgent", "name": "heroku"},
72
+ {"id": "GodotAgent", "name": "godot"},
73
+ {"id": "GoAgent", "name": "go"},
74
+ {"id": "GitlabAgent", "name": "gitlab"},
75
+ {"id": "GitAgent", "name": "git"},
76
+ {"id": "RepoMap", "name": "repomap"},
77
+ {"id": "gemini-1.5-pro-latest", "name": "gemini-pro"},
78
+ {"id": "gemini-1.5-pro", "name": "gemini-1.5-pro"},
79
+ {"id": "claude-3-5-sonnet-20240620", "name": "claude-sonnet-3.5"},
80
+ {"id": "claude-3-5-sonnet", "name": "claude-sonnet-3.5"},
81
+ {"id": "Niansuh", "name": "niansuh"},
82
+ {"id": "o1-preview", "name": "o1-preview"},
83
+ {"id": "claude-3-5-sonnet-20241022", "name": "claude-3-5-sonnet-20241022"},
84
+ {"id": "claude-3-5-sonnet-x", "name": "claude-3-5-sonnet-x"},
85
+ {"id": "gpt-3.5-turbo", "name": "gpt-3.5-turbo"},
86
+
87
+ # Added New Agents
88
+ {"id": "FlaskAgent", "name": "flask"},
89
+ {"id": "FirebaseAgent", "name": "firebase"},
90
+ {"id": "FastAPIAgent", "name": "fastapi"},
91
+ {"id": "ErlangAgent", "name": "erlang"},
92
+ {"id": "ElectronAgent", "name": "electron"},
93
+ {"id": "DockerAgent", "name": "docker"},
94
+ {"id": "DigitalOceanAgent", "name": "digitalocean"},
95
+ {"id": "BitbucketAgent", "name": "bitbucket"},
96
+ {"id": "AzureAgent", "name": "azure"},
97
+ {"id": "FlutterAgent", "name": "flutter"},
98
+ {"id": "YoutubeAgent", "name": "youtube"},
99
+ {"id": "builderAgent", "name": "builder"},
100
+ ]
101
+
102
+ MODEL_MAPPING = {
103
+ "blackboxai": "blackboxai",
104
+ "blackboxai-pro": "blackboxai-pro",
105
+ "flux": "flux",
106
+ "ImageGeneration": "flux",
107
+ "llama-3.1-8b": "llama-3.1-8b",
108
+ "llama-3.1-70b": "llama-3.1-70b",
109
+ "llama-3.1-405b": "llama-3.1-405",
110
+ "gpt-4o": "gpt-4o",
111
+ "gpt-4o-2024-05-13": "gpt-4o",
112
+ "gemini-pro": "gemini-pro",
113
+ "gemini-1.5-flash": "gemini-1.5-flash",
114
+ "claude-sonnet-3.5": "claude-sonnet-3.5",
115
+ "PythonAgent": "python",
116
+ "JavaAgent": "java",
117
+ "JavaScriptAgent": "javascript",
118
+ "HTMLAgent": "html",
119
+ "GoogleCloudAgent": "googlecloud",
120
+ "AndroidDeveloper": "androiddeveloper",
121
+ "SwiftDeveloper": "swiftdeveloper",
122
+ "Next.jsAgent": "next.js",
123
+ "MongoDBAgent": "mongodb",
124
+ "PyTorchAgent": "pytorch",
125
+ "ReactAgent": "react",
126
+ "XcodeAgent": "xcode",
127
+ "AngularJSAgent": "angularjs",
128
+ "HerokuAgent": "heroku",
129
+ "GodotAgent": "godot",
130
+ "GoAgent": "go",
131
+ "GitlabAgent": "gitlab",
132
+ "GitAgent": "git",
133
+ "RepoMap": "repomap",
134
+ # Additional mappings
135
+ "gemini-flash": "gemini-1.5-flash",
136
+ "claude-3.5-sonnet": "claude-sonnet-3.5",
137
+ "gemini-1.5-pro-latest": "gemini-pro",
138
+ "gemini-1.5-pro": "gemini-1.5-pro",
139
+ "claude-3-5-sonnet-20240620": "claude-sonnet-3.5",
140
+ "claude-3-5-sonnet": "claude-sonnet-3.5",
141
+ "Niansuh": "niansuh",
142
+ "o1-preview": "o1-preview",
143
+ "claude-3-5-sonnet-20241022": "claude-3-5-sonnet-20241022",
144
+ "claude-3-5-sonnet-x": "claude-3-5-sonnet-x",
145
+ "gpt-3.5-turbo": "gpt-3.5-turbo",
146
+
147
+ # Added New Agents
148
+ "FlaskAgent": "flask",
149
+ "FirebaseAgent": "firebase",
150
+ "FastAPIAgent": "fastapi",
151
+ "ErlangAgent": "erlang",
152
+ "ElectronAgent": "electron",
153
+ "DockerAgent": "docker",
154
+ "DigitalOceanAgent": "digitalocean",
155
+ "BitbucketAgent": "bitbucket",
156
+ "AzureAgent": "azure",
157
+ "FlutterAgent": "flutter",
158
+ "YoutubeAgent": "youtube",
159
+ "builderAgent": "builder",
160
+ }
161
+
162
+ # Agent modes
163
+ AGENT_MODE = {
164
+ 'flux': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "flux"},
165
+ 'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "niansuh"},
166
+ 'o1-preview': {'mode': True, 'id': "o1Dst8La8", 'name': "o1-preview"},
167
+ 'claude-3-5-sonnet-20241022': {'mode': True, 'id': "Claude-Sonnet-3.5zO2HZSF", 'name': "claude-3-5-sonnet-20241022"},
168
+ 'claude-3-5-sonnet-x': {'mode': True, 'id': "Claude-Sonnet-3.52022JE0UdQ3", 'name': "claude-3-5-sonnet-x"},
169
+ 'gpt-3.5-turbo': {'mode': True, 'id': "GPT-3.5-TurboYxtGz0H", 'name': "gpt-3.5-turbo"},
170
+ }
171
+
172
+ TRENDING_AGENT_MODE = {
173
+ "blackboxai": {},
174
+ "gemini-1.5-flash": {'mode': True, 'id': 'gemini'},
175
+ "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
176
+ 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
177
+ 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"},
178
+ 'blackboxai-pro': {'mode': True, 'id': "blackboxai-pro"},
179
+ 'PythonAgent': {'mode': True, 'id': "python"},
180
+ 'JavaAgent': {'mode': True, 'id': "java"},
181
+ 'JavaScriptAgent': {'mode': True, 'id': "javascript"},
182
+ 'HTMLAgent': {'mode': True, 'id': "html"},
183
+ 'GoogleCloudAgent': {'mode': True, 'id': "googlecloud"},
184
+ 'AndroidDeveloper': {'mode': True, 'id': "android"},
185
+ 'SwiftDeveloper': {'mode': True, 'id': "swift"},
186
+ 'Next.jsAgent': {'mode': True, 'id': "next.js"},
187
+ 'MongoDBAgent': {'mode': True, 'id': "mongodb"},
188
+ 'PyTorchAgent': {'mode': True, 'id': "pytorch"},
189
+ 'ReactAgent': {'mode': True, 'id': "react"},
190
+ 'XcodeAgent': {'mode': True, 'id': "xcode"},
191
+ 'AngularJSAgent': {'mode': True, 'id': "angularjs"},
192
+ 'HerokuAgent': {'mode': True, 'id': "heroku"},
193
+ 'GodotAgent': {'mode': True, 'id': "godot"},
194
+ 'GoAgent': {'mode': True, 'id': "go"},
195
+ 'GitlabAgent': {'mode': True, 'id': "gitlab"},
196
+ 'GitAgent': {'mode': True, 'id': "git"},
197
+ 'RepoMap': {'mode': True, 'id': "repomap"},
198
+ 'FlaskAgent': {'mode': True, 'id': "flask"},
199
+ 'FirebaseAgent': {'mode': True, 'id': "firebase"},
200
+ 'FastAPIAgent': {'mode': True, 'id': "fastapi"},
201
+ 'ErlangAgent': {'mode': True, 'id': "erlang"},
202
+ 'ElectronAgent': {'mode': True, 'id': "electron"},
203
+ 'DockerAgent': {'mode': True, 'id': "docker"},
204
+ 'DigitalOceanAgent': {'mode': True, 'id': "digitalocean"},
205
+ 'BitbucketAgent': {'mode': True, 'id': "bitbucket"},
206
+ 'AzureAgent': {'mode': True, 'id': "azure"},
207
+ 'FlutterAgent': {'mode': True, 'id': "flutter"},
208
+ 'YoutubeAgent': {'mode': True, 'id': "youtube"},
209
+ 'builderAgent': {'mode': True, 'id': "builder"},
210
+ }
211
+
212
+ # Model prefixes
213
+ MODEL_PREFIXES = {
214
+ 'gpt-4o': '@gpt-4o',
215
+ 'gemini-pro': '@gemini-pro',
216
+ 'claude-sonnet-3.5': '@claude-sonnet-3.5',
217
+ 'PythonAgent': '@python',
218
+ 'JavaAgent': '@java',
219
+ 'JavaScriptAgent': '@javascript',
220
+ 'HTMLAgent': '@html',
221
+ 'GoogleCloudAgent': '@googlecloud',
222
+ 'AndroidDeveloper': '@android',
223
+ 'SwiftDeveloper': '@swift',
224
+ 'Next.jsAgent': '@next.js',
225
+ 'MongoDBAgent': '@mongodb',
226
+ 'PyTorchAgent': '@pytorch',
227
+ 'ReactAgent': '@react',
228
+ 'XcodeAgent': '@xcode',
229
+ 'AngularJSAgent': '@angularjs',
230
+ 'HerokuAgent': '@heroku',
231
+ 'GodotAgent': '@godot',
232
+ 'GoAgent': '@go',
233
+ 'GitlabAgent': '@gitlab',
234
+ 'GitAgent': '@git',
235
+ 'blackboxai-pro': '@blackboxai-pro',
236
+ 'flux': '@Image Generation',
237
+ 'FlaskAgent': '@flask',
238
+ 'FirebaseAgent': '@firebase',
239
+ 'FastAPIAgent': '@fastapi',
240
+ 'ErlangAgent': '@erlang',
241
+ 'ElectronAgent': '@electron',
242
+ 'DockerAgent': '@docker',
243
+ 'DigitalOceanAgent': '@digitalocean',
244
+ 'BitbucketAgent': '@bitbucket',
245
+ 'AzureAgent': '@azure',
246
+ 'FlutterAgent': '@flutter',
247
+ 'YoutubeAgent': '@youtube',
248
+ 'builderAgent': '@builder',
249
+ }
250
+
251
+ # Model referers
252
+ MODEL_REFERERS = {
253
+ "blackboxai": "/?model=blackboxai",
254
+ "gpt-4o": "/?model=gpt-4o",
255
+ "gemini-pro": "/?model=gemini-pro",
256
+ "claude-sonnet-3.5": "/?model=claude-sonnet-3.5",
257
+ "blackboxai-pro": "/?model=blackboxai-pro",
258
+ }
259
+
api/utils.py CHANGED
@@ -1,247 +1,247 @@
1
- from datetime import datetime
2
- import json
3
- import uuid
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
- 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
- from api.validate import getHid # Import the asynchronous getHid function
24
-
25
- logger = setup_logger(__name__)
26
-
27
- # Define the blocked message
28
- BLOCKED_MESSAGE = "Generated by BLACKBOX.AI, try unlimited chat https://www.blackbox.ai"
29
-
30
- # Helper function to create chat completion data
31
- def create_chat_completion_data(
32
- content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
33
- ) -> Dict[str, Any]:
34
- return {
35
- "id": f"chatcmpl-{uuid.uuid4()}",
36
- "object": "chat.completion.chunk",
37
- "created": timestamp,
38
- "model": model,
39
- "choices": [
40
- {
41
- "index": 0,
42
- "delta": {"content": content, "role": "assistant"},
43
- "finish_reason": finish_reason,
44
- }
45
- ],
46
- "usage": None,
47
- }
48
-
49
- # Function to convert message to dictionary format, ensuring base64 data and optional model prefix
50
- def message_to_dict(message, model_prefix: Optional[str] = None):
51
- content = message.content if isinstance(message.content, str) else message.content[0]["text"]
52
- if model_prefix:
53
- content = f"{model_prefix} {content}"
54
- if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
55
- # Ensure base64 images are always included for all models
56
- return {
57
- "role": message.role,
58
- "content": content,
59
- "data": {
60
- "imageBase64": message.content[1]["image_url"]["url"],
61
- "fileText": "",
62
- "title": "snapshot",
63
- },
64
- }
65
- return {"role": message.role, "content": content}
66
-
67
- # Function to strip model prefix from content if present
68
- def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
69
- """Remove the model prefix from the response content if present."""
70
- if model_prefix and content.startswith(model_prefix):
71
- logger.debug(f"Stripping prefix '{model_prefix}' from content.")
72
- return content[len(model_prefix):].strip()
73
- return content
74
-
75
- # Process streaming response with headers from config.py
76
- async def process_streaming_response(request: ChatRequest):
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
- model_prefix = MODEL_PREFIXES.get(request.model, "")
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, # Using request_id instead of chat_id
107
- "isChromeExt": False,
108
- "isMicMode": False,
109
- "maxTokens": request.max_tokens,
110
- "messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
111
- "mobileClient": False,
112
- "playgroundTemperature": request.temperature,
113
- "playgroundTopP": request.top_p,
114
- "previewToken": None,
115
- "trendingAgentMode": trending_agent_mode,
116
- "userId": None,
117
- "userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
118
- "userSystemPrompt": None,
119
- "validated": h_value, # Dynamically set the validated field
120
- "visitFromDelta": False,
121
- }
122
-
123
- async with httpx.AsyncClient() as client:
124
- try:
125
- async with client.stream(
126
- "POST",
127
- f"{BASE_URL}/api/chat",
128
- headers=headers_api_chat,
129
- json=json_data,
130
- timeout=100,
131
- ) as response:
132
- response.raise_for_status()
133
- async for chunk in response.aiter_text():
134
- timestamp = int(datetime.now().timestamp())
135
- if chunk:
136
- content = chunk
137
- if content.startswith("$@$v=undefined-rv1$@$"):
138
- content = content[21:]
139
- # Remove the blocked message if present
140
- if BLOCKED_MESSAGE in content:
141
- logger.info(f"Blocked message detected in response for Request ID {request_id}.")
142
- content = content.replace(BLOCKED_MESSAGE, '').strip()
143
- if not content:
144
- continue # Skip if content is empty after removal
145
- cleaned_content = strip_model_prefix(content, model_prefix)
146
- yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
147
-
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 for Request ID {request_id}: {e}")
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 for Request ID {request_id}: {e}")
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
- # Generate a unique ID for this request
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(BASE_URL, next_action=str(uuid.uuid4()), next_router_state_tree=json.dumps([""]))
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' (Request ID: {request_id})")
174
- await asyncio.sleep(delay_seconds)
175
-
176
- # Fetch the h-value for the 'validated' field
177
- h_value = await getHid()
178
- if not h_value:
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", url=f"{BASE_URL}/api/chat", headers=headers_api_chat, json=json_data
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 for Request ID {request_id}: {e}")
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 for Request ID {request_id}: {e}")
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(f"Blocked message detected in response for Request ID {request_id}.")
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.")
231
-
232
- cleaned_full_response = strip_model_prefix(full_response, model_prefix)
233
-
234
- return {
235
- "id": f"chatcmpl-{uuid.uuid4()}",
236
- "object": "chat.completion",
237
- "created": int(datetime.now().timestamp()),
238
- "model": request.model,
239
- "choices": [
240
- {
241
- "index": 0,
242
- "message": {"role": "assistant", "content": cleaned_full_response},
243
- "finish_reason": "stop",
244
- }
245
- ],
246
- "usage": None,
247
- }
 
1
+ from datetime import datetime
2
+ import json
3
+ import uuid
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
+ 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
+ from api.validate import getHid # Import the asynchronous getHid function
24
+
25
+ logger = setup_logger(__name__)
26
+
27
+ # Define the blocked message
28
+ BLOCKED_MESSAGE = "Generated by BLACKBOX.AI, try unlimited chat https://www.blackbox.ai"
29
+
30
+ # Helper function to create chat completion data
31
+ def create_chat_completion_data(
32
+ content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
33
+ ) -> Dict[str, Any]:
34
+ return {
35
+ "id": f"chatcmpl-{uuid.uuid4()}",
36
+ "object": "chat.completion.chunk",
37
+ "created": timestamp,
38
+ "model": model,
39
+ "choices": [
40
+ {
41
+ "index": 0,
42
+ "delta": {"content": content, "role": "assistant"},
43
+ "finish_reason": finish_reason,
44
+ }
45
+ ],
46
+ "usage": None,
47
+ }
48
+
49
+ # Function to convert message to dictionary format, ensuring base64 data and optional model prefix
50
+ def message_to_dict(message, model_prefix: Optional[str] = None):
51
+ content = message.content if isinstance(message.content, str) else message.content[0]["text"]
52
+ if model_prefix:
53
+ content = f"{model_prefix} {content}"
54
+ if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
55
+ # Ensure base64 images are always included for all models
56
+ return {
57
+ "role": message.role,
58
+ "content": content,
59
+ "data": {
60
+ "imageBase64": message.content[1]["image_url"]["url"],
61
+ "fileText": "",
62
+ "title": "snapshot",
63
+ },
64
+ }
65
+ return {"role": message.role, "content": content}
66
+
67
+ # Function to strip model prefix from content if present
68
+ def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
69
+ """Remove the model prefix from the response content if present."""
70
+ if model_prefix and content.startswith(model_prefix):
71
+ logger.debug(f"Stripping prefix '{model_prefix}' from content.")
72
+ return content[len(model_prefix):].strip()
73
+ return content
74
+
75
+ # Process streaming response with headers from config.py
76
+ async def process_streaming_response(request: ChatRequest):
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
+ model_prefix = MODEL_PREFIXES.get(request.model, "")
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, # Using request_id instead of chat_id
107
+ "isChromeExt": False,
108
+ "isMicMode": False,
109
+ "maxTokens": request.max_tokens,
110
+ "messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
111
+ "mobileClient": False,
112
+ "playgroundTemperature": request.temperature,
113
+ "playgroundTopP": request.top_p,
114
+ "previewToken": None,
115
+ "trendingAgentMode": trending_agent_mode,
116
+ "userId": None,
117
+ "userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
118
+ "userSystemPrompt": None,
119
+ "validated": h_value, # Dynamically set the validated field
120
+ "visitFromDelta": False,
121
+ }
122
+
123
+ async with httpx.AsyncClient() as client:
124
+ try:
125
+ async with client.stream(
126
+ "POST",
127
+ f"{BASE_URL}/api/chat",
128
+ headers=headers_api_chat,
129
+ json=json_data,
130
+ timeout=100,
131
+ ) as response:
132
+ response.raise_for_status()
133
+ async for chunk in response.aiter_text():
134
+ timestamp = int(datetime.now().timestamp())
135
+ if chunk:
136
+ content = chunk
137
+ if content.startswith("$@$v=undefined-rv1$@$"):
138
+ content = content[21:]
139
+ # Remove the blocked message if present
140
+ if BLOCKED_MESSAGE in content:
141
+ logger.info(f"Blocked message detected in response for Request ID {request_id}.")
142
+ content = content.replace(BLOCKED_MESSAGE, '').strip()
143
+ if not content:
144
+ continue # Skip if content is empty after removal
145
+ cleaned_content = strip_model_prefix(content, model_prefix)
146
+ yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
147
+
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 for Request ID {request_id}: {e}")
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 for Request ID {request_id}: {e}")
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
+ # Generate a unique ID for this request
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(BASE_URL, next_action=str(uuid.uuid4()), next_router_state_tree=json.dumps([""]))
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' (Request ID: {request_id})")
174
+ await asyncio.sleep(delay_seconds)
175
+
176
+ # Fetch the h-value for the 'validated' field
177
+ h_value = await getHid()
178
+ if not h_value:
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", url=f"{BASE_URL}/api/chat", headers=headers_api_chat, json=json_data
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 for Request ID {request_id}: {e}")
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 for Request ID {request_id}: {e}")
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(f"Blocked message detected in response for Request ID {request_id}.")
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.")
231
+
232
+ cleaned_full_response = strip_model_prefix(full_response, model_prefix)
233
+
234
+ return {
235
+ "id": f"chatcmpl-{uuid.uuid4()}",
236
+ "object": "chat.completion",
237
+ "created": int(datetime.now().timestamp()),
238
+ "model": request.model,
239
+ "choices": [
240
+ {
241
+ "index": 0,
242
+ "message": {"role": "assistant", "content": cleaned_full_response},
243
+ "finish_reason": "stop",
244
+ }
245
+ ],
246
+ "usage": None,
247
+ }
api/validate.py CHANGED
@@ -1,26 +1,14 @@
 
 
1
  import re
2
  import time
3
  import asyncio
4
- import aiohttp
5
- from typing import Optional
6
 
7
  base_url = "https://www.blackbox.ai"
8
  headers = {
9
- 'accept': '*/*',
10
- 'accept-language': 'en-US,en;q=0.9',
11
- 'cache-control': 'no-cache',
12
- 'content-type': 'application/json',
13
- 'origin': base_url,
14
- 'pragma': 'no-cache',
15
- 'priority': 'u=1, i',
16
- 'referer': f'{base_url}/',
17
- 'sec-ch-ua': '"Not?A_Brand";v="99", "Chromium";v="130"',
18
- 'sec-ch-ua-mobile': '?0',
19
- 'sec-ch-ua-platform': '"Linux"',
20
- 'sec-fetch-dest': 'empty',
21
- 'sec-fetch-mode': 'cors',
22
- 'sec-fetch-site': 'same-origin',
23
- 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
24
  }
25
 
26
  # Cache variables
@@ -38,32 +26,45 @@ async def getHid(force_refresh: bool = False) -> Optional[str]:
38
  return cached_hid
39
 
40
  try:
41
- async with aiohttp.ClientSession(headers=headers) as session:
42
- async with session.get(base_url) as response:
43
- if response.status != 200:
44
- print("Failed to load the page.")
45
- return None
 
 
 
 
46
 
47
- page_content = await response.text()
48
- js_files = re.findall(r'static/chunks/\d{4}-[a-fA-F0-9]+\.js', page_content)
 
 
49
 
50
- key_pattern = re.compile(r'w="([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})"')
 
 
51
 
52
- for js_file in js_files:
53
- js_url = f"{base_url}/_next/{js_file}"
54
- async with session.get(js_url) as js_response:
55
- if js_response.status == 200:
56
- js_content = await js_response.text()
57
- match = key_pattern.search(js_content)
58
- if match:
59
- h_value = match.group(1)
60
- print("Found the h-value:", h_value)
61
- # Update the cache
62
- cached_hid = h_value
63
- cache_time = current_time
64
- return h_value
65
- print("The h-value was not found in any JS content.")
 
 
66
  return None
67
- except Exception as e:
68
  print(f"An error occurred during the request: {e}")
69
  return None
 
 
 
 
1
+ # api/validate.py
2
+
3
  import re
4
  import time
5
  import asyncio
6
+ import httpx
7
+ from typing import Optional # Added import for Optional
8
 
9
  base_url = "https://www.blackbox.ai"
10
  headers = {
11
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  }
13
 
14
  # Cache variables
 
26
  return cached_hid
27
 
28
  try:
29
+ async with httpx.AsyncClient() as client:
30
+ # Retrieve the initial HTML content.
31
+ response = await client.get(base_url, headers=headers)
32
+ response.raise_for_status()
33
+ content = response.text
34
+
35
+ # Use a regular expression to find specific `static/chunks` paths.
36
+ pattern = r"static/chunks/app/layout-[a-zA-Z0-9]+\.js"
37
+ match = re.search(pattern, content)
38
 
39
+ if match:
40
+ # Construct the full URL of the JS file.
41
+ js_path = match.group()
42
+ full_url = f"{base_url}/_next/{js_path}"
43
 
44
+ # Request the content of the JS file.
45
+ js_response = await client.get(full_url, headers=headers)
46
+ js_response.raise_for_status()
47
 
48
+ # In JS content, use a regular expression to search for h-value.
49
+ h_pattern = r'h="([0-9a-f-]+)"'
50
+ h_match = re.search(h_pattern, js_response.text)
51
+
52
+ if h_match:
53
+ h_value = h_match.group(1)
54
+ print("Found the h-value:", h_value)
55
+ # Update the cache.
56
+ cached_hid = h_value
57
+ cache_time = current_time
58
+ return h_value
59
+ else:
60
+ print("The h-value was not found in the JS content.")
61
+ return None
62
+ else:
63
+ print("The specified JS file path was not found in the HTML content.")
64
  return None
65
+ except httpx.RequestError as e:
66
  print(f"An error occurred during the request: {e}")
67
  return None
68
+ except httpx.HTTPStatusError as e:
69
+ print(f"HTTP error occurred: {e}")
70
+ return None
main.py CHANGED
@@ -1,5 +1,5 @@
1
- import uvicorn
2
- from api.app import app
3
-
4
- if __name__ == "__main__":
5
- uvicorn.run(app, host="0.0.0.0", port=8001)
 
1
+ import uvicorn
2
+ from api.app import app
3
+
4
+ if __name__ == "__main__":
5
+ uvicorn.run(app, host="0.0.0.0", port=8001)
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- fastapi==0.95.2
2
- httpx==0.23.3
3
- pydantic==1.10.4
4
- python-dotenv==0.21.0
5
- uvicorn==0.21.1
 
1
+ fastapi==0.95.2
2
+ httpx==0.23.3
3
+ pydantic==1.10.4
4
+ python-dotenv==0.21.0
5
+ uvicorn==0.21.1