1

I tried using the below code, but the OpenAI API doesn't have the AuthenticationError method in the library. How can I effectively handle such error.

import openai

# Set up your OpenAI credentials
openai.api_key = 'YOUR_API_KEY'

try:
    # Perform OpenAI API request
    response = openai.some_function()  # Replace with the appropriate OpenAI API function

    # Process the response
    # ...
except openai.AuthenticationError:
    # Handle the AuthenticationError
    print("Authentication error: Invalid API key or insufficient permissions.")
    # Perform any necessary actions, such as displaying an error message or exiting the program

Rok Benko
  • 14,265
  • 2
  • 24
  • 49

1 Answers1

2

Your code isn't correct.

Change this...

except openai.AuthenticationError

...to this.

except openai.error.AuthenticationError

Try the following, as shown in the official OpenAI article:

try:
  #Make your OpenAI API request here
  response = openai.Completion.create(model = "text-davinci-003", prompt = "Hello world")
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
Rok Benko
  • 14,265
  • 2
  • 24
  • 49