AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


AI大模型RAG:LlamaIndex与Qwen2的检索增强生成技术解析
发布日期:2024-08-09 12:36:56 浏览次数: 1826


一、引言

在人工智能的浪潮中,大模型技术以其卓越的数据处理和语言理解能力,成为智能化进程的加速器。特别是检索增强生成(RAG)技术,它通过结合检索系统的高效性和生成模型的创造性,为智能问答系统的发展提供了新动力。本文将深入探讨如何利用LlamaIndexQwen2,实现RAG技术的快速部署和智能交互。


二、概述


本文将深入剖析LlamaIndexQwen2的结合,探讨如何实现高效的RAG技术,赋予AI大模型检索外部数据并生成精准回答的能力。我们将从技术原理到实践部署,逐步引导读者了解RAG技术的核心优势和应用潜力。

LlamaIndex是一种创新的索引构建工具,专为AI模型设计,能够高效地处理和索引化各类文档、网页等数据。它为Qwen2等大模型提供了访问和利用海量知识库的能力,极大地扩展了模型的应用场景和深度。


RAG技术的核心优势在于其结合了检索系统的快速响应和生成模型的创造性。LlamaIndex的引入,使得Qwen2能够快速检索到相关信息,并基于这些信息生成准确、丰富的回答,极大地提升了智能问答系统的性能和用户体验。


三、模型下载安装

1、下载语言模型


首先,我们需要下载Qwen2-7B-Instruct模型,以支持多语言对话能力。以下是使用snapshot_download函数进行模型下载的示例代码:

import torchfrom modelscope import snapshot_download# snapshot_download函数用于下载模型model_dir = snapshot_download('qwen/Qwen2-7B-Instruct',# 模型名称cache_dir='/root/autodl-tmp',# 缓存目录revision='master'# 版本号)

2、下载嵌入模型

同样,我们也需要下载bge-base-zh-v1.5模型,以支持中文文档的检索。下载过程与语言模型类似:

import torchfrom modelscope import snapshot_download# snapshot_download函数用于下载模型model_dir = snapshot_download('AI-ModelScope/bge-base-zh-v1.5',# 模型名称cache_dir='/root/autodl-tmp',# 缓存目录revision='master'# 版本号)

3、安装 LlamaIndex

通过pip命令安装LlamaIndex及其相关扩展包,为RAG技术的实践部署打下基础:

pip install llama-indexpip install llama-index-llms-huggingfacepip install llama-index-readers-webpip install llama-index-corepip install llama-index-llms-openaipip install llama-index-llms-replicatepip install llama-index-embeddings-huggingface

四、模型加载

1、导入依赖库


在设置模型之前,需要导入所有必要的依赖库:

import torchfrom llama_index.core import Settingsfrom llama_index.core.node_parser import SentenceSplitterfrom llama_index.llms.huggingface import HuggingFaceLLMfrom llama_index.embeddings.huggingface import HuggingFaceEmbedding

2、设置提示模版

定义生成提示模板,以增强模型的回答生成能力:


# Set prompt template for generation (optional)from llama_index.core import PromptTemplatedef completion_to_prompt(completion):return f"<|im_start|>system\n<|im_end|>\n<|im_start|>user\n{completion}<|im_end|>\n<|im_start|>assistant\n"def messages_to_prompt(messages):prompt = ""for message in messages:if message.role == "system":prompt += f"<|im_start|>system\n{message.content}<|im_end|>\n"elif message.role == "user":prompt += f"<|im_start|>user\n{message.content}<|im_end|>\n"elif message.role == "assistant":prompt += f"<|im_start|>assistant\n{message.content}<|im_end|>\n"if not prompt.startswith("<|im_start|>system"):prompt = "<|im_start|>system\n" + promptprompt = prompt + "<|im_start|>assistant\n"return prompt

3、加载语言模型

配置Qwen2作为语言模型,并设定生成配置,包括上下文窗口大小和新令牌数量等参数:

