Llamaindex RAG实践-第三期闯关大挑战

1.1 配置基础环境

在资源配置中, 30% A100 * 1 的选项,如果使用10% A100 * 1,无法运行。

1.2 安装 Llamaindex

conda activate demo
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

1.3 下载 Sentence Transformer 模型

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 demo
python download_hf.py

1.4 下载 NLTK 相关资源

使用开源词向量模型构建开源词向量的时候,需要用到第三方库 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

2. LlamaIndex 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 demo
cd ~/llamaindex_demo/
python llamaindex_internlm.py

3. LlamaIndex RAG

安装 LlamaIndex 词嵌入向量依赖

conda activate demo
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)

之后运行

conda activate demo
cd ~/llamaindex_demo/
python llamaindex_RAG.py

4. LlamaIndex web

运行以下指令,新建一个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

根据之前的端口转发方式:

ssh -p {开发机端口} root@ssh.intern-ai.org.cn -CNg -L 7860:127.0.0.1:8501 -o StrictHostKeyChecking=no

LLamaIndex RAG (Retrieval-Augmented Generation) 是一种结合了检索增强生成技术的语言模型应用框架。它通过将传统的语言模型与信息检索系统相结合,使得在生成文本时能够利用外部知识库的信息。 以下是关于 LLamaIndex RAG 的详细介绍: ### 检索增强生成的基本原理 RAG的核心思想是在生成过程中引入额外的知识来源,而不是仅仅依赖于预训练数据集本身。这有助于提高生成内容的相关性和准确性,特别是在需要特定领域专业知识的任务上更为有效。 #### 工作流程概述 1. **查询理解**:首先对用户输入的问题或其他形式的提示进行编码处理; 2. **文档检索**:从预先构建好的数据库、网页等资源中找到最相关的几段文字作为背景材料; 3. **融合表示**:将上述获取到的内容同原始提问一起送入下游任务专用模块内做进一步加工转化; 4. **结果输出**:最终得到的答案既包含了来自范围上下文环境下的自然流畅表达又具备着精确指向性的细节补充说明。 ### 应用场景示例 - 客服机器人可以借助企业内部FAQ文档提供更准确的服务解答。 - 医疗咨询助手依据权威医学文献给出专业建议。 - 教育平台根据教材知识点定制化出题组卷等功能都可以受益于这项技术创新带来的便利之处。 总之,通过集成搜索引擎的能力让机器学习模型更好地服务于实际需求成为了当前研究热点之一,并且随着技术进步未来还会有更多可能性等待探索发现!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值