{"record":{"id":"40921784f96eea00","repo":"xtekky/gpt4free","slug":"invalid-image-element-element","errorCode":null,"errorMessage":"Invalid image element: {element}","messagePattern":"Invalid image element: (.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"g4f/Provider/needs_auth/OpenaiChat.py","lineNumber":407,"sourceCode":"        conversation_id: str = None,\n        status: Optional[str] = None,\n    ) -> ImagePreview | ImageResponse | None:\n        download_urls = []\n        is_sediment = False\n        if prompt is None:\n            try:\n                prompt = element[\"metadata\"][\"dalle\"][\"prompt\"]\n            except KeyError:\n                pass\n        if \"asset_pointer\" in element:\n            element = element[\"asset_pointer\"]\n        if isinstance(element, str) and element.startswith(\"file-service://\"):\n            element = element.split(\"file-service://\", 1)[-1]\n        elif isinstance(element, str) and element.startswith(\"sediment://\"):\n            is_sediment = True\n            element = element.split(\"sediment://\")[-1]\n        else:\n            raise RuntimeError(f\"Invalid image element: {element}\")\n        if is_sediment:\n            url = f\"{cls.url}/backend-api/conversation/{conversation_id}/attachment/{element}/download\"\n        else:\n            url = f\"{cls.url}/backend-api/files/{element}/download\"\n        try:\n            async with session.get(url, headers=auth_result.headers) as response:\n                cls._update_request_args(auth_result, session)\n                await raise_for_status(response)\n                data = await response.json()\n                download_url = data.get(\"download_url\")\n                if download_url is not None:\n                    download_urls.append(download_url)\n                    debug.log(f\"OpenaiChat: Found image: {download_url}\")\n                else:\n                    debug.log(\"OpenaiChat: No download URL found in response: \", data)\n        except Exception as e:\n            debug.error(\"OpenaiChat: Download image failed\")\n            debug.error(e)","sourceCodeStart":389,"sourceCodeEnd":425,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/Provider/needs_auth/OpenaiChat.py#L389-L425","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Update g4f to the latest release — URI scheme handling for generated images changes with the backend","Capture debug logs of the failing element to identify the new scheme and report/patch the branch in get_generated_image","Retry without image-generation parameters if only image-gen flows are affected","Ensure a valid authenticated session, since anomalous payloads can also come from degraded/unauthenticated responses"],"exampleFix":"# before\n# element = \"new-scheme://abc123\" -> RuntimeError\n\n# after\n# patch the dispatcher (or update g4f) to handle the new prefix\nif isinstance(element, str) and element.startswith('new-scheme://'):\n    element = element.split('new-scheme://')[-1]\nelse:\n    raise RuntimeError(f'Invalid image element: {element}')","handlingStrategy":"try-catch","validationCode":"def is_known_image_uri(element) -> bool:\n    if isinstance(element, dict):\n        element = element.get('asset_pointer')\n    return isinstance(element, str) and (\n        element.startswith('file-service://') or element.startswith('sediment://')\n    )","typeGuard":"def is_supported_pointer(element) -> bool:\n    if isinstance(element, dict) and 'asset_pointer' in element:\n        element = element['asset_pointer']\n    return isinstance(element, str) and (\n        element.startswith(('file-service://', 'sediment://'))\n    )","tryCatchPattern":"try:\n    img = await cls.get_generated_image(session, auth_result, element, prompt, conv_id)\nexcept RuntimeError as e:\n    if 'Invalid image element' in str(e):\n        debug.log(f'skipping unsupported image element: {element!r}')\n    else:\n        raise","preventionTips":["Update g4f whenever the OpenAI image backend changes URI schemes","Filter conversation parts through a URI whitelist before retrieval","Report new element schemes upstream with a debug capture"],"tags":["openai-chat","image-generation","parsing","schema-change"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}