Source code for langchain_community.chat_message_histories.firestore
"""Firestore Chat Message History."""from__future__importannotationsimportloggingfromtypingimportTYPE_CHECKING,List,Optionalfromlangchain_core.chat_historyimportBaseChatMessageHistoryfromlangchain_core.messagesimport(BaseMessage,messages_from_dict,messages_to_dict,)logger=logging.getLogger(__name__)ifTYPE_CHECKING:fromgoogle.cloud.firestoreimportClient,DocumentReferencedef_get_firestore_client()->Client:try:importfirebase_adminfromfirebase_adminimportfirestoreexceptImportError:raiseImportError("Could not import firebase-admin python package. ""Please install it with `pip install firebase-admin`.")# For multiple instances, only initialize the app once.try:firebase_admin.get_app()exceptValueErrorase:logger.debug("Initializing Firebase app: %s",e)firebase_admin.initialize_app()returnfirestore.client()
[docs]classFirestoreChatMessageHistory(BaseChatMessageHistory):"""Chat message history backed by Google Firestore."""
[docs]def__init__(self,collection_name:str,session_id:str,user_id:str,firestore_client:Optional[Client]=None,):""" Initialize a new instance of the FirestoreChatMessageHistory class. :param collection_name: The name of the collection to use. :param session_id: The session ID for the chat.. :param user_id: The user ID for the chat. """self.collection_name=collection_nameself.session_id=session_idself.user_id=user_idself._document:Optional[DocumentReference]=Noneself.messages:List[BaseMessage]=[]self.firestore_client=firestore_clientor_get_firestore_client()self.prepare_firestore()
[docs]defprepare_firestore(self)->None:"""Prepare the Firestore client. Use this function to make sure your database is ready. """self._document=self.firestore_client.collection(self.collection_name).document(self.session_id)self.load_messages()
[docs]defload_messages(self)->None:"""Retrieve the messages from Firestore"""ifnotself._document:raiseValueError("Document not initialized")doc=self._document.get()ifdoc.exists:data=doc.to_dict()if"messages"indataandlen(data["messages"])>0:self.messages=messages_from_dict(data["messages"])
[docs]defupsert_messages(self,new_message:Optional[BaseMessage]=None)->None:"""Update the Firestore document."""ifnotself._document:raiseValueError("Document not initialized")self._document.set({"id":self.session_id,"user_id":self.user_id,"messages":messages_to_dict(self.messages),})
[docs]defclear(self)->None:"""Clear session memory from this memory and Firestore."""self.messages=[]ifself._document:self._document.delete()