为什么需要记忆
LLM 的无状态问题
大语言模型本身是无状态的——每次调用都是独立的,模型不会记住上一次的对话内容。这意味着如果不做处理,模型完全不知道之前聊了什么:
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
llm = ChatOpenAI(model="gpt-4o-mini")
# 第一次对话
response1 = llm.invoke([HumanMessage(content="我叫小明,我今年25岁")])
print(response1.content)
# 输出:你好小明!很高兴认识你...
# 第二次对话——模型完全不记得之前的信息
response2 = llm.invoke([HumanMessage(content="我叫什么名字?")])
print(response2.content)
# 输出:抱歉,我不知道你的名字...(因为没有传入历史对话)
2026/5/14大约 12 分钟