
    3fiC%                     v    d dl m Z  d dlmZ d dlmZmZmZmZ d dlm	Z	 d dl
mZ d dlmZmZmZ  G d de      Zy	)
    )datetime)sleep)AnyCallableListUnion)uuid4)BaseChatMessageHistory)BaseMessagemessage_to_dictmessages_from_dictc                   6   e Zd ZU dZdZeed<   dZeed<   dZeed<   de	d	ed
e
ddfdZdede
dee
   fdZd)dZdefdZdefdZdefdZd)dZdeddfdZd)dZdddd fdede
ded ed!ed"ed#e	g eeef   f   ddfd$Zedee   fd%       Zd&eddfd'Zd)d(Zy)*RocksetChatMessageHistorya  Uses Rockset to store chat messages.

    To use, ensure that the `rockset` python package installed.

    Example:
        .. code-block:: python

            from langchain_community.chat_message_histories import (
                RocksetChatMessageHistory
            )
            from rockset import RocksetClient

            history = RocksetChatMessageHistory(
                session_id="MySession",
                client=RocksetClient(),
                collection="langchain_demo",
                sync=True
            )

            history.add_user_message("hi!")
            history.add_ai_message("whats up?")

            print(history.messages)  # noqa: T201
       SLEEP_INTERVAL_MSi  ADD_TIMEOUT_MSi N  CREATE_TIMEOUT_MSmethodtimeoutmethod_paramsreturnNc                    t        j                         } |di |sdt        j                         }||z
  j                         dz  |kD  rt        | d| d      t	        t
        j                  dz          |di |scyy)zPSleeps until meth() evaluates to true. Passes kwargs into
        meth.
        i  z timed out at z msN )r   nowtotal_secondsTimeoutErrorr   r   r   )selfr   r   r   startcurrs         r/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/chat_message_histories/rocksetdb.py_wait_untilz%RocksetChatMessageHistory._wait_until0   sx     )=)<<>Du++-4w>"fX^G9C#HII+==DE	 )=)    queryquery_paramsc                 P    | j                   j                  ||      j                  S )zExecutes an SQL statement and returns the result
        Args:
            - query: The SQL string
            - **query_params: Parameters to pass into the query
        )params)clientsqlresults)r   r#   r$   s      r    _queryz RocksetChatMessageHistory._query;   s!     {{u\:BBBr"   c                 z    | j                   j                  j                  | j                  | j                         y)z-Creates a collection for this message history)name	workspaceN)r'   Collectionscreate_s3_collection
collectionr-   r   s    r    _create_collectionz,RocksetChatMessageHistory._create_collectionC   s,    44DNN 	5 	
r"   c                     	 | j                   j                  j                  | j                         y# | j                  j
                  j                  $ r Y yw xY w)z;Checks whether a collection exists for this message historyr0   FT)r'   r.   getr0   rockset
exceptionsNotFoundExceptionr1   s    r    _collection_existsz,RocksetChatMessageHistory._collection_existsI   sO    	KK##''4??'C  ||&&88 		s   03 #AAc                     | j                   j                  j                  | j                        j                  j
                  dk(  S )z^Checks whether the collection for this message history is ready
        to be queried
        r4   READY)r'   r.   r5   r0   datastatusr1   s    r    _collection_is_readyz.RocksetChatMessageHistory._collection_is_readyQ   s<    
 KK##''4??'CHHOO	
r"   c                 p    t        | j                  d| j                   d| j                              dk7  S )Nz?
                        SELECT 1
                        FROM zd 
                        WHERE _id=:session_id
                        LIMIT 1
                    
session_idr   )lenr*   locationrA   r1   s    r    _document_existsz*RocksetChatMessageHistory._document_existsZ   sK    "mm_ -  $  
 	
r"   c                 L      j                   fdt        j                         y)z\Sleeps until the collection for this message history is ready
        to be queried
        c                  $     j                         S N)r>   r1   s   r    <lambda>zJRocksetChatMessageHistory._wait_until_collection_created.<locals>.<lambda>o   s    D--/ r"   N)r!   r   r   r1   s   `r    _wait_until_collection_createdz8RocksetChatMessageHistory._wait_until_collection_createdj   s     	/%77	
r"   
message_idc                 P      j                   fdt        j                  |       y)z4Sleeps until a message is added to the messages listc           	          t        j                  dj                   dj                   dj                  |             dk7  S )Nzl
                        SELECT * 
                        FROM UNNEST((
                            SELECT z"
                            FROM z
                            WHERE _id = :session_id
                        )) AS message
                        WHERE message.data.additional_kwargs.id = :message_id
                        LIMIT 1
                    )rA   rJ   r   )rB   r*   messages_keyrC   rA   )rJ   r   s    r    rH   zERocksetChatMessageHistory._wait_until_message_added.<locals>.<lambda>v   s^    s$ %)$5$5#6 7""&-- 1		  $)     !  r"   )rJ   N)r!   r   r   )r   rJ   s   ` r    _wait_until_message_addedz3RocksetChatMessageHistory._wait_until_message_addeds   s)    " &44!' 	 	
