Source code for langchain_community.chat_message_histories.momento
from__future__importannotationsimportjsonfromdatetimeimporttimedeltafromtypingimportTYPE_CHECKING,Any,Optionalfromlangchain_core.chat_historyimportBaseChatMessageHistoryfromlangchain_core.messagesimport(BaseMessage,message_to_dict,messages_from_dict,)fromlangchain_core.utilsimportget_from_envifTYPE_CHECKING:importmomentodef_ensure_cache_exists(cache_client:momento.CacheClient,cache_name:str)->None:"""Create cache if it doesn't exist. Raises: SdkException: Momento service or network error Exception: Unexpected response """frommomento.responsesimportCreateCachecreate_cache_response=cache_client.create_cache(cache_name)ifisinstance(create_cache_response,CreateCache.Success)orisinstance(create_cache_response,CreateCache.CacheAlreadyExists):returnNoneelifisinstance(create_cache_response,CreateCache.Error):raisecreate_cache_response.inner_exceptionelse:raiseException(f"Unexpected response cache creation: {create_cache_response}")
[docs]classMomentoChatMessageHistory(BaseChatMessageHistory):"""Chat message history cache that uses Momento as a backend. See https://gomomento.com/"""
[docs]def__init__(self,session_id:str,cache_client:momento.CacheClient,cache_name:str,*,key_prefix:str="message_store:",ttl:Optional[timedelta]=None,ensure_cache_exists:bool=True,):"""Instantiate a chat message history cache that uses Momento as a backend. Note: to instantiate the cache client passed to MomentoChatMessageHistory, you must have a Momento account at https://gomomento.com/. Args: session_id (str): The session ID to use for this chat session. cache_client (CacheClient): The Momento cache client. cache_name (str): The name of the cache to use to store the messages. key_prefix (str, optional): The prefix to apply to the cache key. Defaults to "message_store:". ttl (Optional[timedelta], optional): The TTL to use for the messages. Defaults to None, ie the default TTL of the cache will be used. ensure_cache_exists (bool, optional): Create the cache if it doesn't exist. Defaults to True. Raises: ImportError: Momento python package is not installed. TypeError: cache_client is not of type momento.CacheClientObject """try:frommomentoimportCacheClientfrommomento.requestsimportCollectionTtlexceptImportError:raiseImportError("Could not import momento python package. ""Please install it with `pip install momento`.")ifnotisinstance(cache_client,CacheClient):raiseTypeError("cache_client must be a momento.CacheClient object.")ifensure_cache_exists:_ensure_cache_exists(cache_client,cache_name)self.key=key_prefix+session_idself.cache_client=cache_clientself.cache_name=cache_nameifttlisnotNone:self.ttl=CollectionTtl.of(ttl)else:self.ttl=CollectionTtl.from_cache_ttl()
[docs]@classmethoddeffrom_client_params(cls,session_id:str,cache_name:str,ttl:timedelta,*,configuration:Optional[momento.config.Configuration]=None,api_key:Optional[str]=None,auth_token:Optional[str]=None,# for backwards compatibility**kwargs:Any,)->MomentoChatMessageHistory:"""Construct cache from CacheClient parameters."""try:frommomentoimportCacheClient,Configurations,CredentialProviderexceptImportError:raiseImportError("Could not import momento python package. ""Please install it with `pip install momento`.")ifconfigurationisNone:configuration=Configurations.Laptop.v1()# Try checking `MOMENTO_AUTH_TOKEN` first for backwards compatibilitytry:api_key=auth_tokenorget_from_env("auth_token","MOMENTO_AUTH_TOKEN")exceptValueError:api_key=api_keyorget_from_env("api_key","MOMENTO_API_KEY")credentials=CredentialProvider.from_string(api_key)cache_client=CacheClient(configuration,credentials,default_ttl=ttl)returncls(session_id,cache_client,cache_name,ttl=ttl,**kwargs)
@propertydefmessages(self)->list[BaseMessage]:# type: ignore[override]"""Retrieve the messages from Momento. Raises: SdkException: Momento service or network error Exception: Unexpected response Returns: list[BaseMessage]: List of cached messages """frommomento.responsesimportCacheListFetchfetch_response=self.cache_client.list_fetch(self.cache_name,self.key)ifisinstance(fetch_response,CacheListFetch.Hit):items=[json.loads(m)forminfetch_response.value_list_string]returnmessages_from_dict(items)elifisinstance(fetch_response,CacheListFetch.Miss):return[]elifisinstance(fetch_response,CacheListFetch.Error):raisefetch_response.inner_exceptionelse:raiseException(f"Unexpected response: {fetch_response}")
[docs]defadd_message(self,message:BaseMessage)->None:"""Store a message in the cache. Args: message (BaseMessage): The message object to store. Raises: SdkException: Momento service or network error. Exception: Unexpected response. """frommomento.responsesimportCacheListPushBackitem=json.dumps(message_to_dict(message))push_response=self.cache_client.list_push_back(self.cache_name,self.key,item,ttl=self.ttl)ifisinstance(push_response,CacheListPushBack.Success):returnNoneelifisinstance(push_response,CacheListPushBack.Error):raisepush_response.inner_exceptionelse:raiseException(f"Unexpected response: {push_response}")
[docs]defclear(self)->None:"""Remove the session's messages from the cache. Raises: SdkException: Momento service or network error. Exception: Unexpected response. """frommomento.responsesimportCacheDeletedelete_response=self.cache_client.delete(self.cache_name,self.key)ifisinstance(delete_response,CacheDelete.Success):returnNoneelifisinstance(delete_response,CacheDelete.Error):raisedelete_response.inner_exceptionelse:raiseException(f"Unexpected response: {delete_response}")