LangChain的短期记忆存储实现

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

RunnableWithMessageHistory 是LangChain 内Runnable 接口的实现主要用于:

  • 创建一个带有历史会话记忆功能的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)
相关推荐
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
染指11103 天前
122.Agent-LangChain核心组件-中间件-动态提示词(dynamic_promapt)
人工智能·langchain·agent·agents
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1233 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero073 天前
Jev 与 Laya
python·语言模型