ChatgptFree.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. from __future__ import annotations
  2. import re
  3. import json
  4. import asyncio
  5. from ...requests import StreamSession, raise_for_status
  6. from ...typing import Messages, AsyncGenerator
  7. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  8. from ..helper import format_prompt
  9. class ChatgptFree(AsyncGeneratorProvider, ProviderModelMixin):
  10. url = "https://chatgptfree.ai"
  11. working = False
  12. _post_id = None
  13. _nonce = None
  14. default_model = 'gpt-4o-mini-2024-07-18'
  15. models = [default_model]
  16. model_aliases = {
  17. "gpt-4o-mini": "gpt-4o-mini-2024-07-18",
  18. }
  19. @classmethod
  20. async def create_async_generator(
  21. cls,
  22. model: str,
  23. messages: Messages,
  24. proxy: str = None,
  25. timeout: int = 120,
  26. cookies: dict = None,
  27. **kwargs
  28. ) -> AsyncGenerator[str, None]:
  29. headers = {
  30. 'authority': 'chatgptfree.ai',
  31. 'accept': '*/*',
  32. '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',
  33. 'origin': 'https://chatgptfree.ai',
  34. 'referer': 'https://chatgptfree.ai/chat/',
  35. 'sec-ch-ua': '"Chromium";v="118", "Google Chrome";v="118", "Not=A?Brand";v="99"',
  36. 'sec-ch-ua-mobile': '?0',
  37. 'sec-ch-ua-platform': '"macOS"',
  38. 'sec-fetch-dest': 'empty',
  39. 'sec-fetch-mode': 'cors',
  40. 'sec-fetch-site': 'same-origin',
  41. 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
  42. }
  43. async with StreamSession(
  44. headers=headers,
  45. cookies=cookies,
  46. impersonate="chrome",
  47. proxies={"all": proxy},
  48. timeout=timeout
  49. ) as session:
  50. if not cls._nonce:
  51. async with session.get(f"{cls.url}/") as response:
  52. await raise_for_status(response)
  53. response = await response.text()
  54. result = re.search(r'data-post-id="([0-9]+)"', response)
  55. if not result:
  56. raise RuntimeError("No post id found")
  57. cls._post_id = result.group(1)
  58. result = re.search(r'data-nonce="(.*?)"', response)
  59. if result:
  60. cls._nonce = result.group(1)
  61. else:
  62. raise RuntimeError("No nonce found")
  63. prompt = format_prompt(messages)
  64. data = {
  65. "_wpnonce": cls._nonce,
  66. "post_id": cls._post_id,
  67. "url": cls.url,
  68. "action": "wpaicg_chat_shortcode_message",
  69. "message": prompt,
  70. "bot_id": "0"
  71. }
  72. async with session.post(f"{cls.url}/wp-admin/admin-ajax.php", data=data, cookies=cookies) as response:
  73. await raise_for_status(response)
  74. buffer = ""
  75. async for line in response.iter_lines():
  76. line = line.decode('utf-8').strip()
  77. if line.startswith('data: '):
  78. data = line[6:]
  79. if data == '[DONE]':
  80. break
  81. try:
  82. json_data = json.loads(data)
  83. content = json_data['choices'][0]['delta'].get('content', '')
  84. if content:
  85. yield content
  86. except json.JSONDecodeError:
  87. continue
  88. elif line:
  89. buffer += line
  90. if buffer:
  91. try:
  92. json_response = json.loads(buffer)
  93. if 'data' in json_response:
  94. yield json_response['data']
  95. except json.JSONDecodeError:
  96. print(f"Failed to decode final JSON. Buffer content: {buffer}")