RAG+llamaindex+DSW实操

本文纯干货,不做任何原理性讲解,适合于有一定基础的伙伴进行实践,本次文章将分为以下几个部分来介绍:

  • 环境搭建
  • LlamaIndex 使用
  • 本地知识库准备
  • 基本原理:
    在这里插入图片描述

1. 环境搭建

1.1 配置基础环境

  • 创建虚拟环境,环境名称可以自行取,我的是"llamaindex"
conda create -n llamaindex python=3.10
  • 激活虚拟环境
conda activate llamaindex
  • 安装相关基础依赖 python 虚拟环境:
  • 如果已经安装,直接进行下一步:
conda install pytorch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 pytorch-cuda=11.7 -c pytorch -c nvidia
  • 检查该环境,是否已经安装完成,是否符合要求:
conda list
  • 安装python 依赖包
pip install einops==0.7.0 protobuf==5.26.1
  • 安装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
  • 注意:ERROR: pip’s dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
    lmdeploy 0.5.1 requires torch<=2.2.2,>=2.0.0, but you have torch 2.4.1 which is incompatible.
    lmdeploy 0.5.1 requires triton<=2.2.0,>=2.1.0; sys_platform == “linux”, but you have triton 3.0.0 which is incompatible
    ,执行:
  • 意思是,我们当前的torch版本,triton版本不适配lmdeploy
pip install torch==2.2.2
pip install triton==2.2.0

1.2 词向量模型相关环境

  • 这里要下载的是Sentence Transformer这个词向量模型,也可以换成其他的.
  • 首先,新建一个文件夹
mkdir llamaindex_demo
  • 然后新建一个python文件
cd llamaindex_demo/
touch download_hf.py
  • 编写代码:
import os

# 设置环境变量,设置服务器为hf的镜像服务器
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'

# 下载模型到自己指定的文件夹
os.system('huggingface-cli download --resume-download sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 --local-dir /mnt/workspace/models/sentence-transformer')
  • 下载 NLTK 相关资源,一定要安装在root目录之下,否则找不到
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
  • 安装 LlamaIndex 词嵌入向量依赖
conda activate llamaindex
pip install llama-index-embeddings-huggingface==0.2.0 llama-index-embeddings-instructor==0.1.3

2. 调试

2.1 测试基础模型

  • 在llamaindex_demo文件夹下新建llamaindex_internlm.py文件
cd ../llamaindex_demo/
touch llamaindex_internlm.py
  • 执行以下代码:
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.core.llms import ChatMessage
llm = HuggingFaceLLM(
    model_name="/mnt/workspace/models/internlm2-chat-1_8b",
    tokenizer_name="/mnt/workspace/models/internlm2-chat-1_8b",
    model_kwargs={"trust_remote_code":True},
    tokenizer_kwargs={"trust_remote_code":True}
)
#这里尽量问一个有歧义的问题,方便之后对比
rsp = llm.chat(messages=[ChatMessage(content="swift是什么?")])
print(rsp)

2.2 新建自己的知识库

  • 新建一个文件夹,主要是放自己的知识库:
mkdir data
  • 然后将自己的文档,知识内容放到这个目录下
  • 然后进入目录llamaindex_demo,新建python文件
touch 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="/mnt/workspace/models/sentence-transformer"
)
#将创建的嵌入模型赋值给全局设置的embed_model属性,
#这样在后续的索引构建过程中就会使用这个模型。
Settings.embed_model = embed_model

llm = HuggingFaceLLM(
    model_name="/mnt/workspace/models/internlm2-chat-1_8b",
    tokenizer_name="/mnt/workspace/models/internlm2-chat-1_8b",
    model_kwargs={"trust_remote_code":True},
    tokenizer_kwargs={"trust_remote_code":True}
)
#设置全局的llm属性,这样在索引查询时会使用这个模型。
Settings.llm = llm

#从指定目录读取所有文档,并加载数据到内存中
documents = SimpleDirectoryReader("/mnt/workspace/llamaindex_demo/data").load_data()
print("加载完成")
#创建一个VectorStoreIndex,并使用之前加载的文档来构建索引。
# 此索引将文档转换为向量,并存储这些向量以便于快速检索。
index = VectorStoreIndex.from_documents(documents)
# 创建一个查询引擎,这个引擎可以接收查询并返回相关文档的响应。
query_engine = index.as_query_engine()
response = query_engine.query("swift是什么?")

print(response)

3.应用

  • 至此,一款基本的可实现自定义化的知识库框架的人工智能搭建完成.
  • 如果需要增加,或者删除,只需要在"data"目录下添加,删除即可.
根据提供的引用内容,可以得知prompt+RAG的流程如下: 1. 首先,使用Retriever部分在知识库中检索出top-k个匹配的文档zi。 2. 然后,将query和k个文档拼接起来作为QA的prompt,送入seq2seq模型。 3. seq2seq模型生成回复y。 4. 如果需要进行Re-rank,可以使用LLM来rerank,给LLM写好prompt即可。 下面是一个简单的示例代码,演示如何使用prompt+RAG: ```python from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration # 初始化tokenizer、retriever和seq2seq模型 tokenizer = RagTokenizer.from_pretrained('facebook/rag-token-base') retriever = RagRetriever.from_pretrained('facebook/rag-token-base', index_name='exact', use_dummy_dataset=True) model = RagSequenceForGeneration.from_pretrained('facebook/rag-token-base') # 设置query和context query = "What is the capital of France?" context = "France is a country located in Western Europe. Paris, the capital city of France, is known for its romantic ambiance and iconic landmarks such as the Eiffel Tower." # 使用Retriever部分检索top-k个匹配的文档 retrieved_docs = retriever(query) # 将query和k个文档拼接起来作为QA的prompt input_dict = tokenizer.prepare_seq2seq_batch(query, retrieved_docs[:2], return_tensors='pt') generated = model.generate(input_ids=input_dict['input_ids'], attention_mask=input_dict['attention_mask']) # 输出生成的回复 generated_text = tokenizer.batch_decode(generated, skip_special_tokens=True)[0] print(generated_text) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值