ezzcodeezzlife / dalle2-in-python

Use DALL·E 2 in Python
https://pypi.org/project/dalle2/
MIT License
177 stars 34 forks source link

Raise specifically typed exceptions when a request fails #16

Open nathanfdunn opened 2 years ago

nathanfdunn commented 2 years ago

Is your feature request related to a problem? Please describe. When a request to Dalle fails, the reason is logged but None is returned. This makes it difficult to programmatically figure out why the request failed and respond appropriately. For instance, if a request fails because the prompt violates safety standards, you may want to tell the user to try a different prompts. But if a request fails because of a lack of credits, you may want to tell the user to go add more credits before they try again.

Describe the solution you'd like I think it would be helpful for the Dalle2 client to raise exceptions when there are problems so code like the following would work

import dalle2

try:
    images = dalle2.Dalle2('sess-XXXX').generate('prompt')
except: dalle2.exceptions.PromptRejectedException:
    return {'message': 'Try a different prompt'}
except: dalle2.exceptions.OutOfCreditsException:
    return {'message': 'Please refill your credits'}

Describe alternatives you've considered This would be a breaking change, so it should be considered carefully. Here are some alternatives that would preserve backwards compatibility:

Provide a context object dalle2.error_status that would provide information about the most recent request (similar to how Flask provides a request context object https://flask.palletsprojects.com/en/1.1.x/reqcontext/)

import dalle2

images = dalle2.Dalle2('sess-XXXX').generate('prompt')
if images is None:
    if dalle2.error_status.reason == dalle2.ErrorStatusReason.PROMPT_REJECTED:
        print('Prompt Rejected:', dalle2.error_status.message)
    elif dalle2.error_status.reason == dalle2.ErrorStatusReason.OUT_OF_CREDITS:
        ...
    else:
        ...

But this is less clean and more error prone than exceptions.

Have exceptions be opt-in like client = Dalle2('sess-XXXX', raise_on_error=True). But adding configuration overhead like this would make the package code more complex and also could cause a fair amount of friction for users.

github-actions[bot] commented 2 years ago

Thanks you for your first issue in dalle2-in-python

ezzcodeezzlife commented 2 years ago

yeah great idea. do you want to tackle this issue? seems like you have some experience with this. could assign you @nathanfdunn