Skip to main content

A secure, encrypted MongoDB chat memory for LangChain applications

Project description

LangChain-Encrypted-Mongo-Memory

Python PyPI License: MIT

A Secure, Encrypted MongoDB Chat Memory for LangChain Applications

LangChain-Encrypted-Mongo-Memory extends MongoDBChatMessageHistory to provide AES-128 encryption for all stored messages. Built on top of mores-encryption, it ensures sensitive conversation data remains protected at rest.

Perfect for securing chat histories containing PII, medical data, financial information, or any sensitive conversation data in your LangChain applications.

LangChain-Encrypted-Mongo-Memory removes the cryptographic complexity so you can focus on building — not configuring.


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 Output — Encrypted data stored in URL-safe format
  • Drop-in Replacement — Compatible with LangChain's chat memory interface
  • Persistent Storage — Long-term message storage in MongoDB
  • Type Filtering — Supports human, AI, and system message types
  • Zero-Config Encryption — Automatic key handling via mores-encryption

Installation

pip install langchain-encrypted-mongo-memory

Or install from source:

git clone https://github.com/HATAKEkakshi/langchain-encrypted-mongo-memory.git
cd langchain-encrypted-mongo-memory
pip install -e .

Setup

Generate Encryption Key

Run this command in your terminal:

python -c "from cryptography.fernet import Fernet; print('ENCRYPTION_KEY=' + Fernet.generate_key().decode())"

Save to .env

Copy the output and save it in your .env file:

ENCRYPTION_KEY=your_generated_key_here

Usage

1. Basic Usage

from langchain_encrypted_mongo_memory import EncryptedMongoDBChatMessageHistory
from langchain_core.messages import HumanMessage, AIMessage

# Create encrypted history
history = EncryptedMongoDBChatMessageHistory(
    connection_string="mongodb://localhost:27017",
    database_name="chat_app",
    collection_name="encrypted_messages",
    session_id="user-123"
)

# 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}")

2. Clear Session History

# Clear history for the current session
history.clear()

Why Use LangChain-Encrypted-Mongo-Memory?

Because securing chat history shouldn't be painful.

Most developers store sensitive conversation data in MongoDB without encryption — exposing PII, medical records, and confidential information to potential breaches.

LangChain-Encrypted-Mongo-Memory gives you:

  • Automatic Encryption — Messages encrypted before storage
  • Transparent Decryption — Seamless retrieval without extra code
  • LangChain Compatible — Works with all LangChain memory patterns
  • Production Ready — Built on proven cryptographic standards
  • Minimal Code Changes — Drop-in replacement for MongoDBChatMessageHistory

Configuration

Environment Variables

Variable Description Required Default
ENCRYPTION_KEY Base64-encoded 32-byte Fernet key No (Auto-generated if missing) N/A

MongoDB Connection URLs

# Local MongoDB
connection_string="mongodb://localhost:27017"

# With authentication
connection_string="mongodb://user:password@localhost:27017"

# MongoDB Atlas
connection_string="mongodb+srv://user:password@cluster.mongodb.net"

# With replica set
connection_string="mongodb://host1:27017,host2:27017/?replicaSet=rs0"

API Reference

EncryptedMongoDBChatMessageHistory

EncryptedMongoDBChatMessageHistory(
    connection_string: str,
    database_name: str,
    collection_name: str,
    session_id: str
)
Parameter Type Description
connection_string str MongoDB connection URL
database_name str Name of the database
collection_name str Name of the collection
session_id str Unique identifier for the chat session

Properties

Property Type Description
messages List[BaseMessage] List of decrypted messages

Methods

Method Description
add_message(message) Encrypt and store a message
add_user_message(content) Add a human message
add_ai_message(content) Add an AI message
clear() Delete all messages for this session

Security Implementation Details

  • Encryption: cryptography.fernet.Fernet (AES-128 CBC with PKCS7 padding, HMAC-SHA256 for integrity)
  • Key Management: Automatic loading from ENCRYPTION_KEY environment variable
  • Encoding: All outputs are URL-safe Base64 encoded strings
  • Library: Built on mores-encryption for proven security

Development

Setup

git clone https://github.com/HATAKEkakshi/langchain-encrypted-mongo-memory.git
cd langchain-encrypted-mongo-memory
python -m venv venv
source venv/bin/activate
pip install -e ".[dev]"

Running Tests

# Run all tests
pytest

# With verbose output
pytest -v

# With coverage
pytest --cov=langchain_encrypted_mongo_memory

Documentation & Source Code


License

MIT License — see LICENSE for details.


Author

Hemant KumarGitHub


Acknowledgments

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

langchain_encrypted_mongo_memory-0.2.0.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file langchain_encrypted_mongo_memory-0.2.0.tar.gz.

File metadata

File hashes

Hashes for langchain_encrypted_mongo_memory-0.2.0.tar.gz
Algorithm Hash digest
SHA256 2c54439157302524c3e8ae5abee383433d81faf9bb462f152adc6ab626756f1e
MD5 f7c22b5900e74cddcc678cefd49ded6f
BLAKE2b-256 2b49037808a2abfe7deba918200a98834ade767d446dc3d28b4f440d10f0431f

See more details on using hashes here.

File details

Details for the file langchain_encrypted_mongo_memory-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for langchain_encrypted_mongo_memory-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 63b19c4c53119e9c9d5bd12d2cf0cdc53d805a117a75fd9d7d7047bf31b739ee
MD5 84cfdeabd844df5e6dab0e42a92c1a68
BLAKE2b-256 c4b11be562cf6842c3d3dfc664c89990569767afb9f7209d22d75757147540dd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page