ChatgptFree.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from __future__ import annotations
  2. import re
  3. from ..requests import StreamSession
  4. from ..typing import Messages
  5. from .base_provider import AsyncProvider
  6. from .helper import format_prompt, get_cookies
  7. class ChatgptFree(AsyncProvider):
  8. url = "https://chatgptfree.ai"
  9. supports_gpt_35_turbo = True
  10. working = False
  11. _post_id = None
  12. _nonce = None
  13. @classmethod
  14. async def create_async(
  15. cls,
  16. model: str,
  17. messages: Messages,
  18. proxy: str = None,
  19. timeout: int = 120,
  20. cookies: dict = None,
  21. **kwargs
  22. ) -> str:
  23. if not cookies:
  24. cookies = get_cookies('chatgptfree.ai')
  25. if not cookies:
  26. raise RuntimeError(f"g4f.provider.{cls.__name__} requires cookies [refresh https://chatgptfree.ai on chrome]")
  27. headers = {
  28. 'authority': 'chatgptfree.ai',
  29. 'accept': '*/*',
  30. 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
  31. 'origin': 'https://chatgptfree.ai',
  32. 'referer': 'https://chatgptfree.ai/chat/',
  33. 'sec-ch-ua': '"Chromium";v="118", "Google Chrome";v="118", "Not=A?Brand";v="99"',
  34. 'sec-ch-ua-mobile': '?0',
  35. 'sec-ch-ua-platform': '"macOS"',
  36. 'sec-fetch-dest': 'empty',
  37. 'sec-fetch-mode': 'cors',
  38. 'sec-fetch-site': 'same-origin',
  39. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
  40. }
  41. async with StreamSession(
  42. headers=headers,
  43. cookies=cookies,
  44. impersonate="chrome107",
  45. proxies={"https": proxy},
  46. timeout=timeout
  47. ) as session:
  48. if not cls._nonce:
  49. async with session.get(f"{cls.url}/") as response:
  50. response.raise_for_status()
  51. response = await response.text()
  52. result = re.search(r'data-post-id="([0-9]+)"', response)
  53. if not result:
  54. raise RuntimeError("No post id found")
  55. cls._post_id = result.group(1)
  56. result = re.search(r'data-nonce="(.*?)"', response)
  57. if result:
  58. cls._nonce = result.group(1)
  59. else:
  60. raise RuntimeError("No nonce found")
  61. prompt = format_prompt(messages)
  62. data = {
  63. "_wpnonce": cls._nonce,
  64. "post_id": cls._post_id,
  65. "url": cls.url,
  66. "action": "wpaicg_chat_shortcode_message",
  67. "message": prompt,
  68. "bot_id": "0"
  69. }
  70. async with session.post(f"{cls.url}/wp-admin/admin-ajax.php", data=data, cookies=cookies) as response:
  71. response.raise_for_status()
  72. return (await response.json())["data"]