内存中的短时记忆,在 LangChain 中通常指 ConversationBufferMemory 这类“对话缓冲记忆”工具。它的作用是:在内存中保存最近的对话历史,让大模型能理解上下文,实现连续对话。
from langchain.memory import ConversationBufferMemory
# 创建对话缓冲记忆对象
memory = ConversationBufferMemory()
# 添加用户消息
memory.chat_memory.add_user_message("你好,我是Alex!")
# 添加AI回复
memory.chat_memory.add_ai_message("你好,我是AI助手,请问有什么可以帮助你的吗?")
# 加载当前记忆变量
memory.load_memory_variables({})
结果:
{'history': 'Human: 你好,我是Alex!\nAI: 你好,我是AI助手,请问有什么可以帮助你的吗?'}
# 实现一个最近的对话窗口,超过窗口条数的对话将被删除
from langchain.memory import ConversationBufferWindowMemory
# 创建一个只保留最近1轮对话的记忆窗口
memory = ConversationBufferWindowMemory(k=1)
# 保存第一轮对话
memory.save_context({"input": "你好,我是Alex!"}, {"output": "你好,我是AI助手,请问有什么可以帮助你的吗?"})
# 保存第二轮对话,第一轮会被移除,只保留最近一轮
memory.save_context({"input": "我想学习绘画。"}, {"output": "好的,我帮你找一些绘画的资料。"})
# 加载当前窗口内的记忆变量(只会返回最近一轮对话)
memory.load_memory_variables({})
结果:
{'history': 'Human: 我想学习绘画。\nAI: 好的,我帮你找一些绘画的资料。'}
内存中的短时记忆让大模型能“记住”最近的对话内容,实现自然流畅的多轮对话体验。
ConversationEntityMemory 是 LangChain 中的一种“实体记忆”工具,专门用于在对话中自动识别、追踪和存储“实体”(如人名、地名、组织、专有名词等),让大模型能在多轮对话中持续理解和引用这些实体的相关信息。
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationEntityMemory
from pydantic import SecretStr
import os
import dotenv
# 加载环境变量
dotenv.load_dotenv()
# 初始化腾讯混元大模型
llm = ChatOpenAI(
model="hunyuan-lite",
temperature=0,
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")),
base_url="https://api.hunyuan.cloud.tencent.com/v1",
)
# 创建实体记忆对象
memory = ConversationEntityMemory(llm=llm)
# 输入包含多个实体的对话
_input = {
"input": "小王、小李和小黄经常结伴同游,三人合称“三剑客”。",
}
# 加载当前记忆变量(此时还未存储上下文)
memory.load_memory_variables(_input)
# 保存对话上下文(输入和AI回复)
memory.save_context(
_input,
{"output": "看起来很好玩,我也想加入他们!"}
)
# 查询实体记忆,提取“三剑客”分别是谁
memory.load_memory_variables({"input":"请从上文中找出‘三剑客’分别是谁"})
结果:
{'history': 'Human: 小王、小李和小黄经常结伴同游,三人合称“三剑客”。\nAI: 看起来很好玩,我也想加入他们!',
'entities': {'三剑客': '',
'小王': '小王、小李和小黄经常结伴同游,三人合称“三剑客”。',
'小李': '小李与小王、小黄结伴同游,三人合称“三剑客”。',
'小黄': '小黄是小王、小李和小黄三人中的其中一人,他们经常一起游玩并合称为“三剑客”。'}}
ConversationEntityMemory 让大模型在多轮对话中“认得人、记得事”,实现更智能、更有记忆力的对话体验。
ConversationKGMemory 是 LangChain 中的“知识图谱记忆”工具。它的作用是:在对话过程中自动抽取知识三元组(subject, predicate, object),构建和维护对话中的知识图谱,让大模型能理解和追踪事实关系,实现更智能的多轮推理和问答。
代码:
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationKGMemory
from pydantic import SecretStr
import os
import dotenv
# 加载环境变量
dotenv.load_dotenv()
# 初始化腾讯混元大模型
llm = ChatOpenAI(
model="hunyuan-lite",
temperature=0,
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")),
base_url="https://api.hunyuan.cloud.tencent.com/v1",
)
# 创建知识图谱记忆对象
memory = ConversationKGMemory(llm=llm)
# 保存第一轮对话上下文
memory.save_context(
{"input":"Where is Lisa?"},
{"output":"She is in the meeting room. What do you want to know about her?"}
)
# 保存第二轮对话上下文
memory.save_context(
{"input":"My phone is in her hand."},
{"output":"I will tell her."}
)
# 查询记忆变量,获取与输入相关的知识图谱信息
memory.load_memory_variables({"input":"Where is Lisa?"})
结果:
{'history': 'On Lisa: Lisa is in the meeting room. Lisa holds phone.'}
代码:
# 获取当前对话中的实体信息
memory.get_current_entities("Who holds my phone?")
结果:
['Lisa']
代码:
# 获取输入句子的知识三元组
memory.get_knowledge_triplets("Lisa holds my phone.")
结果:
[KnowledgeTriple(subject='Lisa', predicate='holds', object_='my phone')]
ConversationKGMemory 让大模型在对话中自动“画知识图谱”,实现更强的事实理解和多轮推理能力。
这段代码演示了如何使用 LangChain 框架结合腾讯混元大模型(hunyuan-lite)实现对话摘要记忆功能。主要流程包括:加载环境变量获取 API 密钥,初始化混元大模型作为对话生成器,然后用 ConversationSummaryMemory 记录多轮对话的上下文(输入和输出),最后通过 load_memory_variables 方法获取当前对话的摘要内容。整体实现了对多轮对话内容的自动总结与记忆。
代码:
# 导入所需库
from langchain.memory import ConversationSummaryMemory
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
import os
import dotenv
# 加载环境变量
dotenv.load_dotenv()
# 初始化腾讯混元大模型
llm = ChatOpenAI(
model="hunyuan-lite",
temperature=0,
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")),
base_url="https://api.hunyuan.cloud.tencent.com/v1",
)
# 创建对话摘要记忆对象
memory = ConversationSummaryMemory(llm=llm)
# 保存第一轮对话上下文
memory.save_context(
{"input": "Where is Lisa?"},
{"output": "She is in the meeting room. What do you want to know about her?"}
)
# 保存第二轮对话上下文
memory.save_context(
{"input": "My phone is in her hand."},
{"output": "I will tell her."}
)
# 加载记忆变量(摘要)
memory.load_memory_variables({})
结果:
{'history': "The human asks where Lisa is. The AI informs that Lisa is in the meeting room and inquires about her. The human then tells the AI that his phone is in Lisa's hand. The AI promises to tell Lisa."}
代码:
# 获取当前对话历史消息
messages = memory.chat_memory.messages
# 基于历史消息生成新的对话摘要
memory.predict_new_summary(messages, "")
结果:
"The human asks where Lisa is. The AI informs the human that Lisa is in the meeting room and asks if there is anything specific they want to know about her. The human mentions that Lisa's phone is in her hand. The AI promises to tell Lisa."
ChatMessageHistory 是 LangChain 框架中用于管理和存储对话消息历史的一个类。它可以用来记录用户和 AI 之间的每一句对话(包括用户消息和 AI 回复),并以结构化的方式保存。常见用法包括:
简单来说,ChatMessageHistory 主要用于“原始对话内容的存储与管理”,为对话记忆和上下文处理提供底层支持。
代码:
# 使用ChatMessageHistory来快速获得对话摘要
from langchain.memory import ChatMessageHistory # 导入对话消息历史类
from langchain_openai import ChatOpenAI # 导入腾讯混元大模型接口
from pydantic import SecretStr
import os
import dotenv
dotenv.load_dotenv() # 加载环境变量
# 初始化腾讯混元大模型
llm = ChatOpenAI(
model="hunyuan-lite",
temperature=0,
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")),
base_url="https://api.hunyuan.cloud.tencent.com/v1",
)
history = ChatMessageHistory() # 创建对话历史对象
# 添加用户和AI的对话消息
history.add_user_message("你好,我是Alex!")
history.add_ai_message("你好,我是AI助手,请问有什么可以帮助你的吗?")
# 基于历史消息创建对话摘要记忆对象
memory = ConversationSummaryMemory.from_messages(
llm=llm,
chat_memory=history,
return_messages=True
)
memory.buffer # 查看当前摘要内容
结果:
'The human introduces themselves as Alex and greets the AI assistant. The AI assistant responds with a friendly welcome and inquires about the assistance the human needs.'
代码:
# 使用ChatMessageHistory来快速获得对话摘要
from langchain.memory import ChatMessageHistory # 导入对话消息历史类
from langchain_openai import ChatOpenAI # 导入腾讯混元大模型接口
from pydantic import SecretStr
import os
import dotenv
dotenv.load_dotenv() # 加载环境变量
# 初始化腾讯混元大模型
llm = ChatOpenAI(
model="hunyuan-lite", # 指定混元模型
temperature=0, # 设定温度参数
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")), # 从环境变量获取API密钥
base_url="https://api.hunyuan.cloud.tencent.com/v1", # 腾讯混元API地址
)
history = ChatMessageHistory() # 创建对话历史对象
# 添加用户和AI的对话消息
history.add_user_message("你好,我是Alex!")
history.add_ai_message("你好,我是AI助手,请问有什么可以帮助你的吗?")
# 基于历史消息创建对话摘要记忆对象
memory = ConversationSummaryMemory.from_messages(
llm=llm,
chat_memory=history,
return_messages=True,
buffer="\nThe AI asks if there is anything else it can help with." # 初始摘要内容
)
memory.load_memory_variables({}) # 加载记忆变量(摘要)
结果:
{'history': [SystemMessage(content='The AI asks if there is anything else it can help with. The human introduces themselves as Alex and asks if the AI can assist him.')]}
ConversationSummaryBufferMemory 是 LangChain 框架中一种结合“对话摘要”与“窗口缓冲”机制的记忆类。它的核心作用是:在对话历史较长时,自动对超出窗口长度的旧对话进行摘要,只保留最近的若干轮详细对话内容,从而兼顾上下文完整性与效率。
# 当对话持续进行且对话内容很多的时候,可以使用ConversationSummaryBufferMemory来存储对话摘要
# 这是一种非常有用的方式,它会根据token的数量来自动判断是否需要进行摘要
# 当token数量超过阈值的时候,会自动进行摘要
# 在缓冲区中,会保留最近的k条对话
# 比较久的对话会被删除,在删除前会进行摘要
from langchain.memory import ConversationSummaryBufferMemory
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
import os
import dotenv
dotenv.load_dotenv()
class PatchedChatOpenAI(ChatOpenAI):
def get_num_tokens_from_messages(self, messages):
# 兼容各种 content 类型,简单估算 token 数
text = "".join(
str(item)
for m in messages
for item in (m.content if isinstance(m.content, list) else [m.content])
)
return len(text) # 你也可以除以2或其它方式粗略估算
# 用 PatchedChatOpenAI 替换 ChatOpenAI
llm = PatchedChatOpenAI(
model="hunyuan-lite",
temperature=0,
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")),
base_url="https://api.hunyuan.cloud.tencent.com/v1",
)
memory = ConversationSummaryBufferMemory(
llm=llm,
max_token_limit=100,
return_messages=True
)
memory.save_context(
{"input":"Where is Lisa?"},
{"output":"She is in the meeting room. What do you want to know about her?"}
)
memory.save_context(
{"input":"My phone is in her hand."},
{"output":"I will tell her."}
)
memory.save_context(
{"input":"I need her help too. Can you reach to her now?"},
{"output":"I will try my best."}
)
memory.load_memory_variables({})
结果:
{'history': [SystemMessage(content="The human asks where Lisa is. The AI responds that Lisa is in the meeting room and inquires about the purpose of the question. The human explains that Lisa's phone is in her hand."),
AIMessage(content='I will tell her.'),
HumanMessage(content='I need her help too. Can you reach to her now?'),
AIMessage(content='I will try my best.')]}
ConversationSummaryBufferMemory 让对话系统既能记住长历史,又不会因历史过长而丢失上下文或超出 token 限制,是长对话场景下非常实用的记忆工具。
ConversationTokenBufferMemory 是 LangChain 框架中一种基于 token 数量进行对话历史管理的记忆类。它的主要作用是:只保留最近一段 token 数量不超过设定上限的对话内容,超出部分会被自动丢弃,从而有效控制上下文长度,防止超出大模型的 token 限制。
from langchain.memory import ConversationTokenBufferMemory
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
import os
import dotenv
dotenv.load_dotenv()
class PatchedChatOpenAI(ChatOpenAI):
def get_num_tokens_from_messages(self, messages):
# 兼容各种 content 类型,简单估算 token 数
text = "".join(
str(item)
for m in messages
for item in (m.content if isinstance(m.content, list) else [m.content])
)
return len(text) # 你也可以除以2或其它方式粗略估算
# 用 PatchedChatOpenAI 替换 ChatOpenAI
llm = PatchedChatOpenAI(
model="hunyuan-lite",
temperature=0,
api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")),
base_url="https://api.hunyuan.cloud.tencent.com/v1",
)
memory = ConversationTokenBufferMemory(
llm=llm,
max_token_limit=100,
return_messages=True
)
memory.save_context(
{"input":"Where is Lisa?"},
{"output":"She is in the meeting room. What do you want to know about her?"}
)
memory.save_context(
{"input":"My phone is in her hand."},
{"output":"I will tell her."}
)
memory.save_context(
{"input":"I need her help too. Can you reach to her now?"},
{"output":"I will try my best."}
)
memory.save_context(
{"input":"I do not need to find her anymore"},
{"output":"Okay. I got it."}
)
memory.load_memory_variables({})
结果:
{'history': [AIMessage(content='I will try my best.'),
HumanMessage(content='I do not need to find her anymore'),
AIMessage(content='Okay. I got it.')]}
ConversationTokenBufferMemory 通过 token 数量动态裁剪历史消息,保证上下文长度始终在安全范围内,非常适合需要严格控制 token 长度的对话应用。