Fix the modulenotfounderror no module named openai exception

Solve the no module named openai error in Python

Proceed as following to solve the no module named openai in your Python development environment:

  1. Save your Python script or Notebook.
  2. Open your Windows command window or Anaconda prompt for your environment. For macOS and Linux open the terminal app.
  3. Run the following command: pip3 install openai. On Conda / Anaconda distributions run: conda install openai
  4. The package and its dependencies will be collected and installed.
  5. Close your command prompt or terminal window.
  6. Open your script and keep your coding.

Understanding the openai not found exception in Python

The Open AI library is a 3rd party add-on that is not shipped as part of Python. Hence, you will need install the Open AI Python package before using libraries such as Embeddings, ChatCompletions, Image Generation , Moderations and so forth.

If you call the openai library before importing it first to Jupyter Notebook , Colab, VSCode, PyCharm, Spyder or any other Python development environment you will get the following error:

You will encounter a similar issue when calling not installed Python library including LLM related libraries such as langchain.

Fix the modulenotfounderror Open AI

Local or Virtual Environments

  1. Save your Python script.
  2. Open the command prompt / terminal app
  3. Navigate to the root directory of your Python environment.
  4. Type the following command: pip3 install openai
  5. The package will be connected from the Python Package library and installed.
  6. Once the installation finish, restart your Python development app or Notebook.

Related: How to fix installation of the Python PyTorch package?

Anaconda Navigator

If you are using Conda / MiniConda / Anaconda distributions, proceed as following:

  1. Open your Python Script.
  2. If you are using a Windows operating system, open the Anaconda Prompt application.
  3. Alternatively, open your macOS / Ubuntu terminal app.
  4. Activate your environment by typing: conda activate <path_to_your_env>.
  5. Type the following command: conda install openai.
  6. Restart your Python IDE.