下面是LangChain常用的记忆(memory)组件
提示:下面的记忆组件,定义之后传入chain的memory 参数,就可以使用
ConversationBufferMemory
基于内存的记忆组件,数据存储在内存中
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
memory.save_context({"input": "hi"}, {"output": "whats up"})
RedisChatMessageHistory
基于redis的记忆组件
from langchain.memory import RedisChatMessageHistory
history = RedisChatMessageHistory(
# session_id目的是为了区分多个记忆组件
session_id="abc123",
# 设置redis 连接信息
url="redis://192.168.0.100:6379/0",
# 设置key前缀
key_prefix="demo_prefix:"
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
PostgresChatMessageHistory
基于Postgres数据库的记忆组件
from langchain.memory import PostgresChatMessageHistory
history = PostgresChatMessageHistory(
connection_string="postgresql://postgres:mypassword@localhost/chat_history",
session_id="foo",
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
MongoDBChatMessageHistory
基于MongoDB的记忆组件
from langchain.memory import MongoDBChatMessageHistory
# 设置mongodb数据库连接
connection_string = "mongodb://mongo_user:password123@mongo:27017"
message_history = MongoDBChatMessageHistory(
connection_string=connection_string, session_id="test-session"
)
message_history.add_user_message("hi!")
message_history.add_ai_message("whats up?")