用摘要压缩长历史
前面使用 trim_messages 实现滑动窗口裁剪。但是滑动窗口有一个硬伤,超出窗口的早期消息直接丢弃,信息永久丢失。
很多业务场景不适合粗暴丢弃,用户很早之前提的需求、个人偏好、业务背景,后面对话还需要用到。这时就可以用摘要压缩,历史太长时,把早期的对话总结成一段摘要,保留核心信息,大幅节省 token,同时不会丢失关键上下文。
摘要压缩是什么和窗口记忆的区别
窗口记忆的消息列表是原始消息,只保留最近 N 条,更早的直接删掉。
摘要记忆则是把老旧的、落在窗口之外的多条原始对话,交给 LLM 生成一段文字摘要。原始消息不再放进 prompt,只放摘要 + 最近几条未压缩的原始对话。
结构示意:
送入LLM的上下文 = 系统提示词 + 【历史摘要】 + 【最近N条原始对话】这样做有下面优点:
不再直接丢掉早期信息,关键内容沉淀在摘要里;
摘要文本 token 密度远高于一堆原始问答,同等 token 预算下可以承载更长时间跨度的对话;
搭配滑动窗口一起使用(摘要 + 最近原始消息)是工业界最经典的混合记忆方案,兼顾语义准确和 token 可控。
虽然优点很多,单页存在一下缺点:
压缩需要额外调用一次 LLM,增加耗时、增加调用成本;
摘要会丢失细节,LLM 只能记住总结出来的要点,原始对话里细碎内容无法还原;
摘要存在“摘要漂移”,多次反复压缩、摘要之上再摘要,容易慢慢失真、记错信息;
实现比单纯 trim_messages 复杂,需要维护两个部分:已压缩摘要、待保留的最近原始消息。
简单示例
说那么多,还不如自己体验一把,代码如下:
from typing import List
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.globals import set_debug
from langchain_core.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage
from langchain_core.runnables import RunnableLambda
from langchain_ollama import ChatOllama
# 开启LangChain调试模式,打印完整prompt数据流
set_debug(True)
# 实例化本地千问模型
llm = ChatOllama(model="qwen2.5:3b", temperature=0)
def summarize_history(messages):
# 把已有历史交给模型总结
history_text = "\n".join(f"{m.type}: {m.content}" for m in messages)
summary_prompt = ChatPromptTemplate.from_template(
"把下面对话浓缩成一段摘要:\n{history}"
)
chain = summary_prompt | llm | StrOutputParser()
summary = chain.invoke({"history": history_text})
return [SystemMessage(content="历史摘要:" + summary)]
if __name__ == "__main__":
prompt = ChatPromptTemplate.from_messages([
MessagesPlaceholder("messages"),
])
history: List[BaseMessage] = [
SystemMessage(content="你是友好的助手。"),
HumanMessage(content="我叫小明"),
AIMessage(content="小明你好,你有什么问题吗?"),
HumanMessage(content="今天的天气如何"),
AIMessage(content="今天天气不错,你喜欢打篮球吗?"),
HumanMessage(content="喜欢呀,还喜欢踢足球"),
AIMessage(content="哦!真不错"),
]
# 把本次 input 包装成 HumanMessage 追加到历史消息
def add_user_msg(input_dict: dict) -> dict:
# 历史摘要和总结
msg_list: List[BaseMessage] = summarize_history(input_dict["messages"].copy())
# 最新用户问题
msg_list.append(HumanMessage(content=input_dict["input"]))
return {"messages": msg_list} # 这里的 messages 键在上面 MessagesPlaceholder("messages") 使用
# 将完整的消息列表送入trimmer 做 token+消息条数裁剪
# 最后,把裁剪完的 messages 丢给 prompt 渲染,传给llm
chain_with_trim = (
RunnableLambda(add_user_msg) # 完整的消息列表,包含历史消息摘要+最新问题
| prompt # 渲染成 prompt
| llm # 大模型
)
# 第一轮提问
print("="*60)
resp1 = chain_with_trim.invoke({"messages": history, "input": "我叫什么?"})
print(f"AI回复:{resp1.content}\n")
# 追加本轮问答到历史,形成多轮记忆
history.append(HumanMessage(content="我叫什么?"))
history.append(AIMessage(content=resp1.content))
# 第二轮提问
print("=" * 60)
resp2 = chain_with_trim.invoke({"messages": history, "input": "我喜欢什么运动?"})
print(f"AI回复:{resp2.content}\n")
history.append(HumanMessage(content="我喜欢什么运动?"))
history.append(AIMessage(content=resp2.content))上面代码,使用 summarize_history() 函数将传递给它的消息列表使用 LLM 提取摘要信息,并且返回一个 SystemMessage 系统消息,其中存放摘要信息。
运行上面示例,输出日志如下,仅查看 llm 的日志信息:
(1)生成摘要的 llm 日志
...
[llm/start] [chain:RunnableSequence > chain:add_user_msg > chain:RunnableSequence > llm:ChatOllama] Entering LLM run with input:
{
"prompts": [
"Human: 把下面对话浓缩成一段摘要:\nsystem: 你是友好的助手。\nhuman: 我叫小明\n
ai: 小明你好,你有什么问题吗?\nhuman: 今天的天气如何\nai: 今天天气不错,你喜欢打篮球吗?\n
human: 喜欢呀,还喜欢踢足球\nai: 哦!真不错"
]
}
[llm/end] [chain:RunnableSequence > chain:add_user_msg > chain:RunnableSequence >
llm:ChatOllama] [9.48s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "摘要:小明介绍自己叫小明,询问天气情况。得知天气不错后,小明表示自己喜欢打篮球和踢足球。",
...
}
]
],...
}(2)问题“我叫什么?”的 llm 日志
...
[llm/start] [chain:RunnableSequence > llm:ChatOllama] Entering LLM run with input:
{
"prompts": [
"System: 历史摘要:摘要:小明介绍自己叫小明,询问天气情况。得知天气不错后,小明表示自己喜欢打篮球和踢足球。\nHuman: 我叫什么?"
]
}
[llm/end] [chain:RunnableSequence > llm:ChatOllama] [1.77s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "你叫小明。",
...
}
]
],...
}
...
AI回复:你叫小明。(3)继续对历史信息进行摘要,llm 日志如下
...
[llm/start] [chain:RunnableSequence > chain:add_user_msg >
chain:RunnableSequence > llm:ChatOllama] Entering LLM run with input:
{
"prompts": [
"Human: 把下面对话浓缩成一段摘要:\nsystem: 你是友好的助手。\nhuman: 我叫小明\nai: 小明你好,你有什么问题吗?\n
human: 今天的天气如何\nai: 今天天气不错,你喜欢打篮球吗?\nhuman: 喜欢呀,还喜欢踢足球\n
ai: 哦!真不错\nhuman: 我叫什么?\nai: 你叫小明。"
]
}
[llm/end] [chain:RunnableSequence > chain:add_user_msg > chain:RunnableSequence > llm:ChatOllama] [4.86s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "小明向AI打招呼并询问今天的天气,得知天气不错后,他提到自己喜欢打篮球和踢足球。
最后,小明询问自己的名字,AI确认了他的名字是小明。",
...
}
]
],...
}(4)问题“我喜欢什么运动?”的 llm 日志信息
...
[llm/start] [chain:RunnableSequence > llm:ChatOllama] Entering LLM run with input:
{
"prompts": [
"System: 历史摘要:小明向AI打招呼并询问今天的天气,得知天气不错后,他提到自己喜欢打篮球和踢足球。
最后,小明询问自己的名字,AI确认了他的名字是小明。\nHuman: 我喜欢什么运动?"
]
}
[llm/end] [chain:RunnableSequence > llm:ChatOllama] [4.13s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "根据之前的对话内容,小明提到他喜欢打篮球和踢足球。所以他喜欢的运动包括篮球和足球。",
...
}
]
],...
}
...
AI回复:根据之前的对话内容,小明提到他喜欢打篮球和踢足球。所以他喜欢的运动包括篮球和足球。上面示例中,在每次发起问答时都对当前会话的所有历史记录做了一次摘要提取。这样做存在如下问题:
1、当历史消息过多时,做摘要 llm 时,上下文超限,报错。
2、每次对话都做一次摘要 llm,耗时更久,调用成本更高。一次对话调用了两次 llm。
但这种方式也不是没有优点,它适合对话跨度很长、希望只维护一份摘要的场景。
除了这种策略,除窗口裁剪外,还可以使用分段拼接摘要:保留原有旧摘要不改动,仅对后续新增对话独立生成新摘要;上下文结构:旧摘要 + 新摘要 + 用户问题。
或者使用追加摘要。它会读取已经生成的旧摘要,再把旧摘要和后续新增的对话内容一起交给 LLM,融合、修正、补充信息,产出一份整合后的新版摘要,替换掉原来的旧摘要。最终送入模型的上下文:新版摘要 + 当前用户问题。 它的核心是持续迭代同一份摘要,而不是简单新增一段独立摘要拼接在一起。
这样做的优点是不需要反复重跑历史,节省 LLM 调用。
和 trim_messages 组合:混合记忆方案
该种方案生产首选,摘要压缩解决不丢信息,trim_messages 解决摘要 + 最近消息整体不能超 token 上限。链路顺序:
chat_history → 摘要压缩(旧消息转摘要) → trim_messages(整体token上限保护) → prompt → llm顺序不能颠倒:先摘要压缩,再做 token 裁剪;如果先裁剪再摘要,等于先删掉消息,摘要就失去意义了。
链路片段如下:
base_chain = (
{
# 对历史信息先摘要,再裁剪
"chat_history": RunnableLambda(lambda d: d["chat_history"]) |
compressor_runnable | trimmer,
# 用户当前问题
"query": RunnableLambda(lambda d: d["query"])
}
| chat_prompt
| llm
)完整代码如下:
from typing import List, Optional
import tiktoken
from langchain_core.globals import set_debug
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
from langchain_core.runnables import RunnableLambda, RunnableParallel
from langchain_core.prompts import ChatPromptTemplate
from langchain.chat_models import init_chat_model
from langchain_core.messages.utils import trim_messages
# 开启LangChain调试模式,打印完整prompt数据流
set_debug(True)
# 支持 OpenAI / Ollama / 通义千问等,这里用 ollama 示例
llm = init_chat_model("qwen2.5:3b", model_provider="ollama")
# 摘要可以单独用便宜小模型,也可以复用
summary_llm = init_chat_model("qwen2.5:3b", model_provider="ollama")
# 计算 token 数量
enc = tiktoken.get_encoding("o200k_base")
def custom_token_counter(messages: list[BaseMessage]) -> int:
"""注意:简单版本没有加上chat消息模板的额外token,仅演示签名"""
total = 0
for msg in messages:
total += len(enc.encode(msg.content))
return total
# 追加摘要 Refine Prompt
REFINE_SUMMARY_PROMPT = ChatPromptTemplate.from_messages([
("human", """
你是对话摘要合并器。
已有历史摘要:
{old_summary}
新增对话:
{new_messages}
请基于旧摘要,结合新增对话,生成一份更新后的连续对话摘要。
要求:
- 用户的姓名、身份、核心标识信息,**永远保留,绝不允许省略、删除**;
- 保留用户核心诉求、已确认结论、关键参数
- 修正冲突信息
- 精简,不要冗余
- 只输出摘要正文,不要额外解释
""")
])
# 追加摘要 Runnable(核心 compressor_runnable)
def make_refine_compressor(recent_keep_round: int = 2):
"""
混合压缩:
消息列表尾部保留 recent_keep_round 轮原始问答,更早的全部做Refine追加摘要
返回:[SystemMessage(摘要)] + 最近N轮原始消息
"""
def compressor(messages: List[BaseMessage]) -> List[BaseMessage]:
# 按 human+ai 一轮为单元拆分
rounds = []
buf = []
for msg in messages:
buf.append(msg)
# 当前是 AIMessage,buf 长度大于等于2,并且第一个为 HumanMessage,
# buf = [HumanMessage, AIMessage] 才能满足,这不就是一轮吗?
if isinstance(msg, AIMessage) and len(buf) >= 2 and isinstance(buf[0], HumanMessage):
rounds.append(buf)
buf = [] # 清空,处理下一轮
# 剩余不完整轮次直接并入近期
if buf:
rounds.append(buf)
if len(rounds) <= recent_keep_round:
# 轮数很少,不用摘要,直接返回全部原始消息
return messages
# 拆分:远期需要摘要的轮次 + 近期保留原始的轮次
old_rounds = rounds[:-recent_keep_round] # 历史消息
recent_rounds = rounds[-recent_keep_round:] # 最近消息
recent_messages = [m for r in recent_rounds for m in r]
# 迭代 Refine 追加摘要
summary: Optional[str] = None
for batch in old_rounds:
batch_text = "\n".join([f"{m.type}: {m.content}" for m in batch])
if summary is None:
# 第一次:直接总结这批消息
summary_prompt = ChatPromptTemplate.from_messages([
("human", "总结下面对话,精简保留关键信息:\n{text}")
])
chain = summary_prompt | summary_llm
summary = chain.invoke({"text": batch_text}).content
else:
# 后续:Refine 更新旧摘要
refine_chain = REFINE_SUMMARY_PROMPT | summary_llm
summary = refine_chain.invoke({
"old_summary": summary,
"new_messages": batch_text
}).content
# 摘要包装成 SystemMessage,和近期原始消息合并输出
summary_msg = SystemMessage(content=f"【历史对话摘要】:{summary}")
return [summary_msg] + recent_messages
return RunnableLambda(compressor)
# 构造压缩器:保留最近2轮原始问答,更早的做追加摘要
compressor_runnable = make_refine_compressor(recent_keep_round=2)
# 初始化 trim_messages 裁剪器
trimmer = trim_messages(
max_tokens=300,
strategy="last",
token_counter=custom_token_counter,
include_system=True,
start_on="human",
end_on="ai",
)
# 主Prompt
chat_prompt = ChatPromptTemplate.from_messages([
("system", "你是助手,根据对话历史回答用户问题。"),
("placeholder", "{chat_history}"), # 占位符,历史消息
("human", "{query}"),
])
base_chain = (
RunnableParallel({
"chat_history": RunnableLambda(lambda d: d["chat_history"]) | compressor_runnable | trimmer,
"query": RunnableLambda(lambda d: d["query"])
})
| chat_prompt
| llm
)
if __name__ == "__main__":
# 模拟一段很长的历史对话
history: List[BaseMessage] = [
HumanMessage(content="我叫小明"),
AIMessage(content="小明你好,你有什么问题吗?"),
HumanMessage(content="今天的天气如何"),
AIMessage(content="今天天气不错,你喜欢打篮球吗?"),
HumanMessage(content="喜欢呀,还喜欢踢足球"),
AIMessage(content="哦!真不错,踢足球既能锻炼心肺、协调与爆发力,又能培养团队协作、抗压和坚持的品质。"),
HumanMessage(content="运动前需要做什么准备?"),
AIMessage(content="热身,活动关节、拉伸肌肉,换上合适衣物鞋子,适量补水。"),
]
resp = base_chain.invoke({
"chat_history": history,
"query": "我是谁?"
})
history.append(HumanMessage(content="我是谁?")) # 将问题追加到历史中
history.append(AIMessage(content=resp.content)) # 将模型回答追加到历史中
print(resp.content)
resp = base_chain.invoke({
"chat_history": history,
"query": "我喜欢什么运动?"
})
print(resp.content)注意,上面摘要和聊天均使用 qwen2.5:3b 小模型,摘要时容易丢失关键数据,如用户姓名等。
运行示例,输出日志逐步如下:
1、没有摘要的情况下,先计算第一轮的摘要信息。
[llm/start] [chain:RunnableSequence > chain:RunnableParallel<chat_history,query> > chain:RunnableSequence >
chain:compressor > chain:RunnableSequence > llm:ChatOllama] Entering LLM run with input:
{
"prompts": [
"Human: 总结下面对话,精简保留关键信息:\nhuman: 我叫小明\nai: 小明你好,你有什么问题吗?"
]
}
[llm/end] [chain:RunnableSequence > chain:RunnableParallel<chat_history,query> > chain:RunnableSequence >
chain:compressor > chain:RunnableSequence > llm:ChatOllama] [4.06s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "小明你好,有什么问题吗?",
...
}
]
],...
}2、摘要已经存在,将新对话和摘要进行继续摘要化。
[llm/start] [chain:RunnableSequence > chain:RunnableParallel<chat_history,query> > chain:RunnableSequence >
chain:compressor > chain:RunnableSequence > llm:ChatOllama] Entering LLM run with input:
{
"prompts": [
"Human: \n你是对话摘要合并器。\n已有历史摘要:\n小明你好,有什么问题吗?\n\n
新增对话:\nhuman: 今天的天气如何\nai: 今天天气不错,你喜欢打篮球吗?\n\n
请基于旧摘要,结合新增对话,生成一份更新后的连续对话摘要。\n
要求:\n- 用户的姓名、身份、核心标识信息,**永远保留,绝不允许省略、删除**;\n
- 保留用户核心诉求、已确认结论、关键参数\n- 修正冲突信息\n- 精简,不要冗余\n- 只输出摘要正文,不要额外解释"
]
}
[llm/end] [chain:RunnableSequence > chain:RunnableParallel<chat_history,query> > chain:RunnableSequence >
chain:compressor > chain:RunnableSequence > llm:ChatOllama] [3.77s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "小明你好,今天的天气不错,你喜欢打篮球吗?",
...
}
]
],...
}3、基于摘要和裁剪后的消息+用户问题,发起提问。
[llm/start] [chain:RunnableSequence > llm:ChatOllama] Entering LLM run with input:
{
"prompts": [
"System: 你是助手,根据对话历史回答用户问题。\n
System: 【历史对话摘要】:小明你好,今天的天气不错,你喜欢打篮球吗?\n
Human: 喜欢呀,还喜欢踢足球\n
AI: 哦!真不错,踢足球既能锻炼心肺、协调与爆发力,又能培养团队协作、抗压和坚持的品质。\n
Human: 运动前需要做什么准备?\n
AI: 热身,活动关节、拉伸肌肉,换上合适衣物鞋子,适量补水。\n
Human: 我是谁?"
]
}
[llm/end] [chain:RunnableSequence > llm:ChatOllama] [3.44s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "你在前面的对话中自称为小明。",
...
}
]
],...
}
[chain/end] [chain:RunnableSequence] [11.28s] Exiting Chain run with output:
[outputs]
你在前面的对话中自称为小明。后续的“我喜欢什么运动?”问题,也是类似的套路。