You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS Code中Python的openai/gradio导入无法被Pylance解析求助

解决Pylance提示"Import 'openai'/'gradio' could not be resolved"问题

检查VS Code关联的Python解释器

  • 打开VS Code,按Cmd+Shift+P唤起命令面板,输入Python: Select Interpreter
  • 在弹出的列表中选择你安装的Python 3.9.12版本(通常显示为python3.9或包含虚拟环境路径的选项)
  • 若列表中无对应版本,手动输入解释器路径:Mac下Python3.9的默认安装路径多为/usr/local/bin/python3.9或~/Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9

验证包是否安装在目标解释器环境

  • 打开终端,执行以下命令确认openai和gradio的安装状态:
    python3.9 -m pip list | grep -E "openai|gradio"
    
  • 若输出中无这两个包,使用对应解释器重新安装:
    python3.9 -m pip install openai==0.27.7 gradio
    

手动配置VS Code设置(可选)

  • 若上述步骤无效,直接在settings.json中指定解释器和包路径:
    1. 按Cmd+,打开设置面板,搜索python.pythonPath,将值设为你的Python3.9路径,例如:
      "python.pythonPath": "/usr/local/bin/python3.9"
      
    2. 添加Pylance额外路径配置,确保它能找到包:
      "python.analysis.extraPaths": [
          "/usr/local/lib/python3.9/site-packages"
      ]
      
      (路径可通过python3.9 -c "import site; print(site.getsitepackages())"获取实际地址)

重启VS Code

完成所有配置后,关闭并重新打开VS Code,Pylance的导入提示即可消除。

附带脚本修正提示

你的脚本中Gradio界面的代码被缩进在chatbot函数内部,会导致只有当输入为空时才启动界面,需将这部分代码移到函数外部,修正后代码如下:

import openai
import gradio as gr

print("Debugging AI script")
openai.api_key = "..."

print("API Key: " + openai.api_key)

messages = [
    {
        "role": "system",
        "content":"You are a helpful and kind AI Assistant"
    },
]

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

# 将Gradio界面代码移到函数外部
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)

内容的提问来源于stack exchange,提问作者dancingbush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 08:03:12