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