AIChatFree.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from __future__ import annotations
  2. import time
  3. from hashlib import sha256
  4. from aiohttp import BaseConnector, ClientSession
  5. from ...errors import RateLimitError
  6. from ...requests import raise_for_status
  7. from ...requests.aiohttp import get_connector
  8. from ...typing import AsyncResult, Messages
  9. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  10. class AIChatFree(AsyncGeneratorProvider, ProviderModelMixin):
  11. url = "https://aichatfree.info/"
  12. working = False
  13. supports_stream = True
  14. supports_message_history = True
  15. default_model = 'gemini-pro'
  16. @classmethod
  17. async def create_async_generator(
  18. cls,
  19. model: str,
  20. messages: Messages,
  21. proxy: str = None,
  22. connector: BaseConnector = None,
  23. **kwargs,
  24. ) -> AsyncResult:
  25. headers = {
  26. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0",
  27. "Accept": "*/*",
  28. "Accept-Language": "en-US,en;q=0.5",
  29. "Accept-Encoding": "gzip, deflate, br",
  30. "Content-Type": "text/plain;charset=UTF-8",
  31. "Referer": f"{cls.url}/",
  32. "Origin": cls.url,
  33. "Sec-Fetch-Dest": "empty",
  34. "Sec-Fetch-Mode": "cors",
  35. "Sec-Fetch-Site": "same-origin",
  36. "Connection": "keep-alive",
  37. "TE": "trailers",
  38. }
  39. async with ClientSession(
  40. connector=get_connector(connector, proxy), headers=headers
  41. ) as session:
  42. timestamp = int(time.time() * 1e3)
  43. data = {
  44. "messages": [
  45. {
  46. "role": "model" if message["role"] == "assistant" else "user",
  47. "parts": [{"text": message["content"]}],
  48. }
  49. for message in messages
  50. ],
  51. "time": timestamp,
  52. "pass": None,
  53. "sign": generate_signature(timestamp, messages[-1]["content"]),
  54. }
  55. async with session.post(
  56. f"{cls.url}/api/generate", json=data, proxy=proxy
  57. ) as response:
  58. if response.status == 500:
  59. if "Quota exceeded" in await response.text():
  60. raise RateLimitError(
  61. f"Response {response.status}: Rate limit reached"
  62. )
  63. await raise_for_status(response)
  64. async for chunk in response.content.iter_any():
  65. yield chunk.decode(errors="ignore")
  66. def generate_signature(time: int, text: str, secret: str = ""):
  67. message = f"{time}:{text}:{secret}"
  68. return sha256(message.encode()).hexdigest()