binary-husky/gpt_academic · error · RuntimeError

response.content.decode()

Error message

response.content.decode()

What it means

gen_image() posts to an OpenAI-compatible /images/generations endpoint and expects response JSON to contain data[0].url. Any other body is converted to RuntimeError(response.content.decode()). The status code is not checked, so HTTP errors, HTML proxy pages, and valid b64_json responses all take this path.

Source

Thrown at crazy_functions/Image_Generate.py:42

        'Content-Type': 'application/json'
    }
    data = {
        'prompt': prompt,
        'n': 1,
        'size': resolution,
        'model': model,
        'response_format': 'url'
    }
    if quality is not None:
        data['quality'] = quality
    if style is not None:
        data['style'] = style
    response = requests.post(url, headers=headers, json=data, proxies=proxies)
    # logger.info(response.content)
    try:
        image_url = json.loads(response.content.decode('utf8'))['data'][0]['url']
    except:
        raise RuntimeError(response.content.decode())
    # 文件保存到本地
    r = requests.get(image_url, proxies=proxies)
    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'
    with open(file_path+file_name, 'wb+') as f: f.write(r.content)


    return image_url, file_path+file_name


def edit_image(llm_kwargs, prompt, image_path, resolution="1024x1024", model="dall-e-2"):
    from request_llms.bridge_all import model_info

    proxies = get_conf('proxies')
    api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model'])
    chat_endpoint = model_info[llm_kwargs['llm_model']]['endpoint']
    # 'https://api.openai.com/v1/chat/completions'

View on GitHub (pinned to d6bde0fa54)

Solutions

  1. Print or log response.status_code and response.text to get the real provider error.
  2. Verify the selected model's endpoint becomes a valid images/generations URL and that the provider supports the configured image model.
  3. Check the API key and quota for the selected key pool.
  4. Use valid combinations such as DALL-E 2 sizes 256x256/512x512/1024x1024 and supported DALL-E 3 sizes/quality/style values.
  5. Parse b64_json as a fallback when url is absent.

Example fix

# before
response = requests.post(url, headers=headers, json=data, proxies=proxies)
try:
    image_url = json.loads(response.content.decode('utf8'))['data'][0]['url']
except:
    raise RuntimeError(response.content.decode())

# after
response = requests.post(url, headers=headers, json=data, proxies=proxies, timeout=120)
try:
    payload = response.json()
except Exception as e:
    raise RuntimeError(f"Invalid image API response {response.status_code}: {response.text}") from e
if not response.ok:
    raise RuntimeError(f"Image API error {response.status_code}: {payload}")
item = payload.get("data", [{}])[0]
image_url = item.get("url")
if not image_url and item.get("b64_json"):
    image_url = "data:image/png;base64," + item["b64_json"]
if not image_url:
    raise RuntimeError(f"Image API returned no URL: {payload}")
Defensive patterns

Strategy: try-catch

Validate before calling

valid_sizes = {"256x256", "512x512", "1024x1024"} if model == "dall-e-2" else {"1024x1024", "1792x1024", "1024x1792"}
assert resolution in valid_sizes, resolution
assert model_info[llm_kwargs["llm_model"]]["endpoint"].endswith("/chat/completions")

Type guard

def is_url_image_response(payload) -> bool:
    return (
        isinstance(payload, dict)
        and isinstance(payload.get("data"), list)
        and len(payload["data"]) > 0
        and isinstance(payload["data"][0].get("url"), str)
        and payload["data"][0]["url"].startswith(("http://", "https://", "data:image/"))
    )

Try / catch

try:
    image_url, path = gen_image(...)
except RuntimeError as e:
    show_image_api_error(e)
    raise

Prevention

When it happens

Trigger: requests.post returns 401 for a bad API key, 400 for an invalid model/resolution/quality/style, 404 when the chat endpoint replacement does not map to an image endpoint, 429/5xx from a relay, or JSON whose data item contains b64_json instead of url.

Common situations: The selected GPT chat model is routed through a third-party endpoint that does not support DALL-E; DALL-E 3 receives a DALL-E 2 size; ONE_API/API_KEY is invalid; a proxy returns HTML; response_format is changed to b64_json by the relay.

Related errors


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