
    3fi                        d dl mZ d dlZd dlmZ d dlmZmZmZ d dl	m
Z
 d dlmZmZmZ d dlmZ erd dlZddZ G d	 d
e
      Zy)    )annotationsN)	timedelta)TYPE_CHECKINGAnyOptional)BaseChatMessageHistory)BaseMessagemessage_to_dictmessages_from_dict)get_from_envc                    ddl m} | j                  |      }t        ||j                        st        ||j
                        ryt        ||j                        r|j                  t        d|       )zCreate cache if it doesn't exist.

    Raises:
        SdkException: Momento service or network error
        Exception: Unexpected response
    r   )CreateCacheNz$Unexpected response cache creation: )	momento.responsesr   create_cache
isinstanceSuccessCacheAlreadyExistsErrorinner_exception	Exception)cache_client
cache_namer   create_cache_responses       p/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/chat_message_histories/momento.py_ensure_cache_existsr      ss     .(55jA')<)<={==B 	);+<+<	=#333>?T>UVWW    c                      e Zd ZdZdddd	 	 	 	 	 	 	 	 	 	 	 ddZedddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zedd	       Zdd
Z	ddZ
y)MomentoChatMessageHistoryzZChat message history cache that uses Momento as a backend.

    See https://gomomento.com/zmessage_store:NT)
key_prefixttlensure_cache_existsc               $   	 ddl m} ddlm} t        ||      st        d      |rt        ||       ||z   | _        || _	        || _
        ||j                  |      | _        y|j                         | _        y# t        $ r t	        d      w xY w)a  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
        r   )CacheClient)CollectionTtlVCould not import momento python package. Please install it with `pip install momento`.z2cache_client must be a momento.CacheClient object.N)momentor#   momento.requestsr$   ImportErrorr   	TypeErrorr   keyr   r   ofr    from_cache_ttl)	self
session_idr   r   r   r    r!   r#   r$   s	            r   __init__z"MomentoChatMessageHistory.__init__,   s    <	+6 ,4PQQ z:
*($?$'',DH$335DH  	@ 	s   A: :B)configurationapi_key
auth_tokenc               2   	 ddl m}m}	m}
 ||	j
                  j                         }	 |xs t        dd      }|
j                  |      } ||||      } | |||fd	|i|S # t        $ r t	        d      w xY w# t        $ r |xs t        dd      }Y \w xY w)
z,Construct cache from CacheClient parameters.r   )r#   ConfigurationsCredentialProviderr%   r2   MOMENTO_AUTH_TOKENr1   MOMENTO_API_KEY)default_ttlr    )
r&   r#   r4   r5   r(   Laptopv1r   
ValueErrorfrom_string)clsr.   r   r    r0   r1   r2   kwargsr#   r4   r5   credentialsr   s                r   from_client_paramsz,MomentoChatMessageHistory.from_client_params^   s    	OO  *11446M	L TL?S$TG )44W="=+3O:|ZKSKFKK  	@ 	  	LKi9J!KG	Ls   
A" A: "A7:BBc                   ddl m} | j                  j                  | j                  | j
                        }t        ||j                        r7|j                  D cg c]  }t        j                  |       }}t        |      S t        ||j                        rg S t        ||j                        r|j                  t        d|       c c}w )zRetrieve the messages from Momento.

        Raises:
            SdkException: Momento service or network error
            Exception: Unexpected response

        Returns:
            list[BaseMessage]: List of cached messages
        r   )CacheListFetchUnexpected response: )r   rB   r   
list_fetchr   r*   r   Hitvalue_list_stringjsonloadsr   Missr   r   r   )r-   rB   fetch_responsemitemss        r   messagesz"MomentoChatMessageHistory.messages~   s     	5**55dootxxPnn&8&89,:,L,LMqTZZ]MEM%e,,(;(;<I(<(<= 0003N3CDEE Ns   Cc                R   ddl m} t        j                  t	        |            }| j
                  j                  | j                  | j                  || j                        }t        ||j                        ryt        ||j                        r|j                  t        d|       )zStore a message in the cache.

        Args:
            message (BaseMessage): The message object to store.

        Raises:
            SdkException: Momento service or network error.
            Exception: Unexpected response.
        r   )CacheListPushBack)r    NrC   )r   rO   rG   dumpsr
   r   list_push_backr   r*   r    r   r   r   r   r   )r-   messagerO   itempush_responses        r   add_messagez%MomentoChatMessageHistory.add_message   s     	8zz/'23))88OOTXXt 9 
 m%6%>%>?'8'>'>?///3M?CDDr   c                    ddl m} | j                  j                  | j                  | j
                        }t        ||j                        ryt        ||j                        r|j                  t        d|       )zRemove the session's messages from the cache.

        Raises:
            SdkException: Momento service or network error.
            Exception: Unexpected response.
        r   )CacheDeleteNrC   )r   rW   r   deleter   r*   r   r   r   r   r   )r-   rW   delete_responses      r   clearzMomentoChatMessageHistory.clear   sj     	2++224??DHHMo{':':;):):;!1113O3DEFFr   )r.   strr   momento.CacheClientr   r[   r   r[   r    zOptional[timedelta]r!   bool)r.   r[   r   r[   r    r   r0   z&Optional[momento.config.Configuration]r1   Optional[str]r2   r^   r>   r   returnr   )r_   zlist[BaseMessage])rR   r	   r_   None)r_   r`   )__name__
__module____qualname____doc__r/   classmethodr@   propertyrM   rU   rZ    r   r   r   r   '   s    " +#'$(0606 *06 	06 06 !06 "06d  AE!%$(LL L 	L >L L "L L 
#L L> F F0E.Gr   r   )r   r\   r   r[   r_   r`   )
__future__r   rG   datetimer   typingr   r   r   langchain_core.chat_historyr   langchain_core.messagesr	   r
   r   langchain_core.utilsr   r&   r   r   rg   r   r   <module>rn      sC    "   / / > 
 .X(VG 6 VGr   