GetGpt.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. import json
  3. import uuid
  4. import requests
  5. from Crypto.Cipher import AES
  6. from ...typing import sha256, Dict, get_type_hints
  7. url = 'https://chat.getgpt.world/'
  8. model = ['gpt-3.5-turbo']
  9. supports_stream = True
  10. needs_auth = False
  11. def _create_completion(model: str, messages: list, stream: bool, **kwargs):
  12. def encrypt(e):
  13. t = os.urandom(8).hex().encode('utf-8')
  14. n = os.urandom(8).hex().encode('utf-8')
  15. r = e.encode('utf-8')
  16. cipher = AES.new(t, AES.MODE_CBC, n)
  17. ciphertext = cipher.encrypt(pad_data(r))
  18. return ciphertext.hex() + t.decode('utf-8') + n.decode('utf-8')
  19. def pad_data(data: bytes) -> bytes:
  20. block_size = AES.block_size
  21. padding_size = block_size - len(data) % block_size
  22. padding = bytes([padding_size] * padding_size)
  23. return data + padding
  24. headers = {
  25. 'Content-Type': 'application/json',
  26. 'Referer': 'https://chat.getgpt.world/',
  27. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
  28. }
  29. data = json.dumps({
  30. 'messages': messages,
  31. 'frequency_penalty': kwargs.get('frequency_penalty', 0),
  32. 'max_tokens': kwargs.get('max_tokens', 4000),
  33. 'model': 'gpt-3.5-turbo',
  34. 'presence_penalty': kwargs.get('presence_penalty', 0),
  35. 'temperature': kwargs.get('temperature', 1),
  36. 'top_p': kwargs.get('top_p', 1),
  37. 'stream': True,
  38. 'uuid': str(uuid.uuid4())
  39. })
  40. res = requests.post('https://chat.getgpt.world/api/chat/stream',
  41. headers=headers, json={'signature': encrypt(data)}, stream=True)
  42. for line in res.iter_lines():
  43. if b'content' in line:
  44. line_json = json.loads(line.decode('utf-8').split('data: ')[1])
  45. yield (line_json['choices'][0]['delta']['content'])
  46. params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \
  47. '(%s)' % ', '.join(
  48. [f'{name}: {get_type_hints(_create_completion)[name].__name__}' for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])