DeepSeek 本地知识库搭建(RAG)
大语言模型(Large Language Model,LLM)如DeepSeek,本地部署LLM,并搭建本地知识库。
DeepSeek 本地知识库搭建(RAG)
RAG(Retrieval Augmented Genaration)是一种结合了 信息检索
和 生成式模型
的自然语言处理(NLP)方法。
部署DeepSeek模型
环境准备
创建虚拟环境:
1
2
3
4
5
6
7
8
9
10
11
# 使用 python的 venv 工具
python -m venv deepseek-env # 创建
source deepseek-env/bin/activate # Linux/Mac 激活虚拟环境
# source deepseek-env/Script/activate # Windows
deactivate # 退出虚拟环境
# 使用 conda,如
conda create -n deepseek-env python=3.10
conda activate deepseek-env # 激活虚拟环境
# source activate deepseek-env
conda deactivate # 退出
安装基础依赖:
1
2
3
# pip install torch # PyTorch安装命令参考其官网 与 CUDA版本
pip install transformers
pip install huggingface-hub
模型获取
可以去 Hugging Face
下载,加载模型
时指定具体路径。
也可以直接将 Hugging Face 上模型仓库名,作为参数,来加载模型
,这中方法会将模型下载到默认位置:
- Linux:
~/.cache/huggingface/hub/
- Windows:
C:\Users\<你的用户名>\.cache\huggingface\
- Mac:
~/.cache/huggingface/
加载本地模型
1
2
3
4
5
6
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
model_name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained(model_name, **auto_tokenizer_kwargs)
LangChain 集成知识库
安装库
1
2
3
4
5
6
7
8
9
10
11
12
13
langchain
langchain_community
langchain-huggingface
langchain-chroma
unstructured[all-docs]
sentence-transformers
chromadb
posthog>=2.4.0
httpx[socks]
accelerate>=0.26.0
文档处理流程
向量存储
与本地DeepSeek集成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 创建文本生成管道
pipe = pipeline(
"text-generation",
model=self.model,
tokenizer=self.tokenizer,
max_new_tokens=512,
# temperature=0.3,
)
local_llm = HuggingFacePipeline(pipeline=pipe)
# 构建检索链
qa_chain = RetrievalQA.from_chain_type(
llm=local_llm,
retriever=vector_db.chroma.as_retriever(),
return_source_documents=True
)
query = "问题"
result = qa_chain({"query": query})
大部分代码都有了,有问题可自行补全,懒得粘代码了hhh。
实现Web交互界面
本文由作者按照 CC BY 4.0 进行授权