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-1.0.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-1.0.0.tar.gz.

File metadata

File hashes

Hashes for langchain_encrypted_mongo_memory-1.0.0.tar.gz
Algorithm Hash digest
SHA256 4b2822d3d8574eff3dfc129db1bb9052060115bc324c1d0fab78db8f28d3d6a8
MD5 e0c33139baed3bf4b52139452383afa8
BLAKE2b-256 80dc4553e4247e06cce9254ea15e40e3ffef5fc0cad782ff77734ea83fcb4f23

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for langchain_encrypted_mongo_memory-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0ea79d6bf8f8b43e571f4b9153cc6289ae1f777dbedd4b1647a12ac0a19458e3
MD5 d57f58adb4ab700f5d2630e5bf3607dd
BLAKE2b-256 52063cec69facaa465fe8ae096925c634cc1d669217dd2cef23789ef7891fe8e

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