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

如何在LlamaIndex中使用本地部署的开源LLM替代OpenAI模型?

使用本地开源LLM(如llama-7b-chat)替代ChatGPT的LlamaIndex代码修改方案

完全可以修改现有代码来调用本地已下载权重的开源LLM,以下是具体修改步骤和完整代码:

核心修改点

  • 移除OpenAI API Key相关配置,改用LlamaIndex对本地LLM的支持组件
  • 将原有的GPTVectorStoreIndex替换为通用的VectorStoreIndex(避免绑定OpenAI模型)
  • 配置本地LLM的运行参数,指定模型路径、上下文窗口等

修改后的完整代码

1. 从文本语料库创建并保存索引

# 创建索引并保存
from llama_index import SimpleDirectoryReader, VectorStoreIndex

# 加载本地文本数据
documents = SimpleDirectoryReader('./data').load_data()

# 创建通用向量索引(不再绑定OpenAI)
index = VectorStoreIndex.from_documents(documents)

# 保存存储上下文到本地文件
storage_context_dict = index.storage_context.to_dict()
import json
json.dump(storage_context_dict, open("general_attributes_storage_context_dict.json", 'w'))

2. 加载已保存索引并调用本地LLM查询

# 加载保存的索引并使用本地LLM查询
import json
from llama_index import StorageContext, load_index_from_storage
from llama_index.llms import LlamaCPP
from llama_index.llms.llama_utils import messages_to_prompt, completion_to_prompt

# 加载本地LLM模型,替换为你的模型文件路径
llm = LlamaCPP(
    model_path="./llama-7b-chat.gguf.q4_0.bin",  # 本地模型文件路径
    temperature=0.1,
    max_new_tokens=256,
    context_window=3900,
    generate_kwargs={},
    model_kwargs={"n_gpu_layers": 1},  # 根据GPU配置调整,无GPU可设为0
    messages_to_prompt=messages_to_prompt,
    completion_to_prompt=completion_to_prompt,
    verbose=True,
)

# 加载存储上下文
saved_context = json.load(open("general_attributes_storage_context_dict.json"))
storage_context = StorageContext.from_dict(saved_context)
stored_index = load_index_from_storage(storage_context)

# 将本地LLM绑定到查询引擎
query_engine = stored_index.as_query_engine(llm=llm)
response = query_engine.query("some question")
print(response)

注意事项

  • 确保已安装依赖包:pip install llama-index llama-cpp-python
  • 模型文件需为GGUF格式(llama-7b-chat的GGUF版本可从官方渠道下载)
  • 根据硬件配置调整n_gpu_layers参数,GPU显存不足时可降低该值或设为0(纯CPU运行)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:46:02