ChatGpt.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. from __future__ import annotations
  2. from ..typing import Messages, CreateResult
  3. from ..providers.base_provider import AbstractProvider, ProviderModelMixin
  4. import time
  5. import uuid
  6. import random
  7. import json
  8. from requests import Session
  9. from .openai.new import (
  10. get_config,
  11. get_answer_token,
  12. process_turnstile,
  13. get_requirements_token
  14. )
  15. def format_conversation(messages: list):
  16. conversation = []
  17. for message in messages:
  18. conversation.append({
  19. 'id': str(uuid.uuid4()),
  20. 'author': {
  21. 'role': message['role'],
  22. },
  23. 'content': {
  24. 'content_type': 'text',
  25. 'parts': [
  26. message['content'],
  27. ],
  28. },
  29. 'metadata': {
  30. 'serialization_metadata': {
  31. 'custom_symbol_offsets': [],
  32. },
  33. },
  34. 'create_time': round(time.time(), 3),
  35. })
  36. return conversation
  37. def init_session(user_agent):
  38. session = Session()
  39. cookies = {
  40. '_dd_s': '',
  41. }
  42. headers = {
  43. 'accept': '*/*',
  44. 'accept-language': 'en-US,en;q=0.8',
  45. 'cache-control': 'no-cache',
  46. 'pragma': 'no-cache',
  47. 'priority': 'u=0, i',
  48. 'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
  49. 'sec-ch-ua-arch': '"arm"',
  50. 'sec-ch-ua-bitness': '"64"',
  51. 'sec-ch-ua-mobile': '?0',
  52. 'sec-ch-ua-model': '""',
  53. 'sec-ch-ua-platform': '"macOS"',
  54. 'sec-ch-ua-platform-version': '"14.4.0"',
  55. 'sec-fetch-dest': 'document',
  56. 'sec-fetch-mode': 'navigate',
  57. 'sec-fetch-site': 'none',
  58. 'sec-fetch-user': '?1',
  59. 'upgrade-insecure-requests': '1',
  60. 'user-agent': user_agent,
  61. }
  62. session.get('https://chatgpt.com/', cookies=cookies, headers=headers)
  63. return session
  64. class ChatGpt(AbstractProvider, ProviderModelMixin):
  65. label = "ChatGpt"
  66. url = "https://chatgpt.com"
  67. working = True
  68. supports_message_history = True
  69. supports_system_message = True
  70. supports_stream = True
  71. default_model = 'auto'
  72. models = [
  73. default_model,
  74. 'gpt-3.5-turbo',
  75. 'gpt-4o',
  76. 'gpt-4o-mini',
  77. 'gpt-4',
  78. 'gpt-4-turbo',
  79. 'chatgpt-4o-latest',
  80. ]
  81. model_aliases = {
  82. "gpt-4o": "chatgpt-4o-latest",
  83. }
  84. @classmethod
  85. def get_model(cls, model: str) -> str:
  86. if model in cls.models:
  87. return model
  88. elif model in cls.model_aliases:
  89. return cls.model_aliases[model]
  90. else:
  91. return cls.default_model
  92. @classmethod
  93. def create_completion(
  94. cls,
  95. model: str,
  96. messages: Messages,
  97. stream: bool,
  98. **kwargs
  99. ) -> CreateResult:
  100. model = cls.get_model(model)
  101. if model not in cls.models:
  102. raise ValueError(f"Model '{model}' is not available. Available models: {', '.join(cls.models)}")
  103. user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
  104. session: Session = init_session(user_agent)
  105. config = get_config(user_agent)
  106. pow_req = get_requirements_token(config)
  107. headers = {
  108. 'accept': '*/*',
  109. 'accept-language': 'en-US,en;q=0.8',
  110. 'content-type': 'application/json',
  111. 'oai-device-id': f'{uuid.uuid4()}',
  112. 'oai-language': 'en-US',
  113. 'origin': 'https://chatgpt.com',
  114. 'priority': 'u=1, i',
  115. 'referer': 'https://chatgpt.com/',
  116. 'sec-ch-ua-mobile': '?0',
  117. 'sec-ch-ua-platform': '"Linux"',
  118. 'sec-fetch-dest': 'empty',
  119. 'sec-fetch-mode': 'cors',
  120. 'sec-fetch-site': 'same-origin',
  121. 'sec-gpc': '1',
  122. 'user-agent': f'{user_agent}'
  123. }
  124. response = session.post('https://chatgpt.com/backend-anon/sentinel/chat-requirements',
  125. headers=headers, json={'p': pow_req})
  126. if response.status_code != 200:
  127. return
  128. response_data = response.json()
  129. if "detail" in response_data and "Unusual activity" in response_data["detail"]:
  130. return
  131. turnstile = response_data.get('turnstile', {})
  132. turnstile_required = turnstile.get('required')
  133. pow_conf = response_data.get('proofofwork', {})
  134. if turnstile_required:
  135. turnstile_dx = turnstile.get('dx')
  136. turnstile_token = process_turnstile(turnstile_dx, pow_req)
  137. headers = {**headers,
  138. 'openai-sentinel-turnstile-token': turnstile_token,
  139. 'openai-sentinel-chat-requirements-token': response_data.get('token'),
  140. 'openai-sentinel-proof-token': get_answer_token(
  141. pow_conf.get('seed'), pow_conf.get('difficulty'), config
  142. )}
  143. json_data = {
  144. 'action': 'next',
  145. 'messages': format_conversation(messages),
  146. 'parent_message_id': str(uuid.uuid4()),
  147. 'model': model,
  148. 'timezone_offset_min': -120,
  149. 'suggestions': [
  150. 'Can you help me create a personalized morning routine that would help increase my productivity throughout the day? Start by asking me about my current habits and what activities energize me in the morning.',
  151. 'Could you help me plan a relaxing day that focuses on activities for rejuvenation? To start, can you ask me what my favorite forms of relaxation are?',
  152. 'I have a photoshoot tomorrow. Can you recommend me some colors and outfit options that will look good on camera?',
  153. 'Make up a 5-sentence story about "Sharky", a tooth-brushing shark superhero. Make each sentence a bullet point.',
  154. ],
  155. 'history_and_training_disabled': False,
  156. 'conversation_mode': {
  157. 'kind': 'primary_assistant',
  158. },
  159. 'force_paragen': False,
  160. 'force_paragen_model_slug': '',
  161. 'force_nulligen': False,
  162. 'force_rate_limit': False,
  163. 'reset_rate_limits': False,
  164. 'websocket_request_id': str(uuid.uuid4()),
  165. 'system_hints': [],
  166. 'force_use_sse': True,
  167. 'conversation_origin': None,
  168. 'client_contextual_info': {
  169. 'is_dark_mode': True,
  170. 'time_since_loaded': random.randint(22, 33),
  171. 'page_height': random.randint(600, 900),
  172. 'page_width': random.randint(500, 800),
  173. 'pixel_ratio': 2,
  174. 'screen_height': random.randint(800, 1200),
  175. 'screen_width': random.randint(1200, 2000),
  176. },
  177. }
  178. time.sleep(2)
  179. response = session.post('https://chatgpt.com/backend-anon/conversation',
  180. headers=headers, json=json_data, stream=True)
  181. replace = ''
  182. for line in response.iter_lines():
  183. if line:
  184. decoded_line = line.decode()
  185. if decoded_line.startswith('data:'):
  186. json_string = decoded_line[6:].strip()
  187. if json_string == '[DONE]':
  188. break
  189. if json_string:
  190. try:
  191. data = json.loads(json_string)
  192. except json.JSONDecodeError:
  193. continue
  194. if data.get('message') and data['message'].get('author'):
  195. role = data['message']['author'].get('role')
  196. if role == 'assistant':
  197. tokens = data['message']['content'].get('parts', [])
  198. if tokens:
  199. yield tokens[0].replace(replace, '')
  200. replace = tokens[0]