基于DeepSeek API构建带记忆的对话系统:技术实现详解
引言
在现代AI应用中,能够记住对话历史的聊天系统变得越来越重要。无论是客服机器人、个人助手还是技术咨询系统,上下文记忆能力都是提升用户体验的关键。本文将介绍如何使用DeepSeek API和LangChain框架,构建一个具有记忆功能的对话系统。
技术栈概览
我们主要使用以下工具:
- DeepSeek API:国内领先的大语言模型服务
- LangChain:用于构建基于LLM的应用程序的框架
- 内存存储:简单的对话历史记录方式
环境准备
首先确保已安装必要的Python库:
pip install langchain-openai langchain-core
代码解析
1. 初始化DeepSeek模型
model = ChatOpenAI(model_name="deepseek-chat",openai_api_key=os.getenv("DEEPSEEK_API_KEY"), # 需要你提前准备好 api keyopenai_api_base="https://api.deepseek.com/v1"
)
这里我们配置了DeepSeek的聊天模型,API密钥从环境变量获取,确保安全性。
2. 构建对话模板
prompt = ChatPromptTemplate.from_messages([("system", "你是世界级技术专家"), # 随便啦MessagesPlaceholder(variable_name="history"),("user", "{input}")
])
这个模板定义了对话结构:
- 系统角色设定:将AI设为"世界级技术专家"
- 历史消息占位符:用于插入之前的对话
- 用户输入:最新的用户消息
3. 创建可运行链
runnable = prompt | model
使用LangChain的管道操作符(|
)将提示模板和模型连接起来,形成一个可执行的链。
4. 实现对话历史存储
store = {}def get_session_history(session_id: str) -> BaseChatMessageHistory:if session_id not in store:store[session_id] = InMemoryChatMessageHistory()return store[session_id]
我们使用内存中的字典来存储不同会话的历史记录,每个会话ID对应一个独立的历史记录。
5. 添加历史记录功能
with_message_history = RunnableWithMessageHistory(runnable=runnable,get_session_history=get_session_history,input_messages_key="input",history_messages_key="history",
)
RunnableWithMessageHistory
包装器为我们的链添加了历史记录功能,自动管理对话上下文的存储和检索。
6. 测试对话系统
# 第一次对话
response = with_message_history.invoke({"session_id": "123","input": "我是 Bob",},config={"configurable": {"session_id": "123"}}
)# 第二次对话,测试记忆功能
response1 = with_message_history.invoke({"session_id": "123","input": "你知道我的名字吗?",},config={"configurable": {"session_id": "123"}}
)print(response1.content)
应用场景
这种带记忆的对话系统可用于:
- 个性化客服:记住用户偏好和历史问题
- 教育辅导:跟踪学习进度和之前的错误
- 技术咨询:保持复杂问题的上下文
- 心理辅导:建立连续的对话关系
进阶优化
- 持久化存储:将内存存储替换为数据库,如Redis或MongoDB
- 记忆窗口:限制记忆的对话轮数,避免上下文过长
- 记忆摘要:对长对话生成摘要而非存储全部内容
- 多模态记忆:扩展支持图像、文件等更多类型的记忆
完整代码
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI
from langchain_core.chat_history import BaseChatMessageHistory, InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
import os# 初始化DeepSeek模型
model = ChatOpenAI(model_name="deepseek-chat",openai_api_key=os.getenv("DEEPSEEK_API_KEY"),openai_api_base="https://api.deepseek.com/v1"
)# 构建对话模板
prompt = ChatPromptTemplate.from_messages([("system", "你是世界级技术专家"),MessagesPlaceholder(variable_name="history"),("user", "{input}")
])# 创建可运行链
runnable = prompt | model# 实现对话历史存储
store = {}def get_session_history(session_id: str) -> BaseChatMessageHistory:if session_id not in store:store[session_id] = InMemoryChatMessageHistory()return store[session_id]# 添加历史记录功能
with_message_history = RunnableWithMessageHistory(runnable=runnable,get_session_history=get_session_history,input_messages_key="input",history_messages_key="history",
)# 测试对话
response = with_message_history.invoke({"session_id": "123", "input": "我是 Bob"},config={"configurable": {"session_id": "123"}}
)response1 = with_message_history.invoke({"session_id": "123", "input": "你知道我的名字吗?"},config={"configurable": {"session_id": "123"}}
)print(response1.content)
结语
通过DeepSeek API和LangChain框架,我们轻松构建了一个具有记忆功能的对话系统。这种架构不仅适用于简单的聊天应用,还可以扩展为复杂的企业级解决方案。随着DeepSeek模型的不断升级,开发者可以期待更强大的上下文理解和记忆能力。
希望这篇技术博客能帮助你快速上手构建带记忆的AI对话系统!