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

llama-index 0.7.2构建文本语料库索引时遇ChatCompletion导入错误求助

问题:llama-index 0.7.2版本导入ChatCompletion失败

我编写了Python代码,通过llama-index从文本语料库构建索引并提交查询获取响应。该代码在llama-index 0.6.9版本的机器上可正常运行,但升级到0.7.2版本后出现ImportError,提示无法从openai导入ChatCompletion。

代码示例

# function to index corpus and get response

def index_response(api_key, text_path,query):
    
    # api key you generate in your openai account
    
    import os
    
    # add your openai api key here
    
    os.environ['OPENAI_API_KEY']=api_key
    
    # Load your data into 'Documents' a custom type by llamaIndex
    from llama_index import SimpleDiretoryReader, Document
    
    with open(text_path,'r') as file:
        
        text_history = file.read()
        
    documents = [Document(text_history)]
    
    from llama_index import GPTVectorStoreIndex
    
    index = GPTVectorStoreIndex.from_documents(documents)
    
    query_engine = index.as_query_engine()
    response=query_engine.query(query)
    
    return response.response
    
    

# initial query

prompt="This is some text to help clarify my search.  "

query1="Here is my question?"

prompt_submit=prompt+query1

# prompt_submit

response_string=index_response(api_key=apikey, 
               text_path='~/path/data/',
               query=prompt_submit)

response_string

错误信息

ImportError: cannot import name 'ChatCompletion' from 'openai' (/home/user/anaconda3/envs/LLMenv/lib/python3.10/site-packages/openai/__init__.py)

解决方法

  • 安装兼容版本的openai库:llama-index 0.7.2与openai 0.28.x版本兼容,执行以下命令降级openai:
    pip install openai==0.28.1
    
  • 修正代码拼写错误:原代码中SimpleDiretoryReader拼写错误,应改为SimpleDirectoryReader,避免后续读取文件时出现异常。
  • 若需使用openai 1.x+版本,需调整llama-index的配置以适配新版openai的接口变更,但此方法复杂度较高,优先推荐降级openai到兼容版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:45:03