
使用 DeepSeek R1 和 Ollama 开发 RAG 系统(包含完整代码)
你是否曾希望能够直接向PDF或技术手册提问?
本指南将向您展示如何使用检索增强生成(RAG)系统构建一个系统,使用DeepSeek R1,一个开源推理工具,以及Ollama,一个轻量级的本地AI模型运行框架。
想要简化您的API工作流程吗?
Apidog充当创建、管理和运行测试及模拟服务器的全能解决方案。使用Apidog,您可以:
- 自动化关键工作流程,无需 juggling 多个工具或编写大量脚本。
- 维护顺畅的CI/CD管道。
- 识别瓶颈以确保API可靠性。
节省时间,专注于完善您的产品。
为什么选择 DeepSeek R1?
DeepSeek R1,一个与 OpenAI 的 o1 相媲美但便宜 95% 的模型,正在革新检索增强生成(RAG)系统。开发者们喜欢它的:
- 聚焦检索:每个答案仅使用 3 个文档块。
- 严格提示:通过“我不知道”的回答避免幻觉。
- 本地执行:消除了云 API 的延迟。
构建本地 RAG 系统所需的内容
1. Ollama
Ollama 允许您在本地运行像 DeepSeek R1 这样的模型。
- 下载: Ollama
- 设置: 通过终端安装并运行以下命令。
2. DeepSeek R1 模型变体
DeepSeek R1 的参数范围从 1.5B 到 671B。对于轻量级的 RAG 应用,建议从 1.5B 模型 开始。
ollama run deepseek-r1:1.5b
专业提示: 更大的模型(例如,70B)提供更好的推理能力,但需要更多的 RAM。
构建RAG管道的分步指南
第一步:导入库
我们将使用:
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
Step 2: 上传和处理 PDF
利用 Streamlit 的文件上传器选择本地 PDF。使用 PDFPlumberLoader
高效提取文本,无需手动解析。
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
if uploaded_file:
with open("temp.pdf", "wb") as f:
f.write(uploaded_file.getvalue())
loader = PDFPlumberLoader("temp.pdf")
docs = loader.load()
第3步:战略性地分块文档
利用Streamlit的文件上传器选择本地PDF。使用 PDFPlumberLoader
高效提取文本,无需手动解析。
text_splitter = SemanticChunker(HuggingFaceEmbeddings())
documents = text_splitter.split_documents(docs)
第4步:创建可搜索的知识库
为文档块生成向量嵌入并将其存储在FAISS索引中。
- 嵌入允许快速、上下文相关的搜索。
embeddings = HuggingFaceEmbeddings()
vector_store = FAISS.from_documents(documents, embeddings)
retriever = vector_store.as_retriever(search_kwargs={"k": 3})
第5步:配置DeepSeek R1
设置一个检索问答链,使用DeepSeek R1 1.5B模型。
- 这确保了答案基于PDF的内容,而不是依赖于模型的训练数据。
llm = Ollama(model="deepseek-r1:1.5b")
prompt = """
1. 仅使用以下上下文。
2. 如果不确定,请说“我不知道”。
3. 保持答案在4句话以内。
上下文:{context}
问题:{question}
答案:
"""
QA_CHAIN_PROMPT = PromptTemplate.from_template(prompt)
第6步:组装RAG链
将上传、分块和检索整合成一个统一的管道。
- 这种方法为模型提供了经过验证的上下文,提高了准确性。
llm_chain = LLMChain(llm=llm, prompt=QA_CHAIN_PROMPT)
document_prompt = PromptTemplate(
template="Context:\\ncontent:{page_content}\\nsource:{source}",
input_variables=["page_content", "source"]
)
qa = RetrievalQA(
combine_documents_chain=StuffDocumentsChain(
llm_chain=llm_chain,
document_prompt=document_prompt
),
retriever=retriever
)
第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)
您可以在此找到完整代码:https://gist.github.com/lisakim0/0204d7504d17cefceaf2d37261c1b7d5.js
RAG与DeepSeek的未来
DeepSeek R1 只是一个开始。未来的 RAG 系统可能会通过即将推出的功能,如 自我验证 和 多跳推理,自主辩论和完善其逻辑。