原文:书生实战llamaindex+RAG
未使用RAG进行提问“Xtuner是什么?”,模型无法准确回答。使用RAG技术后模型能够回答“Xtuner是什么?”。
前四小结是对上面链接书生实战的复现,第五节是对前四小节的应用。
GPU显存运行大概8G到10G左右。
本人小白,有错的地方还请多多指教。
最终效果:
一、环境配置和模型准备
1.创建conda环境,并安装相关依赖
conda create -n llamaindex python=3.10
conda activate llamaindex
conda install pytorch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 pytorch-cuda=11.7 -c pytorch -c nvidia
pip install einops
pip install protobuf
2.安装Llamaindex
安装 Llamaindex和相关的包
conda activate llamaindex
pip install llama-index==0.10.38 llama-index-llms-huggingface==0.2.0 "transformers[torch]==4.41.1" "huggingface_hub[inference]==0.23.1" huggingface_hub==0.23.1 sentence-transformers==2.7.0 sentencepiece==0.2.0
3.下载 Sentence Transformer 模型
源词向量模型 Sentence Transformer:(也可以选用别的开源词向量模型来进行 Embedding,目前选用这个模型是相对轻量、支持中文且效果较好的,同学们可以自由尝试别的开源词向量模型)
新建一个python文件
cd ~
mkdir llamaindex_demo
mkdir model
cd ~/llamaindex_demo
touch download_hf.py
打开download_hf.py
贴入以下代码
import os
# 设置环境变量
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
# 下载模型
os.system('huggingface-cli download --resume-download sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 --local-dir /root/model/sentence-transformer')
在 /root/llamaindex_demo 目录下执行该脚本即可自动开始下载:
cd /root/llamaindex_demo
conda activate llamaindex
python download_hf.py
下载NLTK相关资源:
cd /root
git clone https://gitee.com/yzy0612/nltk_data.git --branch gh-pages
cd nltk_data
mv packages/* ./
cd tokenizers
unzip punkt.zip
cd ../taggers
unzip averaged_perceptron_tagger.zip
二、lamaIndex HuggingFaceLLM
运行以下指令,把 InternLM2 1.8B
软连接出来:
cd ~/model
ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-1_8b/ ./
新建一个python文件:
cd ~/llamaindex_demo
touch llamaindex_internlm.py
打开llamaindex_internlm.py 贴入以下代码
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.core.llms import ChatMessage
llm = HuggingFaceLLM(
model_name="/root/model/internlm2-chat-1_8b",
tokenizer_name="/root/model/internlm2-chat-1_8b",
model_kwargs={"trust_remote_code":True},
tokenizer_kwargs={"trust_remote_code":True}
)
rsp = llm.chat(messages=[ChatMessage(content="xtuner是什么?")])
print(rsp)
运行:
conda activate llamaindex
cd ~/llamaindex_demo/
python llamaindex_internlm.py
llamaindex_internlm.py运行结果:
三、LlamaIndex RAG
安装 LlamaIndex
词嵌入向量依赖
conda activate llamaindex
pip install llama-index-embeddings-huggingface llama-index-embeddings-instructor
运行以下命令,获取知识库
cd ~/llamaindex_demo
mkdir data
cd data
git clone https://github.com/InternLM/xtuner.git
mv xtuner/README_zh-CN.md ./
运行以下指令,新建一个python文件
cd ~/llamaindex_demo
touch llamaindex_RAG.py
打开llamaindex_RAG.py
贴入以下代码
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM
#初始化一个HuggingFaceEmbedding对象,用于将文本转换为向量表示
embed_model = HuggingFaceEmbedding(
#指定了一个预训练的sentence-transformer模型的路径
model_name="/root/model/sentence-transformer"
)
#将创建的嵌入模型赋值给全局设置的embed_model属性,
#这样在后续的索引构建过程中就会使用这个模型。
Settings.embed_model = embed_model
llm = HuggingFaceLLM(
model_name="/root/model/internlm2-chat-1_8b",
tokenizer_name="/root/model/internlm2-chat-1_8b",
model_kwargs={"trust_remote_code":True},
tokenizer_kwargs={"trust_remote_code":True}
)
#设置全局的llm属性,这样在索引查询时会使用这个模型。
Settings.llm = llm
#从指定目录读取所有文档,并加载数据到内存中
documents = SimpleDirectoryReader("/root/llamaindex_demo/data").load_data()
#创建一个VectorStoreIndex,并使用之前加载的文档来构建索引。
# 此索引将文档转换为向量,并存储这些向量以便于快速检索。
index = VectorStoreIndex.from_documents(documents)
# 创建一个查询引擎,这个引擎可以接收查询并返回相关文档的响应。
query_engine = index.as_query_engine()
response = query_engine.query("xtuner是什么?")
print(response)
运行llamaindex_RAG.py:
conda activate llamaindex
cd ~/llamaindex_demo/
python llamaindex_RAG.py
llamaindex_RAG.py运行结果:
四、LlamaIndex web
运行之前首先安装依赖
pip install streamlit==1.36.0
运行以下指令,新建一个python文件
cd ~/llamaindex_demo
touch app.py
打开app.py
贴入以下代码
import streamlit as st
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM
st.set_page_config(page_title="llama_index_demo", page_icon="🦜🔗")
st.title("llama_index_demo")
# 初始化模型
@st.cache_resource
def init_models():
embed_model = HuggingFaceEmbedding(
model_name="/root/model/sentence-transformer"
)
Settings.embed_model = embed_model
llm = HuggingFaceLLM(
model_name="/root/model/internlm2-chat-1_8b",
tokenizer_name="/root/model/internlm2-chat-1_8b",
model_kwargs={"trust_remote_code": True},
tokenizer_kwargs={"trust_remote_code": True}
)
Settings.llm = llm
documents = SimpleDirectoryReader("/root/llamaindex_demo/data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
return query_engine
# 检查是否需要初始化模型
if 'query_engine' not in st.session_state:
st.session_state['query_engine'] = init_models()
def greet2(question):
response = st.session_state['query_engine'].query(question)
return response
# Store LLM generated responses
if "messages" not in st.session_state.keys():
st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?"}]
# Display or clear chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.write(message["content"])
def clear_chat_history():
st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?"}]
st.sidebar.button('Clear Chat History', on_click=clear_chat_history)
# Function for generating LLaMA2 response
def generate_llama_index_response(prompt_input):
return greet2(prompt_input)
# User-provided prompt
if prompt := st.chat_input():
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.write(prompt)
# Gegenerate_llama_index_response last message is not from assistant
if st.session_state.messages[-1]["role"] != "assistant":
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
response = generate_llama_index_response(prompt)
placeholder = st.empty()
placeholder.markdown(response)
message = {"role": "assistant", "content": response}
st.session_state.messages.append(message)
运行:
streamlit run app.py
运行结果:
我是通过vscode自动映射访问的,没有访问上图中的url。运行app.py后,VScode的端口(PORTS)界面会自动映射url,点击即可跳转至浏览器进行访问。
最终效果:
五、 进行llamaindex构建自己的文档检索功能
1.创建txt文件,内容随意,文件名随意,也可以是.md文件:
以我自己的为例,把上面两个txt文件放在一个datatest文件夹里 ,然后地址是/root/llamaindex_demo/datatest
2.测试llamaindex_internlm.py能否回答你txt文档相关的问题
比如问题“介绍一下英雄联盟杰斯”
然后修改llamaindex_internlm.py文档,把下图中“xtuner是什么?”修改成“介绍一下英雄联盟杰斯”或者你自己的问题。
然后终端运行llamaindex_internlm.py:
conda activate llamaindex
cd ~/llamaindex_demo/
python llamaindex_internlm.py
运行结果:
可以看到都是模型乱回答的,已经出现胡言乱语了,模型应该知道英雄联盟是款游戏,但是对杰斯的具体信息还是不太了解,自己编造的一些信息。
3. 使用llamaindex能否正确回答问题
修改llamaindex_RAG.py文档,把下图中“xtuner是什么?”修改成“介绍一下英雄联盟杰斯”或者你自己的问题。
地址修改成刚创建txt文件夹的地址,例如:/root/llamaindex_demo/datatest
运行llamaindex_RAG.py:
conda activate llamaindex
cd ~/llamaindex_demo/
python llamaindex_RAG.py
运行结果如下:
引用的txt文档如下:
总结:
能够通过引用回答出杰斯的信息,并且是符合杰斯的。
4.web界面
只需要修改app.py中的读取文件地址就够了,如下图,改成txt文件的地址
然后运行app.py:
streamlit run app.py
最终运行结果: