gpt4 book ai didi

python - OpenAI API : How do I handle errors in Python?

转载 作者:行者123 更新时间:2023-12-02 22:47:09 25 4
gpt4 key购买 nike

我尝试使用以下代码,但 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

最佳答案

您的代码不正确。

改变这个...

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

关于python - OpenAI API : How do I handle errors in Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76363168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com