mirror of
https://github.com/hwchase17/langchain.git
synced 2025-09-15 06:26:12 +00:00
mongodb[patch]: Migrate MongoDBChatMessageHistory (#18590)
## **Description** Migrate the `MongoDBChatMessageHistory` to the managed `langchain-mongodb` partner-package ## **Dependencies** None ## **Twitter handle** @mongodb ## **tests and docs** - [x] Migrate existing integration test - [x ]~ Convert existing integration test to a unit test~ Creation is out of scope for this ticket - [x ] ~Considering delaying work until #17470 merges to leverage the `MockCollection` object. ~ - [x] **Lint and test**: Run `make format`, `make lint` and `make test` from the root of the package(s) you've modified. See contribution guidelines for more: https://python.langchain.com/docs/contributing/ --------- Co-authored-by: Erick Friis <erick@langchain.dev>
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory
|
||||
from langchain_mongodb.vectorstores import (
|
||||
MongoDBAtlasVectorSearch,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"MongoDBAtlasVectorSearch",
|
||||
"MongoDBChatMessageHistory",
|
||||
]
|
||||
|
@@ -0,0 +1,84 @@
|
||||
import json
|
||||
import logging
|
||||
from typing import List
|
||||
|
||||
from langchain_core.chat_history import BaseChatMessageHistory
|
||||
from langchain_core.messages import (
|
||||
BaseMessage,
|
||||
message_to_dict,
|
||||
messages_from_dict,
|
||||
)
|
||||
from pymongo import MongoClient, errors
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_DBNAME = "chat_history"
|
||||
DEFAULT_COLLECTION_NAME = "message_store"
|
||||
|
||||
|
||||
class MongoDBChatMessageHistory(BaseChatMessageHistory):
|
||||
"""Chat message history that stores history in MongoDB.
|
||||
|
||||
Args:
|
||||
connection_string: connection string to connect to MongoDB
|
||||
session_id: arbitrary key that is used to store the messages
|
||||
of a single chat session.
|
||||
database_name: name of the database to use
|
||||
collection_name: name of the collection to use
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
connection_string: str,
|
||||
session_id: str,
|
||||
database_name: str = DEFAULT_DBNAME,
|
||||
collection_name: str = DEFAULT_COLLECTION_NAME,
|
||||
):
|
||||
self.connection_string = connection_string
|
||||
self.session_id = session_id
|
||||
self.database_name = database_name
|
||||
self.collection_name = collection_name
|
||||
|
||||
try:
|
||||
self.client: MongoClient = MongoClient(connection_string)
|
||||
except errors.ConnectionFailure as error:
|
||||
logger.error(error)
|
||||
|
||||
self.db = self.client[database_name]
|
||||
self.collection = self.db[collection_name]
|
||||
self.collection.create_index("SessionId")
|
||||
|
||||
@property
|
||||
def messages(self) -> List[BaseMessage]: # type: ignore
|
||||
"""Retrieve the messages from MongoDB"""
|
||||
try:
|
||||
cursor = self.collection.find({"SessionId": self.session_id})
|
||||
except errors.OperationFailure as error:
|
||||
logger.error(error)
|
||||
|
||||
if cursor:
|
||||
items = [json.loads(document["History"]) for document in cursor]
|
||||
else:
|
||||
items = []
|
||||
|
||||
messages = messages_from_dict(items)
|
||||
return messages
|
||||
|
||||
def add_message(self, message: BaseMessage) -> None:
|
||||
"""Append the message to the record in MongoDB"""
|
||||
try:
|
||||
self.collection.insert_one(
|
||||
{
|
||||
"SessionId": self.session_id,
|
||||
"History": json.dumps(message_to_dict(message)),
|
||||
}
|
||||
)
|
||||
except errors.WriteError as err:
|
||||
logger.error(err)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear session memory from MongoDB"""
|
||||
try:
|
||||
self.collection.delete_many({"SessionId": self.session_id})
|
||||
except errors.WriteError as err:
|
||||
logger.error(err)
|
Reference in New Issue
Block a user