2026 年 LangChain (记忆)Memory 怎么用?三个核心类 + 完整代码示例

什么是记忆,在lainchain中有什么作用 ?**

LLM 本身是无状态的------每次调用都是全新的,它不记得上一轮说了什么。记忆就是在每次请求时,把历史对话塞进 Prompt,让 LLM "看起来"有记忆。

例子:

没有记忆:

用户:"我叫李明" → LLM 回答

用户:"我叫什么?" → LLM:"我不知道你叫什么" ❌

有记忆:

用户:"我叫李明" → 存入历史

用户:"我叫什么?" → Prompt = 历史 + 新问题 → LLM:"你叫李明" ✅

如何使用以当前的最新版本的lainchain 1.2.15举例说明

python 复制代码
 import os

from dotenv import load_dotenv

load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), "../.env"))

from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableConfig
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI

# 1. 用dict 管理多用户历史
store = {}


def get_session_heistory(session_id: str):
    if (session_id) not in store:
        # 通过 InMemoryChatMessageHistory 获取历史对话记忆
        store[session_id] = InMemoryChatMessageHistory()
    return store[session_id]


# 2 建立Prompt 必须有Messagesplaceholder
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "你是一个客服助手"),
        MessagesPlaceholder(variable_name="history"),  # 历史注入这里
        ("human", "{input}"),
    ]
)

# 3 .组装chain
llm = ChatOpenAI(
    model="deepseek-chat",
    api_key=lambda: os.getenv("OPENAI_API_KEY") or "",
    base_url=os.getenv("OPENAI_API_BASE"),
    temperature=0,
)
chain = prompt | llm


# 4 包装带历史的 chai
chain_with_history = RunnableWithMessageHistory(
    chain,
    get_session_heistory,
    input_messages_key="input", #用户输入的 key
    history_messages_key="history",  # 必须和MessagesPlaceholder
)


# 5 使用 (每次必须传 config)

cfg: RunnableConfig = {"configurable": {"session_id": "user_001"}}

chain_with_history.invoke({"input": "我叫李明"}, config=cfg)
chain_with_history.invoke({"input":"你记得我叫什么?"}, config=cfg)

# 查看对话历史
# 查看某个用户的所有历史
history = store["user_001"]
for msg in history.messages:
    print(msg.type, ":", msg.content)

# 清除历史
print('-----------新建窗口清除历史对话')

history.clear()

print(len( history.messages))

流程图如下:

关于记忆主要使用的api

  • InMemoryChatMessageHistory 是历史的容器,负责存储所有对话消息。
  • RunnableWithMessageHistory 是 chain 的包装器,负责每次 invoke 时自动读取和写入历史。

总结:

用 RunnableWithMessageHistory 实现对话记忆,核心就是 5 步:

1 用 dict + InMemoryChatMessageHistory 管理多用户历史

2 Prompt 里用 MessagesPlaceholder 留历史槽位

3 组装普通 chain(prompt | llm)

4 用 RunnableWithMessageHistory 包装 chain,绑定历史管理函数

5 每次调用传入含 session_id 的 config

相关推荐
光电的一只菜鸡7 分钟前
为什么调整LSC会对AF产生影响
android·开发语言·kotlin
zhangjw3410 分钟前
第47篇:Java综合实战:电商秒杀系统(高并发场景)
java·开发语言
计算机魔术师21 分钟前
Suno 发布 v6 音乐模型,推出 v6、v6-wild、v6-mini 三个版本
前端
Web3&Basketball23 分钟前
LLM 峰谷定价怎么吃满:一个能对账的错峰调度器
python·性能优化·大模型·任务调度·成本优化·deepseek·推理优化
2601_9622186125 分钟前
万象生鲜系统订单全生命周期状态同步技术实现业务可视
大数据·数据库·人工智能·python·算法
FOAF-lambda31 分钟前
uiautomation-new 控件方位的使用
开发语言·python
OKkankan35 分钟前
LangChain能力详解!:从工具调用到 LangSmith——让聊天模型具备实时交互能力!
开发语言·python·langchain
whyweplay39 分钟前
elpis : DSL动态组件学习
前端
richard_yuu39 分钟前
AOI 实战第五篇:c_broken 漏检严重,V4 迭代背后的权衡
开发语言·深度学习·yolo
用户921080262861 小时前
前端 Vue 专栏 06:异步更新机制、任务队列与 nextTick
前端