我在Visual Studio Code (VSC) 中尝试执行Python脚本时遇到了以下异常。我怀疑这是一个简单的环境配置问题,但我对Python还不太熟悉,无法找到问题所在。
无法通过Pylance解析“openai”的导入,无法通过Pylance解析“gradio”的导入
我使用的是Mac Catalina 10.15.7,VSC版本为1.75.1。我已经安装了Python、openai和gradio:
–version Python 3.9.12 (base)
–version openai 0.27.7pip install gradio
这是我的脚本:
import openaiimport gradio as grprint("Debugging AI script")openai.api_key = "..."print("API Key: " + openai.api_key)messages = [ { "role": "system", "content":"You are a helpful andd kind AI Assitant" },]def chatbot(input): if input: messages.append({ "role":"user", "content": input }) chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages = messages) reply = chat.choices[0].message.content messages.append({ "role":"assistant", "content": reply }) return reply inputs = gr.inputs.Textbox(lines=7, label="Chat with Mega Brain") outputs = gr.outputs.Textbox(label="Speak Sir") gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="AI Mega-Brain Mega-Chat", description="Ask the Brain anything", theme="compact").launch(share=True)
我尝试了许多解决方案,包括这里发布的解决方案,但都没有效果。
任何帮助都将不胜感激。谢谢
回答:
您需要确保VS Code使用的解释器与您在终端中使用的解释器相匹配。在您安装Python的环境中输入:which python
(或which python3
,这取决于您的设置)。
然后按照这些说明选择与上述命令输出相匹配的路径。
最后,我强烈建议您为每个项目设置独立的环境(参见:Mamba、Conda或Poetry,它们以略有不同的方式实现类似的目标)