{"record":{"id":"b380bde5bf2e8ec2","repo":"binary-husky/gpt_academic","slug":"response-content-decode","errorCode":null,"errorMessage":"response.content.decode()","messagePattern":"response\\.content\\.decode\\(\\)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"crazy_functions/Image_Generate.py","lineNumber":42,"sourceCode":"        'Content-Type': 'application/json'\n    }\n    data = {\n        'prompt': prompt,\n        'n': 1,\n        'size': resolution,\n        'model': model,\n        'response_format': 'url'\n    }\n    if quality is not None:\n        data['quality'] = quality\n    if style is not None:\n        data['style'] = style\n    response = requests.post(url, headers=headers, json=data, proxies=proxies)\n    # logger.info(response.content)\n    try:\n        image_url = json.loads(response.content.decode('utf8'))['data'][0]['url']\n    except:\n        raise RuntimeError(response.content.decode())\n    # 文件保存到本地\n    r = requests.get(image_url, proxies=proxies)\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    with open(file_path+file_name, 'wb+') as f: f.write(r.content)\n\n\n    return image_url, file_path+file_name\n\n\ndef edit_image(llm_kwargs, prompt, image_path, resolution=\"1024x1024\", model=\"dall-e-2\"):\n    from request_llms.bridge_all import model_info\n\n    proxies = get_conf('proxies')\n    api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model'])\n    chat_endpoint = model_info[llm_kwargs['llm_model']]['endpoint']\n    # 'https://api.openai.com/v1/chat/completions'","sourceCodeStart":24,"sourceCodeEnd":60,"githubUrl":"https://github.com/binary-husky/gpt_academic/blob/d6bde0fa54373309bd05823a49bda8da019d2c77/crazy_functions/Image_Generate.py#L24-L60","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Print or log response.status_code and response.text to get the real provider error.","Verify the selected model's endpoint becomes a valid images/generations URL and that the provider supports the configured image model.","Check the API key and quota for the selected key pool.","Use valid combinations such as DALL-E 2 sizes 256x256/512x512/1024x1024 and supported DALL-E 3 sizes/quality/style values.","Parse b64_json as a fallback when url is absent."],"exampleFix":"# before\nresponse = requests.post(url, headers=headers, json=data, proxies=proxies)\ntry:\n    image_url = json.loads(response.content.decode('utf8'))['data'][0]['url']\nexcept:\n    raise RuntimeError(response.content.decode())\n\n# after\nresponse = requests.post(url, headers=headers, json=data, proxies=proxies, timeout=120)\ntry:\n    payload = response.json()\nexcept Exception as e:\n    raise RuntimeError(f\"Invalid image API response {response.status_code}: {response.text}\") from e\nif not response.ok:\n    raise RuntimeError(f\"Image API error {response.status_code}: {payload}\")\nitem = payload.get(\"data\", [{}])[0]\nimage_url = item.get(\"url\")\nif not image_url and item.get(\"b64_json\"):\n    image_url = \"data:image/png;base64,\" + item[\"b64_json\"]\nif not image_url:\n    raise RuntimeError(f\"Image API returned no URL: {payload}\")\n","handlingStrategy":"try-catch","validationCode":"valid_sizes = {\"256x256\", \"512x512\", \"1024x1024\"} if model == \"dall-e-2\" else {\"1024x1024\", \"1792x1024\", \"1024x1792\"}\nassert resolution in valid_sizes, resolution\nassert model_info[llm_kwargs[\"llm_model\"]][\"endpoint\"].endswith(\"/chat/completions\")\n","typeGuard":"def is_url_image_response(payload) -> bool:\n    return (\n        isinstance(payload, dict)\n        and isinstance(payload.get(\"data\"), list)\n        and len(payload[\"data\"]) > 0\n        and isinstance(payload[\"data\"][0].get(\"url\"), str)\n        and payload[\"data\"][0][\"url\"].startswith((\"http://\", \"https://\", \"data:image/\"))\n    )\n","tryCatchPattern":"try:\n    image_url, path = gen_image(...)\nexcept RuntimeError as e:\n    show_image_api_error(e)\n    raise\n","preventionTips":["Check the model endpoint supports images/generations.","Use model-specific valid sizes and styles.","Always log status code and response body for image APIs.","Handle both url and b64_json response formats."],"tags":["openai","image-generation","http","api-response"],"backgroundTag":null,"analyzedSha":"d6bde0fa54373309bd05823a49bda8da019d2c77","analyzedAt":"2026-08-14T22:48:35.038Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}