使用Redis存储和检索聊天消息历史:快速上手指南

115 阅读2分钟

引言

Redis(Remote Dictionary Server)是一种开源的内存数据库,常用于分布式内存键值存储、缓存和消息代理。由于其内存设计,Redis提供了低延迟的读写操作,特别适合需要缓存的场景。在NoSQL数据库中,Redis是最受欢迎的选择之一。

本文将介绍如何使用Redis来存储和检索聊天消息历史,对初学者和有经验的开发者都有帮助。

主要内容

1. 环境设置

首先,我们需要安装相应的依赖并启动Redis实例。

pip install -U langchain-community redis
redis-server

这样可以确保我们有一个可用的Redis服务在本地运行。

2. 使用Redis存储和检索消息

借助langchain-community库,我们可以很方便地使用Redis来存储聊天消息。

from langchain_community.chat_message_histories import RedisChatMessageHistory

# 使用API代理服务提高访问稳定性
history = RedisChatMessageHistory("foo", url="redis://localhost:6379")

# 添加用户消息
history.add_user_message("hi!")

# 添加AI响应消息
history.add_ai_message("whats up?")

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

3. 在链式调用中使用

我们可以将Redis与AI模型结合起来,实现对话历史的动态调整。

pip install -U langchain-openai

下面是一个使用Redis存储对话历史的完整示例:

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"
    ),
    input_messages_key="question",
    history_messages_key="history",
)

# 配置并进行调用
config = {"configurable": {"session_id": "foo"}}
chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
chain_with_history.invoke({"question": "Whats my name"}, config=config)

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

常见问题和解决方案

  • 网络访问问题:某些地区可能会遇到访问限制,建议使用API代理服务以提高访问稳定性。
  • 内存限制问题:Redis是内存数据库,所以在使用时需要关注服务器的内存使用情况。

总结和进一步学习资源

通过Redis存储和检索聊天历史,可以大幅提高应用的响应速度和用户体验。建议读者进一步探索:

参考资料

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

---END---