Encrypted Redis chat message history for LangChain with AES-128 encryption via mores-encryption.
Project description
langchain-encrypted-redis-memory
A secure, encrypted Redis chat message history for LangChain applications. This package extends RedisChatMessageHistory to provide AES-128 encryption for all stored messages, ensuring sensitive conversation data remains protected at rest.
Features
- AES-128 Encryption - Messages encrypted using Fernet (AES-128 CBC with PKCS7 padding)
- HMAC-SHA256 Integrity - Cryptographic verification of message integrity
- URL-safe Base64 - Encrypted data stored in URL-safe format
- Drop-in Replacement - Compatible with LangChain's chat memory interface
- TTL Support - Optional time-to-live for automatic message expiration
- Type Filtering - Supports human, AI, and system message types
Installation
pip install langchain-encrypted-redis-memory
Or install from source:
git clone https://github.com/HATAKEkakshi/langchain-encrypted-redis-memory.git
cd langchain-encrypted-redis-memory
pip install -e .
Requirements
- Python >= 3.8
- Redis server
- Environment variable
ENCRYPTION_KEY(32-byte URL-safe base64 key)
Generate Encryption Key
from cryptography.fernet import Fernet
key = Fernet.generate_key()
print(key.decode()) # Add this to your .env file
Or via command line:
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
Quick Start
Basic Usage
from langchain_encrypted_redis_memory import EncryptedRedisChatMessageHistory
from langchain_core.messages import HumanMessage, AIMessage
# Create encrypted history
history = EncryptedRedisChatMessageHistory(
session_id="user-123",
url="redis://localhost:6379"
)
# Add messages (automatically encrypted)
history.add_message(HumanMessage(content="Hello, how are you?"))
history.add_message(AIMessage(content="I'm doing great, thank you!"))
# Retrieve messages (automatically decrypted)
messages = history.messages
for msg in messages:
print(f"{msg.type}: {msg.content}")
With TTL (Auto-expiry)
# Messages expire after 1 hour
history = EncryptedRedisChatMessageHistory(
session_id="user-123",
url="redis://localhost:6379",
ttl=3600 # seconds
)
With LangChain ConversationBufferMemory
from langchain.memory import ConversationBufferMemory
from langchain_encrypted_redis_memory import EncryptedRedisChatMessageHistory
history = EncryptedRedisChatMessageHistory(
session_id="user-123",
url="redis://localhost:6379"
)
memory = ConversationBufferMemory(
chat_memory=history,
return_messages=True
)
Reset Session History
# Clear history for a specific session
EncryptedRedisChatMessageHistory.reset_session_history(
url="redis://localhost:6379",
session_id="user-123"
)
Configuration
Environment Variables
Create a .env file in your project root:
ENCRYPTION_KEY=your-32-byte-url-safe-base64-key
Redis Connection
The url parameter accepts standard Redis connection strings:
# Local Redis
url="redis://localhost:6379"
# With password
url="redis://:password@localhost:6379"
# With database selection
url="redis://localhost:6379/1"
# Redis Sentinel
url="redis+sentinel://localhost:26379/mymaster/0"
API Reference
EncryptedRedisChatMessageHistory
Constructor
EncryptedRedisChatMessageHistory(
session_id: str,
url: str,
ttl: Optional[int] = None,
key_prefix: str = "message_store:"
)
| Parameter | Type | Description |
|---|---|---|
session_id |
str |
Unique identifier for the chat session |
url |
str |
Redis connection URL |
ttl |
int |
Optional TTL in seconds for message expiration |
key_prefix |
str |
Prefix for Redis keys (default: message_store:) |
Properties
| Property | Type | Description |
|---|---|---|
messages |
List[BaseMessage] |
List of decrypted messages |
Methods
| Method | Description |
|---|---|
add_message(message) |
Encrypt and store a message |
clear() |
Delete all messages for this session |
reset_session_history(url, session_id) |
Static method to clear a session |
Security
Encryption Details
- Algorithm: AES-128 in CBC mode with PKCS7 padding
- Key Derivation: Fernet specification (URL-safe base64)
- Integrity: HMAC-SHA256 for authentication
- IV: Randomly generated for each encryption operation
Best Practices
- Key Management: Store
ENCRYPTION_KEYsecurely (secrets manager, environment variable) - Key Rotation: Implement key rotation for long-lived applications
- Network Security: Use TLS for Redis connections in production
- Access Control: Use Redis ACLs to limit access
Development
Setup
# Clone repository
git clone https://github.com/HATAKEkakshi/langchain-encrypted-redis-memory.git
cd langchain-encrypted-redis-memory
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install with dev dependencies
pip install -e ".[dev]"
Running Tests
# Run all tests
pytest
# With verbose output
pytest -v
# With coverage
pytest --cov=langchain_encrypted_redis_memory
# Skip integration tests
pytest -m "not integration"
Code Quality
# Format code
black langchain_encrypted_redis_memory tests
# Lint
flake8 langchain_encrypted_redis_memory tests
# Type check
mypy langchain_encrypted_redis_memory
Project Structure
langchain-encrypted-redis-memory/
├── langchain_encrypted_redis_memory/
│ ├── __init__.py
│ └── EncryptedRedisChatMemory.py
├── tests/
│ ├── __init__.py
│ └── test_encrypted_redis_chat_memory.py
├── .gitignore
├── .env.example
├── LICENSE
├── README.md
├── pyproject.toml
├── pytest.ini
├── requirements.txt
└── setup.cfg
Dependencies
- langchain - LLM application framework
- langchain-community - Community integrations
- redis - Redis Python client
- mores-encryption - Encryption utilities
License
MIT License - see LICENSE for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Author
Hemant Kumar - GitHub
Acknowledgments
- LangChain for the excellent LLM framework
- cryptography for secure encryption primitives
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file langchain_encrypted_redis_memory-0.1.0.tar.gz.
File metadata
- Download URL: langchain_encrypted_redis_memory-0.1.0.tar.gz
- Upload date:
- Size: 9.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3aa634a6229ea7322300ddf9b69049300884691dfd8f4e32f628a1edbce36ecb
|
|
| MD5 |
ae314ee1e239db1f14b77375dd9c70d0
|
|
| BLAKE2b-256 |
9240c66f0aedaeaa0b5e4b543f3a11ed7499343e6df90014645aacd49642ab7f
|
File details
Details for the file langchain_encrypted_redis_memory-0.1.0-py3-none-any.whl.
File metadata
- Download URL: langchain_encrypted_redis_memory-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a3f46a6152f15818a7bfc3d58d13a4fd8fadbbb45a592efaa91c5c62579d34c5
|
|
| MD5 |
9d7db2f40fc0bf450212629ffeeab68e
|
|
| BLAKE2b-256 |
cb34a97bce0e7df290ad3dea66a0b38f5432b569f882ad1084e02b16d3234a36
|