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

使用OpenAI库调用Embedding接口出现AttributeError问题求助

问题

运行基于openai库的Python脚本时,执行以下函数触发报错:

def gpt3_embedding(content, engine='text-embedding-ada-002'):
    #delay_print('Making a vector')
    content = content.encode(encoding='ASCII',errors='ignore').decode()
    response = openai.Embedding.create(input=content,model=engine)
    vector = response['data'][0]['embedding']  # this is a normal list
    #delay_print('Vector returned')
    return vector

报错信息:

AttributeError: module 'openai' has no attribute 'Embedding'

注:使用最新版openai包和Python 3.11.1,正常情况下该错误不应出现。

解决步骤
  • 确认openai版本并升级:
    执行pip show openai查看当前版本,若版本低于v1.x,运行pip install --upgrade openai完成升级。注意如果存在多Python环境,要确保使用对应环境的pip命令。
  • 排查命名冲突:
    检查脚本所在目录是否存在名为openai.py的自定义文件,该文件会覆盖官方库导致导入错误,若有则立即重命名。同时确保脚本开头的导入语句为import openai,避免子模块导入或重命名引发的冲突。
  • 适配新版API调用格式:
    新版openai库(v1.x+)将Embedding改为小写的embeddings,且返回结果为对象而非字典。修改后的函数代码如下:
def gpt3_embedding(content, engine='text-embedding-ada-002'):
    content = content.encode(encoding='ASCII',errors='ignore').decode()
    response = openai.embeddings.create(input=content, model=engine)
    vector = response.data[0].embedding
    return vector
  • 验证密钥配置:
    确保已通过openai.api_key = "你的API密钥"或设置环境变量OPENAI_API_KEY完成密钥配置,避免因权限问题引发的间接错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:39:27