DeepSeek-7B-chat 与 Langchain 集成指南
本文重点介绍如何将
deepseek-7b-chat模型接入
langchain中的
langchain.llms.base模块下的
llm类。关于向量数据库集成或
gradio界面搭建等内容,可参考 internlm 的 langchain 实现方式。
环境依赖安装
除了运行模型所需的基础依赖外,还需安装特定版本的 langchain 库:
pip install langchain==0.0.292
将 DeepSeek-7B-chat 接入 LangChain
为了更高效地开发基于 LLM 的应用,我们可以基于本地部署的
deepseek-7b-chat模型自定义一个 LLM 类,从而将其无缝集成至 LangChain 框架中。一旦完成该自定义类的编写,即可像调用其他 LangChain 支持的模型一样使用,无需关心底层实现差异。
实现过程较为直接:只需继承
langchain.llms.base.LLM类,并重写其构造函数和
_call方法即可:
from langchain.llms.base import LLM from typing import Any, List, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig import torchclass DeepSeek_LLM(LLM):
自定义基于本地 DeepSeek-7B-chat 的 LLM 类
tokenizer: AutoTokenizer = None model: AutoModelForCausalLM = None def __init__(self, model_path: str): # model_path: DeepSeek-7B-chat 模型的本地路径 # 初始化 tokenizer 和模型 super().__init__() print("正在从本地加载模型...") self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) self.model = AutoModelForCausalLM.from_pretrained( model_path, trust_remote_code=True, torch_dtype=torch.bfloat16, device_map="auto" ) self.model.generation_config = GenerationConfig.from_pretrained(model_path) self.model.generation_config.pad_token_id = self.model.generation_config.eos_token_id self.model = self.model.eval() print("模型加载完成") def _call(self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) -> str: # 重写生成逻辑 messages = [ {"role": "user", "content": prompt} ] # 构建输入张量 input_tensor = self.tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt" ).to(self.model.device) # 生成输出 outputs = self.model.generate(input_tensor, max_new_tokens=100) response = self.tokenizer.decode(outputs[0][input_tensor.shape[1]:], skip_special_tokens=True) return response @property def _llm_type(self) -> str: return "DeepSeek_LLM"使用示例
完成自定义类后,便可像使用任何 LangChain 内置大模型一样进行调用:
llm = DeepSeek_LLM('/root/autodl-tmp/deepseek-ai/deepseek-llm-7b-chat')llm('你好')
效果如下图所示:

![[大模型]DeepSeek-7B-chat langchain 接入](https://img.php.cn/upload/article/001/503/042/175428169821661.jpg)










