xtekky/gpt4free · error · RuntimeError

Invalid image element: {element}

Error message

Invalid image element: {element}

What it means

In OpenaiChat's generated-image retrieval, an element from the conversation payload must be either a 'file-service://' or 'sediment://' URI (optionally wrapped in an asset_pointer dict). If it is neither shape, RuntimeError 'Invalid image element' is raised — the code cannot construct a download URL for that element.

Source

Thrown at g4f/Provider/needs_auth/OpenaiChat.py:407

        conversation_id: str = None,
        status: Optional[str] = None,
    ) -> ImagePreview | ImageResponse | None:
        download_urls = []
        is_sediment = False
        if prompt is None:
            try:
                prompt = element["metadata"]["dalle"]["prompt"]
            except KeyError:
                pass
        if "asset_pointer" in element:
            element = element["asset_pointer"]
        if isinstance(element, str) and element.startswith("file-service://"):
            element = element.split("file-service://", 1)[-1]
        elif isinstance(element, str) and element.startswith("sediment://"):
            is_sediment = True
            element = element.split("sediment://")[-1]
        else:
            raise RuntimeError(f"Invalid image element: {element}")
        if is_sediment:
            url = f"{cls.url}/backend-api/conversation/{conversation_id}/attachment/{element}/download"
        else:
            url = f"{cls.url}/backend-api/files/{element}/download"
        try:
            async with session.get(url, headers=auth_result.headers) as response:
                cls._update_request_args(auth_result, session)
                await raise_for_status(response)
                data = await response.json()
                download_url = data.get("download_url")
                if download_url is not None:
                    download_urls.append(download_url)
                    debug.log(f"OpenaiChat: Found image: {download_url}")
                else:
                    debug.log("OpenaiChat: No download URL found in response: ", data)
        except Exception as e:
            debug.error("OpenaiChat: Download image failed")
            debug.error(e)

View on GitHub (pinned to 973504e177)

Solutions

  1. Update g4f to the latest release — URI scheme handling for generated images changes with the backend
  2. Capture debug logs of the failing element to identify the new scheme and report/patch the branch in get_generated_image
  3. Retry without image-generation parameters if only image-gen flows are affected
  4. Ensure a valid authenticated session, since anomalous payloads can also come from degraded/unauthenticated responses

Example fix

# before
# element = "new-scheme://abc123" -> RuntimeError

# after
# patch the dispatcher (or update g4f) to handle the new prefix
if isinstance(element, str) and element.startswith('new-scheme://'):
    element = element.split('new-scheme://')[-1]
else:
    raise RuntimeError(f'Invalid image element: {element}')
Defensive patterns

Strategy: try-catch

Validate before calling

def is_known_image_uri(element) -> bool:
    if isinstance(element, dict):
        element = element.get('asset_pointer')
    return isinstance(element, str) and (
        element.startswith('file-service://') or element.startswith('sediment://')
    )

Type guard

def is_supported_pointer(element) -> bool:
    if isinstance(element, dict) and 'asset_pointer' in element:
        element = element['asset_pointer']
    return isinstance(element, str) and (
        element.startswith(('file-service://', 'sediment://'))
    )

Try / catch

try:
    img = await cls.get_generated_image(session, auth_result, element, prompt, conv_id)
except RuntimeError as e:
    if 'Invalid image element' in str(e):
        debug.log(f'skipping unsupported image element: {element!r}')
    else:
        raise

Prevention

When it happens

Trigger: While scanning streamed lines with pattern file-service://[\w-]+, or processing message parts whose asset_pointer values use a new URI scheme (e.g. a different backend prefix), the element string falls through both startswith checks.

Common situations: OpenAI changing the attachment URI scheme (new protocol prefix); parts containing plain IDs or dicts without asset_pointer after an API change; g4f version behind the current chat backend.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/40921784f96eea00. Report an issue: GitHub.