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

XFEstudio/gpt4free

fix: update error handling, URL, and media name logic across providers

- Changed documentation URL in README.md for detailed guidance link - In g4f/Provider/Cloudflare.py, broadened exception handling in async argument fetching to catch all exceptions in one place and only specific exceptions in another - In g4f/Provider/PollinationsAI.py, removed raising of exception for unknown model not in image_models and replaced it with pass - In g4f/Provider/needs_auth/OpenaiChat.py, modified session post call to always use cls._headers - Changed if-chain in OpenaiChat.py to use elif for checking element prefix "sediment://" - Added logic to extract and yield generated images for unique "file-service://" matches in streamed responses within OpenaiChat.py - Commented out multimodal_text image asset pointer handling in OpenaiChat.py - In g4f/client/__init__.py resolve_media(), set media name to basename of file path using os.path.basename

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

代码差异

5 个文件 +24 -13
Modified README.md +1 -1
@@ -45,7 +45,7 @@ docker pull hlohaus789/g4f
45 45 Reach out for help in our [Support Group: discord.gg/qXA4Wf4Fsm](https://discord.gg/qXA4Wf4Fsm).
46 46
47 47 - **Read our Documentation** 📖
48 Find detailed guidance and resources at [gpt4free.github.io/docs](https://github.com/gpt4free/gpt4free.github.io/blob/main/docs/main.md).
48 Find detailed guidance and resources at [gpt4free.github.io/docs](https://github.com/gpt4free/gpt4free.github.io).
49 49
50 50 ## 🔻 Site Takedown
51 51
Modified g4f/Provider/Cloudflare.py +6 -2
@@ -80,7 +80,7 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
80 80 try:
81 81 cls._args = await get_args_from_nodriver(cls.url)
82 82 read_models()
83 except (RuntimeError, FileNotFoundError) as e:
83 except Exception as e:
84 84 debug.log(f"Nodriver is not available: {type(e).__name__}: {e}")
85 85 cls.models = cls.fallback_models
86 86 get_running_loop(check_nested=True)
@@ -107,7 +107,11 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
107 107 with cache_file.open("r") as f:
108 108 cls._args = json.load(f)
109 109 elif has_nodriver:
110 cls._args = await get_args_from_nodriver(cls.url, proxy, timeout, cookies)
110 try:
111 cls._args = await get_args_from_nodriver(cls.url)
112 except (RuntimeError, FileNotFoundError) as e:
113 debug.log(f"Nodriver is not available: {type(e).__name__}: {e}")
114 cls._args = {"headers": DEFAULT_HEADERS, "cookies": {}, "impersonate": "chrome"}
111 115 else:
112 116 cls._args = {"headers": DEFAULT_HEADERS, "cookies": {}, "impersonate": "chrome"}
113 117 try:
Modified g4f/Provider/PollinationsAI.py +1 -2
@@ -194,8 +194,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
194 194 try:
195 195 model = cls.get_model(model)
196 196 except ModelNotFoundError:
197 if model not in cls.image_models:
198 raise
197 pass
199 198
200 199 if model in cls.image_models:
201 200 async for chunk in cls._generate_image(
Modified g4f/Provider/needs_auth/OpenaiChat.py +15 -7
@@ -153,8 +153,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
153 153 "use_case": "multimodal"
154 154 }
155 155 # Post the image data to the service and get the image data
156 headers = auth_result.headers if hasattr(auth_result, "headers") else None
157 async with session.post(f"{cls.url}/backend-api/files", json=data, headers=headers) as response:
156 async with session.post(f"{cls.url}/backend-api/files", json=data, headers=cls._headers) as response:
158 157 cls._update_request_args(auth_result, session)
159 158 await raise_for_status(response, "Create file failed")
160 159 image_data = {
@@ -266,7 +265,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
266 265 element = element["asset_pointer"]
267 266 if isinstance(element, str) and element.startswith("file-service://"):
268 267 element = element.split("file-service://", 1)[-1]
269 if isinstance(element, str) and element.startswith("sediment://"):
268 elif isinstance(element, str) and element.startswith("sediment://"):
270 269 is_sediment = True
271 270 element = element.split("sediment://")[-1]
272 271 else:
@@ -459,7 +458,16 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
459 458 raise RuntimeError((await response.json()), data)
460 459 await raise_for_status(response)
461 460 buffer = u""
461 matches = []
462 462 async for line in response.iter_lines():
463 pattern = re.compile(r"file-service://[\w-]+")
464 for match in pattern.finditer(line.decode(errors="ignore")):
465 if match.group(0) in matches:
466 continue
467 matches.append(match.group(0))
468 generated_image = await cls.get_generated_image(session, auth_result, match.group(0), prompt)
469 if generated_image is not None:
470 yield generated_image
463 471 async for chunk in cls.iter_messages_line(session, auth_result, line, conversation, sources):
464 472 if isinstance(chunk, str):
465 473 chunk = chunk.replace("\ue203", "").replace("\ue204", "").replace("\ue206", "")
@@ -572,10 +580,10 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
572 580 if c.get("content_type") == "text" and m.get("author", {}).get("role") == "tool" and "initial_text" in m.get("metadata", {}):
573 581 fields.is_thinking = True
574 582 yield Reasoning(status=m.get("metadata", {}).get("initial_text"))
575 if c.get("content_type") == "multimodal_text":
576 for part in c.get("parts"):
577 if isinstance(part, dict) and part.get("content_type") == "image_asset_pointer":
578 yield await cls.get_generated_image(session, auth_result, part, fields.prompt, fields.conversation_id)
583 #if c.get("content_type") == "multimodal_text":
584 # for part in c.get("parts"):
585 # if isinstance(part, dict) and part.get("content_type") == "image_asset_pointer":
586 # yield await cls.get_generated_image(session, auth_result, part, fields.prompt, fields.conversation_id)
579 587 if m.get("author", {}).get("role") == "assistant":
580 588 if fields.parent_message_id is None:
581 589 fields.parent_message_id = v.get("message", {}).get("id")
Modified g4f/client/__init__.py +1 -1
@@ -54,7 +54,7 @@ def resolve_media(kwargs: dict, image = None, image_name: str = None) -> None:
54 54 kwargs["media"] = [kwargs["media"]]
55 55 for idx, media in enumerate(kwargs.get("media", [])):
56 56 if not isinstance(media, (list, tuple)):
57 kwargs["media"][idx] = (media, getattr(media, "name", None))
57 kwargs["media"][idx] = (media, os.path.basename(getattr(media, "name", "")))
58 58
59 59 # Synchronous iter_response function
60 60 def iter_response(