binary-husky/gpt_academic · error · RuntimeError

No image URL found in the response.

Error message

No image URL found in the response.

What it means

After a 200 response from the NanoBanana-compatible endpoint, gen_image_banana() only sets image_url when it finds choices[0].message.images[].image_url.url. This RuntimeError means the HTTP call succeeded but the response contained no image URL. It is immediately caught by the surrounding except and usually re-raised as error 9.

Source

Thrown at crazy_functions/Image_Generate.py:259

        response = requests.post(url, headers=headers, json=payload)
        result = response.json()
        image_url = None
        generated_content = ""
        if result.get("choices"):
            message = result["choices"][0]["message"]
            if message.get("images"):
                generated_content = message.get('reasoning', "") + message.get('content', "")
                for image in message["images"]:
                    image_url = image["image_url"]["url"]
                    print(f"Generated image: {image_url[:50]}...")


        if response.status_code != 200:
            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)
            return

        if image_url is None:
            raise RuntimeError("No image URL found in the response.")

        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:

View on GitHub (pinned to d6bde0fa54)

Solutions

  1. Log response.status_code and the complete response JSON for the failing request.
  2. Confirm the configured base URL, API key, and model actually support image generation and the modalities field.
  3. Inspect generated_content for safety/refusal text and rewrite the prompt if needed.
  4. Switch to a supported NanoBanana/Gemini image model or provider.
  5. Add an explicit schema check that reports the missing field instead of a generic no-URL error.

Example fix

# before
if image_url is None:
    raise RuntimeError("No image URL found in the response.")

# after
if image_url is None:
    raise RuntimeError(
        "No image URL found in the response. "
        f"Status={response.status_code}, content={generated_content!r}, payload={result!r}"
    )
Defensive patterns

Strategy: validation

Validate before calling

payload = {
    "model": expected_image_model,
    "modalities": ["image", "text"],
    ...
}
assert "image" in payload["modalities"]
assert api_key and base_url.startswith(("http://", "https://"))

Type guard

def has_banana_image_url(result) -> bool:
    try:
        images = result["choices"][0]["message"]["images"]
        return bool(images) and isinstance(images[0]["image_url"]["url"], str) and bool(images[0]["image_url"]["url"])
    except (KeyError, IndexError, TypeError):
        return False

Try / catch

try:
    yield from gen_image_banana(...)
except RuntimeError as e:
    if "No image URL" in str(e):
        log_banana_payload_and_prompt()
    raise

Prevention

When it happens

Trigger: The model returns text only, a safety filter refuses the prompt, the response has no choices, message.images is absent or empty, or the provider uses a different response schema.

Common situations: The relay/model named google/gemini-3-pro-image-preview is not actually enabled for image output; GEMINI_API_KEY/GEMINI_BASE_URL or ONE_API key lacks image access; prompt is blocked; quota is exhausted; a provider returns an OpenAI chat schema without the images extension.

Related errors


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