[docs]@deprecated(since="0.0.25",removal="1.0",alternative_import="langchain_mongodb.MongoDBChatMessageHistory",)classMongoDBChatMessageHistory(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 create_index: whether to create an index with name SessionId. Set to False if such an index already exists. """
@propertydefmessages(self)->List[BaseMessage]:# type: ignore"""Retrieve the messages from MongoDB"""frompymongoimporterrorstry:cursor=self.collection.find({"SessionId":self.session_id})excepterrors.OperationFailureaserror:logger.error(error)ifcursor:items=[json.loads(document["History"])fordocumentincursor]else:items=[]messages=messages_from_dict(items)returnmessages
[docs]defadd_message(self,message:BaseMessage)->None:"""Append the message to the record in MongoDB"""frompymongoimporterrorstry:self.collection.insert_one({"SessionId":self.session_id,"History":json.dumps(message_to_dict(message)),})excepterrors.WriteErroraserr:logger.error(err)
[docs]defclear(self)->None:"""Clear session memory from MongoDB"""frompymongoimporterrorstry:self.collection.delete_many({"SessionId":self.session_id})excepterrors.WriteErroraserr:logger.error(err)