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
代码差异
@@ -45,7 +45,7 @@ docker pull hlohaus789/g4f
Reach out for help in our [Support Group: discord.gg/qXA4Wf4Fsm](https://discord.gg/qXA4Wf4Fsm).
- **Read our Documentation** 📖
Find detailed guidance and resources at [gpt4free.github.io/docs](https://github.com/gpt4free/gpt4free.github.io/blob/main/docs/main.md).
Find detailed guidance and resources at [gpt4free.github.io/docs](https://github.com/gpt4free/gpt4free.github.io).
## 🔻 Site Takedown
@@ -80,7 +80,7 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
try:
cls._args = await get_args_from_nodriver(cls.url)
read_models()
except (RuntimeError, FileNotFoundError) as e:
except Exception as e:
debug.log(f"Nodriver is not available: {type(e).__name__}: {e}")
cls.models = cls.fallback_models
get_running_loop(check_nested=True)
@@ -107,7 +107,11 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
with cache_file.open("r") as f:
cls._args = json.load(f)
elif has_nodriver:
cls._args = await get_args_from_nodriver(cls.url, proxy, timeout, cookies)
try:
cls._args = await get_args_from_nodriver(cls.url)
except (RuntimeError, FileNotFoundError) as e:
debug.log(f"Nodriver is not available: {type(e).__name__}: {e}")
cls._args = {"headers": DEFAULT_HEADERS, "cookies": {}, "impersonate": "chrome"}
else:
cls._args = {"headers": DEFAULT_HEADERS, "cookies": {}, "impersonate": "chrome"}
try:
@@ -194,8 +194,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
try:
model = cls.get_model(model)
except ModelNotFoundError:
if model not in cls.image_models:
raise
pass
if model in cls.image_models:
async for chunk in cls._generate_image(
@@ -153,8 +153,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
"use_case": "multimodal"
}
# Post the image data to the service and get the image data
headers = auth_result.headers if hasattr(auth_result, "headers") else None
async with session.post(f"{cls.url}/backend-api/files", json=data, headers=headers) as response:
async with session.post(f"{cls.url}/backend-api/files", json=data, headers=cls._headers) as response:
cls._update_request_args(auth_result, session)
await raise_for_status(response, "Create file failed")
image_data = {
@@ -266,7 +265,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
element = element["asset_pointer"]
if isinstance(element, str) and element.startswith("file-service://"):
element = element.split("file-service://", 1)[-1]
if isinstance(element, str) and element.startswith("sediment://"):
elif isinstance(element, str) and element.startswith("sediment://"):
is_sediment = True
element = element.split("sediment://")[-1]
else:
@@ -459,7 +458,16 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
raise RuntimeError((await response.json()), data)
await raise_for_status(response)
buffer = u""
matches = []
async for line in response.iter_lines():
pattern = re.compile(r"file-service://[\w-]+")
for match in pattern.finditer(line.decode(errors="ignore")):
if match.group(0) in matches:
continue
matches.append(match.group(0))
generated_image = await cls.get_generated_image(session, auth_result, match.group(0), prompt)
if generated_image is not None:
yield generated_image
async for chunk in cls.iter_messages_line(session, auth_result, line, conversation, sources):
if isinstance(chunk, str):
chunk = chunk.replace("\ue203", "").replace("\ue204", "").replace("\ue206", "")
@@ -572,10 +580,10 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
if c.get("content_type") == "text" and m.get("author", {}).get("role") == "tool" and "initial_text" in m.get("metadata", {}):
fields.is_thinking = True
yield Reasoning(status=m.get("metadata", {}).get("initial_text"))
if c.get("content_type") == "multimodal_text":
for part in c.get("parts"):
if isinstance(part, dict) and part.get("content_type") == "image_asset_pointer":
yield await cls.get_generated_image(session, auth_result, part, fields.prompt, fields.conversation_id)
#if c.get("content_type") == "multimodal_text":
# for part in c.get("parts"):
# if isinstance(part, dict) and part.get("content_type") == "image_asset_pointer":
# yield await cls.get_generated_image(session, auth_result, part, fields.prompt, fields.conversation_id)
if m.get("author", {}).get("role") == "assistant":
if fields.parent_message_id is None:
fields.parent_message_id = v.get("message", {}).get("id")
@@ -54,7 +54,7 @@ def resolve_media(kwargs: dict, image = None, image_name: str = None) -> None:
kwargs["media"] = [kwargs["media"]]
for idx, media in enumerate(kwargs.get("media", [])):
if not isinstance(media, (list, tuple)):
kwargs["media"][idx] = (media, getattr(media, "name", None))
kwargs["media"][idx] = (media, os.path.basename(getattr(media, "name", "")))
# Synchronous iter_response function
def iter_response(