如何添加消息历史
本指南假设您熟悉以下概念:
在构建聊天机器人时,将对话状态传入和传出链是至关重要的。RunnableWithMessageHistory
类允许我们为某些类型的链添加消息历史。它包装另一个可运行对象,并管理其聊天消息历史。具体来说,它在将之前的消息传递给可运行对象之前加载对话中的先前消息,并在调用可运行对象后将生成的响应保存为消息。该类还通过使用 session_id
保存每个对话来支持多个对话 - 然后在调用可运行对象时期望在配置中传递 session_id
,并使用它查找相关的对话历史。
在实践中,这看起来像:
<!--IMPORTS:[{"imported": "RunnableWithMessageHistory", "source": "langchain_core.runnables.history", "docs": "https://python.langchain.com/api_reference/core/runnables/langchain_core.runnables.history.RunnableWithMessageHistory.html", "title": "How to add message history"}]-->
from langchain_core.runnables.history import RunnableWithMessageHistory
with_message_history = RunnableWithMessageHistory(
# The underlying runnable
runnable,
# A function that takes in a session id and returns a memory object
get_session_history,
# Other parameters that may be needed to align the inputs/outputs
# of the Runnable with the memory object
...
)
with_message_history.invoke(
# The same input as before
{"ability": "math", "input": "What does cosine mean?"},
# Configuration specifying the `session_id`,
# which controls which conversation to load
config={"configurable": {"session_id": "abc123"}},
)
为了正确设置这一点,有两个主要事项需要考虑:
- 如何存储和加载消息?(这在上面的示例中是
get_session_history
) - 你正在包装的底层 Runnable 是什么,它的输入/输出是什么?(这在上面的示例中是
runnable
,以及你传递给RunnableWithMessageHistory
的任何其他参数,以对齐输入/输出)
让我们下面逐步了解这些内容(以及更多)。
如何存储和加载消息
这其中一个关键部分是存储和加载消息。
在构造 RunnableWithMessageHistory
时,你需要传入一个 get_session_history
函数。
该函数应接受一个 session_id
并返回一个 BaseChatMessageHistory
对象。
什么是 session_id
?
session_id
是与这些输入消息对应的会话(对话)线程的标识符。这使你能够同时与同一链维护多个对话/线程。
什么是 BaseChatMessageHistory
?
BaseChatMessageHistory
是一个可以加载和保存消息对象的类。它将被 RunnableWithMessageHistory
调用以实现这一功能。这些类通常使用会话 ID 初始化。
让我们创建一个 get_session_history
对象来用于这个示例。为了简单起见,我们将使用一个简单的 SQLiteMessage。
! rm memory.db
<!--IMPORTS:[{"imported": "SQLChatMessageHistory", "source": "langchain_community.chat_message_histories", "docs": "https://python.langchain.com/api_reference/community/chat_message_histories/langchain_community.chat_message_histories.sql.SQLChatMessageHistory.html", "title": "How to add message history"}]-->
from langchain_community.chat_message_histories import SQLChatMessageHistory
def get_session_history(session_id):
return SQLChatMessageHistory(session_id, "sqlite:///memory.db")
请查看 内存集成 页面,了解使用其他大模型供应商(Redis、Postgres 等)实现的聊天消息历史。