Redis Chat Message History
Redis (Remote Dictionary Server) is an open-source in-memory storage, used as a distributed, in-memory key–value database, cache and message broker, with optional durability.
Redis
offers low-latency reads and writes. Redis is the most popular NoSQL database, and one of the most popular databases overall.
This notebook demonstrates how to use the RedisChatMessageHistory
class from the langchain-redis package to store and manage chat message history using Redis.
Setup
First, we need to install the required dependencies and ensure we have a Redis instance running.
%pip install -qU langchain-redis langchain-openai redis
Make sure you have a Redis server running. You can start one using Docker with the following command:
docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
Or install and run Redis locally according to the instructions for your operating system.
import os
# Use the environment variable if set, otherwise default to localhost
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
print(f"Connecting to Redis at: {REDIS_URL}")
Connecting to Redis at: redis://redis:6379
Importing Required Libraries
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
from langchain_redis import RedisChatMessageHistory