Blackbox.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. from __future__ import annotations
  2. from aiohttp import ClientSession
  3. import random
  4. import string
  5. import json
  6. import re
  7. import aiohttp
  8. import json
  9. from pathlib import Path
  10. from ..typing import AsyncResult, Messages, ImagesType
  11. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  12. from ..image import ImageResponse, to_data_uri
  13. from ..cookies import get_cookies_dir
  14. from .helper import format_prompt
  15. class Blackbox(AsyncGeneratorProvider, ProviderModelMixin):
  16. label = "Blackbox AI"
  17. url = "https://www.blackbox.ai"
  18. api_endpoint = "https://www.blackbox.ai/api/chat"
  19. working = True
  20. supports_stream = True
  21. supports_system_message = True
  22. supports_message_history = True
  23. default_model = 'blackboxai'
  24. default_vision_model = default_model
  25. default_image_model = 'flux'
  26. image_models = ['ImageGeneration', 'repomap']
  27. vision_models = [default_model, 'gpt-4o', 'gemini-pro', 'gemini-1.5-flash', 'llama-3.1-8b', 'llama-3.1-70b', 'llama-3.1-405b']
  28. userSelectedModel = ['gpt-4o', 'gemini-pro', 'claude-sonnet-3.5', 'blackboxai-pro']
  29. agentMode = {
  30. 'ImageGeneration': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "Image Generation"}
  31. }
  32. trendingAgentMode = {
  33. "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
  34. "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
  35. 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
  36. 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"},
  37. #
  38. 'Python Agent': {'mode': True, 'id': "Python Agent"},
  39. 'Java Agent': {'mode': True, 'id': "Java Agent"},
  40. 'JavaScript Agent': {'mode': True, 'id': "JavaScript Agent"},
  41. 'HTML Agent': {'mode': True, 'id': "HTML Agent"},
  42. 'Google Cloud Agent': {'mode': True, 'id': "Google Cloud Agent"},
  43. 'Android Developer': {'mode': True, 'id': "Android Developer"},
  44. 'Swift Developer': {'mode': True, 'id': "Swift Developer"},
  45. 'Next.js Agent': {'mode': True, 'id': "Next.js Agent"},
  46. 'MongoDB Agent': {'mode': True, 'id': "MongoDB Agent"},
  47. 'PyTorch Agent': {'mode': True, 'id': "PyTorch Agent"},
  48. 'React Agent': {'mode': True, 'id': "React Agent"},
  49. 'Xcode Agent': {'mode': True, 'id': "Xcode Agent"},
  50. 'AngularJS Agent': {'mode': True, 'id': "AngularJS Agent"},
  51. #
  52. 'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},
  53. #
  54. 'repomap': {'mode': True, 'id': "repomap"},
  55. #
  56. 'Heroku Agent': {'mode': True, 'id': "Heroku Agent"},
  57. 'Godot Agent': {'mode': True, 'id': "Godot Agent"},
  58. 'Go Agent': {'mode': True, 'id': "Go Agent"},
  59. 'Gitlab Agent': {'mode': True, 'id': "Gitlab Agent"},
  60. 'Git Agent': {'mode': True, 'id': "Git Agent"},
  61. 'Flask Agent': {'mode': True, 'id': "Flask Agent"},
  62. 'Firebase Agent': {'mode': True, 'id': "Firebase Agent"},
  63. 'FastAPI Agent': {'mode': True, 'id': "FastAPI Agent"},
  64. 'Erlang Agent': {'mode': True, 'id': "Erlang Agent"},
  65. 'Electron Agent': {'mode': True, 'id': "Electron Agent"},
  66. 'Docker Agent': {'mode': True, 'id': "Docker Agent"},
  67. 'DigitalOcean Agent': {'mode': True, 'id': "DigitalOcean Agent"},
  68. 'Bitbucket Agent': {'mode': True, 'id': "Bitbucket Agent"},
  69. 'Azure Agent': {'mode': True, 'id': "Azure Agent"},
  70. 'Flutter Agent': {'mode': True, 'id': "Flutter Agent"},
  71. 'Youtube Agent': {'mode': True, 'id': "Youtube Agent"},
  72. 'builder Agent': {'mode': True, 'id': "builder Agent"},
  73. }
  74. additional_prefixes = {
  75. 'gpt-4o': '@GPT-4o',
  76. 'gemini-pro': '@Gemini-PRO',
  77. 'claude-sonnet-3.5': '@Claude-Sonnet-3.5'
  78. }
  79. model_prefixes = {
  80. **{
  81. mode: f"@{value['id']}" for mode, value in trendingAgentMode.items()
  82. if mode not in ["gemini-1.5-flash", "llama-3.1-8b", "llama-3.1-70b", "llama-3.1-405b", "repomap"]
  83. },
  84. **additional_prefixes
  85. }
  86. models = list(dict.fromkeys([default_model, *userSelectedModel, *list(agentMode.keys()), *list(trendingAgentMode.keys())]))
  87. model_aliases = {
  88. ### chat ###
  89. "gpt-4": "gpt-4o",
  90. "gemini-flash": "gemini-1.5-flash",
  91. "claude-3.5-sonnet": "claude-sonnet-3.5",
  92. ### image ###
  93. "flux": "ImageGeneration",
  94. }
  95. @classmethod
  96. def _get_cache_file(cls) -> Path:
  97. dir = Path(get_cookies_dir())
  98. dir.mkdir(exist_ok=True)
  99. return dir / 'blackbox.json'
  100. @classmethod
  101. def _load_cached_value(cls) -> str | None:
  102. cache_file = cls._get_cache_file()
  103. if cache_file.exists():
  104. try:
  105. with open(cache_file, 'r') as f:
  106. data = json.load(f)
  107. return data.get('validated_value')
  108. except Exception as e:
  109. print(f"Error reading cache file: {e}")
  110. return None
  111. @classmethod
  112. def _save_cached_value(cls, value: str):
  113. cache_file = cls._get_cache_file()
  114. try:
  115. with open(cache_file, 'w') as f:
  116. json.dump({'validated_value': value}, f)
  117. except Exception as e:
  118. print(f"Error writing to cache file: {e}")
  119. @classmethod
  120. async def fetch_validated(cls):
  121. # Let's try to load the value from the cache first
  122. cached_value = cls._load_cached_value()
  123. if cached_value:
  124. return cached_value
  125. async with aiohttp.ClientSession() as session:
  126. try:
  127. async with session.get(cls.url) as response:
  128. if response.status != 200:
  129. print("Failed to load the page.")
  130. return cached_value
  131. page_content = await response.text()
  132. js_files = re.findall(r'static/chunks/\d{4}-[a-fA-F0-9]+\.js', page_content)
  133. 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})"')
  134. for js_file in js_files:
  135. js_url = f"{cls.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. match = key_pattern.search(js_content)
  140. if match:
  141. validated_value = match.group(1)
  142. # Save the new value to the cache file
  143. cls._save_cached_value(validated_value)
  144. return validated_value
  145. except Exception as e:
  146. print(f"Error fetching validated value: {e}")
  147. return cached_value
  148. @staticmethod
  149. def generate_id(length=7):
  150. characters = string.ascii_letters + string.digits
  151. return ''.join(random.choice(characters) for _ in range(length))
  152. @classmethod
  153. def add_prefix_to_messages(cls, messages: Messages, model: str) -> Messages:
  154. prefix = cls.model_prefixes.get(model, "")
  155. if not prefix:
  156. return messages
  157. new_messages = []
  158. for message in messages:
  159. new_message = message.copy()
  160. if message['role'] == 'user':
  161. new_message['content'] = (prefix + " " + message['content']).strip()
  162. new_messages.append(new_message)
  163. return new_messages
  164. @classmethod
  165. async def create_async_generator(
  166. cls,
  167. model: str,
  168. messages: Messages,
  169. prompt: str = None,
  170. proxy: str = None,
  171. web_search: bool = False,
  172. images: ImagesType = None,
  173. top_p: float = 0.9,
  174. temperature: float = 0.5,
  175. max_tokens: int = 1024,
  176. **kwargs
  177. ) -> AsyncResult:
  178. message_id = cls.generate_id()
  179. messages = cls.add_prefix_to_messages(messages, model)
  180. validated_value = await cls.fetch_validated()
  181. formatted_message = format_prompt(messages)
  182. model = cls.get_model(model)
  183. messages = [{"id": message_id, "content": formatted_message, "role": "user"}]
  184. if images is not None:
  185. messages[-1]['data'] = {
  186. "imagesData": [
  187. {
  188. "filePath": f"MultipleFiles/{image_name}",
  189. "contents": to_data_uri(image)
  190. }
  191. for image, image_name in images
  192. ],
  193. "fileText": "",
  194. "title": ""
  195. }
  196. headers = {
  197. 'accept': '*/*',
  198. 'content-type': 'application/json',
  199. 'origin': cls.url,
  200. 'referer': f'{cls.url}/',
  201. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
  202. }
  203. data = {
  204. "messages": messages,
  205. "id": message_id,
  206. "previewToken": None,
  207. "userId": None,
  208. "codeModelMode": True,
  209. "agentMode": cls.agentMode.get(model, {}) if model in cls.agentMode else {},
  210. "trendingAgentMode": cls.trendingAgentMode.get(model, {}) if model in cls.trendingAgentMode else {},
  211. "isMicMode": False,
  212. "userSystemPrompt": None,
  213. "maxTokens": max_tokens,
  214. "playgroundTopP": top_p,
  215. "playgroundTemperature": temperature,
  216. "isChromeExt": False,
  217. "githubToken": None,
  218. "clickedAnswer2": False,
  219. "clickedAnswer3": False,
  220. "clickedForceWebSearch": False,
  221. "visitFromDelta": False,
  222. "mobileClient": False,
  223. "userSelectedModel": model if model in cls.userSelectedModel else None,
  224. "webSearchMode": web_search,
  225. "validated": validated_value,
  226. "imageGenerationMode": False,
  227. "webSearchModePrompt": web_search
  228. }
  229. async with ClientSession(headers=headers) as session:
  230. async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
  231. response.raise_for_status()
  232. response_text = await response.text()
  233. if model in cls.image_models:
  234. image_matches = re.findall(r'!\[.*?\]\((https?://[^\)]+)\)', response_text)
  235. if image_matches:
  236. image_url = image_matches[0]
  237. yield ImageResponse(image_url, prompt)
  238. return
  239. response_text = re.sub(r'Generated by BLACKBOX.AI, try unlimited chat https://www.blackbox.ai', '', response_text, flags=re.DOTALL)
  240. json_match = re.search(r'\$~~~\$(.*?)\$~~~\$', response_text, re.DOTALL)
  241. if json_match:
  242. search_results = json.loads(json_match.group(1))
  243. answer = response_text.split('$~~~$')[-1].strip()
  244. formatted_response = f"{answer}\n\n**Source:**"
  245. for i, result in enumerate(search_results, 1):
  246. formatted_response += f"\n{i}. {result['title']}: {result['link']}"
  247. yield formatted_response
  248. else:
  249. yield response_text.strip()