使用 DeepSeek R1 和 Ollama 开发 RAG 系统


 

1.概述

掌握如何借助 DeepSeek R1 与 Ollama 搭建检索增强生成(RAG)系统。本文将通过代码示例,为你提供详尽的分步指南、设置说明,分享打造智能 AI 应用的最佳实践。

2.内容

2.1 为什么选择DeepSeek R1?

在这篇文章中,我们将探究性能上可与 OpenAI 的 o1 相媲美、但成本却低 95% 的 DeepSeek R1,如何为你的检索增强生成(RAG)系统带来强大助力。我们来深入剖析为何开发者们纷纷热衷于这项技术,以及你怎样利用它构建自己的 RAG 流程。

DeepSeek R1 的 15 亿参数模型在这方面表现出色,原因如下:

  • 精准检索:每个答案仅关联 3 个文档片段
  • 严格提示:采用 “我不知道” 策略,避免模型产生幻觉
  • 本地执行:与云 API 相比,实现零延迟

环境:

组件成本
DeepSeek R1 1.5B免费
Ollama免费
16GB 内存的个人电脑0 元

2.2 构建本地 RAG 系统所需的条件

1.Ollama

Ollama 允许你在本地运行诸如 DeepSeek R1 之类的模型。

  • 下载:Ollama
  • 设置:通过终端安装并运行以下命令。
ollama run deepseek-r1  # For the 7B model (default)  

 2.DeepSeek R1 模型

DeepSeek R1 的参数范围从 1.5B 到 671B。对于轻量级 RAG 应用程序,请从1.5B 模型开始。

ollama run deepseek-r1:1.5b 

提示:更大的模型(例如 70B)提供更好的推理能力,但需要更多的 RAM。

 2.3 构建 RAG 管道

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  

复制代码

 2.上传并处理 PDF

利用 Streamlit 的文件上传器选择本地 PDF。用于PDFPlumberLoader高效提取文本,无需手动解析。

复制代码

# Streamlit文件上传器
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")

if uploaded_file:
    # 临时保存PDF文件
    with open("temp.pdf", "wb") as f:
        f.write(uploaded_file.getvalue())

    # 加载PDF文本
    loader = PDFPlumberLoader("temp.pdf")
    docs = loader.load()

复制代码

3.策略性地整理文件

我们打算使用递归字符文本分割器(RecursiveCharacterTextSplitter),该代码会将原始的 PDF 文本拆分成更小的片段(块)。下面我们来解释一下合理分块与不合理分块的概念:

为什么要进行语义分块呢?
语义分块能够将相关的句子归为一组(例如,“Milvus 如何存储数据” 这样的内容会保持完整),还能避免拆分表格或图表。

利用 Streamlit 的文件上传器选择本地 PDF。用于PDFPlumberLoader高效提取文本,无需手动解析。

# 将文本拆分为语义块  
text_splitter = SemanticChunker(HuggingFaceEmbeddings())   
documents = text_splitter.split_documents(docs)

这一步通过让各文本片段稍有重叠来保留上下文信息,这有助于语言模型更准确地回答问题。小而明确的文档片段还能让搜索变得更高效、更具相关性。

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  

复制代码

这一过程将文本转换为一种数值表示形式,从而使查询变得更加容易。后续的查询操作将针对该索引展开,以找出上下文最为相关的文本片段。

5.配置 DeepSeek R1

在这里,你要使用 Deepseek R1 1.5B 参数模型作为本地大语言模型(LLM)来实例化一个检索问答(RetrievalQA)链。

复制代码

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)  

复制代码

这个模板会迫使模型依据你 PDF 文档的内容来给出答案。通过将语言模型与和 FAISS 索引绑定的检索器相结合,任何通过该链发起的查询都会从 PDF 内容中查找相关上下文,从而让答案有原始材料作为依据。

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  
)

复制代码

这就是检索增强生成(RAG)设计的核心所在,它为大语言模型提供经过验证的上下文信息,而非让其单纯依赖自身的内部训练数据。

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)  

复制代码

一旦用户输入查询内容,检索链就会找出最匹配的文本片段,将其输入到语言模型中,并显示答案。只要正确安装了langchain库,代码现在应该就能正常运行,不会再触发模块缺失的错误。
提出并提交问题,即可立即获得答案!

8.完整示例代码

复制代码

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
from langchain.prompts import PromptTemplate
from langchain.chains.llm import LLMChain
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains import RetrievalQA

# color palette
primary_color = "#1E90FF"
secondary_color = "#FF6347"
background_color = "#F5F5F5"
text_color = "#4561e9"

# Custom CSS
st.markdown(f"""
    <style>
    .stApp {{
        background-color: {background_color};
        color: {text_color};
    }}
    .stButton>button {{
        background-color: {primary_color};
        color: white;
        border-radius: 5px;
        border: none;
        padding: 10px 20px;
        font-size: 16px;
    }}
    .stTextInput>div>div>input {{
        border: 2px solid {primary_color};
        border-radius: 5px;
        padding: 10px;
        font-size: 16px;
    }}
    .stFileUploader>div>div>div>button {{
        background-color: {secondary_color};
        color: white;
        border-radius: 5px;
        border: none;
        padding: 10px 20px;
        font-size: 16px;
    }}
    </style>
""", unsafe_allow_html=True)

