Cannot import OpenAI class from openai library - import error

I’m having trouble updating my code to use the new OpenAI API after they made changes to their library. I upgraded from version 0.28.0 to 1.10.0 but now I keep getting an import error when trying to use the OpenAI class.

The weird thing is that it works fine when I test it in a Python shell, but fails when running through my Flask app with gunicorn on my EC2 server.

Here’s my code:

from openai import OpenAI
api_client = OpenAI()

def generate_response(user_input):
    result = api_client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {
                "role": "user", 
                "content": user_input
            }
        ],
        temperature=0.8,
        max_tokens=200
    )
    return result.choices[0].message.content

The error I get is: ImportError: cannot import name 'OpenAI' from 'openai'

I tried reinstalling the package and upgrading it but nothing seems to work. Has anyone run into this issue before? What could be causing the difference between the Python shell and the Flask environment?

It appears you’re likely encountering an environment issue. When you run your code in the Python shell, it’s likely utilizing a different Python environment than your Flask app when invoked with gunicorn. To resolve this, make sure to activate the correct virtual environment where the OpenAI package is installed before starting your gunicorn server. You might also want to check your Flask application’s sys.path to confirm which directories it’s accessing for module imports. Additionally, ensure that your requirements.txt has the correct version specified and that all dependencies are installed in the same environment where gunicorn is executed.