r"   c                     | j                   j                  j                  | j                  | j                  d| j
                  | j                  g ig       y)zPCreates or replaces a document for this message history with no
        messages_idr0   r-   r<   N)r'   	Documentsadd_documentsr0   r-   rA   rM   r1   s    r    _create_empty_docz+RocksetChatMessageHistory._create_empty_doc   sH     	++nn$//4+<+<bAB 	, 	
r"   commonsmessagesFc                  (    t        t                     S rG   )strr	   r   r"   r    rH   z"RocksetChatMessageHistory.<lambda>   s    S\ r"   rA   r'   r0   r-   rM   syncmessage_uuid_methodc                 f   	 ddl }t        ||j                        st	        dt        |             || _        || _        || _        || _	        d| j                   d| j                   d| _
        || _         || _        || _        || _        	 | j                  j                  d       | j!                         s1| j#                          | j%                          | j'                          y| j)                         s| j'                          yy# t        $ r t        d      w xY w# t        $ r Y w xY w)a  Constructs a new RocksetChatMessageHistory.

        Args:
            - session_id: The ID of the chat session
            - client: The RocksetClient object to use to query
            - collection: The name of the collection to use to store chat
                          messages. If a collection with the given name
                          does not exist in the workspace, it is created.
            - workspace: The workspace containing `collection`. Defaults
                         to `"commons"`
            - messages_key: The DB column containing message history.
                            Defaults to `"messages"`
            - sync: Whether to wait for messages to be added. Defaults
                    to `False`. NOTE: setting this to `True` will slow
                    down performance.
            - message_uuid_method: The method that generates message IDs.
                    If set, all messages will have an `id` field within the
                    `additional_kwargs` property. If this param is not set
                    and `sync` is `False`, message IDs will not be created.
                    If this param is not set and `sync` is `True`, the
                    `uuid.uuid4` method will be used to create message IDs.
        r   Nz]Could not import rockset client python package. Please install it with `pip install rockset`.z;client should be an instance of rockset.RocksetClient, got "z"."	langchain)r6   ImportError
isinstanceRocksetClient
ValueErrortyperA   r'   r0   r-   rC   rM   rZ   rY   set_applicationAttributeErrorr9   r2   rI   rT   rD   )	r   rA   r'   r0   r-   rM   rY   rZ   r6   s	            r    __init__z"RocksetChatMessageHistory.__init__   s7   @	 &'"7"78F|n& 
 %$"DNN+3t.?qA(#6 		KK''4
 &&(##%//1""$&&(""$ )A  	@ 	0  		s   D D$ D!$	D0/D0c           	          t        | j                  d| j                   d| j                   d| j                              S )zMessages in this chat history.za
                    SELECT *
                    FROM UNNEST ((
                        SELECT "z"
                        FROM zX
                        WHERE _id = :session_id
                    ))
                r@   )r   r*   rM   rC   rA   r1   s    r    rV   z"RocksetChatMessageHistory.messages   sV     "KK! "&!2!2 3 4"mm_ -	  ??  

 	
r"   messagec                 D   | j                   r+d|j                  vr| j                         |j                  d<   | j                  j                  j                  | j                  | j                  | j                  j                  j                  j                  | j                  | j                  j                  j                  j                  dd| j                   dt!        |            g      g       | j                   r| j#                  |j                  d          yy)	zpAdd a Message object to the history.

        Args:
            message: A BaseMessage object to store.
        idADD/z/-)oppathvalue)ri   patchrQ   N)rY   additional_kwargsrZ   r'   rR   patch_documentsr0   r-   r6   modelpatch_documentPatchDocumentrA   patch_operationPatchOperationrM   r   rN   )r   rg   s     r    add_messagez%RocksetChatMessageHistory.add_message   s     99W%>%>>.2.F.F.HG%%d+--nn""11??**::II$#$T%6%6$7r!:"1'": J  @ 	 	. 	
  99**7+D+DT+JK r"   c                       j                           j                  r$ j                   fdt        j                         yy)z*Removes all messages from the chat historyc                       j                    S rG   )rV   r1   s   r    rH   z1RocksetChatMessageHistory.clear.<locals>.<lambda>
  s    DMM) r"   N)rT   rY   r!   r   r   r1   s   `r    clearzRocksetChatMessageHistory.clear  s5     99))88 r"   )r   N)__name__
__module____qualname____doc__r   int__annotations__r   r   r   r   r!   rX   r   r*   r2   boolr9   r>   rD   rI   rN   rT   r   re   propertyr   rV   rw   rz   r   r"   r    r   r      sp   : sNC"s"	F( 	FS 	F3 	FSW 	FCC C Cc C
D 
d 

$ 
 

C 
D 
0
 #&=QC%C% C% 	C%
 C% C% C% &b%S/&9:C% 
C%J 
${+ 
 
 L; L4 L6r"   r   N)r   timer   typingr   r   r   r   uuidr	   langchain_core.chat_historyr
   langchain_core.messagesr   r   r   r   r   r"   r    <module>r      s0      - -  > ~ 6 ~r"   