# Streamlit app title
st.title("Build a RAG System with DeepSeek R1 & Ollama")

# Load the PDF
uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")

if uploaded_file is not None:
    # Save the uploaded file to a temporary location
    with open("temp.pdf", "wb") as f:
        f.write(uploaded_file.getvalue())

    # Load the PDF
    loader = PDFPlumberLoader("temp.pdf")
    docs = loader.load()

    # Split into chunks
    text_splitter = SemanticChunker(HuggingFaceEmbeddings())
    documents = text_splitter.split_documents(docs)

    # Instantiate the embedding model
    embedder = HuggingFaceEmbeddings()

    # Create the vector store and fill it with embeddings
    vector = FAISS.from_documents(documents, embedder)
    retriever = vector.as_retriever(search_type="similarity", search_kwargs={"k": 3})

    # Define llm
    llm = Ollama(model="deepseek-r1")

    # Define the prompt
    prompt = """
    1. Use the following pieces of context to answer the question at the end.
    2. If you don't know the answer, just say that "I don't know" but don't make up an answer on your own.\n
    3. Keep the answer crisp and limited to 3,4 sentences.

    Context: {context}

    Question: {question}

    Helpful Answer:"""

    QA_CHAIN_PROMPT = PromptTemplate.from_template(prompt)

    llm_chain = LLMChain(
        llm=llm,
        prompt=QA_CHAIN_PROMPT,
        callbacks=None,
        verbose=True)

    document_prompt = PromptTemplate(
        input_variables=["page_content", "source"],
        template="Context:\ncontent:{page_content}\nsource:{source}",
    )

    combine_documents_chain = StuffDocumentsChain(
        llm_chain=llm_chain,
        document_variable_name="context",
        document_prompt=document_prompt,
        callbacks=None)

    qa = RetrievalQA(
        combine_documents_chain=combine_documents_chain,
        verbose=True,
        retriever=retriever,
        return_source_documents=True)

    # User input
    user_input = st.text_input("Ask a question related to the PDF :")

    # Process user input
    if user_input:
        with st.spinner("Processing..."):
            response = qa(user_input)["result"]
            st.write("Response:")
            st.write(response)
else:
    st.write("Please upload a PDF file to proceed.")

复制代码

3.总结

本文详细介绍了利用 DeepSeek R1 和 Ollama 构建检索增强生成(RAG)系统的方法。首先说明了 DeepSeek R1 1.5B 模型的优势,如精准检索、避免幻觉、零延迟等。接着阐述了搭建流程,包括用 Ollama 本地运行模型、上传 PDF 文件、使用递归字符文本分割器进行语义分块、生成向量嵌入并存储于 FAISS 索引、实例化检索问答链,最后整合各步骤形成连贯流程。通过 Streamlit 实现用户输入问题并即时获取答案,且确保安装langchain库可避免错误。

### 使用 Ollama DeepSeek R1 构建 RAG 系统 #### 一、环境准备 为了构建基于检索增强生成 (RAG) 的系统,需先安装并配置好必要的软件包服务。这包括但不限于 Python 开发环境以及 Docker 容器平台用于部署 Ollama 及其关联组件。 - **Ollama**: 轻量级的本地 AI 模型执行框架能够简化模型管理流程,在本地环境中高效运行复杂算法[^2]。 - **DeepSeek R1**: 推理工具支持多种自然语言处理任务,适用于创建智能对话代理或其他交互式应用实例[^3]。 #### 二、集成与开发 通过组合上述两个关键技术要素——即作为底层支撑架构部分的 Ollama 平台同上层业务逻辑实现者角色定位下的 DeepSeek R1 工具集——可达成如下目标: - 实现从文档库中提取相关信息片段的功能; - 将获取到的知识点融合至最终输出的回答文本里去; 具体操作步骤涉及编写自定义脚本以调用 API 或 SDK 方法完成数据交换过程,并确保整个工作流顺畅无阻地运转起来。 ```python from deepseek_r1 import create_retriever, generate_response def rag_pipeline(query): retriever = create_retriever() docs = retriever.search_documents(query=query) response = generate_response(context=docs, query=query) return response ``` 此段代码展示了如何初始化一个检索器对象 `retriever` ,并通过该对象的方法 `search_documents()` 执行查询请求从而获得一系列候选文件列表 `docs` 。随后借助于另一个辅助函数 `generate_response()` 来合成最终回复内容给定用户提问 `query` 。 #### 三、优化建议 当遇到回答质量不高或效率低下的情况时,应当考虑采取措施改善现有状况。例如重新审视输入资料的质量控制环节,或是微调参与运算的各项超参数设置等手段来提升整体表现水平[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值