Getting error when import openai to python

时间:2024-10-26 07:45:08

题意:OpenAI 的库导入到 Python 项目中时遇到错误

问题背景 :

I installed openai using this command:

我使用这条命令安装了 openai:

pip install openai

When I import openai I'm getting this kind of error.

当我尝试导入 openai 时,我遇到了这种错误

How do I fix this issue?

我怎样解决这个问题?

  1. Traceback (most recent call last):
  2. File "test_1.py", line 1, in <module>
  3. import openai
  4. File "/home/nadun/.local/lib/python2.7/site-packages/openai/__init__.py", line 30, in <module>
  5. from openai.api_resources import * # noqa
  6. File "/home/nadun/.local/lib/python2.7/site-packages/openai/api_resources/__init__.py", line 1, in <module>
  7. from openai.api_resources.completion import Completion
  8. File "/home/nadun/.local/lib/python2.7/site-packages/openai/api_resources/", line 14
  9. def create(cls, *args, timeout=None, **kwargs):
  10. ^
  11. SyntaxError: invalid syntax

问题解决:

Looks like you have installed openai at the python 2.7 and it needs python 3.

看起来你在 Python 2.7 上安装了 openai,但它需要 Python 3

Step by step guide if you need help on that:

如果你需要这方面的帮助,以下是一个逐步指南

Check your environment version: python -V

使用命令检查你的环境版本

The output should be something like: Python 2.7.*

输出结果应该是类似: ...

What worked for me was uninstalling the openai at Python 2.7: pip uninstall openai

对我来说有效的方法是在 Python 2.7 环境中卸载 openai:pip uninstall openai

Installing python 3 and making sure the environment is set to it, you can manage that with pyenv. Once you have pyenv installed and a version 3 installed (at this day, my version is 3.11.3), you should be able to run those commands:

pyenv versions

安装 Python 3 并确保环境已设置为它,你可以使用 pyenv 来管理。一旦你安装了 pyenv 并安装了 Python 3 的一个版本(目前,我的版本是 3.11.3),你应该能够运行以下命令:

It should output a version 3.*. If it does not appear, check the "manage that with pyenv" link again.

它应该会输出一个 3.* 版本的编号。如果没有出现,请再次检查“使用 pyenv 管理”的链接。

Set your environment version to 3 (in my case, 3.11.3): pyenv global 3.11.3

设置你的环境版本为 3(在我的情况下是 3.11.3):pyenv global 3.11.3

Check your environment is set to 3.* : python -V

检查你的环境是否设置为 3.* 版本:python -V

The output should be something like: Python 3.*

输出应该是类似于:Python 3.*

Then install openai cli: pip install --upgrade openai

然后安装 openai 命令行界面(CLI):pip install --upgrade openai