Skip to main content

会话缓冲窗口内存

ConversationBufferWindowMemory 保留了会话随时间变化的交互列表。它只使用最后 K 个交互。这对于保持最近交互的滑动窗口很有用,以防缓冲区过大。

首先,让我们探索这种类型内存的基本功能。

from langchain.memory import ConversationBufferWindowMemory

memory = ConversationBufferWindowMemory(k=1)
memory.save_context({"input": "hi"}, {"output": "whats up"})
memory.save_context({"input": "not much you"}, {"output": "not much"})

memory.load_memory_variables({})

{'history': 'Human: not much you\nAI: not much'}

我们还可以将历史记录作为消息列表获取(如果与聊天模型一起使用,这很有用)。

memory = ConversationBufferWindowMemory(k=1, return_messages=True)
memory.save_context({"input": "hi"}, {"output": "whats up"})
memory.save_context({"input": "not much you"}, {"output": "not much"})

memory.load_memory_variables({})

{'history': [HumanMessage(content='not much you', additional_kwargs={}),
AIMessage(content='not much', additional_kwargs={})]}

在链中使用

让我们通过一个示例来演示,再次设置 verbose=True 以便查看提示。

from langchain.llms import OpenAI
from langchain.chains import ConversationChain

conversation_with_summary = ConversationChain(
llm=OpenAI(temperature=0),
# 我们设置一个较小的 k=2,只保留最后 2 个交互在内存中
memory=ConversationBufferWindowMemory(k=2),
verbose=True
)

conversation_with_summary.predict(input="Hi, what's up?")
> 进入新的 ConversationChain 链...
格式化后的提示:
以下是人类和 AI 之间友好对话。AI 健谈并提供了许多来自上下文的具体细节。如果 AI 不知道问题的答案,它会真实地说不知道。

当前对话:

Human: Hi, what's up?
AI:

> 链结束。

"嗨!我很好。我目前正在帮助一位客户解决技术问题。你呢?"
conversation_with_summary.predict(input="What's their issues?")
> 进入新的 ConversationChain 链...
格式化后的提示:
以下是人类和 AI 之间友好对话。AI 健谈并提供了许多来自上下文的具体细节。如果 AI 不知道问题的答案,它会真实地说不知道。

当前对话:
Human: Hi, what's up?
AI: 嗨!我很好。我目前正在帮助一位客户解决技术问题。你呢?
Human: What's their issues?
AI:

> 链结束。

"客户在连接他们的 Wi-Fi 网络时遇到了问题。我正在帮助他们解决问题并连接网络。"
conversation_with_summary.predict(input="Is it going well?")
> 进入新的 ConversationChain 链...
格式化后的提示:
以下是人类和 AI 之间友好对话。AI 健谈并提供了许多来自上下文的具体细节。如果 AI 不知道问题的答案,它会真实地说不知道。

当前对话:
Human: Hi, what's up?
AI: 嗨!我很好。我目前正在帮助一位客户解决技术问题。你呢?
Human: What's their issues?
AI: 客户在连接他们的 Wi-Fi 网络时遇到了问题。我正在帮助他们解决问题并连接网络。
Human: Is it going well?
AI:

> 链结束。

"是的,目前进展顺利。我们已经找到了问题,并正在解决方案。"
# 注意这里第一个交互不会出现。
conversation_with_summary.predict(input="What's the solution?")
> 进入新的 ConversationChain 链...
格式化后的提示:
以下是人类和 AI 之间友好对话。AI 健谈并提供了许多来自上下文的具体细节。如果 AI 不知道问题的答案,它会真实地说不知道。

当前对话:
Human: What's their issues?
AI: 客户在连接他们的 Wi-Fi 网络时遇到了问题。我正在帮助他们解决问题并连接网络。
Human: Is it going well?
AI: 是的,目前进展顺利。我们已经找到了问题,并正在解决方案。
Human: What's the solution?
AI:

> 链结束。

"解决方案是重置路由器并重新配置设置。我们目前正在进行这个过程。"