微信扫码
添加专属顾问
我要投稿
构建智能RAG系统,提升回答的准确性和时效性。 核心内容: 1. RAG技术的原理和优势 2. 系统构建所需的关键技术栈 3. 实施步骤:加载PDF文档并进行处理
Retrieval-Augmented Generation(RAG)技术已经成为了一项革命性的突破。它打破了传统语言模型仅依赖预训练知识的局限,通过动态检索外部信息,生成更加相关和准确的回答。本文将详细介绍如何使用LangChain、FAISS和DeepSeek-LLM构建一个处理PDF文档、检索相关内容并生成智能响应的RAG系统。
RAG技术是一种结合了检索和生成能力的新型语言模型应用方式。其核心在于,首先使用一个检索器从知识库中获取与查询相关的文档片段,然后基于这些检索到的上下文,利用语言模型(LLM)生成回答。这种方式显著提高了回答的准确性和时效性,因为它能够实时地、基于事实地、动态地生成响应。
在构建 RAG 系统时,选择合适的技术工具至关重要。本文所介绍的系统使用了以下几种关键技术:
首先,我们使用LangChain的PyPDFLoader加载PDF文件,并将其拆分成较小的文本块。这一步骤是为了方便后续对文本进行向量化处理。
from langchain.document_loaders import PyPDFLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterpdf = "/kaggle/input/about-me-rag/about-me-rag.pdf" # PDF File Path# Load the PDFloader = PyPDFLoader(pdf)documents = loader.load()# Split the text into chunkstext_splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=50)texts = text_splitter.split_documents(documents)
接下来,我们使用Hugging Face Sentence Transformers将文本块转换成向量嵌入,并将这些嵌入存储在FAISS中。这样,我们就可以在需要时高效地检索到与查询相关的文本块。
from langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.vectorstores import FAISS# Load embedding modelembeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")# Create vector storevector_store = FAISS.from_documents(texts, embeddings)vector_store.save_local("faiss_index") # Save for reuse
DeepSeek-LLM模型用于生成回答。我们利用Hugging Face Transformers库加载这个模型,并确保它在GPU上运行以加速处理速度。
from transformers import AutoTokenizer, AutoModelForCausalLMimport torchmodel_version = "deepseek-ai/deepseek-llm-7b-chat"tokenizer = AutoTokenizer.from_pretrained(model_version)model = AutoModelForCausalLM.from_pretrained(model_version)# Move model to GPU if availabledevice = "cuda" if torch.cuda.is_available() else "cpu"model = model.to(device)
现在,我们将所有组件连接在一起,形成一个完整的RAG管道。我们使用LangChain的RetrievalQA模块来实现这一点,它允许我们定义检索器、语言模型和提示模板。
from langchain.llms import HuggingFacePipelinefrom transformers import pipelinefrom langchain.prompts import PromptTemplatefrom langchain.chains import RetrievalQA# Define the retrieverretriever = vector_store.as_retriever(search_kwargs={"k": 3}) # Retrieve top 3 chunks# Create a Hugging Face pipeline for text generationpipe = pipeline( "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=256, temperature=0.7)# Wrap the pipeline for LangChain compatibilityllm = HuggingFacePipeline(pipeline=pipe)# Define the Prompt Templatetemplate = """Use the following context to answer the question. If unsure, say "I don't know."Context:{context}Question: {question}Answer:"""prompt = PromptTemplate(template=template, input_variables=["context", "question"])# Define the RAG Chainrag_chain = RetrievalQA.from_chain_type( llm=llm, retriever=retriever, chain_type_kwargs={"prompt": prompt}, return_source_documents=True)
最后,我们可以向系统提出查询,并基于PDF文档的内容获得回答。RAG管道会检索相关文本块,并使用DeepSeek-LLM模型生成回答。
query = "What is Singistic?"result = rag_chain({"query": query})# Extract the generated answeranswer = result["result"].split("Answer:")[1].strip()print(answer)
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2024-10-27
2024-09-04
2024-07-18
2024-05-05
2024-06-20
2024-06-13
2024-07-09
2024-07-09
2024-05-19
2024-07-07