LangChain的短期记忆存储实现

LangChain的短期记忆存储怎么实现?

RunnableWithMessageHistoryLangChainRunnable 接口的实现主要用于:

  • 创建一个带有历史会话记忆功能的Runnable实例(链)

他在创建的时候需要提供一个BaseChatMessageHistory 的具体实现用来存储历史消息

  • InMemoryChatMessageHistory 可以实现在内存中存储历史会话

额外的如果想要invoke活着stream执行链的同时,将提示词pring出来,可以在链中加入自定义函数实现。

  • 注意:函数的输入应原封不动的返回出去,避免破坏原有业务,仅在return之前,print所需要的信息即可

使用InMemoryChatMessageHistory仅可以在内存中临时存储会话记忆,一但程序退出,则记忆丢失。

InMemoryChatMessageHistory 类继承自 BaseChatMessageHistory

python 复制代码
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_core.prompts import PromptTemplate,ChatPromptTemplate,MessagesPlaceholder
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_core.chat_history import InMemoryChatMessageHistory
str_perser = StrOutputParser()

# prompt = PromptTemplate.from_template(
#   "你需要根据会话历史回应用户问题,对话历史{chat_history},用户提问{input},请回答"
# )

prompt = ChatPromptTemplate.from_messages(
  [
    ("system","你需要根据会话历史回应用户问题,对话历史:"),
    MessagesPlaceholder("chat_history"),
    ("human","请回答如下问题{input}")
  ]
)

history_dict = {}     #key就是sessionid value就是InMemoryChatMessageHistory实例对象

def get_history(session_id):
  if session_id not in history_dict:
    history_dict[session_id] = InMemoryChatMessageHistory()
  return history_dict[session_id]

def print_prompt(full_prompt):
  print("="*5,full_prompt.to_string(),"+"*5)
  return full_prompt

base_chain = prompt | print_prompt | model | str_perser

coverSation_chain = RunnableWithMessageHistory(
  base_chain,                               #被增强的原有链
  get_history,                              #通过会话id获取InMemoryChatMessageHistory类对象
  input_messages_key="input",               #表示用户在模版中的输入占位符
  history_messages_key="chat_history"       #表示会话历史中的占位符
)

if __name__ == "__main__":
  # 固定格式添加langchain的配置,为当前程序添加所属的session_id
  session_config = {
    "configurable":{
      "session_id": "user_test"
    }
  }
  res = coverSation_chain.invoke({"input":"小明有五只乌龟"},session_config)
  print("第1次执行",res)
  res = coverSation_chain.invoke({"input":"小红有六只鸟"},session_config)
  print("第2次执行",res)
  res = coverSation_chain.invoke({"input":"一共有几个动物"},session_config)
  print("第3次执行",res)
相关推荐
2601_962299241 小时前
Azure python操作系统列表
python·操作系统·azure·虚拟机·存储配置文件
学术 学术 Fun2 小时前
如何用 API 与 Webhook 批量把图表图片转换成 VSDX
python·自动化·api·visio
2601_962100543 小时前
python包和模块的内容整理
python·模块·导入·虚拟环境·
二进制漫游记4 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
-今昭-4 小时前
《V2V 迁移实战:将 VMware 虚拟机转为 OpenStack 可用 Glance qcow2 镜像》
开发语言·python
2601_962381585 小时前
【转】Python渗透测试工具:sqlmap
python·渗透测试·sql注入·sqlmap·数据库安全
用户3721574261355 小时前
如何使用 Python 从 Word 文档中提取图片
python
白山编程大哥7 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
昭昭日月明8 小时前
RAGFlow 入门,不用从零造轮子
python·ai编程
莓有烦恼吖9 小时前
Vibe Coding 的一些思考
python