FreeChatgpt.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from __future__ import annotations
  2. import json, random
  3. from aiohttp import ClientSession
  4. from ..typing import AsyncResult, Messages
  5. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  6. class FreeChatgpt(AsyncGeneratorProvider, ProviderModelMixin):
  7. url = "https://free.chatgpt.org.uk"
  8. working = True
  9. supports_message_history = True
  10. default_model = "google-gemini-pro"
  11. @classmethod
  12. async def create_async_generator(
  13. cls,
  14. model: str,
  15. messages: Messages,
  16. proxy: str = None,
  17. **kwargs
  18. ) -> AsyncResult:
  19. headers = {
  20. "Accept": "application/json, text/event-stream",
  21. "Content-Type":"application/json",
  22. "Accept-Encoding": "gzip, deflate, br",
  23. "Accept-Language": "en-US,en;q=0.5",
  24. "Host":"free.chatgpt.org.uk",
  25. "Referer":f"{cls.url}/",
  26. "Origin":f"{cls.url}",
  27. "Sec-Fetch-Dest": "empty",
  28. "Sec-Fetch-Mode": "cors",
  29. "Sec-Fetch-Site": "same-origin",
  30. "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  31. }
  32. async with ClientSession(headers=headers) as session:
  33. data = {
  34. "messages": messages,
  35. "stream": True,
  36. "model": cls.get_model(""),
  37. "temperature": kwargs.get("temperature", 0.5),
  38. "presence_penalty": kwargs.get("presence_penalty", 0),
  39. "frequency_penalty": kwargs.get("frequency_penalty", 0),
  40. "top_p": kwargs.get("top_p", 1)
  41. }
  42. async with session.post(f'{cls.url}/api/openai/v1/chat/completions', json=data, proxy=proxy) as response:
  43. response.raise_for_status()
  44. started = False
  45. async for line in response.content:
  46. if line.startswith(b"data: [DONE]"):
  47. break
  48. elif line.startswith(b"data: "):
  49. line = json.loads(line[6:])
  50. if(line["choices"]==[]):
  51. continue
  52. chunk = line["choices"][0]["delta"].get("content")
  53. if chunk:
  54. started = True
  55. yield chunk
  56. if not started:
  57. raise RuntimeError("Empty response")