This tutorial enhances in-memory chat history by using Redis for persistent conversation context across sessions.
In this tutorial, we’ll enhance our in-memory chat history demo by persisting conversation context in Redis. Externalizing message history enables multi-session, multi-tenant applications that can resume context across restarts and deployments.
# Start math sessionredis_chain.invoke( {"ability": "math", "input": "What does cosine mean?"}, config={"configurable": {"session_id": "math-thread1"}},)# Follow-up in the same sessionredis_chain.invoke( {"ability": "math", "input": "Tell me more!"}, config={"configurable": {"session_id": "math-thread1"}},)# → AIMessage: It oscillates between -1 and 1 and is key in wave analysis.
# Start physics sessionredis_chain.invoke( {"ability": "physics", "input": "What is the theory of relativity?"}, config={"configurable": {"session_id": "phy-thread1"}},)# Follow-up in the same sessionredis_chain.invoke( {"ability": "physics", "input": "Tell me more!"}, config={"configurable": {"session_id": "phy-thread1"}},)# → AIMessage: Einstein’s theory unifies mass–energy equivalence and spacetime curvature.
You can explore stored message lists directly within Redis.
Copy
Ask AI
# Ensure Redis container is runningdocker ps# Enter the Redis CLIdocker exec -it <container_id> shredis-cli# List all session keys127.0.0.1:6379> KEYS *1) "message_store:math-thread1"2) "message_store:phy-thread1"
After a restart or in a new notebook, simply re-import and re-create redis_chain. Invocations with existing session IDs will automatically load prior context:
Copy
Ask AI
# Resume math threadredis_chain.invoke( {"ability": "math", "input": "Tell me more!"}, config={"configurable": {"session_id": "math-thread1"}},)# Resume physics threadredis_chain.invoke( {"ability": "physics", "input": "Tell me more!"}, config={"configurable": {"session_id": "phy-thread1"}},)# → AIMessage: There are special and general relativity covering inertial and accelerated frames.
Swapping session IDs lets you switch contexts on the fly: