返回提交历史
Modified
g4f/Provider/PollinationsAI.py
+1
-1
Modified
g4f/Provider/hf_space/__init__.py
+1
-1
Modified
g4f/errors.py
+3
-0
Modified
g4f/image/copy_images.py
+0
-2
Modified
g4f/providers/base_provider.py
+3
-3
Modified
g4f/providers/response.py
+2
-1
Modified
g4f/providers/retry_provider.py
+13
-21
Modified
g4f/requests/raise_for_status.py
+1
-4
XFEstudio/gpt4free
Auth on Cloudflare error
b49d71db
代码差异
8 个文件
+24
-33
@@ -396,7 +396,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
396
396
except Exception as e:
397
397
responses.add(e)
398
398
debug.error(f"Error fetching image: {e}")
399
responses.add(ImageResponse(str(response.url), prompt, {"headers": headers}))
399
responses.add(ImageResponse(str(response.url), prompt, {"headers": headers, "source_url": str(response.url)}))
400
400
finished += 1
401
401
responses.add(Reasoning(label=f"Image {finished}/{n} generated in {time.time() - start:.2f}s"))
402
402
tasks: list[asyncio.Task] = []
@@ -20,8 +20,8 @@ from .StabilityAI_SD35Large import StabilityAI_SD35Large
20
20
21
21
class HuggingSpace(AsyncGeneratorProvider, ProviderModelMixin):
22
22
url = "https://huggingface.co/spaces"
23
24
23
working = True
24
active_by_default = True
25
25
26
26
default_model = Qwen_Qwen_2_72B.default_model
27
27
default_image_model = BlackForestLabs_Flux1Dev.default_model
@@ -43,6 +43,9 @@ class ResponseError(Exception):
43
43
class ResponseStatusError(Exception):
44
44
...
45
45
46
class CloudflareError(ResponseStatusError):
47
...
48
46
49
class RateLimitError(ResponseStatusError):
47
50
...
48
51
@@ -134,8 +134,6 @@ async def copy_media(
134
134
Download and store images locally with Unicode-safe filenames
135
135
Returns list of relative image URLs
136
136
"""
137
if add_url:
138
add_url = not cookies
139
137
ensure_media_dir()
140
138
media_dir = get_media_dir()
141
139
if thumbnail:
@@ -20,7 +20,7 @@ from .asyncio import get_running_loop, to_sync_generator, to_async_iterator
20
20
from .response import BaseConversation, AuthResult
21
21
from .helper import concat_chunks
22
22
from ..cookies import get_cookies_dir
23
from ..errors import ModelNotFoundError, ResponseError, MissingAuthError, NoValidHarFileError, PaymentRequiredError
23
from ..errors import ModelNotFoundError, ResponseError, MissingAuthError, NoValidHarFileError, PaymentRequiredError, CloudflareError
24
24
25
25
SAFE_PARAMETERS = [
26
26
"model", "messages", "stream", "timeout",
@@ -468,7 +468,7 @@ class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
468
468
try:
469
469
auth_result = cls.get_auth_result()
470
470
yield from to_sync_generator(cls.create_authed(model, messages, auth_result, **kwargs))
471
except (MissingAuthError, NoValidHarFileError):
471
except (MissingAuthError, NoValidHarFileError, CloudflareError):
472
472
response = cls.on_auth(**kwargs)
473
473
for chunk in response:
474
474
if isinstance(chunk, AuthResult):
@@ -495,7 +495,7 @@ class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
495
495
response = to_async_iterator(cls.create_authed(model, messages, **kwargs, auth_result=auth_result))
496
496
async for chunk in response:
497
497
yield chunk
498
except (MissingAuthError, NoValidHarFileError):
498
except (MissingAuthError, NoValidHarFileError, CloudflareError):
499
499
if cache_file.exists():
500
500
cache_file.unlink()
501
501
response = cls.on_auth_async(**kwargs)
@@ -363,7 +363,8 @@ class ImageResponse(MediaResponse):
363
363
"""Return images as markdown."""
364
364
if self.get("width") and self.get("height"):
365
365
return "\n".join([
366
f'<a href="{html.escape(url)}" data-width="{self.get("width")}" data-height="{self.get("height")}"><img src="{url.replace("/media/", "/thumbnail/")}" alt="{html.escape(self.alt)}"></a>'
366
f'<a href="{html.escape(url)}" data-width="{self.get('width')}" data-height="{self.get('height')}" data-source="{html.escape(self.get('source_url', ''))}">'
367
+ f'<img src="{url.replace("/media/", "/thumbnail/")}" alt="{html.escape(self.alt)}"></a>'
367
368
for url in self.get_list()
368
369
])
369
370
return format_images_markdown(self.urls, self.alt, self.get("preview"))
@@ -32,18 +32,15 @@ class IterListProvider(BaseRetryProvider):
32
32
self,
33
33
model: str,
34
34
messages: Messages,
35
stream: bool = False,
36
ignore_stream: bool = False,
37
35
ignored: list[str] = [],
38
36
api_key: str = None,
39
37
**kwargs,
40
38
) -> CreateResult:
41
39
"""
42
Create a completion using available providers, with an option to stream the response.
40
Create a completion using available providers.
43
41
Args:
44
42
model (str): The model to be used for completion.
45
43
messages (Messages): The messages to be used for generating completion.
46
stream (bool, optional): Flag to indicate if the response should be streamed. Defaults to False.
47
44
Yields:
48
45
CreateResult: Tokens or results from the completion.
49
46
Raises:
@@ -51,7 +48,7 @@ class IterListProvider(BaseRetryProvider):
51
48
"""
52
49
exceptions = {}
53
50
started: bool = False
54
for provider in self.get_providers(stream and not ignore_stream, ignored):
51
for provider in self.get_providers(ignored):
55
52
self.last_provider = provider
56
53
alias = model
57
54
if not model:
@@ -70,7 +67,7 @@ class IterListProvider(BaseRetryProvider):
70
67
if api_key:
71
68
extra_body["api_key"] = api_key
72
69
try:
73
response = provider.create_function(alias, messages, stream=stream, **extra_body)
70
response = provider.create_function(alias, messages, **extra_body)
74
71
for chunk in response:
75
72
if chunk:
76
73
yield chunk
@@ -91,8 +88,6 @@ class IterListProvider(BaseRetryProvider):
91
88
self,
92
89
model: str,
93
90
messages: Messages,
94
stream: bool = True,
95
ignore_stream: bool = False,
96
91
ignored: list[str] = [],
97
92
api_key: str = None,
98
93
conversation: JsonConversation = None,
@@ -101,7 +96,7 @@ class IterListProvider(BaseRetryProvider):
101
96
exceptions = {}
102
97
started: bool = False
103
98
104
for provider in self.get_providers(stream and not ignore_stream, ignored):
99
for provider in self.get_providers(ignored):
105
100
self.last_provider = provider
106
101
alias = model
107
102
if not model:
@@ -122,7 +117,7 @@ class IterListProvider(BaseRetryProvider):
122
117
if conversation is not None and hasattr(conversation, provider.__name__):
123
118
extra_body["conversation"] = JsonConversation(**getattr(conversation, provider.__name__))
124
119
try:
125
response = provider.async_create_function(model, messages, stream=stream, **extra_body)
120
response = provider.async_create_function(model, messages, **extra_body)
126
121
if hasattr(response, "__aiter__"):
127
122
async for chunk in response:
128
123
if isinstance(chunk, JsonConversation):
@@ -153,8 +148,8 @@ class IterListProvider(BaseRetryProvider):
153
148
create_function = create_completion
154
149
async_create_function = create_async_generator
155
150
156
def get_providers(self, stream: bool, ignored: list[str]) -> list[ProviderType]:
157
providers = [p for p in self.providers if (p.supports_stream or not stream) and p.__name__ not in ignored]
151
def get_providers(self, ignored: list[str]) -> list[ProviderType]:
152
providers = [p for p in self.providers if p.__name__ not in ignored]
158
153
if self.shuffle:
159
154
random.shuffle(providers)
160
155
return providers
@@ -183,15 +178,13 @@ class RetryProvider(IterListProvider):
183
178
self,
184
179
model: str,
185
180
messages: Messages,
186
stream: bool = False,
187
181
**kwargs,
188
182
) -> CreateResult:
189
183
"""
190
Create a completion using available providers, with an option to stream the response.
184
Create a completion using available providers.
191
185
Args:
192
186
model (str): The model to be used for completion.
193
187
messages (Messages): The messages to be used for generating completion.
194
stream (bool, optional): Flag to indicate if the response should be streamed. Defaults to False.
195
188
Yields:
196
189
CreateResult: Tokens or results from the completion.
197
190
Raises:
@@ -206,7 +199,7 @@ class RetryProvider(IterListProvider):
206
199
try:
207
200
if debug.logging:
208
201
print(f"Using {provider.__name__} provider (attempt {attempt + 1})")
209
response = provider.create_function(model, messages, stream=stream, **kwargs)
202
response = provider.create_function(model, messages, **kwargs)
210
203
for chunk in response:
211
204
yield chunk
212
205
if is_content(chunk):
@@ -221,13 +214,12 @@ class RetryProvider(IterListProvider):
221
214
raise e
222
215
raise_exceptions(exceptions)
223
216
else:
224
yield from super().create_completion(model, messages, stream, **kwargs)
217
yield from super().create_completion(model, messages, **kwargs)
225
218
226
219
async def create_async_generator(
227
220
self,
228
221
model: str,
229
222
messages: Messages,
230
stream: bool = True,
231
223
**kwargs
232
224
) -> AsyncResult:
233
225
exceptions = {}
@@ -239,7 +231,7 @@ class RetryProvider(IterListProvider):
239
231
for attempt in range(self.max_retries):
240
232
try:
241
233
debug.log(f"Using {provider.__name__} provider (attempt {attempt + 1})")
242
response = provider.async_create_function(model, messages, stream=stream, **kwargs)
234
response = provider.async_create_function(model, messages, **kwargs)
243
235
if hasattr(response, "__aiter__"):
244
236
async for chunk in response:
245
237
yield chunk
@@ -258,7 +250,7 @@ class RetryProvider(IterListProvider):
258
250
print(f"{provider.__name__}: {e.__class__.__name__}: {e}")
259
251
raise_exceptions(exceptions)
260
252
else:
261
async for chunk in super().create_async_generator(model, messages, stream, **kwargs):
253
async for chunk in super().create_async_generator(model, messages, **kwargs):
262
254
yield chunk
263
255
264
256
def raise_exceptions(exceptions: dict) -> None:
@@ -279,4 +271,4 @@ def raise_exceptions(exceptions: dict) -> None:
279
271
f"{p}: {type(exception).__name__}: {exception}" for p, exception in exceptions.items()
280
272
])) from list(exceptions.values())[0]
281
273
282
raise RetryNoProviderError("No provider found")
274
raise RetryNoProviderError("No content response from any provider. ")
@@ -4,12 +4,9 @@ from typing import Union
4
4
from aiohttp import ClientResponse
5
5
from requests import Response as RequestsResponse
6
6
7
from ..errors import ResponseStatusError, RateLimitError, MissingAuthError
7
from ..errors import ResponseStatusError, RateLimitError, MissingAuthError, CloudflareError
8
8
from . import Response, StreamResponse
9
9
10
class CloudflareError(ResponseStatusError):
11
...
12
13
10
def is_cloudflare(text: str) -> bool:
14
11
if "Generated by cloudfront" in text or '<p id="cf-spinner-please-wait">' in text:
15
12
return True