FreeNetfly.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from __future__ import annotations
  2. import json
  3. import asyncio
  4. from aiohttp import ClientSession, ClientTimeout, ClientError
  5. from typing import AsyncGenerator
  6. from ...typing import AsyncResult, Messages
  7. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  8. class FreeNetfly(AsyncGeneratorProvider, ProviderModelMixin):
  9. url = "https://free.netfly.top"
  10. api_endpoint = "/api/openai/v1/chat/completions"
  11. working = False
  12. default_model = 'gpt-3.5-turbo'
  13. models = [
  14. 'gpt-3.5-turbo',
  15. 'gpt-4',
  16. ]
  17. @classmethod
  18. async def create_async_generator(
  19. cls,
  20. model: str,
  21. messages: Messages,
  22. proxy: str = None,
  23. **kwargs
  24. ) -> AsyncResult:
  25. headers = {
  26. "accept": "application/json, text/event-stream",
  27. "accept-language": "en-US,en;q=0.9",
  28. "content-type": "application/json",
  29. "dnt": "1",
  30. "origin": cls.url,
  31. "referer": f"{cls.url}/",
  32. "sec-ch-ua": '"Not/A)Brand";v="8", "Chromium";v="126"',
  33. "sec-ch-ua-mobile": "?0",
  34. "sec-ch-ua-platform": '"Linux"',
  35. "sec-fetch-dest": "empty",
  36. "sec-fetch-mode": "cors",
  37. "sec-fetch-site": "same-origin",
  38. "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
  39. }
  40. data = {
  41. "messages": messages,
  42. "stream": True,
  43. "model": model,
  44. "temperature": 0.5,
  45. "presence_penalty": 0,
  46. "frequency_penalty": 0,
  47. "top_p": 1
  48. }
  49. max_retries = 5
  50. retry_delay = 2
  51. for attempt in range(max_retries):
  52. try:
  53. async with ClientSession(headers=headers) as session:
  54. timeout = ClientTimeout(total=60)
  55. async with session.post(f"{cls.url}{cls.api_endpoint}", json=data, proxy=proxy, timeout=timeout) as response:
  56. response.raise_for_status()
  57. async for chunk in cls._process_response(response):
  58. yield chunk
  59. return # If successful, exit the function
  60. except (ClientError, asyncio.TimeoutError) as e:
  61. if attempt == max_retries - 1:
  62. raise # If all retries failed, raise the last exception
  63. await asyncio.sleep(retry_delay)
  64. retry_delay *= 2 # Exponential backoff
  65. @classmethod
  66. async def _process_response(cls, response) -> AsyncGenerator[str, None]:
  67. buffer = ""
  68. async for line in response.content:
  69. buffer += line.decode('utf-8')
  70. if buffer.endswith('\n\n'):
  71. for subline in buffer.strip().split('\n'):
  72. if subline.startswith('data: '):
  73. if subline == 'data: [DONE]':
  74. return
  75. try:
  76. data = json.loads(subline[6:])
  77. content = data['choices'][0]['delta'].get('content')
  78. if content:
  79. yield content
  80. except json.JSONDecodeError:
  81. print(f"Failed to parse JSON: {subline}")
  82. except KeyError:
  83. print(f"Unexpected JSON structure: {data}")
  84. buffer = ""
  85. # Process any remaining data in the buffer
  86. if buffer:
  87. for subline in buffer.strip().split('\n'):
  88. if subline.startswith('data: ') and subline != 'data: [DONE]':
  89. try:
  90. data = json.loads(subline[6:])
  91. content = data['choices'][0]['delta'].get('content')
  92. if content:
  93. yield content
  94. except (json.JSONDecodeError, KeyError):
  95. pass