Llama Index中GPTSimpleVectorIndex初始化报'unexpected keyword argument'错误求助
解决Llama Index中
TypeError: __init__() got an unexpected keyword argument 'llm_predictor'错误 这个错误源于你使用的Llama Index版本(v0.8及以上)重构了索引构造API,GPTSimpleVectorIndex不再支持直接传入llm_predictor和prompt_helper参数,需要通过ServiceContext封装这些组件。
修改步骤
- 从
llama_index导入ServiceContext类 - 将
llm_predictor和prompt_helper封装到ServiceContext实例中 - 构造索引时传入
service_context参数,替代原来的两个独立参数
修改后的完整代码
from llama_index import SimpleDirectoryReader, GPTListIndex, GPTSimpleVectorIndex, LLMPredictor, PromptHelper, ServiceContext from langchain import OpenAI import gradio as gr import sys import os os.environ["OPENAI_API_KEY"] = 'MYKEY' def construct_index(directory_path): max_input_size = 4096 num_outputs = 512 max_chunk_overlap = 20 chunk_size_limit = 600 prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit) llm_predictor_gpt = LLMPredictor(llm=OpenAI(temperature=0.7, model_name="text-davinci-003", max_tokens=num_outputs)) # 封装ServiceContext service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor_gpt, prompt_helper=prompt_helper) documents = SimpleDirectoryReader(directory_path).load_data() # 用新版本推荐的from_documents方法构造索引 index = GPTSimpleVectorIndex.from_documents(documents, service_context=service_context) index.save_to_disk('index.json') return index def chatbot(input_text): index = GPTSimpleVectorIndex.load_from_disk('index.json') response = index.query(input_text, response_mode="compact") return response.response # Gradio新版本中gr.inputs.Textbox已弃用,改用gr.Textbox iface = gr.Interface(fn=chatbot, inputs=gr.Textbox(lines=7, label="Enter your text"), outputs="text", title="Custom-trained AI Chatbot") index = construct_index("salesdocs") iface.launch(share=False)
额外说明
- 新版本Llama Index推荐使用
from_documents方法构造索引,替代直接实例化的方式 - 若你的Gradio版本较新,
gr.inputs.Textbox会触发警告,替换为gr.Textbox即可消除
内容的提问来源于stack exchange,提问作者t25
相关产品推荐
相关产品推荐

