Issue
I am having an issue installing the openai.error
package in Python. This is what I am trying to install:
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import openai
from openai.error import OpenAIError
import re
import os
After installing the OpenAI package, I thought the openai.error
package would install automatically. However, it gives me this error:
Traceback (most recent call last):
File "c:\Users\User\Downloads\Examiner.Production\IELTS_Examiner_Private\app.py", line 4, in <module>
from openai.error import OpenAIError
ModuleNotFoundError: No module named 'openai.error'
Solution
Just use import openai
and that's it. Remove from openai.error import OpenAIError
.
Then simply handle errors as follows:
import os
from openai import OpenAI
client = OpenAI()
OpenAI.api_key = os.getenv('OPENAI_API_KEY')
try:
# Make your OpenAI API request here
response = client.completions.create(model="gpt-3.5-turbo-instruct",
prompt="Say this is a test")
print(response)
except client.error.Timeout as e:
# Handle timeout error, e.g. retry or log
print(f"OpenAI API request timed out: {e}")
pass
except client.error.APIError as e:
# Handle API error, e.g. retry or log
print(f"OpenAI API returned an API Error: {e}")
pass
except client.error.APIConnectionError as e:
# Handle connection error, e.g. check network or log
print(f"OpenAI API request failed to connect: {e}")
pass
except client.error.InvalidRequestError as e:
# Handle invalid request error, e.g. validate parameters or log
print(f"OpenAI API request was invalid: {e}")
pass
except client.error.AuthenticationError as e:
# Handle authentication error, e.g. check credentials or log
print(f"OpenAI API request was not authorized: {e}")
pass
except client.error.PermissionError as e:
# Handle permission error, e.g. check scope or log
print(f"OpenAI API request was not permitted: {e}")
pass
except client.error.RateLimitError as e:
# Handle rate limit error, e.g. wait or log
print(f"OpenAI API request exceeded rate limit: {e}")
pass
See the official OpenAI documentation.
EDIT
If you don't want to handle every error type separately, simply print whatever error pops up.
import os
from openai import OpenAI
client = OpenAI()
OpenAI.api_key = os.getenv('OPENAI_API_KEY')
try:
# Make your OpenAI API request here
response = client.completions.create(model="gpt-3.5-turbo-instruct",
prompt="Say this is a test")
print(response)
except client.error as e:
# Handle errors
print(e)
Answered By - Rok Benko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.