Dall-E error handling in python

I’m trying to catch errors in python discord requests to Dall-E 3.
The trouble is, I’m not super comfortable in Python, so its entirely possible I’m one misunderstanding away from having this fully working.

What I would like, ideally, is if the image generation fails, my code to send error information back as ‘response’ (that’s the variable that gets printed in Discord).

I’ve tried like a dozen different variants of this code, but it all just falls right through the except blocks.

Currently, either the image generates successfully, leading to:

  • response = “”
  • embed = a discord embed object with the generated image in it

These work great

Or the generation fails, because one of my friends put in something rude or whatever, the code falls right through all the “except” blocks and returns a blank response and a None embed. Why? :frowning:

Code:

from openai Import OpenAI
ai_client = OpenAI()

#other stuff

def DallE(prompt):
    embed = None
    createdImage = None
    response = ''
    try :
        createdImage = ai_client.images.generate(
            model="dall-e-3",
            prompt=prompt,
            n=1,
            size="1024x1024"
        )
        embed = discord.Embed(description=prompt.strip())
        embed.set_image(url=createdImage.data[0].url)
    except openai.BadRequestError as e:
        print(f"BadRequestError: {e}")
        response = 'error'
        if e.response:
            response = "e.status: " + e.response.status
        else:
            response = "e.message: " + e.message
        pass
    except:
        print("Fall-through Exception")
        response = 'Unexpected error, sorry.'
        pass
    finally:
        return embed,response

# other stuff

The error I’m trying to catch and print to discord is this, although I’d like to ideally catch ALL errors and print them to discord:

openai.BadRequestError: Error code: 400 - {'error': {'code': 'content_policy_violation', 'message': 'Your request was rejected as a result of our safety system. Your prompt may contain text that is not allowed by our safety system.', 'param': None, 'type': 'invalid_request_error'}}

The openai library has error values. However, the OpenAI class imported alone doesn’t give handling.

import openai

Then openai.BadRequestError is a case that be given unique handling.

Here’s just a paste of a framework, placing methods for almost everything one might encounter, although there may be further message-based actions you may want to discriminate.

try:
    response = client.chat.completions.with_raw_response.create(
        model=self.aimodel.currentText(),
        messages = mymessages,
        temperature=softmax_temperature,
        max_tokens=response_tokens,
        top_p=top_p_set,
    )
except openai.error.Timeout as e:
    # Handle timeout error, e.g. retry or log
    print(f"OpenAI API request timed out: {e}")
    pass
except openai.error.APIError as e:
    # Handle API error, e.g. retry or log
    print(f"OpenAI API returned an API Error: {e}")
    pass
except openai.error.APIConnectionError as e:
    # Handle connection error, e.g. check network or log
    print(f"OpenAI API request failed to connect: {e}")
    pass
except openai.error.InvalidRequestError as e:
    # Handle invalid request error, e.g. validate parameters or log
    print(f"OpenAI API request was invalid: {e}")
    pass
except openai.error.AuthenticationError as e:
    # Handle authentication error, e.g. check credentials or log
    print(f"OpenAI API request was not authorized: {e}")
    pass
except openai.error.PermissionError as e:
    # Handle permission error, e.g. check scope or log
    print(f"OpenAI API request was not permitted: {e}")
    pass
except openai.error.RateLimitError as e:
    # Handle rate limit error, e.g. wait or log
    print(f"OpenAI API request exceeded rate limit: {e}")
    pass
except Exception as e:
    error_message = f"Error: {str(e)}"
    print(error_message)
    # general handling
    pass

Perfect, thank you! That cleared a ton of things up.