使用 DeepSeek R1 和 Ollama 搭建一個 RAG 系統(tǒng)(包含完整代碼)
你有沒有想過,能不能像跟人聊天一樣,直接問 PDF 文件或技術(shù)手冊問題?比如你有一本很厚的說明書,不想一頁頁翻,只想問它:“這個功能怎么用?”或者“這個參數(shù)是什么意思?”現(xiàn)在有了 AI 技術(shù),這完全可以實現(xiàn)!
這篇文章教你如何用兩個工具(DeepSeek R1 和 Ollama)來搭建一個智能系統(tǒng),讓它幫你從 PDF 里找答案。這個系統(tǒng)叫 RAG(檢索增強生成),簡單來說就是:先找資料,再生成答案。
為什么要用 DeepSeek R1?
- 省錢:它比 OpenAI 的模型便宜 95%,效果卻差不多。
- 精準:每次只從 PDF 里找 3 個相關(guān)片段來回答問題,避免瞎編。
- 本地運行:不用聯(lián)網(wǎng),速度快,隱私也有保障。
你需要準備什么?
(1) Ollama:一個讓你在電腦上本地運行 AI 模型的工具。
下載地址:https://ollama.com/
安裝后,運行命令:
ollama run deepseek-r1 # 默認用7B模型
(2) DeepSeek R1 模型:有不同大小,最小的 1.5B 模型適合普通電腦,更大的模型效果更好,但需要更強的電腦配置。
運行小模型:
ollama run deepseek-r1:1.5b
(3) 通用配置原則 模型顯存占用(估算):
- 每 1B 參數(shù)約需 1.5-2GB 顯存(FP16 精度)或 0.75-1GB 顯存(INT8/4-bit 量化)。
- 例如:32B 模型在 FP16 下需約 48-64GB 顯存,量化后可能降至 24-32GB。
內(nèi)存需求:至少為模型大小的 2 倍(用于加載和計算緩沖)。
存儲:建議 NVMe SSD,模型文件大小從 1.5B(約 3GB)到 32B(約 64GB)不等。
怎么搭建這個系統(tǒng)?
第一步:導入工具包
我們用 Python 寫代碼,需要用到一些工具包:
- LangChain:處理文檔和檢索。
- Streamlit:做一個簡單的網(wǎng)頁界面。
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
第二步:上傳 PDF
用 Streamlit 做一個上傳按鈕,把 PDF 傳上去,然后用工具提取里面的文字。
uploaded_file = st.file_uploader("上傳PDF文件", type="pdf")
if uploaded_file:
with open("temp.pdf", "wb") as f:
f.write(uploaded_file.getvalue())
loader = PDFPlumberLoader("temp.pdf")
docs = loader.load()
第三步:把 PDF 切成小塊
PDF 內(nèi)容太長,直接喂給 AI 會吃不消。所以要把文字切成小塊,方便 AI 理解。
text_splitter = SemanticChunker(HuggingFaceEmbeddings())
documents = text_splitter.split_documents(docs)
第四步:建一個“知識庫”
把切好的文字塊轉(zhuǎn)換成向量(一種數(shù)學表示),存到一個叫 FAISS 的數(shù)據(jù)庫里。這樣 AI 就能快速找到相關(guān)內(nèi)容。
embeddings = HuggingFaceEmbeddings()
vector_store = FAISS.from_documents(documents, embeddings)
retriever = vector_store.as_retriever(search_kwargs={"k": 3}) # 每次找3個相關(guān)塊
第五步:設(shè)置 AI 模型
用 DeepSeek R1 模型來生成答案。告訴它:只根據(jù) PDF 內(nèi)容回答,不知道就說“我不知道”。
llm = Ollama(model="deepseek-r1:1.5b")
prompt = """
1. 僅使用以下上下文。
2. 如果不確定,回答“我不知道”。
3. 答案保持在4句話以內(nèi)。
上下文: {context}
問題: {question}
答案:
"""
QA_CHAIN_PROMPT = PromptTemplate.from_template(prompt)
第六步:把整個流程串起來
把上傳、切塊、檢索和生成答案的步驟整合成一個完整的系統(tǒng)。
llm_chain = LLMChain(llm=llm, prompt=QA_CHAIN_PROMPT)
document_prompt = PromptTemplate(
template="上下文:\n內(nèi)容:{page_content}\n來源:{source}",
input_variables=["page_content", "source"]
)
qa = RetrievalQA(
combine_documents_chain=StuffDocumentsChain(
llm_chain=llm_chain,
document_prompt=document_prompt
),
retriever=retriever
)
第七步:做個網(wǎng)頁界面
用 Streamlit 做一個簡單的網(wǎng)頁,用戶可以輸入問題,系統(tǒng)會實時返回答案。
user_input = st.text_input("向你的PDF提問:")
if user_input:
with st.spinner("思考中..."):
response = qa(user_input)["result"]
st.write(response)
未來展望
DeepSeek R1 只是開始,未來還會有更多強大的功能,比如:
- 自我驗證:AI 能檢查自己的答案對不對。
- 多跳推理:AI 能通過多個步驟推導出復雜問題的答案。
總結(jié)
用這個系統(tǒng),你可以輕松地從 PDF 里提取信息,像跟人聊天一樣問問題。趕緊試試吧,釋放 AI 的潛力!