ChatGptt.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from __future__ import annotations
  2. import os
  3. import re
  4. from aiohttp import ClientSession
  5. from ...typing import AsyncResult, Messages
  6. from ...requests.raise_for_status import raise_for_status
  7. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  8. from ..helper import format_prompt
  9. class ChatGptt(AsyncGeneratorProvider, ProviderModelMixin):
  10. url = "https://chatgptt.me"
  11. api_endpoint = "https://chatgptt.me/wp-admin/admin-ajax.php"
  12. working = False
  13. supports_stream = True
  14. supports_system_message = True
  15. supports_message_history = True
  16. default_model = 'gpt-4o'
  17. models = ['gpt-4', default_model, 'gpt-4o-mini']
  18. @classmethod
  19. async def create_async_generator(
  20. cls,
  21. model: str,
  22. messages: Messages,
  23. proxy: str = None,
  24. **kwargs
  25. ) -> AsyncResult:
  26. model = cls.get_model(model)
  27. headers = {
  28. "authority": "chatgptt.me",
  29. "accept": "application/json",
  30. "origin": cls.url,
  31. "referer": f"{cls.url}/chat",
  32. "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
  33. }
  34. async with ClientSession(headers=headers) as session:
  35. # Get initial page content
  36. initial_response = await session.get(cls.url)
  37. await raise_for_status(initial_response)
  38. html = await initial_response.text()
  39. # Extract nonce and post ID with error handling
  40. nonce_match = re.search(r'data-nonce=["\']([^"\']+)["\']', html)
  41. post_id_match = re.search(r'data-post-id=["\']([^"\']+)["\']', html)
  42. if not nonce_match or not post_id_match:
  43. raise RuntimeError("Required authentication tokens not found in page HTML")
  44. nonce_ = nonce_match.group(1)
  45. post_id = post_id_match.group(1)
  46. # Prepare payload with session data
  47. payload = {
  48. '_wpnonce': nonce_,
  49. 'post_id': post_id,
  50. 'url': cls.url,
  51. 'action': 'wpaicg_chat_shortcode_message',
  52. 'message': format_prompt(messages),
  53. 'bot_id': '0',
  54. 'chatbot_identity': 'shortcode',
  55. 'wpaicg_chat_client_id': os.urandom(5).hex(),
  56. 'wpaicg_chat_history': None
  57. }
  58. # Stream the response
  59. async with session.post(cls.api_endpoint, headers=headers, data=payload, proxy=proxy) as response:
  60. await raise_for_status(response)
  61. result = await response.json()
  62. yield result['data']