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)
相关推荐
love530love6 分钟前
根治 PyTorch CUDA `pynvml` 弃用警告:直接修改 `torch/cuda/__init__.py` 的实践记录
人工智能·pytorch·windows·python·深度学习·机器学习·pynvml
程序员小远13 分钟前
接口测试详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
CTA量化套保22 分钟前
期货实盘委托成交持仓对不上:天勤排查顺序与字段对照
python
机汇五金_25 分钟前
从钣金加工到成品装配,弱电箱是如何制造出来的?
网络·python·制造
键盘上的猫头鹰1 小时前
【Linux 基础教程(四)】文件内容查看、打包压缩与搜索、重定向管道及环境变量
linux·服务器·python
独挽离人1 小时前
【无标题】
python
天天进步20152 小时前
Python全栈项目--社区问答平台
开发语言·python·django
噜噜噜阿鲁~2 小时前
python学习笔记 | 12.0、错误、调试和测试
笔记·python·学习
像云~2 小时前
Agent开发理解
langchain·spring ai·agent开发
AI视觉网奇2 小时前
Bambu Studio 发现 xx个开放边
开发语言·人工智能·python