探索Redis:如何存储和检索聊天消息历史

134 阅读2分钟

引言

Redis是一种开源的内存存储,广泛用于作为分布式的键值数据库、缓存和消息代理,具有可选的持久性功能。由于其设计特性以及全部数据存储于内存中,Redis能够提供低延迟的读写操作,非常适合需要缓存的使用场景。本文将重点介绍如何使用Redis来存储和检索聊天消息历史。

主要内容

Redis的基本安装和设置

在开始之前,需要安装必要的依赖项,并使用以下命令启动Redis实例:

pip install -U langchain-community redis
redis-server

使用Redis存储聊天消息

在这个部分,我们将使用RedisChatMessageHistory来存储和检索聊天消息。

from langchain_community.chat_message_histories import RedisChatMessageHistory

# 创建Redis聊天消息历史对象
history = RedisChatMessageHistory("foo", url="redis://localhost:6379") # 使用API代理服务提高访问稳定性

# 添加用户和AI消息
history.add_user_message("hi!")
history.add_ai_message("whats up?")

# 检索消息
print(history.messages)
# 输出: [HumanMessage(content='hi!'), AIMessage(content='whats up?')]

在链中使用消息历史

我们可以将消息历史集成到一个聊天链中,以增强对话的流畅性。

pip install -U langchain-openai
from typing import Optional
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI

# 定义提示模板
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You're an assistant."),
        MessagesPlaceholder(variable_name="history"),
        ("human", "{question}"),
    ]
)

# 创建链
chain = prompt | ChatOpenAI()

# 将历史记录与链集成
chain_with_history = RunnableWithMessageHistory(
    chain,
    lambda session_id: RedisChatMessageHistory(
        session_id, url="redis://localhost:6379" # 使用API代理服务提高访问稳定性
    ),
    input_messages_key="question",
    history_messages_key="history",
)

# 配置并运行链
config = {"configurable": {"session_id": "foo"}}

response1 = chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
response2 = chain_with_history.invoke({"question": "What's my name"}, config=config)

print(response2)
# 输出: AIMessage(content='Your name is Bob, as you mentioned earlier. Is there anything specific you would like assistance with, Bob?')

常见问题和解决方案

  1. 连接错误:如果在连接Redis时遇到问题,请检查Redis服务是否已启动,并确保URL和端口设置正确。

  2. 网络限制:在某些地区,可能需要使用API代理服务来提高访问稳定性。

  3. 数据持久性:默认情况下,Redis在内存中存储数据,可能导致断电时数据丢失。可以配置RDB或AOF进行数据持久化。

总结和进一步学习资源

本文介绍了如何使用Redis来存储和检索聊天历史记录,并演示了如何在聊天链中使用历史记录。要深入学习,可以参考以下资源:

参考资料

  1. Redis Documentation
  2. Langchain GitHub Repository

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

---END---