Airforce.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import json
  2. import random
  3. import re
  4. import requests
  5. from aiohttp import ClientSession
  6. from typing import List
  7. from requests.packages.urllib3.exceptions import InsecureRequestWarning
  8. from ..typing import AsyncResult, Messages
  9. from ..image import ImageResponse
  10. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  11. from .. import debug
  12. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  13. def split_message(message: str, max_length: int = 1000) -> List[str]:
  14. """Splits the message into parts up to (max_length)."""
  15. chunks = []
  16. while len(message) > max_length:
  17. split_point = message.rfind(' ', 0, max_length)
  18. if split_point == -1:
  19. split_point = max_length
  20. chunks.append(message[:split_point])
  21. message = message[split_point:].strip()
  22. if message:
  23. chunks.append(message)
  24. return chunks
  25. class Airforce(AsyncGeneratorProvider, ProviderModelMixin):
  26. url = "https://llmplayground.net"
  27. api_endpoint_completions = "https://api.airforce/chat/completions"
  28. api_endpoint_imagine2 = "https://api.airforce/imagine2"
  29. working = True
  30. supports_stream = False
  31. supports_system_message = True
  32. supports_message_history = True
  33. default_model = "gpt-4o-mini"
  34. default_image_model = "flux"
  35. hidden_models = {"Flux-1.1-Pro"}
  36. additional_models_imagine = ["flux-1.1-pro", "midjourney", "dall-e-3"]
  37. model_aliases = {
  38. # Alias mappings for models
  39. "gpt-4": "gpt-4o",
  40. "openchat-3.5": "openchat-3.5-0106",
  41. "deepseek-coder": "deepseek-coder-6.7b-instruct",
  42. "hermes-2-dpo": "Nous-Hermes-2-Mixtral-8x7B-DPO",
  43. "hermes-2-pro": "hermes-2-pro-mistral-7b",
  44. "openhermes-2.5": "openhermes-2.5-mistral-7b",
  45. "lfm-40b": "lfm-40b-moe",
  46. "german-7b": "discolm-german-7b-v1",
  47. "llama-2-7b": "llama-2-7b-chat-int8",
  48. "llama-3.1-70b": "llama-3.1-70b-turbo",
  49. "neural-7b": "neural-chat-7b-v3-1",
  50. "zephyr-7b": "zephyr-7b-beta",
  51. "evil": "any-uncensored",
  52. "sdxl": "stable-diffusion-xl-lightning",
  53. "sdxl": "stable-diffusion-xl-base",
  54. "flux-pro": "flux-1.1-pro",
  55. "llama-3.1-8b": "llama-3.1-8b-chat"
  56. }
  57. @classmethod
  58. def get_models(cls):
  59. if not cls.image_models:
  60. try:
  61. url = "https://api.airforce/imagine2/models"
  62. response = requests.get(url, verify=False)
  63. response.raise_for_status()
  64. cls.image_models = response.json()
  65. cls.image_models.extend(cls.additional_models_imagine)
  66. except Exception as e:
  67. debug.log(f"Error fetching image models: {e}")
  68. if not cls.models:
  69. try:
  70. url = "https://api.airforce/models"
  71. response = requests.get(url, verify=False)
  72. response.raise_for_status()
  73. data = response.json()
  74. cls.models = [model['id'] for model in data['data']]
  75. cls.models.extend(cls.image_models)
  76. cls.models = [model for model in cls.models if model not in cls.hidden_models]
  77. except Exception as e:
  78. debug.log(f"Error fetching text models: {e}")
  79. return cls.models
  80. @classmethod
  81. async def check_api_key(cls, api_key: str) -> bool:
  82. """
  83. Always returns True to allow all models.
  84. """
  85. if not api_key or api_key == "null":
  86. return True # No restrictions if no key.
  87. headers = {
  88. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
  89. "Accept": "*/*",
  90. }
  91. try:
  92. async with ClientSession(headers=headers) as session:
  93. async with session.get(f"https://api.airforce/check?key={api_key}") as response:
  94. if response.status == 200:
  95. data = await response.json()
  96. return data.get('info') in ['Sponsor key', 'Premium key']
  97. return False
  98. except Exception as e:
  99. print(f"Error checking API key: {str(e)}")
  100. return False
  101. @classmethod
  102. def _filter_content(cls, part_response: str) -> str:
  103. """
  104. Filters out unwanted content from the partial response.
  105. """
  106. part_response = re.sub(
  107. r"One message exceeds the \d+chars per message limit\..+https:\/\/discord\.com\/invite\/\S+",
  108. '',
  109. part_response
  110. )
  111. part_response = re.sub(
  112. r"Rate limit \(\d+\/minute\) exceeded\. Join our discord for more: .+https:\/\/discord\.com\/invite\/\S+",
  113. '',
  114. part_response
  115. )
  116. return part_response
  117. @classmethod
  118. def _filter_response(cls, response: str) -> str:
  119. """
  120. Filters the full response to remove system errors and other unwanted text.
  121. """
  122. filtered_response = re.sub(r"\[ERROR\] '\w{8}-\w{4}-\w{4}-\w{4}-\w{12}'", '', response) # any-uncensored
  123. filtered_response = re.sub(r'<\|im_end\|>', '', filtered_response) # remove <|im_end|> token
  124. filtered_response = re.sub(r'</s>', '', filtered_response) # neural-chat-7b-v3-1
  125. filtered_response = re.sub(r'^(Assistant: |AI: |ANSWER: |Output: )', '', filtered_response) # phi-2
  126. filtered_response = cls._filter_content(filtered_response)
  127. return filtered_response
  128. @classmethod
  129. async def generate_image(
  130. cls,
  131. model: str,
  132. prompt: str,
  133. api_key: str,
  134. size: str,
  135. seed: int,
  136. proxy: str = None
  137. ) -> AsyncResult:
  138. headers = {
  139. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
  140. "Accept": "image/avif,image/webp,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5",
  141. "Accept-Language": "en-US,en;q=0.5",
  142. "Accept-Encoding": "gzip, deflate, br, zstd",
  143. "Content-Type": "application/json",
  144. "Authorization": f"Bearer {api_key}",
  145. }
  146. params = {"model": model, "prompt": prompt, "size": size, "seed": seed}
  147. async with ClientSession(headers=headers) as session:
  148. async with session.get(cls.api_endpoint_imagine2, params=params, proxy=proxy) as response:
  149. if response.status == 200:
  150. image_url = str(response.url)
  151. yield ImageResponse(images=image_url, alt=prompt)
  152. else:
  153. error_text = await response.text()
  154. raise RuntimeError(f"Image generation failed: {response.status} - {error_text}")
  155. @classmethod
  156. async def generate_text(
  157. cls,
  158. model: str,
  159. messages: Messages,
  160. max_tokens: int,
  161. temperature: float,
  162. top_p: float,
  163. stream: bool,
  164. api_key: str,
  165. proxy: str = None
  166. ) -> AsyncResult:
  167. """
  168. Generates text, buffers the response, filters it, and returns the final result.
  169. """
  170. headers = {
  171. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
  172. "Accept": "application/json, text/event-stream",
  173. "Accept-Language": "en-US,en;q=0.5",
  174. "Accept-Encoding": "gzip, deflate, br, zstd",
  175. "Content-Type": "application/json",
  176. "Authorization": f"Bearer {api_key}",
  177. }
  178. full_message = "\n".join([msg['content'] for msg in messages])
  179. message_chunks = split_message(full_message, max_length=1000)
  180. data = {
  181. "messages": [{"role": "user", "content": chunk} for chunk in message_chunks],
  182. "model": model,
  183. "max_tokens": max_tokens,
  184. "temperature": temperature,
  185. "top_p": top_p,
  186. "stream": stream,
  187. }
  188. async with ClientSession(headers=headers) as session:
  189. async with session.post(cls.api_endpoint_completions, json=data, proxy=proxy) as response:
  190. response.raise_for_status()
  191. if stream:
  192. buffer = [] # Buffer to collect partial responses
  193. async for line in response.content:
  194. line = line.decode('utf-8').strip()
  195. if line.startswith('data: '):
  196. try:
  197. json_str = line[6:] # Remove 'data: ' prefix
  198. chunk = json.loads(json_str)
  199. if 'choices' in chunk and chunk['choices']:
  200. delta = chunk['choices'][0].get('delta', {})
  201. if 'content' in delta:
  202. buffer.append(delta['content'])
  203. except json.JSONDecodeError:
  204. continue
  205. # Combine the buffered response and filter it
  206. filtered_response = cls._filter_response(''.join(buffer))
  207. yield filtered_response
  208. else:
  209. # Non-streaming response
  210. result = await response.json()
  211. if 'choices' in result and result['choices']:
  212. message = result['choices'][0].get('message', {})
  213. content = message.get('content', '')
  214. filtered_response = cls._filter_response(content)
  215. yield filtered_response
  216. @classmethod
  217. async def create_async_generator(
  218. cls,
  219. model: str,
  220. messages: Messages,
  221. prompt: str = None,
  222. proxy: str = None,
  223. max_tokens: int = 4096,
  224. temperature: float = 1,
  225. top_p: float = 1,
  226. stream: bool = True,
  227. api_key: str = None,
  228. size: str = "1:1",
  229. seed: int = None,
  230. **kwargs
  231. ) -> AsyncResult:
  232. if not await cls.check_api_key(api_key):
  233. pass
  234. model = cls.get_model(model)
  235. if model in cls.image_models:
  236. if prompt is None:
  237. prompt = messages[-1]['content']
  238. if seed is None:
  239. seed = random.randint(0, 10000)
  240. async for result in cls.generate_image(model, prompt, api_key, size, seed, proxy):
  241. yield result
  242. else:
  243. async for result in cls.generate_text(model, messages, max_tokens, temperature, top_p, stream, api_key, proxy):
  244. yield result