在使用ConversationBufferMemory进行多轮对话的时候,可能需要定期清除memory的内存以免造成输入太长的情况。
可以采用clear()
的方法清除,以下是示例代码:
from langchain.memory import ConversationBufferMemory
# 创建一个 ConversationBufferMemory 对象
memory = ConversationBufferMemory()
# 添加一些对话历史记录
memory.save_context({"input": "Hello, how are you?"}, {"output": "I'm good, thank you!"})
memory.save_context({"input": "What's the weather like today?"}, {"output": "It's sunny and warm."})
# 查看当前内存中的内容
print("Before clearing memory:")
print(memory.chat_memory)
# 清除内存
memory.clear()
# 查看内存是否已清空
print("After clearing memory:")
print(memory.chat_memory)
输出如下:
Before clearing memory:
Human: Hello, how are you?
AI: I'm good, thank you!
Human: What's the weather like today?
AI: It's sunny and warm.
After clearing memory:
Process finished with exit code 0