binary-husky/gpt_academic · error · RuntimeError

Failed to generate image, please try again later

Error message

Failed to generate image, please try again later: {str(e)}

What it means

This is the catch-all wrapper around gen_image_banana(). Every exception in the try block is shown as a generic failure message and re-raised as RuntimeError with only str(e). It hides whether the real failure was error 7, error 8, requests.post, response.json(), base64 decoding, or writing the output file.

Solutions

  1. Capture the full exception chain and log response details instead of relying on the generic message.
  2. Verify GEMINI/ONE_API configuration and test the endpoint with the same payload.
  3. Handle both https and base64 image URLs.
  4. Retry only transient network/5xx failures with backoff.
  5. Ensure get_log_folder()/image_gen is writable.

Example fix

# before
except Exception as e:
    yield from update_ui_latest_msg(...)
    raise RuntimeError(f"Failed to generate image, please try again later: {str(e)}")

# after
except Exception as e:
    logger.exception("NanoBanana image generation failed")
    yield from update_ui_latest_msg(...)
    raise RuntimeError(
        f"Failed to generate image: {type(e).__name__}: {e}"
    ) from e
Defensive patterns

Strategy: try-catch

Validate before calling

api_key = get_conf("GEMINI_API_KEY") if not get_conf("REROUTE_ALL_TO_ONE_API") else get_conf("ONE_API_KEY")
if not api_key:
    raise ValueError("Image API key is not configured")
if not get_conf("REROUTE_ALL_TO_ONE_API") and not get_conf("GEMINI_BASE_URL"):
    raise ValueError("GEMINI_BASE_URL is not configured")

Try / catch

try:
    yield from gen_image_banana(...)
except RuntimeError as e:
    logger.exception("Image plugin failed")
    chatbot.append(["图像生成失败", str(e)])
    yield from update_ui(chatbot=chatbot, history=history)

Prevention

When it happens

Trigger: Any network/request exception; missing or malformed JSON; missing choices/message/images/image_url fields; a non-base64 URL; invalid resolution/aspect ratio; quota/authentication failure; inability to create gpt_log/image_gen or write the PNG.

Common situations: Wrong GEMINI_BASE_URL/GEMINI_API_KEY or ONE_API_URL/ONE_API_KEY; model not enabled for images; provider returns https rather than base64; disk permission issues; transient network failure.

Related errors


AI-assisted analysis of binary-husky/gpt_academic@d6bde0fa54 (2026-08-14). Data as JSON: /api/errors/715646770e2bd948. Report an issue: GitHub.

Appendix: source

Thrown at crazy_functions/Image_Generate.py:279

        logger.info(f'Generated image.')
        yield from update_ui_latest_msg(lastmsg=f"Downloading image", chatbot=chatbot, history=history, delay=0)

        if ';base64,' in image_url:
            base64_string = image_url.split('base64,')[-1]
            image_data = base64.b64decode(base64_string)
            file_path = f'{get_log_folder()}/image_gen/'
            os.makedirs(file_path, exist_ok=True)
            file_name = 'Image' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.png'
            fp = file_path+file_name
            with open(fp, 'wb+') as f: f.write(image_data)
        else:
            raise ValueError("Invalid image URL format.")

        return image_url, fp

    except Exception as e:
        yield from update_ui_latest_msg(lastmsg=f"Generate failed, please try again later.", chatbot=chatbot, history=history, delay=0)
        raise RuntimeError(f"Failed to generate image, please try again later: {str(e)}")









@CatchException
def 图片生成_NanoBanana(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, user_request):
    history = []    # 清空历史,以免输入溢出

    if prompt.strip() == "":
        chatbot.append((prompt, "[Local Message] 图像生成提示为空白"))
        yield from update_ui(chatbot=chatbot, history=history)
        return
    chatbot.append((

View on GitHub (pinned to d6bde0fa54)