Datawhale干货
作者:昊然,Datawhale成员
Datawhale干货
作者:昊然,Datawhale成员
完整教程
本教程将详细介绍如何利用 DeepSeek R1 和 Ollama 构建本地化的 RAG(检索增强生成)应用。
前期准备
Step1:下载 Ollama
Step2:验证安装
Step3:拉取模型
从命令行,参考 Ollama 模型列表 (https://ollama.com/library)和 文本嵌入模型列表 (https://python.langchain.com/v0.2/docs/integrations/text_embedding/)拉取模型。在该教程中,我们以 deepseek-r1:1.5b 和 nomic-embed-text 为例: 命令行输入 ollama pull deepseek-r1:1.5b,拉取通用的开源大语言模型 deepseek-r1:1.5b;(拉取模型时,可能比较缓慢。如果出现拉取错误,可以重新输入指令拉取) 命令行输入 ollama pull nomic-embed-text 拉取 文本嵌入模型 (https://ollama.com/search?c=embedding)nomic-embed-text。 当应用运行时,所有模型将自动在 localhost:11434 上启动。 注意,你的模型选择需要考虑你的本地硬件能力,该教程的参考显存大小 CPU Memory > 8GB。
Step4:部署模型
Step5:安装依赖
# langchain_community
pip install langchain langchain_community
# Chroma
pip install langchain_chroma
# Ollama
pip install langchain_ollama
本地 RAG 应用实现
from langchain_community.document_loaders import PDFPlumberLoader
file = "DeepSeek_R1.pdf"
# Load the PDF
loader = PDFPlumberLoader(file)
docs = loader.load()
from langchain.text_splitter import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)
all_splits = text_splitter.split_documents(docs)
from langchain_chroma import Chroma
from langchain_ollama import OllamaEmbeddings
local_embeddings = OllamaEmbeddings(model="nomic-embed-text")
vectorstore = Chroma.from_documents(documents=all_splits, embedding=local_embeddings)
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import ChatOllama
model = ChatOllama(
model="deepseek-r1:1.5b",
)
prompt = ChatPromptTemplate.from_template(
"Summarize the main themes in these retrieved docs: {docs}"
)
# 将传入的文档转换成字符串的形式
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
chain = {"docs": format_docs} | prompt | model | StrOutputParser()
question = "What is the purpose of the DeepSeek project?"
docs = vectorstore.similarity_search(question)
chain.invoke(docs)
from langchain_core.runnables import RunnablePassthrough
RAG_TEMPLATE = """
You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
<context>
{context}
</context>
Answer the following question:
{question}"""
rag_prompt = ChatPromptTemplate.from_template(RAG_TEMPLATE)
retriever = vectorstore.as_retriever()
qa_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| rag_prompt
| model
| StrOutputParser()
)
question = "What is the purpose of the DeepSeek project?"
# Run
qa_chain.invoke(question)
总结
文档处理:使用 PDFPlumberLoader 加载 PDF 文档,并通过 RecursiveCharacterTextSplitter 将文本切分成适当大小的块。 向量存储:利用 Chroma 数据库和 Ollama 的嵌入模型建立向量存储系统,为后续的相似度检索提供基础。 Chain 构建:设计并实现处理链,将文档处理、提示模板和模型响应整合成流程化的处理过程。 RAG 实现:通过整合检索和问答功能,实现了完整的检索增强生成系统,能够基于文档内容回答用户问询。
一起“点赞”三连↓