XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

fix: improve error handling and response processing in Kimi and PollinationsAI

- In g4f/Provider/Kimi.py, added a try-except block around raise_for_status to catch exceptions containing "匿名聊天使用次数超过" and raise MissingAuthError; also included a yield statement for JsonConversation. - In g4f/Provider/PollinationsAI.py, added a yield statement for Reasoning before the class definition. - Updated get_image function in PollinationsAI to remove responses.add for the response URL and streamline response handling. - In the main loop of PollinationsAI, modified response processing to handle exceptions by cancelling tasks and raising errors if conditions are met, or yielding Reasoning with status and progress labels. - Adjusted responses handling to increment finished count and yield progress Reasoning only when no exception occurs.

9eeafff5
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

2 个文件 +24 -15
Modified g4f/Provider/Kimi.py +8 -1
@@ -8,6 +8,7 @@ from ..providers.helper import get_last_user_message
8 8 from ..requests import StreamSession, sse_stream, raise_for_status
9 9 from ..providers.response import AuthResult, TitleGeneration, JsonConversation, FinishReason
10 10 from ..typing import AsyncResult, Messages
11 from ..errors import MissingAuthError
11 12
12 13 class Kimi(AsyncAuthedProvider, ProviderModelMixin):
13 14 url = "https://www.kimi.com"
@@ -65,9 +66,15 @@ class Kimi(AsyncAuthedProvider, ProviderModelMixin):
65 66 "source":"web",
66 67 "tags":[]
67 68 }) as response:
68 await raise_for_status(response)
69 try:
70 await raise_for_status(response)
71 except Exception as e:
72 if "匿名聊天使用次数超过" in str(e):
73 raise MissingAuthError("Anonymous chat usage limit exceeded")
74 raise e
69 75 chat_data = await response.json()
70 76 conversation = JsonConversation(chat_id=chat_data.get("id"))
77 yield conversation
71 78 data = {
72 79 "kimiplus_id": "kimi",
73 80 "extend": {"sidebar": True},
Modified g4f/Provider/PollinationsAI.py +16 -14
@@ -60,6 +60,7 @@ FOLLOWUPS_DEVELOPER_MESSAGE = [{
60 60 "role": "developer",
61 61 "content": "Provide conversation options.",
62 62 }]
63
63 64 class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
64 65 label = "Pollinations AI"
65 66 url = "https://pollinations.ai"
@@ -82,7 +83,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
82 83 default_audio_model = "openai-audio"
83 84 default_voice = "alloy"
84 85 text_models = [default_model, "evil"]
85 image_models = [default_image_model, "turbo", "kontext", "gptimage", "transparent"]
86 image_models = [default_image_model, "turbo", "kontext"]
86 87 audio_models = {default_audio_model: []}
87 88 vision_models = [default_vision_model]
88 89 _models_loaded = False
@@ -385,34 +386,35 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
385 386 timeout=ClientTimeout(timeout)
386 387 ) as session:
387 388 responses = set()
388 responses.add(Reasoning(label=f"Generating {n} {'image' if n == 1 else 'images'}"))
389 yield Reasoning(label=f"Generating {n} {'image' if n == 1 else 'images'}")
389 390 finished = 0
390 391 start = time.time()
391 392 async def get_image(responses: set, i: int, seed: Optional[int] = None):
392 nonlocal finished
393 393 try:
394 394 async with session.get(get_url_with_seed(i, seed), allow_redirects=False, headers=headers) as response:
395 395 await raise_for_status(response)
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, "source_url": str(response.url)}))
400 finished += 1
401 responses.add(Reasoning(label=f"Image {finished}/{n} generated in {time.time() - start:.2f}s"))
399 responses.add(ImageResponse(str(response.url), prompt, {"headers": headers}))
402 400 tasks: list[asyncio.Task] = []
403 401 for i in range(int(n)):
404 402 tasks.append(asyncio.create_task(get_image(responses, i, seed)))
405 403 while finished < n or len(responses) > 0:
406 404 while len(responses) > 0:
407 405 item = responses.pop()
408 if isinstance(item, Exception) and finished < 2:
409 yield Reasoning(status="")
410 for task in tasks:
411 task.cancel()
412 if cls.login_url in str(item):
413 raise MissingAuthError(item)
414 raise item
415 yield item
406 if isinstance(item, Exception):
407 if finished < 2:
408 yield Reasoning(status="")
409 for task in tasks:
410 task.cancel()
411 if cls.login_url in str(item):
412 raise MissingAuthError(item)
413 raise item
414 else:
415 finished += 1
416 yield Reasoning(label=f"Image {finished}/{n} generated in {time.time() - start:.2f}s")
417 yield item
416 418 await asyncio.sleep(1)
417 419 yield Reasoning(status="")
418 420 await asyncio.gather(*tasks)