Python import openai 异常报错的解决方法

在使用 OpenAI API 的项目时,使用 pip install openai 安装后,执行 import openai 报错:ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with LibreSSL 2.8.3. See: https://github.com/urllib3/urllib3/issues/2168,本文主要记录一下解决这个报错异常的方法。

报错信息:

 Python 3.9.6 (default, Mar 10 2023, 20:16:38)
[Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import openai

Traceback (most recent call last):
  File "", line 1, in 
  File "/Users/yule/Library/Python/3.9/lib/python/site-packages/openai/__init__.py", line 19, in 
    from openai.api_resources import (
  File "/Users/mic/Library/Python/3.9/lib/python/site-packages/openai/api_resources/__init__.py", line 1, in 
    from openai.api_resources.audio import Audio  # noqa: F401
  File "/Users/mic/Library/Python/3.9/lib/python/site-packages/openai/api_resources/audio.py", line 4, in 
    from openai import api_requestor, util
  File "/Users/mic/Library/Python/3.9/lib/python/site-packages/openai/api_requestor.py", line 22, in 
    import requests
  File "/Users/mic/Library/Python/3.9/lib/python/site-packages/requests/__init__.py", line 43, in 
    import urllib3
  File "/Users/mic/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py", line 38, in 
    raise ImportError(
ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with LibreSSL 2.8.3. See: https://github.com/urllib3/urllib3/issues/2168

问题原因:

Python 环境中当前安装的“ssl”模块版本是使用 LibreSSL 2.8.3 编译的,该版本与 urllib3 v2.0 不兼容。

解决方法:

安装兼容的openssl:

brew install openssl@1.1

或者可以安装兼容的urllib3:

pip install urllib3==1.26.6

pip uninstall urllib3
pip install 'urllib3<2.0'

推荐阅读
cjavapy编程之路首页