Samfy001 commited on
Commit
8754765
·
verified ·
1 Parent(s): 42f36d3

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +28 -0
  2. blackbox_server.py +487 -0
  3. config.py +126 -0
  4. requirements.txt +6 -0
  5. start_server.py +34 -0
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Python 3.11 slim
2
+ FROM python:3.11-slim
3
+
4
+ WORKDIR /app
5
+
6
+ ENV PYTHONUNBUFFERED=1 \
7
+ PYTHONDONTWRITEBYTECODE=1
8
+
9
+ # System deps for building wheels if needed
10
+ RUN apt-get update && apt-get install -y \
11
+ gcc \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Install Python deps
15
+ COPY requirements.txt ./
16
+ RUN pip install --no-cache-dir --upgrade pip && \
17
+ pip install --no-cache-dir -r requirements.txt
18
+
19
+ # Copy app
20
+ COPY . .
21
+
22
+ # Hugging Face Spaces expects port 7860
23
+ EXPOSE 7860
24
+
25
+ # Start server
26
+ CMD ["uvicorn", "blackbox_server:app", "--host", "0.0.0.0", "--port", "7860"]
27
+
28
+
blackbox_server.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Blackbox.ai Reverse OpenAI-Compatible API Server
4
+
5
+ This server accepts OpenAI-compatible Chat Completions requests and forwards them
6
+ to Blackbox.ai's chat endpoint using the exact required payload structure and headers.
7
+ It streams responses back as OpenAI-style SSE chunks or returns a non-streaming
8
+ OpenAI-compatible response.
9
+ """
10
+ import json
11
+ import time
12
+ import uuid
13
+ import logging
14
+ import requests
15
+ from typing import List, Dict, Any, Optional, Union, AsyncGenerator
16
+
17
+ from fastapi import FastAPI, HTTPException, Request
18
+ from fastapi.middleware.cors import CORSMiddleware
19
+ from fastapi.responses import StreamingResponse, JSONResponse
20
+ from pydantic import BaseModel, Field
21
+
22
+ try:
23
+ from .config import (
24
+ BLACKBOX_HEADERS,
25
+ BLACKBOX_COOKIES_STRING,
26
+ MODEL_MAPPING,
27
+ SERVER_CONFIG,
28
+ BLACKBOX_VALIDATED,
29
+ BLACKBOX_STATIC_SESSION,
30
+ BLACKBOX_STATIC_SUBSCRIPTION,
31
+ BLACKBOX_STATIC_BASE_FIELDS,
32
+ )
33
+ except ImportError:
34
+ # Allow running as a module or from root
35
+ try:
36
+ from config import (
37
+ BLACKBOX_HEADERS,
38
+ BLACKBOX_COOKIES_STRING,
39
+ MODEL_MAPPING,
40
+ SERVER_CONFIG,
41
+ BLACKBOX_VALIDATED,
42
+ BLACKBOX_STATIC_SESSION,
43
+ BLACKBOX_STATIC_SUBSCRIPTION,
44
+ BLACKBOX_STATIC_BASE_FIELDS,
45
+ )
46
+ except ImportError:
47
+ raise
48
+
49
+ logger = logging.getLogger(__name__)
50
+ logging.basicConfig(level=logging.INFO)
51
+
52
+ BLACKBOX_CHAT_URL = "https://www.blackbox.ai/api/chat"
53
+ REQUEST_TIMEOUT = 120
54
+
55
+
56
+ # ===== OpenAI-compatible Pydantic models =====
57
+ class OpenAIMessage(BaseModel):
58
+ role: str = Field(description="Role: system, user, assistant, function, or tool")
59
+ content: Optional[Union[str, List[Dict[str, Any]]]] = Field(None, description="Message content")
60
+ name: Optional[str] = None
61
+ function_call: Optional[Dict[str, Any]] = None
62
+ tool_calls: Optional[List[Dict[str, Any]]] = None
63
+ tool_call_id: Optional[str] = None
64
+
65
+ def get_text(self) -> str:
66
+ if isinstance(self.content, str):
67
+ return self.content
68
+ if isinstance(self.content, list):
69
+ text_parts: List[str] = []
70
+ for item in self.content:
71
+ if isinstance(item, dict):
72
+ if item.get("type") == "text":
73
+ text_parts.append(item.get("text", ""))
74
+ elif item.get("type") == "image_url":
75
+ text_parts.append("[Image]")
76
+ return "".join(text_parts)
77
+ return str(self.content) if self.content is not None else ""
78
+
79
+ class Config:
80
+ extra = "allow"
81
+
82
+
83
+ class OpenAIFunction(BaseModel):
84
+ name: str
85
+ description: Optional[str] = None
86
+ parameters: Optional[Dict[str, Any]] = None
87
+
88
+ class Config:
89
+ extra = "allow"
90
+
91
+
92
+ class OpenAITool(BaseModel):
93
+ type: str = Field(default="function")
94
+ function: Optional[OpenAIFunction] = None
95
+
96
+ class Config:
97
+ extra = "allow"
98
+
99
+
100
+ class OpenAIChatRequest(BaseModel):
101
+ model: str = Field(..., description="OpenAI model name")
102
+ messages: List[OpenAIMessage]
103
+ max_tokens: Optional[int] = None
104
+ temperature: Optional[float] = None
105
+ top_p: Optional[float] = None
106
+ n: Optional[int] = 1
107
+ stream: Optional[bool] = False
108
+ stop: Optional[Union[str, List[str]]] = None
109
+ presence_penalty: Optional[float] = None
110
+ frequency_penalty: Optional[float] = None
111
+ logit_bias: Optional[Dict[str, float]] = None
112
+ user: Optional[str] = None
113
+ tools: Optional[List[OpenAITool]] = None
114
+ tool_choice: Optional[Union[str, Dict[str, Any]]] = None
115
+ functions: Optional[List[OpenAIFunction]] = None
116
+ function_call: Optional[Union[str, Dict[str, Any]]] = None
117
+
118
+ class Config:
119
+ extra = "allow"
120
+
121
+
122
+ class OpenAIChoice(BaseModel):
123
+ index: int = 0
124
+ message: Dict[str, Any]
125
+ finish_reason: Optional[str] = None
126
+
127
+
128
+ class OpenAIChatResponse(BaseModel):
129
+ id: str
130
+ object: str = "chat.completion"
131
+ created: int
132
+ model: str
133
+ choices: List[OpenAIChoice]
134
+ usage: Optional[Dict[str, int]] = None
135
+
136
+
137
+ class OpenAIStreamChoice(BaseModel):
138
+ index: int = 0
139
+ delta: Dict[str, Any]
140
+ finish_reason: Optional[str] = None
141
+
142
+
143
+ class OpenAIStreamChunk(BaseModel):
144
+ id: str
145
+ object: str = "chat.completion.chunk"
146
+ created: int
147
+ model: str
148
+ choices: List[OpenAIStreamChoice]
149
+
150
+
151
+ def _parse_cookie_string(cookie_string: str) -> Dict[str, str]:
152
+ cookies: Dict[str, str] = {}
153
+ if not cookie_string:
154
+ return cookies
155
+ parts = [p.strip() for p in cookie_string.split(";") if p.strip()]
156
+ for part in parts:
157
+ if "=" in part:
158
+ name, value = part.split("=", 1)
159
+ cookies[name.strip()] = value.strip()
160
+ return cookies
161
+
162
+
163
+ def _blackbox_headers() -> Dict[str, str]:
164
+ # Return a copy so we can safely mutate per-request if needed
165
+ return dict(BLACKBOX_HEADERS)
166
+
167
+
168
+ def _build_blackbox_payload(openai_req: OpenAIChatRequest) -> Dict[str, Any]:
169
+ """
170
+ Build the exact Blackbox payload including all fields from the provided curl.
171
+ We only map OpenAI messages/model into the appropriate fields and keep all other
172
+ fields present so the upstream accepts the request.
173
+ """
174
+ # Generate short ids
175
+ def short_id() -> str:
176
+ return uuid.uuid4().hex[:7]
177
+
178
+ # Use user-provided top-level id if supplied as an extra field
179
+ extra_top = getattr(openai_req, "model_extra", {}) or {}
180
+ req_id = str(extra_top.get("id")) if extra_top.get("id") else short_id()
181
+
182
+ # Map OpenAI messages to Blackbox format (id, content, role)
183
+ bb_messages: List[Dict[str, Any]] = []
184
+ first = True
185
+ for msg in openai_req.messages:
186
+ msg_role = str(getattr(msg, "role", "")).strip() or "user"
187
+ # Coerce unknown roles to 'user' to avoid upstream rejection
188
+ if msg_role not in {"system", "user", "assistant"}:
189
+ msg_role = "user"
190
+ msg_content = msg.get_text()
191
+ # Ensure minimally valid defaults to avoid 501 from upstream on malformed content
192
+ if not msg_content:
193
+ msg_content = ""
194
+ # Reuse provided message.id if present in extras; ensure first message id matches top-level id
195
+ msg_extra = getattr(msg, "model_extra", {}) or {}
196
+ msg_id = str(msg_extra.get("id")) if msg_extra.get("id") else (req_id if first else short_id())
197
+ bb_messages.append({
198
+ "id": msg_id,
199
+ "content": msg_content,
200
+ "role": msg_role,
201
+ })
202
+ first = False
203
+
204
+ # Determine Blackbox agent from model mapping
205
+ agent = MODEL_MAPPING.get(openai_req.model, MODEL_MAPPING.get("default"))
206
+
207
+ payload: Dict[str, Any] = {
208
+ "messages": bb_messages,
209
+ "agentMode": {
210
+ "name": agent["name"],
211
+ "id": agent["id"],
212
+ "mode": True,
213
+ },
214
+ "id": req_id,
215
+ # Include all base fields exactly
216
+ **BLACKBOX_STATIC_BASE_FIELDS,
217
+ # Ensure these fields reflect user-provided values
218
+ "maxTokens": (openai_req.max_tokens if (openai_req.max_tokens is not None and openai_req.max_tokens > 0) else 1024),
219
+ "userSelectedModel": agent["name"],
220
+ "userSelectedAgent": "VscodeAgent",
221
+ # Use validated token as provided
222
+ "validated": BLACKBOX_VALIDATED,
223
+ # Session/subscription from provided curl
224
+ "session": BLACKBOX_STATIC_SESSION,
225
+ "subscriptionCache": {
226
+ **BLACKBOX_STATIC_SUBSCRIPTION
227
+ },
228
+ # Blackbox expects streaming
229
+ "stream": True,
230
+ }
231
+
232
+ return payload
233
+
234
+
235
+ def _extract_blackbox_text(line: str) -> Optional[str]:
236
+ """Try to extract textual delta from a Blackbox SSE line."""
237
+ # Lines may be plain or prefixed with 'data: '
238
+ if line.startswith("data: "):
239
+ data_part = line[6:].strip()
240
+ elif line.startswith("data:"):
241
+ data_part = line[5:].strip()
242
+ else:
243
+ data_part = line.strip()
244
+
245
+ if not data_part or data_part == "[DONE]":
246
+ return None
247
+
248
+ # Try JSON
249
+ try:
250
+ obj = json.loads(data_part)
251
+ # Common patterns: {"type": "response"|"delta"|..., "data"|"text"|"delta": "..."}
252
+ for key in ("data", "text", "delta", "output"):
253
+ val = obj.get(key)
254
+ if isinstance(val, str) and val:
255
+ return val
256
+ # Some responses nest under obj["message"]["content"] etc.
257
+ message = obj.get("message")
258
+ if isinstance(message, dict):
259
+ content = message.get("content")
260
+ if isinstance(content, str) and content:
261
+ return content
262
+ except Exception:
263
+ # Not JSON - possibly plain text token
264
+ if data_part:
265
+ return data_part
266
+ return None
267
+
268
+
269
+ async def _stream_openai_chunks(openai_req: OpenAIChatRequest, request_id: str) -> AsyncGenerator[str, None]:
270
+ """Forward to Blackbox with streaming, convert to OpenAI SSE chunks."""
271
+ headers = _blackbox_headers()
272
+ cookies = _parse_cookie_string(BLACKBOX_COOKIES_STRING)
273
+ payload = _build_blackbox_payload(openai_req)
274
+
275
+ with requests.Session() as sess:
276
+ try:
277
+ resp = sess.post(
278
+ BLACKBOX_CHAT_URL,
279
+ headers=headers,
280
+ cookies=cookies,
281
+ json=payload,
282
+ stream=True,
283
+ timeout=REQUEST_TIMEOUT
284
+ )
285
+ except requests.RequestException as e:
286
+ raise HTTPException(status_code=502, detail=f"Upstream connection error: {e}")
287
+
288
+ if resp.status_code != 200:
289
+ detail = resp.text[:500]
290
+ raise HTTPException(status_code=502, detail=f"Upstream error {resp.status_code}: {detail}")
291
+
292
+ created = int(time.time())
293
+
294
+ # Initial role chunk
295
+ initial = OpenAIStreamChunk(
296
+ id=request_id,
297
+ created=created,
298
+ model=openai_req.model,
299
+ choices=[OpenAIStreamChoice(index=0, delta={"role": "assistant"}, finish_reason=None)]
300
+ )
301
+ yield f"data: {initial.model_dump_json()}\n\n"
302
+
303
+ for raw_line in resp.iter_lines():
304
+ if not raw_line:
305
+ continue
306
+ try:
307
+ line = raw_line.decode("utf-8", errors="ignore")
308
+ except Exception:
309
+ continue
310
+
311
+ text = _extract_blackbox_text(line)
312
+ if text is None:
313
+ continue
314
+
315
+ chunk = OpenAIStreamChunk(
316
+ id=request_id,
317
+ created=created,
318
+ model=openai_req.model,
319
+ choices=[OpenAIStreamChoice(index=0, delta={"content": text}, finish_reason=None)]
320
+ )
321
+ yield f"data: {chunk.model_dump_json()}\n\n"
322
+
323
+ # Final chunk
324
+ final = OpenAIStreamChunk(
325
+ id=request_id,
326
+ created=created,
327
+ model=openai_req.model,
328
+ choices=[OpenAIStreamChoice(index=0, delta={}, finish_reason="stop")]
329
+ )
330
+ yield f"data: {final.model_dump_json()}\n\n"
331
+ yield "data: [DONE]\n\n"
332
+
333
+
334
+ def _complete_non_streaming(openai_req: OpenAIChatRequest) -> str:
335
+ """Forward to Blackbox, collect all streamed text, and return a single string."""
336
+ headers = _blackbox_headers()
337
+ cookies = _parse_cookie_string(BLACKBOX_COOKIES_STRING)
338
+ payload = _build_blackbox_payload(openai_req)
339
+ # Force stream true upstream; we will aggregate locally
340
+ payload["stream"] = True
341
+
342
+ with requests.Session() as sess:
343
+ try:
344
+ resp = sess.post(
345
+ BLACKBOX_CHAT_URL,
346
+ headers=headers,
347
+ cookies=cookies,
348
+ json=payload,
349
+ stream=True,
350
+ timeout=REQUEST_TIMEOUT
351
+ )
352
+ except requests.RequestException as e:
353
+ raise HTTPException(status_code=502, detail=f"Upstream connection error: {e}")
354
+
355
+ if resp.status_code != 200:
356
+ detail = resp.text[:500]
357
+ raise HTTPException(status_code=502, detail=f"Upstream error {resp.status_code}: {detail}")
358
+
359
+ full = []
360
+ for raw_line in resp.iter_lines():
361
+ if not raw_line:
362
+ continue
363
+ try:
364
+ line = raw_line.decode("utf-8", errors="ignore")
365
+ except Exception:
366
+ continue
367
+ text = _extract_blackbox_text(line)
368
+ if text:
369
+ full.append(text)
370
+ return "".join(full)
371
+
372
+
373
+ # ===== FastAPI App =====
374
+ app = FastAPI(
375
+ title="Blackbox.ai Reverse OpenAI API",
376
+ version="1.0.0",
377
+ description="OpenAI-compatible API that proxies to Blackbox.ai chat"
378
+ )
379
+
380
+ app.add_middleware(
381
+ CORSMiddleware,
382
+ allow_origins=["*"],
383
+ allow_credentials=True,
384
+ allow_methods=["*"],
385
+ allow_headers=["*"],
386
+ )
387
+
388
+
389
+ @app.get("/")
390
+ async def root():
391
+ return {
392
+ "message": "Blackbox.ai Reverse OpenAI API",
393
+ "version": "1.0.0",
394
+ "status": "running",
395
+ "endpoints": ["/v1/chat/completions", "/v1/models", "/health"],
396
+ }
397
+
398
+
399
+ @app.get("/health")
400
+ async def health():
401
+ return {
402
+ "status": "healthy",
403
+ "timestamp": int(time.time()),
404
+ "upstream": "blackbox.ai",
405
+ }
406
+
407
+
408
+ @app.get("/v1/models")
409
+ async def list_models():
410
+ created = int(time.time())
411
+ data = []
412
+ # Expose mapped models (keys of MODEL_MAPPING excluding 'default')
413
+ for model_name in [k for k in MODEL_MAPPING.keys() if k != "default"]:
414
+ data.append({
415
+ "id": model_name,
416
+ "object": "model",
417
+ "created": created,
418
+ "owned_by": "blackbox",
419
+ })
420
+ if not data:
421
+ data.append({
422
+ "id": "gpt-5",
423
+ "object": "model",
424
+ "created": created,
425
+ "owned_by": "blackbox",
426
+ })
427
+ return {"object": "list", "data": data}
428
+
429
+
430
+ @app.post("/v1/chat/completions")
431
+ async def chat_completions(request: OpenAIChatRequest):
432
+ request_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
433
+ logger.info(f"[{request_id}] Chat request: model={request.model}, stream={request.stream}")
434
+
435
+ # Streamed
436
+ if bool(request.stream):
437
+ return StreamingResponse(
438
+ _stream_openai_chunks(request, request_id),
439
+ media_type="text/event-stream",
440
+ headers={
441
+ "Cache-Control": "no-cache",
442
+ "Connection": "keep-alive",
443
+ "X-Accel-Buffering": "no",
444
+ "Access-Control-Allow-Origin": "*",
445
+ "Access-Control-Allow-Headers": "*",
446
+ },
447
+ )
448
+
449
+ # Non-streaming
450
+ content = _complete_non_streaming(request)
451
+ created = int(time.time())
452
+ response = OpenAIChatResponse(
453
+ id=request_id,
454
+ created=created,
455
+ model=request.model,
456
+ choices=[OpenAIChoice(index=0, message={"role": "assistant", "content": content}, finish_reason="stop")],
457
+ usage={
458
+ "prompt_tokens": len(" ".join([m.get_text() for m in request.messages]).split()),
459
+ "completion_tokens": len(content.split()),
460
+ "total_tokens": len(" ".join([m.get_text() for m in request.messages]).split()) + len(content.split()),
461
+ },
462
+ )
463
+ return response
464
+
465
+
466
+ @app.post("/v1/chat/completions/raw")
467
+ async def raw_validator(req: Request):
468
+ body = await req.body()
469
+ try:
470
+ obj = json.loads(body)
471
+ _ = OpenAIChatRequest(**obj)
472
+ return {"valid": True}
473
+ except Exception as e:
474
+ return JSONResponse(status_code=422, content={"valid": False, "error": str(e)})
475
+
476
+
477
+ if __name__ == "__main__":
478
+ try:
479
+ import uvicorn
480
+ host = SERVER_CONFIG.get("host", "0.0.0.0")
481
+ port = int(SERVER_CONFIG.get("port", 8090))
482
+ logger.info(f"Starting Blackbox Reverse API on {host}:{port}")
483
+ uvicorn.run(app, host=host, port=port, log_level="info")
484
+ except Exception as e:
485
+ logger.error(f"Failed to start server: {e}")
486
+
487
+
config.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for Blackbox.ai Reverse API
2
+
3
+ # Exact headers from the provided curl (values may be environment-specific; update as needed)
4
+ BLACKBOX_HEADERS = {
5
+ "accept": "text/event-stream",
6
+ "accept-language": "en-US,en;q=0.8",
7
+ "accept-encoding": "gzip, deflate, br",
8
+ "content-type": "application/json",
9
+ "cache-control": "no-cache",
10
+ "x-requested-with": "XMLHttpRequest",
11
+ "origin": "https://www.blackbox.ai",
12
+ "priority": "u=1, i",
13
+ "referer": "https://www.blackbox.ai/",
14
+ "sec-ch-ua": '"Not;A=Brand";v="99", "Brave";v="139", "Chromium";v="139"',
15
+ "sec-ch-ua-mobile": "?0",
16
+ "sec-ch-ua-platform": '"Windows"',
17
+ "sec-fetch-dest": "empty",
18
+ "sec-fetch-mode": "cors",
19
+ "sec-fetch-site": "same-origin",
20
+ "sec-gpc": "1",
21
+ "connection": "keep-alive",
22
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
23
+ }
24
+
25
+ # Cookies string copied from the curl (keep exact; rotate as needed)
26
+ # NOTE: For security, consider sourcing from environment variables.
27
+ BLACKBOX_COOKIES_STRING = (
28
+ "sessionId=b64ccc84-522a-44b9-8377-90ffd899011b; intercom-id-x55eda6t=34e51fb9-a65a-4335-9c36-4c672b803c2e; "
29
+ "intercom-device-id-x55eda6t=99577693-78bb-4280-9ea3-180d18ec6ca7; __Host-authjs.csrf-token=e29b4390dee01e7490dabe14bae60a8e477c8739d20ba067ebb25f5e79ab61ff%7C2813747e5b5cdfd657d57b13c73f9cf2d1016fd6308f6da7bbfb7f2e3efad13b; "
30
+ "__Secure-authjs.callback-url=https%3A%2F%2Fwww.blackbox.ai; render_app_version_affinity=dep-d2fa0m3uibrs739mupe0; "
31
+ "intercom-session-x55eda6t=cjI3dFduQ2NUOEk3eEtBM3JrN2VveW9pRGdUTGFXZGphTWxIaEp0bURxZEdGcmNvQzBGdjJCRDJsOFRaSzBRVFo4VE16M3k2ZlBQNnFlbUtLZHl4NXF0Wlh0Tm5ybHJBNnNDNXoxTzR1d0U9LS1Wc0ZoL3ZIRjU1bmtNTDhMczNNR3ZnPT0=--fbbd01990ae2a547e64a92fd1abb2609ab813626; "
32
+ "__Secure-authjs.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..BgcqZx4gcRJdUsPN.prubG8glk1Wvcij_gljlKT29lrn60kRF4siLxXJZ7mgBHb4F0ml-tUh-OeL1dbIyTytfSFPhky4-yOkMbrir29ieYbUwKzmFO1pvpYDb_BkD3Oe9tz02d7A1qB7ZQnXPambEMKSDSU833UbNVMye3YBX-_lGesaIMkZCrnY_zvfD76Jp51t7EX7vJWQexNGmj8rKUtLDCCMQ9UK-OmYOBU-HgVoBpY3fUHt1E31EFRWm6TYrTBmVkmp9QZ2a8REQCddF6TJH_SHtB-Cl_ZRFmlAR18tQ4D7VM24nh_C7QXj9QfPL51JKkhavx-n8cftQTOVOwYH7qFICb-hYHq-o8BwPnfZH4bwdQNsBWO6oq4WWcLJroCvocwJvLrzY7RH8s1FkGwXVRL_ZxKF2ei3RdN0W_Isw92zcmjsS2NHBwA9_KlGnOTPhkg1mfkWTF5D5Ns11EVpfcktRHMr30x_Q1AgoB0fxEnh0KWL2LroaAzK6CNbAKVBJx9lDy5NOC-83RCAItY9WAgEMFFpmbProB8UmdcRMiRUiM7f-l-gU-jqKAfZqV9xLCw.W2qJTuS_QKIDmIbTLGDIyw"
33
+ )
34
+
35
+ # Map OpenAI model names to Blackbox agent tuples {name, id}
36
+ MODEL_MAPPING = {
37
+ # OpenAI GPT-5
38
+ "gpt-5": {"name": "openai/gpt-5-chat", "id": "GPT-5"},
39
+ # Anthropic Claude Opus
40
+ "anthropic/claude-opus-4.1": {"name": "anthropic/claude-opus-4.1", "id": "Claude Opus 4.1"},
41
+ "claude-opus-4.1": {"name": "anthropic/claude-opus-4.1", "id": "Claude Opus 4.1"},
42
+ # Fallback
43
+ "default": {"name": "openai/gpt-5-chat", "id": "GPT-5"},
44
+ }
45
+
46
+ # Exact validated token from the provided curl
47
+ BLACKBOX_VALIDATED = "a38f5889-8fef-46d4-8ede-bf4668b6a9bb"
48
+
49
+ # Session block from the provided curl
50
+ BLACKBOX_STATIC_SESSION = {
51
+ "user": {
52
+ "name": "Scgaming",
53
+ "email": "scgaming69106@gmail.com",
54
+ "image": "https://lh3.googleusercontent.com/a/ACg8ocKRmB3MEWHP-MSiFqW4ci8BlhSBtijO1Bm5n_LZKQ1obC4lnA=s96-c",
55
+ "id": "117887095473341798642",
56
+ },
57
+ "expires": "2025-09-14T09:45:11.827Z",
58
+ "isNewUser": True,
59
+ }
60
+
61
+ BLACKBOX_STATIC_SUBSCRIPTION = {
62
+ "status": "PREMIUM",
63
+ "customerId": "cus_SrjMSDi5fRfu9d",
64
+ "expiryTimestamp": 1757840511,
65
+ "lastChecked": 1755248526265,
66
+ "isTrialSubscription": True,
67
+ "hasPaymentVerificationFailure": False,
68
+ "verificationFailureTimestamp": None,
69
+ "plan": "ultimate",
70
+ "billing": "monthly",
71
+ }
72
+
73
+ BLACKBOX_STATIC_BASE_FIELDS = {
74
+ "previewToken": None,
75
+ "userId": None,
76
+ "codeModelMode": True,
77
+ "trendingAgentMode": {},
78
+ "isMicMode": False,
79
+ "userSystemPrompt": None,
80
+ "playgroundTopP": None,
81
+ "playgroundTemperature": None,
82
+ "isChromeExt": False,
83
+ "githubToken": "",
84
+ "clickedAnswer2": False,
85
+ "clickedAnswer3": False,
86
+ "clickedForceWebSearch": False,
87
+ "visitFromDelta": False,
88
+ "isMemoryEnabled": False,
89
+ "mobileClient": False,
90
+ "imageGenerationMode": False,
91
+ "imageGenMode": "autoMode",
92
+ "webSearchModePrompt": False,
93
+ "deepSearchMode": False,
94
+ "domains": None,
95
+ "vscodeClient": False,
96
+ "codeInterpreterMode": False,
97
+ "customProfile": {
98
+ "name": "",
99
+ "occupation": "",
100
+ "traits": [],
101
+ "additionalInfo": "",
102
+ "enableNewChats": False,
103
+ },
104
+ "webSearchModeOption": {
105
+ "autoMode": True,
106
+ "webMode": False,
107
+ "offlineMode": False,
108
+ },
109
+ "isPremium": True,
110
+ "beastMode": False,
111
+ "reasoningMode": False,
112
+ "designerMode": False,
113
+ "workspaceId": "",
114
+ "asyncMode": False,
115
+ "integrations": {},
116
+ "isTaskPersistent": False,
117
+ "selectedElement": None,
118
+ }
119
+
120
+ # Server host/port
121
+ SERVER_CONFIG = {
122
+ "host": "0.0.0.0",
123
+ "port": 8090,
124
+ }
125
+
126
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi==0.104.1
2
+ uvicorn[standard]==0.24.0
3
+ pydantic==2.5.0
4
+ requests==2.31.0
5
+ orjson==3.10.7
6
+
start_server.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import socket
4
+ import uvicorn
5
+ from blackbox_server import app
6
+
7
+ try:
8
+ from config import SERVER_CONFIG
9
+ except Exception:
10
+ SERVER_CONFIG = {"host": "0.0.0.0", "port": 8090}
11
+
12
+
13
+ def find_free_port(start_port: int, max_tries: int = 50) -> int:
14
+ """Find an available TCP port starting from start_port."""
15
+ for port in range(start_port, start_port + max_tries):
16
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
17
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
18
+ try:
19
+ s.bind(("0.0.0.0", port))
20
+ return port
21
+ except OSError:
22
+ continue
23
+ return start_port
24
+
25
+ if __name__ == "__main__":
26
+ host = SERVER_CONFIG.get("host", "0.0.0.0")
27
+ base_port = int(os.getenv("PORT") or SERVER_CONFIG.get("port", 8090))
28
+ port = find_free_port(base_port)
29
+ if port != base_port:
30
+ print(f"⚠️ Port {base_port} in use. Switching to free port {port}.")
31
+ print(f"🚀 Starting Blackbox Reverse OpenAI API Server on {host}:{port} ...")
32
+ uvicorn.run(app, host=host, port=port, reload=False, log_level="info")
33
+
34
+