ImportError: cannot import name 'OpenAI' from partially initialized module 'openai' (most likely due to a circular import)
Asked Answered
E

5

9

I am trying to use the OpenAI Python SDK, I installed the latest version via pip and verified that it is installed via pip list. Now when I go to run the code and make a simple request I get an error that there is a circular import which I have never seen before.

from openai import OpenAI

client = OpenAI()
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    response_format={"type": "json_object"},
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant designed to output JSON.",
        },
        {"role": "user", "content": "Who won the world series in 2020?"},
    ],
)
print(response.content)

Here is the error:

ImportError: cannot import name 'OpenAI' from partially initialized module 'openai' (most likely due to a circular import) (.../.pyenv/versions/3.11.5/lib/python3.11/site-packages/openai/__init__.py)
Ecklund answered 10/11, 2023 at 18:45 Comment(1)
pip uninstall openai; pip install openai community.openai.com/t/cannot-import-name-openai-from-openai/…Kingsize
P
16

The problem was that the file was called json.py – renaming it fixed the error. This can also happen if you call your file openai.py.

Palestra answered 10/11, 2023 at 18:56 Comment(1)
My file was named openai.py. Didn't even cross my mind I was trying to reference itself this way.Margie
T
7

Simple Solution to this:

Make sure to update the package:pip install openai --upgrade

Thalia answered 26/12, 2023 at 13:22 Comment(0)
C
3

Make sure your executable/current/working file name is not openai.py

And you have installed the latest version of openai (currently: 1.10.11)

Churchill answered 30/1 at 18:31 Comment(0)
L
0

Installing the module using the git link worked for me. Make sure to delete the existing openai module in your site-packages folder or use pip uninstall openai

pip install git+https://github.com/openai/openai-python
Lanneret answered 17/4 at 18:34 Comment(0)
B
0

My problem was that I was getting my openai and OpenAI confused.

WRONG

from langchain import openai

this should be:

CORRECT

from langchain import OpenAI
Buhrstone answered 1/5 at 23:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.