gpt4free/g4f/Provider/FreeGpt.py

68 lines
2.2 KiB
Python
Raw Normal View History

from __future__ import annotations
2024-07-08 23:49:38 +03:00
import time
import hashlib
import random
from typing import AsyncGenerator, Optional, Dict, Any
from ..typing import Messages
2024-04-07 00:18:44 +03:00
from ..requests import StreamSession, raise_for_status
from .base_provider import AsyncGeneratorProvider
from ..errors import RateLimitError
2024-07-08 23:49:38 +03:00
# Constants
DOMAINS = [
"https://s.aifree.site",
"https://v.aifree.site/"
]
2024-07-08 23:49:38 +03:00
RATE_LIMIT_ERROR_MESSAGE = "当前地区当日额度已消耗完"
class FreeGpt(AsyncGeneratorProvider):
2024-07-08 23:49:38 +03:00
url: str = "https://freegptsnav.aifree.site"
working: bool = True
supports_message_history: bool = True
supports_system_message: bool = True
supports_gpt_35_turbo: bool = True
@classmethod
async def create_async_generator(
cls,
model: str,
messages: Messages,
2024-07-08 23:49:38 +03:00
proxy: Optional[str] = None,
2023-10-09 11:22:17 +03:00
timeout: int = 120,
2024-07-08 23:49:38 +03:00
**kwargs: Any
) -> AsyncGenerator[str, None]:
prompt = messages[-1]["content"]
timestamp = int(time.time())
data = cls._build_request_data(messages, prompt, timestamp)
domain = random.choice(DOMAINS)
2023-10-09 11:22:17 +03:00
async with StreamSession(
2024-04-07 00:18:44 +03:00
impersonate="chrome",
2023-10-09 11:22:17 +03:00
timeout=timeout,
2024-07-08 23:49:38 +03:00
proxies={"all": proxy} if proxy else None
2023-10-09 11:22:17 +03:00
) as session:
async with session.post(f"{domain}/api/generate", json=data) as response:
2024-04-07 00:18:44 +03:00
await raise_for_status(response)
async for chunk in response.iter_content():
2024-07-08 23:49:38 +03:00
chunk_decoded = chunk.decode(errors="ignore")
if chunk_decoded == RATE_LIMIT_ERROR_MESSAGE:
raise RateLimitError("Rate limit reached")
2024-07-08 23:49:38 +03:00
yield chunk_decoded
@staticmethod
def _build_request_data(messages: Messages, prompt: str, timestamp: int, secret: str = "") -> Dict[str, Any]:
return {
"messages": messages,
"time": timestamp,
"pass": None,
"sign": generate_signature(timestamp, prompt, secret)
}
def generate_signature(timestamp: int, message: str, secret: str = "") -> str:
data = f"{timestamp}:{message}:{secret}"
return hashlib.sha256(data.encode()).hexdigest()