Search code examples
openai-api

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


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)

Solution

  • 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.