Blackbox.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. from ..typing import AsyncResult, Messages, ImageType
  9. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  10. from ..image import ImageResponse, to_data_uri
  11. class Blackbox(AsyncGeneratorProvider, ProviderModelMixin):
  12. label = "Blackbox AI"
  13. url = "https://www.blackbox.ai"
  14. api_endpoint = "https://www.blackbox.ai/api/chat"
  15. working = True
  16. supports_stream = True
  17. supports_system_message = True
  18. supports_message_history = True
  19. _last_validated_value = None
  20. default_model = 'blackboxai'
  21. image_models = ['Image Generation', 'repomap']
  22. userSelectedModel = ['gpt-4o', 'gemini-pro', 'claude-sonnet-3.5', 'blackboxai-pro']
  23. agentMode = {
  24. 'Image Generation': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "Image Generation"},
  25. }
  26. trendingAgentMode = {
  27. "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
  28. "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
  29. 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
  30. 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"},
  31. #
  32. 'Python Agent': {'mode': True, 'id': "Python Agent"},
  33. 'Java Agent': {'mode': True, 'id': "Java Agent"},
  34. 'JavaScript Agent': {'mode': True, 'id': "JavaScript Agent"},
  35. 'HTML Agent': {'mode': True, 'id': "HTML Agent"},
  36. 'Google Cloud Agent': {'mode': True, 'id': "Google Cloud Agent"},
  37. 'Android Developer': {'mode': True, 'id': "Android Developer"},
  38. 'Swift Developer': {'mode': True, 'id': "Swift Developer"},
  39. 'Next.js Agent': {'mode': True, 'id': "Next.js Agent"},
  40. 'MongoDB Agent': {'mode': True, 'id': "MongoDB Agent"},
  41. 'PyTorch Agent': {'mode': True, 'id': "PyTorch Agent"},
  42. 'React Agent': {'mode': True, 'id': "React Agent"},
  43. 'Xcode Agent': {'mode': True, 'id': "Xcode Agent"},
  44. 'AngularJS Agent': {'mode': True, 'id': "AngularJS Agent"},
  45. 'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},
  46. #
  47. 'repomap': {'mode': True, 'id': "repomap"},
  48. #
  49. 'Heroku Agent': {'mode': True, 'id': "Heroku Agent"},
  50. 'Godot Agent': {'mode': True, 'id': "Godot Agent"},
  51. 'Go Agent': {'mode': True, 'id': "Go Agent"},
  52. 'Gitlab Agent': {'mode': True, 'id': "Gitlab Agent"},
  53. 'Git Agent': {'mode': True, 'id': "Git Agent"},
  54. 'Flask Agent': {'mode': True, 'id': "Flask Agent"},
  55. 'Firebase Agent': {'mode': True, 'id': "Firebase Agent"},
  56. 'FastAPI Agent': {'mode': True, 'id': "FastAPI Agent"},
  57. 'Erlang Agent': {'mode': True, 'id': "Erlang Agent"},
  58. 'Electron Agent': {'mode': True, 'id': "Electron Agent"},
  59. 'Docker Agent': {'mode': True, 'id': "Docker Agent"},
  60. 'DigitalOcean Agent': {'mode': True, 'id': "DigitalOcean Agent"},
  61. 'Bitbucket Agent': {'mode': True, 'id': "Bitbucket Agent"},
  62. 'Azure Agent': {'mode': True, 'id': "Azure Agent"},
  63. 'Flutter Agent': {'mode': True, 'id': "Flutter Agent"},
  64. 'Youtube Agent': {'mode': True, 'id': "Youtube Agent"},
  65. 'builder Agent': {'mode': True, 'id': "builder Agent"},
  66. }
  67. model_prefixes = {mode: f"@{value['id']}" for mode, value in trendingAgentMode.items() if mode not in ["gemini-1.5-flash", "llama-3.1-8b", "llama-3.1-70b", "llama-3.1-405b", "repomap"]}
  68. models = [default_model, *userSelectedModel, *list(agentMode.keys()), *list(trendingAgentMode.keys())]
  69. model_aliases = {
  70. "gemini-flash": "gemini-1.5-flash",
  71. "claude-3.5-sonnet": "claude-sonnet-3.5",
  72. "flux": "Image Generation",
  73. }
  74. @classmethod
  75. async def fetch_validated(cls):
  76. # If the key is already stored in memory, return it
  77. if cls._last_validated_value:
  78. return cls._last_validated_value
  79. # If the key is not found, perform a search
  80. async with aiohttp.ClientSession() as session:
  81. try:
  82. async with session.get(cls.url) as response:
  83. if response.status != 200:
  84. print("Failed to load the page.")
  85. return cls._last_validated_value
  86. page_content = await response.text()
  87. js_files = re.findall(r'static/chunks/\d{4}-[a-fA-F0-9]+\.js', page_content)
  88. 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})"')
  89. for js_file in js_files:
  90. js_url = f"{cls.url}/_next/{js_file}"
  91. async with session.get(js_url) as js_response:
  92. if js_response.status == 200:
  93. js_content = await js_response.text()
  94. match = key_pattern.search(js_content)
  95. if match:
  96. validated_value = match.group(1)
  97. cls._last_validated_value = validated_value # Keep in mind
  98. return validated_value
  99. except Exception as e:
  100. print(f"Error fetching validated value: {e}")
  101. return cls._last_validated_value
  102. @staticmethod
  103. def generate_id(length=7):
  104. characters = string.ascii_letters + string.digits
  105. return ''.join(random.choice(characters) for _ in range(length))
  106. @classmethod
  107. def add_prefix_to_messages(cls, messages: Messages, model: str) -> Messages:
  108. prefix = cls.model_prefixes.get(model, "")
  109. if not prefix:
  110. return messages
  111. new_messages = []
  112. for message in messages:
  113. new_message = message.copy()
  114. if message['role'] == 'user':
  115. new_message['content'] = (prefix + " " + message['content']).strip()
  116. new_messages.append(new_message)
  117. return new_messages
  118. @classmethod
  119. def get_model(cls, model: str) -> str:
  120. if model in cls.models:
  121. return model
  122. elif model in cls.model_aliases:
  123. return cls.model_aliases[model]
  124. else:
  125. return cls.default_model
  126. @classmethod
  127. async def create_async_generator(
  128. cls,
  129. model: str,
  130. messages: Messages,
  131. proxy: str = None,
  132. web_search: bool = False,
  133. image: ImageType = None,
  134. image_name: str = None,
  135. **kwargs
  136. ) -> AsyncResult:
  137. model = cls.get_model(model)
  138. message_id = cls.generate_id()
  139. messages_with_prefix = cls.add_prefix_to_messages(messages, model)
  140. validated_value = await cls.fetch_validated()
  141. if image is not None:
  142. messages_with_prefix[-1]['data'] = {
  143. 'fileText': '',
  144. 'imageBase64': to_data_uri(image),
  145. 'title': image_name
  146. }
  147. headers = {
  148. 'accept': '*/*',
  149. 'accept-language': 'en-US,en;q=0.9',
  150. 'cache-control': 'no-cache',
  151. 'content-type': 'application/json',
  152. 'origin': cls.url,
  153. 'pragma': 'no-cache',
  154. 'priority': 'u=1, i',
  155. 'referer': f'{cls.url}/',
  156. 'sec-ch-ua': '"Not?A_Brand";v="99", "Chromium";v="130"',
  157. 'sec-ch-ua-mobile': '?0',
  158. 'sec-ch-ua-platform': '"Linux"',
  159. 'sec-fetch-dest': 'empty',
  160. 'sec-fetch-mode': 'cors',
  161. 'sec-fetch-site': 'same-origin',
  162. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
  163. }
  164. data = {
  165. "messages": messages_with_prefix,
  166. "id": message_id,
  167. "previewToken": None,
  168. "userId": None,
  169. "codeModelMode": True,
  170. "agentMode": cls.agentMode.get(model, {}) if model in cls.agentMode else {},
  171. "trendingAgentMode": cls.trendingAgentMode.get(model, {}) if model in cls.trendingAgentMode else {},
  172. "isMicMode": False,
  173. "userSystemPrompt": None,
  174. "maxTokens": 1024,
  175. "playgroundTopP": 0.9,
  176. "playgroundTemperature": 0.5,
  177. "isChromeExt": False,
  178. "githubToken": None,
  179. "clickedAnswer2": False,
  180. "clickedAnswer3": False,
  181. "clickedForceWebSearch": False,
  182. "visitFromDelta": False,
  183. "mobileClient": False,
  184. "userSelectedModel": model if model in cls.userSelectedModel else None,
  185. "webSearchMode": web_search,
  186. "validated": validated_value,
  187. }
  188. async with ClientSession(headers=headers) as session:
  189. async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
  190. response.raise_for_status()
  191. response_text = await response.text()
  192. if model in cls.image_models:
  193. image_matches = re.findall(r'!\[.*?\]\((https?://[^\)]+)\)', response_text)
  194. if image_matches:
  195. image_url = image_matches[0]
  196. image_response = ImageResponse(images=[image_url], alt="Generated Image")
  197. yield image_response
  198. return
  199. response_text = re.sub(r'Generated by BLACKBOX.AI, try unlimited chat https://www.blackbox.ai', '', response_text, flags=re.DOTALL)
  200. json_match = re.search(r'\$~~~\$(.*?)\$~~~\$', response_text, re.DOTALL)
  201. if json_match:
  202. search_results = json.loads(json_match.group(1))
  203. answer = response_text.split('$~~~$')[-1].strip()
  204. formatted_response = f"{answer}\n\n**Source:**"
  205. for i, result in enumerate(search_results, 1):
  206. formatted_response += f"\n{i}. {result['title']}: {result['link']}"
  207. yield formatted_response
  208. else:
  209. yield response_text.strip()