While working with API to edit image, I got the following error:
Attempt 1/3 failed: 400 Client Error: Bad Request for url:
"https://api.openai.com/v1/images/edits"
Retrying in 5 seconds…
Attempt 2/3 failed: 500 Server Error: Internal Server Error for url: https://api.openai.com/v1/images/edits
Retrying in 5 seconds…
Attempt 3/3 failed: 500 Server Error: Internal Server Error for url: https://api.openai.com/v1/images/edits
Error: Max retries reached. Check API key, network, or server status.
API Error: The server had an error processing your request. Sorry about that! You can retry your request, or contact us through our help center at help.openai.com if you keep seeing this error. (Please include the request ID req_e558c2bbb2416b28bc702c64bc86874a in your email.) (Code: None)
Error: Unexpected response format. Check API response.
The API key is working. I have checked. Some part of the Code is:
API endpoint
url = "https://api.openai.com/v1/images/edits"
Prepare the data payload
data = {
“model”: “dall-e-2”, # Use the correct model for image editing
“prompt”: prompt,
“n”: 1, # Generate one image
“response_format”: “b64_json”, # Return base64-encoded image
}
Set headers with authorization
headers = {
“Authorization”: f"Bearer {API_KEY}"
}
Files list, sending image as a file to OpenAI
files = {
“image”: (os.path.basename(image_path), open(image_path, “rb”), “image/png”),
}
Retry mechanism
max_retries = 3
retry_delay = 5 # seconds
for attempt in range(max_retries):
try:
# Send the request to the OpenAI API for image editing
response = requests.post(url, headers=headers, files=files, data=data)
response.raise_for_status() # Check for HTTP errors
break
except requests.exceptions.RequestException as e:
print(f"Attempt {attempt + 1}/{max_retries} failed: {e}“)
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds…”)
time.sleep(retry_delay)
else:
print(“Error: Max retries reached. Check API key, network, or server status.”)
files[“image”][1].close() # Close the file before exit
exit(1)
Any idea about how to solve this?

