Blackbox.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. from __future__ import annotations
  2. from aiohttp import ClientSession
  3. import os
  4. import re
  5. import json
  6. import random
  7. import string
  8. from pathlib import Path
  9. from typing import Optional
  10. from datetime import datetime, timedelta
  11. from ..typing import AsyncResult, Messages, MediaListType
  12. from ..requests.raise_for_status import raise_for_status
  13. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  14. from ..image import to_data_uri
  15. from .helper import render_messages
  16. from ..providers.response import JsonConversation
  17. from ..tools.media import merge_media
  18. from .. import debug
  19. class Conversation(JsonConversation):
  20. validated_value: str = None
  21. chat_id: str = None
  22. message_history: Messages = []
  23. def __init__(self, model: str):
  24. self.model = model
  25. class Blackbox(AsyncGeneratorProvider, ProviderModelMixin):
  26. label = "Blackbox AI"
  27. url = "https://www.blackbox.ai"
  28. api_endpoint = "https://www.blackbox.ai/api/chat"
  29. working = True
  30. supports_stream = True
  31. supports_system_message = True
  32. supports_message_history = True
  33. default_model = "blackboxai"
  34. default_vision_model = default_model
  35. models = [
  36. default_model,
  37. "gpt-4.1-mini",
  38. "gpt-4.1-nano",
  39. "gpt-4",
  40. "gpt-4o",
  41. "gpt-4o-mini",
  42. # Trending agent modes
  43. 'Python Agent',
  44. 'HTML Agent',
  45. 'Builder Agent',
  46. 'Java Agent',
  47. 'JavaScript Agent',
  48. 'React Agent',
  49. 'Android Agent',
  50. 'Flutter Agent',
  51. 'Next.js Agent',
  52. 'AngularJS Agent',
  53. 'Swift Agent',
  54. 'MongoDB Agent',
  55. 'PyTorch Agent',
  56. 'Xcode Agent',
  57. 'Azure Agent',
  58. 'Bitbucket Agent',
  59. 'DigitalOcean Agent',
  60. 'Docker Agent',
  61. 'Electron Agent',
  62. 'Erlang Agent',
  63. 'FastAPI Agent',
  64. 'Firebase Agent',
  65. 'Flask Agent',
  66. 'Git Agent',
  67. 'Gitlab Agent',
  68. 'Go Agent',
  69. 'Godot Agent',
  70. 'Google Cloud Agent',
  71. 'Heroku Agent'
  72. ]
  73. vision_models = [default_vision_model]
  74. # Trending agent modes
  75. trendingAgentMode = {
  76. 'Python Agent': {'mode': True, 'id': "python"},
  77. 'HTML Agent': {'mode': True, 'id': "html"},
  78. 'Builder Agent': {'mode': True, 'id': "builder"},
  79. 'Java Agent': {'mode': True, 'id': "java"},
  80. 'JavaScript Agent': {'mode': True, 'id': "javascript"},
  81. 'React Agent': {'mode': True, 'id': "react"},
  82. 'Android Agent': {'mode': True, 'id': "android"},
  83. 'Flutter Agent': {'mode': True, 'id': "flutter"},
  84. 'Next.js Agent': {'mode': True, 'id': "next.js"},
  85. 'AngularJS Agent': {'mode': True, 'id': "angularjs"},
  86. 'Swift Agent': {'mode': True, 'id': "swift"},
  87. 'MongoDB Agent': {'mode': True, 'id': "mongodb"},
  88. 'PyTorch Agent': {'mode': True, 'id': "pytorch"},
  89. 'Xcode Agent': {'mode': True, 'id': "xcode"},
  90. 'Azure Agent': {'mode': True, 'id': "azure"},
  91. 'Bitbucket Agent': {'mode': True, 'id': "bitbucket"},
  92. 'DigitalOcean Agent': {'mode': True, 'id': "digitalocean"},
  93. 'Docker Agent': {'mode': True, 'id': "docker"},
  94. 'Electron Agent': {'mode': True, 'id': "electron"},
  95. 'Erlang Agent': {'mode': True, 'id': "erlang"},
  96. 'FastAPI Agent': {'mode': True, 'id': "fastapi"},
  97. 'Firebase Agent': {'mode': True, 'id': "firebase"},
  98. 'Flask Agent': {'mode': True, 'id': "flask"},
  99. 'Git Agent': {'mode': True, 'id': "git"},
  100. 'Gitlab Agent': {'mode': True, 'id': "gitlab"},
  101. 'Go Agent': {'mode': True, 'id': "go"},
  102. 'Godot Agent': {'mode': True, 'id': "godot"},
  103. 'Google Cloud Agent': {'mode': True, 'id': "googlecloud"},
  104. 'Heroku Agent': {'mode': True, 'id': "heroku"},
  105. }
  106. # Complete list of all models (for authorized users)
  107. _all_models = list(dict.fromkeys([
  108. *models,
  109. *list(trendingAgentMode.keys())
  110. ]))
  111. @classmethod
  112. async def fetch_validated(cls, url: str = "https://www.blackbox.ai", force_refresh: bool = False) -> Optional[str]:
  113. cache_path = Path(os.path.expanduser("~")) / ".g4f" / "cache"
  114. cache_file = cache_path / 'blackbox.json'
  115. if not force_refresh and cache_file.exists():
  116. try:
  117. with open(cache_file, 'r') as f:
  118. data = json.load(f)
  119. if data.get('validated_value'):
  120. return data['validated_value']
  121. except Exception as e:
  122. debug.log(f"Blackbox: Error reading cache: {e}")
  123. js_file_pattern = r'static/chunks/\d{4}-[a-fA-F0-9]+\.js'
  124. uuid_pattern = r'["\']([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})["\']'
  125. def is_valid_context(text: str) -> bool:
  126. return any(char + '=' in text for char in 'abcdefghijklmnopqrstuvwxyz')
  127. async with ClientSession() as session:
  128. try:
  129. async with session.get(url) as response:
  130. if response.status != 200:
  131. return None
  132. page_content = await response.text()
  133. js_files = re.findall(js_file_pattern, page_content)
  134. for js_file in js_files:
  135. js_url = f"{url}/_next/{js_file}"
  136. async with session.get(js_url) as js_response:
  137. if js_response.status == 200:
  138. js_content = await js_response.text()
  139. for match in re.finditer(uuid_pattern, js_content):
  140. start = max(0, match.start() - 10)
  141. end = min(len(js_content), match.end() + 10)
  142. context = js_content[start:end]
  143. if is_valid_context(context):
  144. validated_value = match.group(1)
  145. cache_file.parent.mkdir(exist_ok=True, parents=True)
  146. try:
  147. with open(cache_file, 'w') as f:
  148. json.dump({'validated_value': validated_value}, f)
  149. except Exception as e:
  150. debug.log(f"Blackbox: Error writing cache: {e}")
  151. return validated_value
  152. except Exception as e:
  153. debug.log(f"Blackbox: Error retrieving validated_value: {e}")
  154. return None
  155. @classmethod
  156. def generate_id(cls, length: int = 7) -> str:
  157. chars = string.ascii_letters + string.digits
  158. return ''.join(random.choice(chars) for _ in range(length))
  159. @classmethod
  160. async def create_async_generator(
  161. cls,
  162. model: str,
  163. messages: Messages,
  164. prompt: str = None,
  165. proxy: str = None,
  166. media: MediaListType = None,
  167. top_p: float = None,
  168. temperature: float = None,
  169. max_tokens: int = None,
  170. conversation: Conversation = None,
  171. return_conversation: bool = True,
  172. **kwargs
  173. ) -> AsyncResult:
  174. model = cls.get_model(model)
  175. headers = {
  176. 'accept': '*/*',
  177. 'accept-language': 'en-US,en;q=0.9',
  178. 'content-type': 'application/json',
  179. 'origin': 'https://www.blackbox.ai',
  180. 'referer': 'https://www.blackbox.ai/',
  181. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
  182. }
  183. async with ClientSession(headers=headers) as session:
  184. if conversation is None or not hasattr(conversation, "chat_id"):
  185. conversation = Conversation(model)
  186. conversation.validated_value = await cls.fetch_validated()
  187. conversation.chat_id = cls.generate_id()
  188. conversation.message_history = []
  189. current_messages = []
  190. for i, msg in enumerate(render_messages(messages)):
  191. msg_id = conversation.chat_id if i == 0 and msg["role"] == "user" else cls.generate_id()
  192. current_msg = {
  193. "id": msg_id,
  194. "content": msg["content"],
  195. "role": msg["role"]
  196. }
  197. current_messages.append(current_msg)
  198. media = list(merge_media(media, messages))
  199. if media:
  200. current_messages[-1]['data'] = {
  201. "imagesData": [
  202. {
  203. "filePath": f"/{image_name}",
  204. "contents": to_data_uri(image)
  205. }
  206. for image, image_name in media
  207. ],
  208. "fileText": "",
  209. "title": ""
  210. }
  211. data = {
  212. "messages": current_messages,
  213. "agentMode": {},
  214. "id": conversation.chat_id,
  215. "previewToken": None,
  216. "userId": None,
  217. "codeModelMode": True,
  218. "trendingAgentMode": cls.trendingAgentMode.get(model, {}) if model in cls.trendingAgentMode else {},
  219. "isMicMode": False,
  220. "userSystemPrompt": None,
  221. "maxTokens": max_tokens,
  222. "playgroundTopP": top_p,
  223. "playgroundTemperature": temperature,
  224. "isChromeExt": False,
  225. "githubToken": "",
  226. "clickedAnswer2": False,
  227. "clickedAnswer3": False,
  228. "clickedForceWebSearch": False,
  229. "visitFromDelta": False,
  230. "isMemoryEnabled": False,
  231. "mobileClient": False,
  232. "userSelectedModel": None,
  233. "validated": conversation.validated_value,
  234. "imageGenerationMode": False,
  235. "webSearchModePrompt": False,
  236. "deepSearchMode": False,
  237. "designerMode": False,
  238. "domains": None,
  239. "vscodeClient": False,
  240. "codeInterpreterMode": False,
  241. "customProfile": {
  242. "additionalInfo": "",
  243. "enableNewChats": False,
  244. "name": "",
  245. "occupation": "",
  246. "traits": []
  247. },
  248. "webSearchModeOption": {
  249. "autoMode": False,
  250. "webMode": False,
  251. "offlineMode": False
  252. },
  253. "session": None,
  254. "isPremium": True,
  255. "subscriptionCache": None,
  256. "beastMode": False,
  257. "reasoningMode": False,
  258. "workspaceId": "",
  259. "asyncMode": False,
  260. "webSearchMode": False
  261. }
  262. # Continue with the API request and async generator behavior
  263. async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
  264. await raise_for_status(response)
  265. # Collect the full response
  266. full_response = []
  267. async for chunk in response.content.iter_any():
  268. if chunk:
  269. chunk_text = chunk.decode()
  270. full_response.append(chunk_text)
  271. yield chunk_text
  272. full_response_text = ''.join(full_response)
  273. # Handle conversation history
  274. if return_conversation:
  275. conversation.message_history.append({"role": "assistant", "content": full_response_text})
  276. yield conversation