AiChats.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from __future__ import annotations
  2. import json
  3. import base64
  4. from aiohttp import ClientSession
  5. from ...typing import AsyncResult, Messages
  6. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  7. from ...image import ImageResponse
  8. from ..helper import format_prompt
  9. class AiChats(AsyncGeneratorProvider, ProviderModelMixin):
  10. url = "https://ai-chats.org"
  11. api_endpoint = "https://ai-chats.org/chat/send2/"
  12. working = False
  13. supports_message_history = True
  14. default_model = 'gpt-4'
  15. models = ['gpt-4', 'dalle']
  16. @classmethod
  17. async def create_async_generator(
  18. cls,
  19. model: str,
  20. messages: Messages,
  21. proxy: str = None,
  22. **kwargs
  23. ) -> AsyncResult:
  24. headers = {
  25. "accept": "application/json, text/event-stream",
  26. "accept-language": "en-US,en;q=0.9",
  27. "cache-control": "no-cache",
  28. "content-type": "application/json",
  29. "origin": cls.url,
  30. "pragma": "no-cache",
  31. "referer": f"{cls.url}/{'image' if model == 'dalle' else 'chat'}/",
  32. "sec-ch-ua": '"Chromium";v="127", "Not)A;Brand";v="99"',
  33. "sec-ch-ua-mobile": "?0",
  34. "sec-ch-ua-platform": '"Linux"',
  35. "sec-fetch-dest": "empty",
  36. "sec-fetch-mode": "cors",
  37. "sec-fetch-site": "same-origin",
  38. "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
  39. 'cookie': 'muVyak=LSFNvUWqdgKkGprbDBsfieIoEMzjOQ; LSFNvUWqdgKkGprbDBsfieIoEMzjOQ=ac28831b98143847e83dbe004404e619-1725548624-1725548621; muVyak_hits=9; ai-chat-front=9d714d5dc46a6b47607c9a55e7d12a95; _csrf-front=76c23dc0a013e5d1e21baad2e6ba2b5fdab8d3d8a1d1281aa292353f8147b057a%3A2%3A%7Bi%3A0%3Bs%3A11%3A%22_csrf-front%22%3Bi%3A1%3Bs%3A32%3A%22K9lz0ezsNPMNnfpd_8gT5yEeh-55-cch%22%3B%7D',
  40. }
  41. async with ClientSession(headers=headers) as session:
  42. if model == 'dalle':
  43. prompt = messages[-1]['content'] if messages else ""
  44. else:
  45. prompt = format_prompt(messages)
  46. data = {
  47. "type": "image" if model == 'dalle' else "chat",
  48. "messagesHistory": [
  49. {
  50. "from": "you",
  51. "content": prompt
  52. }
  53. ]
  54. }
  55. try:
  56. async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
  57. response.raise_for_status()
  58. if model == 'dalle':
  59. response_json = await response.json()
  60. if 'data' in response_json and response_json['data']:
  61. image_url = response_json['data'][0].get('url')
  62. if image_url:
  63. async with session.get(image_url) as img_response:
  64. img_response.raise_for_status()
  65. image_data = await img_response.read()
  66. base64_image = base64.b64encode(image_data).decode('utf-8')
  67. base64_url = f"data:image/png;base64,{base64_image}"
  68. yield ImageResponse(base64_url, prompt)
  69. else:
  70. yield f"Error: No image URL found in the response. Full response: {response_json}"
  71. else:
  72. yield f"Error: Unexpected response format. Full response: {response_json}"
  73. else:
  74. full_response = await response.text()
  75. message = ""
  76. for line in full_response.split('\n'):
  77. if line.startswith('data: ') and line != 'data: ':
  78. message += line[6:]
  79. message = message.strip()
  80. yield message
  81. except Exception as e:
  82. yield f"Error occurred: {str(e)}"
  83. @classmethod
  84. async def create_async(
  85. cls,
  86. model: str,
  87. messages: Messages,
  88. proxy: str = None,
  89. **kwargs
  90. ) -> str:
  91. async for response in cls.create_async_generator(model, messages, proxy, **kwargs):
  92. if isinstance(response, ImageResponse):
  93. return response.images[0]
  94. return response