File size: 9,907 Bytes
4ef6033 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
import asyncio
import json
import logging
import os
import random
import string
import time
import uuid
from http import HTTPStatus
from typing import AsyncGenerator, Dict, List, Any
import aiohttp
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from tenacity import (
retry,
stop_after_attempt,
wait_exponential,
retry_if_exception_type,
RetryError,
)
# βββ Logging βββ
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger("proxy")
# βββ Config βββ
BLACKBOX_URL = "https://www.blackbox.ai/api/chat"
CONNECTION_LIMIT = 200
CONNECTION_LIMIT_PER_HOST = 50
REQUEST_TIMEOUT = 300
WORKER_COUNT = 10
# βββ Static Headers βββ
HEADERS = {
"accept": "*/*",
"content-type": "application/json",
"origin": "https://www.blackbox.ai",
"referer": "https://www.blackbox.ai/",
"user-agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/136.0.0.0 Safari/537.36"
),
}
# βββ FastAPI Setup βββ
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
HTTP_SESSION: aiohttp.ClientSession = None
REQUEST_QUEUE: asyncio.Queue = asyncio.Queue()
WORKER_TASKS: List[asyncio.Task] = []
# βββ Retryable Error βββ
class RetryableStatusError(Exception):
def __init__(self, status: int, text: str):
self.status = status
self.text = text
super().__init__(f"status={status} body={text[:100]}...")
RETRYABLE_STATUSES = {400, 429, 500, 502, 503, 504}
# βββ Random Data βββ
_ascii = string.ascii_letters + string.digits
def _rand(n, pool=_ascii): return "".join(random.choice(pool) for _ in range(n))
def random_email(): return _rand(12) + "@gmail.com"
def random_id(): return _rand(21, string.digits)
def random_customer_id(): return "cus_" + _rand(12)
# βββ Payload Generator βββ
def build_payload(messages: List[Dict[str, Any]]) -> Dict[str, Any]:
return {
"messages": messages,
"id": _rand(8),
"agentMode": {},
"codeModelMode": True,
"trendingAgentMode": {},
"isMicMode": False,
"userSystemPrompt": None,
"maxTokens": 1024,
"playgroundTopP": None,
"playgroundTemperature": None,
"isChromeExt": False,
"githubToken": "",
"clickedAnswer2": False,
"clickedAnswer3": False,
"clickedForceWebSearch": False,
"visitFromDelta": False,
"isMemoryEnabled": False,
"mobileClient": False,
"userSelectedModel": None,
"validated": str(uuid.uuid4()),
"imageGenerationMode": False,
"webSearchModePrompt": False,
"deepSearchMode": True,
"domains": None,
"vscodeClient": False,
"codeInterpreterMode": False,
"customProfile": {
"name": "",
"occupation": "",
"traits": [],
"additionalInfo": "",
"enableNewChats": False
},
"session": {
"user": {
"name": "S.C gaming",
"email": random_email(),
"image": "https://lh3.googleusercontent.com/a/default",
"id": random_id()
},
"expires": "2025-12-31T23:59:59Z",
"isNewUser": False
},
"isPremium": True,
"subscriptionCache": {
"status": "PREMIUM",
"customerId": random_customer_id(),
"expiryTimestamp": int(time.time()) + 30 * 86400,
"lastChecked": int(time.time()),
"isTrialSubscription": False
},
"beastMode": False,
"reasoningMode": False,
"designerMode": False
}
# βββ Retry Wrapper βββ
def log_retry(retry_state):
rid = retry_state.kwargs.get("request_id", "unknown")
attempt = retry_state.attempt_number
err = retry_state.outcome.exception()
logger.warning("[%s] retry %s/10 due to %s", rid, attempt, err)
@retry(
stop=stop_after_attempt(10),
wait=wait_exponential(min=1, max=10),
retry=retry_if_exception_type(
(aiohttp.ClientConnectionError, aiohttp.ClientResponseError, asyncio.TimeoutError, RetryableStatusError)
),
before_sleep=log_retry
)
async def get_blackbox_response(*, data, stream: bool, request_id: str) -> AsyncGenerator[str, None]:
assert HTTP_SESSION
async with HTTP_SESSION.post(BLACKBOX_URL, json=data, headers=HEADERS, timeout=REQUEST_TIMEOUT) as resp:
if resp.status != 200:
body = await resp.text()
logger.error("[%s] Upstream %s error: %s", request_id, BLACKBOX_URL, resp.status)
if resp.status in RETRYABLE_STATUSES:
raise RetryableStatusError(resp.status, body)
raise HTTPException(status_code=502, detail=f"Upstream error {resp.status}")
if stream:
async for chunk in resp.content.iter_any():
if chunk:
yield chunk.decode("utf-8", "ignore")
else:
yield await resp.text()
# βββ Worker Thread βββ
async def _worker():
while True:
try:
data, request_id, out_q = await REQUEST_QUEUE.get()
try:
async for piece in get_blackbox_response(data=data, stream=False, request_id=request_id):
await out_q.put(piece)
except Exception as e:
await out_q.put(f"Error:{e}")
finally:
await out_q.put(None)
REQUEST_QUEUE.task_done()
except asyncio.CancelledError:
break
# βββ Middleware βββ
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request.state.request_id = rid = str(uuid.uuid4())
logger.info("[%s] %s %s", rid, request.method, request.url.path)
start = time.perf_counter()
resp = await call_next(request)
logger.info("[%s] finished in %.2fs", rid, time.perf_counter() - start)
return resp
# βββ Root & Health βββ
@app.get("/")
async def root():
return {"message": "API is running"}
@app.get("/health")
async def health():
return {"status": "ok"}
# βββ Chat Completion βββ
@app.post("/v1/chat/completions")
async def chat_completions(request: Request):
rid = request.state.request_id
try:
body = await request.json()
messages = body.get("messages", [])
if not messages:
raise HTTPException(status_code=400, detail="Missing 'messages'")
stream = body.get("stream", False)
payload = build_payload(messages)
if not stream:
q: asyncio.Queue = asyncio.Queue()
await REQUEST_QUEUE.put((payload, rid, q))
chunks: List[str] = []
while True:
part = await q.get()
if part is None:
break
if isinstance(part, str) and part.startswith("Error:"):
raise HTTPException(status_code=502, detail=part)
chunks.append(part)
answer = "".join(chunks) or "No response."
return {
"id": str(uuid.uuid4()),
"object": "chat.completion",
"created": int(time.time()),
"model": "DeepResearch",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": answer},
"finish_reason": "stop",
}
],
}
async def event_stream():
try:
async for chunk in get_blackbox_response(data=payload, stream=True, request_id=rid):
msg = {
"id": str(uuid.uuid4()),
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": "DeepResearch",
"choices": [{"index": 0, "delta": {"content": chunk}}],
}
yield f"data: {json.dumps(msg)}\n\n"
yield "data: [DONE]\n\n"
except Exception as e:
logger.error("[%s] stream error: %s", rid, e)
raise HTTPException(status_code=500, detail="streaming error")
return StreamingResponse(event_stream(), media_type="text/event-stream")
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
except RetryError as re:
logger.error("[%s] retries failed: %s", rid, re)
raise HTTPException(status_code=502, detail="Blackbox upstream failed")
except Exception as e:
logger.exception("[%s] error", rid)
raise HTTPException(status_code=500, detail="Internal proxy error")
# βββ Startup & Shutdown βββ
@app.on_event("startup")
async def startup():
global HTTP_SESSION, WORKER_TASKS
HTTP_SESSION = aiohttp.ClientSession(
connector=aiohttp.TCPConnector(limit=CONNECTION_LIMIT, limit_per_host=CONNECTION_LIMIT_PER_HOST),
timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT),
)
WORKER_TASKS = [asyncio.create_task(_worker()) for _ in range(WORKER_COUNT)]
logger.info("Started %d workers", WORKER_COUNT)
@app.on_event("shutdown")
async def shutdown():
for t in WORKER_TASKS:
t.cancel()
await asyncio.gather(*WORKER_TASKS, return_exceptions=True)
if HTTP_SESSION:
await HTTP_SESSION.close()
logger.info("Shutdown complete")
|