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)
相关推荐
GIS兵墩墩2 小时前
postgis--PostgreSQL16及其plpython3u扩展
python·postgis
魔都吴所谓2 小时前
【Python】从零构建:IP地理位置查询实战指南
开发语言·python·tcp/ip
测试19983 小时前
使用Python自动化生成接口测试用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
智算菩萨3 小时前
【Pygame】第10章 游戏状态管理与场景切换机制
python·游戏·pygame
songcream13 小时前
TensorFlow的一些基本概念
人工智能·python·tensorflow
AI逐月5 小时前
解决 ComfyUI 插件安装后 Nanobind 报错问题:soxr 版本冲突原理解读
开发语言·python
AC赳赳老秦5 小时前
Windows 系统 OpenClaw 执行策略报错及管理员权限设置深度解析与实操指南
运维·人工智能·python·django·自动化·媒体·openclaw
软件开发技术深度爱好者5 小时前
用python + pillow实现GUI界面图片GUI处理工具
开发语言·python