FreeGpt.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from __future__ import annotations
  2. import time, hashlib, random
  3. from ..typing import AsyncResult, Messages
  4. from ..requests import StreamSession
  5. from .base_provider import AsyncGeneratorProvider
  6. domains = [
  7. 'https://s.aifree.site'
  8. ]
  9. class FreeGpt(AsyncGeneratorProvider):
  10. url = "https://freegpts1.aifree.site/"
  11. working = False
  12. supports_message_history = True
  13. supports_gpt_35_turbo = True
  14. @classmethod
  15. async def create_async_generator(
  16. cls,
  17. model: str,
  18. messages: Messages,
  19. proxy: str = None,
  20. timeout: int = 120,
  21. **kwargs
  22. ) -> AsyncResult:
  23. async with StreamSession(
  24. impersonate="chrome107",
  25. timeout=timeout,
  26. proxies={"https": proxy}
  27. ) as session:
  28. prompt = messages[-1]["content"]
  29. timestamp = int(time.time())
  30. data = {
  31. "messages": messages,
  32. "time": timestamp,
  33. "pass": None,
  34. "sign": generate_signature(timestamp, prompt)
  35. }
  36. url = random.choice(domains)
  37. async with session.post(f"{url}/api/generate", json=data) as response:
  38. response.raise_for_status()
  39. async for chunk in response.iter_content():
  40. chunk = chunk.decode()
  41. if chunk == "当前地区当日额度已消耗完":
  42. raise RuntimeError("Rate limit reached")
  43. yield chunk
  44. def generate_signature(timestamp: int, message: str, secret: str = ""):
  45. data = f"{timestamp}:{message}:{secret}"
  46. return hashlib.sha256(data.encode()).hexdigest()