Search code examples
pythonpython-3.xpipopenai-api

ImportError: cannot import name 'Iterator' from 'typing_extensions'


When I try to install openai on my Google Colab, I get this error:

from openai import OpenAI


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-6-5ee9a4e68b89> in <cell line: 1>()
----> 1 from openai import OpenAI

5 frames
/usr/local/lib/python3.10/dist-packages/openai/_utils/_streams.py in <module>
      1 from typing import Any
----> 2 from typing_extensions import Iterator, AsyncIterator
      3 
      4 
      5 def consume_sync_iterator(iterator: Iterator[Any]) -> None:

ImportError: cannot import name 'Iterator' from 'typing_extensions' (/usr/local/lib/python3.10/dist-packages/typing_extensions.py)

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.

My details to reproduce:

Python 3.10.12

OS is Windows 11

typing_extensions is 4.9.0

Edit:

my typing_extensions details:

enter image description here


Solution

  • I found a related issue on OpenAI forum:

    https://community.openai.com/t/error-while-importing-openai-from-open-import-openai/578166/26

    Solution 1:

    Credit to @Aymane_oub

    pip install --force-reinstall typing-extensions==4.5
    pip install --force-reinstall openai==1.8
    

    Solution 2:

    Credit to @Shannon-21

    After navigating through the answers I found that I can change the import of the file that is trying to import Iterator from typing_extensions in this way (On Google Colab):

    %%writefile /usr/local/lib/python3.10/dist-packages/openai/_utils/_streams.py
    from typing import Any
    from typing_extensions import AsyncIterator
    from typing import Iterator # import Iterator from the correct library
    
    def consume_sync_iterator(iterator: Iterator[Any]) -> None:
        for _ in iterator:
            ...
    
    async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None:
        async for _ in iterator:
            ...
    

    #output enter image description here

    After running the above code on my colab cell, I was able to use:

    enter image description here

    Link to answer : https://community.openai.com/t/error-while-importing-openai-from-open-import-openai/578166/27?u=rubeenatalha313