{"record":{"id":"a6bc9f12361740d9","repo":"binary-husky/gpt_academic","slug":"invalid-image-url-format","errorCode":null,"errorMessage":"Invalid image URL format.","messagePattern":"Invalid image URL format\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"crazy_functions/Image_Generate.py","lineNumber":273,"sourceCode":"            yield from update_ui_latest_msg(lastmsg=f\"Generate Failed\\n\\n{generated_content}\\n\\nStatus Code: {response.status_code}\", chatbot=chatbot, history=history, delay=0)\n            return\n\n        if image_url is None:\n            raise RuntimeError(\"No image URL found in the response.\")\n\n        logger.info(f'Generated image.')\n        yield from update_ui_latest_msg(lastmsg=f\"Downloading image\", chatbot=chatbot, history=history, delay=0)\n\n        if ';base64,' in image_url:\n            base64_string = image_url.split('base64,')[-1]\n            image_data = base64.b64decode(base64_string)\n            file_path = f'{get_log_folder()}/image_gen/'\n            os.makedirs(file_path, exist_ok=True)\n            file_name = 'Image' + time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime()) + '.png'\n            fp = file_path+file_name\n            with open(fp, 'wb+') as f: f.write(image_data)\n        else:\n            raise ValueError(\"Invalid image URL format.\")\n\n        return image_url, fp\n\n    except Exception as e:\n        yield from update_ui_latest_msg(lastmsg=f\"Generate failed, please try again later.\", chatbot=chatbot, history=history, delay=0)\n        raise RuntimeError(f\"Failed to generate image, please try again later: {str(e)}\")\n\n\n\n\n\n\n\n\n\n@CatchException\ndef 图片生成_NanoBanana(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, user_request):\n    history = []    # 清空历史,以免输入溢出","sourceCodeStart":255,"sourceCodeEnd":291,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/crazy_functions/Image_Generate.py#L255-L291","documentation":"gen_image_banana() supports only inline data URIs: it requires ';base64,' in image_url. If the provider returns an ordinary https URL or a malformed URL, this ValueError is raised. Like error 7, it is caught immediately and normally surfaces wrapped as error 9.","triggerScenarios":"The image endpoint returns https://.../image.png instead of data:image/png;base64,..., or the nested image_url.url field has an unexpected format.","commonSituations":"Using an OpenAI-compatible relay that returns temporary download URLs; a NanoBanana proxy configured not to inline base64; partial URL truncation; provider schema changes.","solutions":["Log image_url to see whether it is an https URL or malformed data.","Add an else branch that downloads the remote URL, as gen_image() already does.","Configure the provider/relay to return base64 data URIs if local download is undesirable.","Validate the URL scheme before decoding base64.","Preserve the original ValueError in the outer error message."],"exampleFix":"# before\nif ';base64,' in image_url:\n    ...\nelse:\n    raise ValueError(\"Invalid image URL format.\")\n\n# after\nif image_url.startswith((\"http://\", \"https://\")):\n    r = requests.get(image_url, proxies=proxies, timeout=120)\n    r.raise_for_status()\n    image_data = r.content\nelif \";base64,\" in image_url:\n    image_data = base64.b64decode(image_url.split(\"base64,\", 1)[1])\nelse:\n    raise ValueError(f\"Invalid image URL format: {image_url[:100]}\")\n","handlingStrategy":"validation","validationCode":"from urllib.parse import urlparse\nparsed = urlparse(image_url or \"\")\nis_data_uri = (image_url or \"\").startswith(\"data:\") and \";base64,\" in image_url\nis_http_url = parsed.scheme in {\"http\", \"https\"} and bool(parsed.netloc)\nassert is_data_uri or is_http_url\n","typeGuard":"def classify_image_url(url) -> str:\n    if not isinstance(url, str) or not url:\n        return \"invalid\"\n    if url.startswith(\"data:\") and \";base64,\" in url:\n        return \"base64\"\n    if urlparse(url).scheme in {\"http\", \"https\"} and urlparse(url).netloc:\n        return \"remote\"\n    return \"invalid\"\n","tryCatchPattern":"try:\n    image_data = decode_or_download_image(image_url)\nexcept ValueError as e:\n    report_unsupported_image_url(image_url)\n    raise\n","preventionTips":["Do not assume every image API returns inline base64.","Support both data URIs and temporary https URLs.","Validate URL scheme before base64 decoding.","Log a truncated URL for schema debugging."],"tags":["image-generation","url","base64","downloading"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}