基于DeepSeek R1的RAG实战
你是否曾希望直接向 PDF 或技术手册提问?本指南将向你展示如何使用开源推理工具 DeepSeek R1 和用于运行本地 AI 模型的轻量级框架 Ollama 构建检索增强生成 (RAG) 系统。
1、为什么选择 DeepSeek R1?
DeepSeek R1 是一种与 OpenAI 的 o1 相当但便宜 95% 的模型,它正在彻底改变 RAG 系统。开发人员喜欢它,因为它:
- 重点检索:每个答案仅使用 3 个文档块。
- 严格提示:避免用“我不知道”的回答产生幻觉。
- 本地执行:消除云 API 延迟。
2、构建本地 RAG 系统所需的条件
2.1 Ollama
Ollama 可让你在本地运行 DeepSeek R1 等模型。
- 下载:Ollama
- 设置:通过终端安装并运行以下命令。
ollama run deepseek-r1 # For the 7B model (default)
2.2 DeepSeek R1 模型变体
DeepSeek R1 参数范围从 1.5B 到 671B。对于轻量级 RAG 应用程序,请从 1.5B 模型开始。
ollama run deepseek-r1:1.5b
专业提示:较大的模型(例如 70B)提供更好的推理能力,但需要更多 RAM。
3、构建 RAG 管道的分步指南
3.1 导入库
我们将使用:
import streamlit as st
from langchain_community.document_loaders import PDFPlumberLoader
from langchain_experimental.text_splitter import SemanticChunker
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.llms import Ollama
3.2 上传和处理 PDF
利用 Streamlit 的文件上传器选择本地 PDF。使用 PDFPlumberLoader
高效提取文本,无需手动解析。
# Streamlit file uploader
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
if uploaded_file:
# Save PDF temporarily
with open("temp.pdf", "wb") as f:
f.write(uploaded_file.getvalue())
# Load PDF text
loader = PDFPlumberLoader("temp.pdf")
docs = loader.load()
3.3 策略性地分块文档
利用 Streamlit 的文件上传器选择本地 PDF。使用 SemanticChunker
策略性地分块文本。
# Split text into semantic chunks
text_splitter = SemanticChunker(HuggingFaceEmbeddings())
documents = text_splitter.split_documents(docs)
3.4 创建可搜索的知识库
为块生成向量嵌入并将其存储在 FAISS 索引中。
嵌入允许快速、上下文相关的搜索。
# Generate embeddings
embeddings = HuggingFaceEmbeddings()
vector_store = FAISS.from_documents(documents, embeddings)
# Connect retriever
retriever = vector_store.as_retriever(search_kwargs={"k": 3}) # Fetch top 3 chunks
3.5 配置 DeepSeek R1
使用 DeepSeek R1 1.5B 模型设置 RetrievalQA 链。
这可确保答案以 PDF 的内容为基础,而不是依赖于模型的训练数据。
llm = Ollama(model="deepseek-r1:1.5b") # Our 1.5B parameter model
# Craft the prompt template
prompt = """
1. Use ONLY the context below.
2. If unsure, say "I don’t know".
3. Keep answers under 4 sentences.
Context: {context}
Question: {question}
Answer:
"""
QA_CHAIN_PROMPT = PromptTemplate.from_template(prompt)
3.6 组装 RAG 链
将上传、分块和检索集成到一个有凝聚力的管道中。
这种方法为模型提供了经过验证的上下文,从而提高了准确性。
# Chain 1: Generate answers
llm_chain = LLMChain(llm=llm, prompt=QA_CHAIN_PROMPT)
# Chain 2: Combine document chunks
document_prompt = PromptTemplate(
template="Context:\ncontent:{page_content}\nsource:{source}",
input_variables=["page_content", "source"]
)
# Final RAG pipeline
qa = RetrievalQA(
combine_documents_chain=StuffDocumentsChain(
llm_chain=llm_chain,
document_prompt=document_prompt
),
retriever=retriever
)
3.7 启动 Web 界面
Streamlit 使用户能够键入问题并立即获得答案。
查询检索匹配的块,将它们提供给模型,并实时显示结果。
# Streamlit UI
user_input = st.text_input("Ask your PDF a question:")
if user_input:
with st.spinner("Thinking..."):
response = qa(user_input)["result"]
st.write(response)
你可以在此处找到完整代码。
4、使用 DeepSeek 的 RAG 的未来
DeepSeek R1 只是一个开始。借助即将推出的自我验证和多跳推理等功能,未来的 RAG 系统可以自主辩论和完善其逻辑。
立即构建你自己的 RAG 系统并释放基于文档的 AI 的全部潜力!
原文链接:Developing RAG Systems with DeepSeek R1 & Ollama (Complete Code Included)
汇智网翻译整理,转载请标明出处