irudnyts / openai

An R package-wrapper around OpenAI API
https://irudnyts.github.io/openai/
Other
164 stars 28 forks source link

Returning error code? #23

Closed isinaltinkaya closed 1 year ago

isinaltinkaya commented 1 year ago

Hi! I have been using this package, and I must say I really liked it and greatly appreciate it.

Is it possible for you to return a return code with the response indicating if the returned item is a real response or an error? After ChatGPT release the server started to give error messages instead of replies occasionally. It would be awesome if it was handled in openai package.

Thanks!

irudnyts commented 1 year ago

I was developing {openai} with this principle in mind, i.e., if the error happens on the API side, I need to turn it into an R error with an explicit message.

Your use-case can be solved with tryCatch() function:

library(openai)

try_create_completion <- function(prompt) {
    tryCatch(
        create_completion(prompt),
        error = function(e) "Hey, something went wrong!" # if the error happens, this is what returned
    )
}

try_create_completion(34) # will print "Hey, something went wrong!" since it is
                          # not allowed to pass 34 as `prompt` argument

try_create_completion(34) # will be executed nomrally unless there is an issue
                          # on the server end

You can replace "Hey, something went wrong!" with FALSE, and this is going to be an indicator that there is an error.

Please let me know if this helps.