使用gpt_index与langchain构建GPT-3检索索引遇参数错误求助
解决GPTSimpleVectorIndex初始化时的TypeError: unexpected keyword argument 'llm_predictor'问题
问题背景
在基于OpenAI API构建检索索引聊天机器人时,使用gpt_index库的GPTSimpleVectorIndex类初始化时传入llm_predictor和prompt_helper参数,触发错误:
TypeError: __init__() got an unexpected keyword argument 'llm_predictor'
错误原因
你参考的教程基于旧版本的gpt_index(现已更名为llama-index),新版本中GPTSimpleVectorIndex的初始化参数结构已变更,不再直接接受llm_predictor和prompt_helper作为独立参数,需要通过ServiceContext对象统一传递这些组件。
解决方案
修改代码,通过ServiceContext封装llm_predictor和prompt_helper,再传递给GPTSimpleVectorIndex:
- 导入
ServiceContext类 - 创建
ServiceContext实例,注入llm_predictor和prompt_helper - 初始化
GPTSimpleVectorIndex时传入service_context参数
修改后的完整代码
from gpt_index import SimpleDirectoryReader, GPTListIndex, readers, GPTSimpleVectorIndex, LLMPredictor, PromptHelper, ServiceContext from langchain import OpenAI import sys import os from IPython.display import Markdown, display def construct_index(directory_path): # 补充缺失的参数定义示例(根据你的实际需求调整数值) max_input_size = 4096 num_outputs = 512 max_chunk_overlap = 20 chunk_size_limit = 600 llm_predictor = LLMPredictor(llm=OpenAI(temperature=0, model_name="text-davinci-003", max_tokens=num_outputs)) prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit) # 创建ServiceContext service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper) documents = SimpleDirectoryReader(directory_path).load_data() index = GPTSimpleVectorIndex( documents, service_context=service_context ) index.save_to_disk('index.json') return index def ask_lenny(): index = GPTSimpleVectorIndex.load_from_disk('index.json') while True: query = input("What do you want to ask Lenny? ") response = index.query(query, response_mode="compact") display(Markdown(f"Lenny Bot says: <b>{response.response}</b>"))
额外说明
- 如果你的环境安装的是最新版的
llama-index(原gpt_index),导入路径需调整为from llama_index import ...,但核心逻辑一致。 - 确保你的
langchain和gpt_index(或llama-index)版本匹配,避免因版本差异导致的参数不兼容问题。
内容的提问来源于stack exchange,提问作者lionkingx
相关产品推荐
相关产品推荐

