FreeGpt.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from __future__ import annotations
  2. import time
  3. import hashlib
  4. import random
  5. from typing import AsyncGenerator, Optional, Dict, Any
  6. from ..typing import Messages
  7. from ..requests import StreamSession, raise_for_status
  8. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  9. from ..errors import RateLimitError
  10. # Constants
  11. DOMAINS = [
  12. "https://s.aifree.site",
  13. "https://v.aifree.site/",
  14. "https://al.aifree.site/",
  15. "https://u4.aifree.site/"
  16. ]
  17. RATE_LIMIT_ERROR_MESSAGE = "当前地区当日额度已消耗完"
  18. class FreeGpt(AsyncGeneratorProvider, ProviderModelMixin):
  19. url = "https://freegptsnav.aifree.site"
  20. working = True
  21. supports_message_history = True
  22. supports_system_message = True
  23. default_model = 'gemini-pro'
  24. @classmethod
  25. async def create_async_generator(
  26. cls,
  27. model: str,
  28. messages: Messages,
  29. proxy: Optional[str] = None,
  30. timeout: int = 120,
  31. **kwargs: Any
  32. ) -> AsyncGenerator[str, None]:
  33. prompt = messages[-1]["content"]
  34. timestamp = int(time.time())
  35. data = cls._build_request_data(messages, prompt, timestamp)
  36. domain = random.choice(DOMAINS)
  37. async with StreamSession(
  38. impersonate="chrome",
  39. timeout=timeout,
  40. proxies={"all": proxy} if proxy else None
  41. ) as session:
  42. async with session.post(f"{domain}/api/generate", json=data) as response:
  43. await raise_for_status(response)
  44. async for chunk in response.iter_content():
  45. chunk_decoded = chunk.decode(errors="ignore")
  46. if chunk_decoded == RATE_LIMIT_ERROR_MESSAGE:
  47. raise RateLimitError("Rate limit reached")
  48. yield chunk_decoded
  49. @staticmethod
  50. def _build_request_data(messages: Messages, prompt: str, timestamp: int, secret: str = "") -> Dict[str, Any]:
  51. return {
  52. "messages": messages,
  53. "time": timestamp,
  54. "pass": None,
  55. "sign": generate_signature(timestamp, prompt, secret)
  56. }
  57. def generate_signature(timestamp: int, message: str, secret: str = "") -> str:
  58. data = f"{timestamp}:{message}:{secret}"
  59. return hashlib.sha256(data.encode()).hexdigest()