# Set Qwen2 as the language model and set generation configSettings.llm = HuggingFaceLLM(model_name="/root/autodl-tmp/qwen/Qwen2-7B-Instruct",tokenizer_name="/root/autodl-tmp/qwen/Qwen2-7B-Instruct",#model_name="Qwen/Qwen2-7B-Instruct",#tokenizer_name="Qwen/Qwen2-7B-Instruct",context_window=30000,max_new_tokens=2000,generate_kwargs={"temperature": 0.7, "top_k": 50, "top_p": 0.95},messages_to_prompt=messages_to_prompt,completion_to_prompt=completion_to_prompt,device_map="auto",)

加载成功如下:

4、加载嵌入模型


选择适当的嵌入模型,以支持文档的向量化处理:

# Set embedding modelSettings.embed_model = HuggingFaceEmbedding(model_name = "/root/autodl-tmp/AI-ModelScope/bge-base-zh-v1.5")

5、设置文件分块大小

定义文件分块大小,以优化检索效率:

# Set the size of the text chunk for retrievalSettings.transformations = [SentenceSplitter(chunk_size=1024)]
五、构建索引
现在我们可以从文档或网站构建索引。


1、文档内容索引构建


以下代码片段展示了如何为本地名为’document’的文件夹中的文件(无论是PDF格式还是TXT格式)构建索引。


在文件夹中放入:谜语问答游戏.pdf

from llama_index.core import VectorStoreIndex, SimpleDirectoryReaderdocuments = SimpleDirectoryReader("./document").load_data()index = VectorStoreIndex.from_documents(documents,embed_model=Settings.embed_model,transformations=Settings.transformations)

2、网站内容索引构建

以下代码片段展示了如何为一系列网站的内容构建索引。
from llama_index.readers.web import SimpleWebPageReaderfrom llama_index.core import VectorStoreIndex, SimpleDirectoryReaderdocuments = SimpleWebPageReader(html_to_text=True).load_data(["web_address_1","web_address_2",...])index = VectorStoreIndex.from_documents(documents,embed_model=Settings.embed_model,transformations=Settings.transformations)

检索增强(RAG测试

现在您可以输入查询,Qwen2 将基于索引文档的内容提供答案。


1、第一轮提问:

query_engine = index.as_query_engine()your_query = "你是谁?"print(query_engine.query(your_query).response)

输出:

根据给定的上下文信息,无法直接回答“你是谁?”这个问题,因为它要求提供身份或自我介绍的信息,而这在提供的内容中并未提及。所以,基于给定的信息集,这个问题的答案不能被确定。

2、第二轮提问:

query_engine = index.as_query_engine()your_query = "什么是属于你的,但其他人比你使用它更多?"print(query_engine.query(your_query).response)

输出:

你的名字。```

3、第三轮提问:

query_engine = index.as_query_engine()your_query = "路的左边有一座绿房子,路的右边有一座红房子。那么,白宫在哪里?"print(query_engine.query(your_query).response)

输出:

在美国华盛顿。

七、索引保存加载

1、索引保存到本地


数据默认存储在内存中。 要保留到磁盘(在):./storage (会自动在同级目录创建文件夹storage
index.storage_context.persist()

执行后保存文件如下:

2、从磁盘重新加载索引


from llama_index.core import StorageContext, load_index_from_storage# rebuild storage contextstorage_context = StorageContext.from_defaults(persist_dir="./storage")# load indexindex = load_index_from_storage(storage_context)

3、加载后重新测试

query_engine = index.as_query_engine()your_query = "没有翅膀我也能飞翔。没有眼睛我也能哭。每当我走的时候,黑暗就跟着我。我是什么?"print(query_engine.query(your_query).response)

输出:

一朵云。

八、结语

通过本文的实践部署,我们成功地将 LlamaIndex Qwen2 结合,实现了高效的 RAG 技术。这不仅提升了智能问答系统的性能,也为开发者提供了一个强大的工具,以构建更加智能和响应迅速的 AI 应用。随着技术的不断发展,我们期待看到更多创新的 RAG 应用出现,推动 AI 领域的进步。


点亮“关注”,设为“星标”,精彩不迷路!我们携手探索AI的无限可能,精彩内容,持续为您更新!


53AI,企业落地应用大模型首选服务商

产品:大模型应用平台+智能体定制开发+落地咨询服务

承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

与创始人交个朋友

回到顶部

 
扫码咨询