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)
相关推荐
knight_9___3 小时前
RAG面试篇6
人工智能·python·机器学习·agent·rag
weixin_568996063 小时前
如何用 IndexedDB 存储从 API 获取的超大列表并实现二级索引
jvm·数据库·python
2301_775148154 小时前
如何授权AWR报告生成_GRANT SELECT ANY DICTIONARY诊断权限
jvm·数据库·python
刀法如飞4 小时前
一款Python语言Django框架DDD脚手架,开箱即用
python·架构·django
Csvn5 小时前
🌟 LangChain 30 天保姆级教程 · Day 30|终章!RAG 项目打包交付:Docker + CI/CD + 文档,打造企业级 AI 知识库!
langchain
itzixiao5 小时前
L1-051 打折(5分)[java][python]
java·python·算法
HappyAcmen5 小时前
10.常见报错排查与基础调试
开发语言·python
山川而川-R5 小时前
Windows新系统_安装anaconda-2026-4.24
python
ID_180079054735 小时前
Python 实现京东商品详情 API 数据准确性校验(极简可直接用)
java·前端·python
码农的神经元5 小时前
配电网智能决策平台:从风险感知到自愈控制的 Python 实现
开发语言·python