OpenAI API:如何处理Python中的错误?

ffx8fchx  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(299)

我尝试使用下面的代码,但OpenAI API在库中没有AuthenticationError方法。如何有效地处理这样的错误。

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
mlmc2os5

mlmc2os51#

您的代码不正确。

把这个换了。。

except openai.AuthenticationError

...这个

except openai.error.AuthenticationError

尝试以下操作,如官方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

相关问题