
    hh                        d dl mZ d dlmZ d dlmZmZmZmZm	Z	 d dl
mZ d dlmZmZmZ erd dlmZ dd
Z G d de          ZdS )    )annotations)Decimal)TYPE_CHECKINGDictListOptionalSequence)BaseChatMessageHistory)BaseMessagemessages_from_dictmessages_to_dict)Sessionitemr   returnc                   t          | t                    rd | D             S t          | t                    rd |                                 D             S t          | t                    rt          t          |                     S | S )Nc                ,    g | ]}t          |          S  convert_messages).0is     p/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_community/chat_message_histories/dynamodb.py
<listcomp>z$convert_messages.<locals>.<listcomp>   s!    222 ##222    c                4    i | ]\  }}|t          |          S r   r   )r   kvs      r   
<dictcomp>z$convert_messages.<locals>.<dictcomp>   s'    @@@41a#A&&@@@r   )
isinstancelistdictitemsfloatr   str)r   s    r   r   r      s    $ "22T2222	D$		 "@@4::<<@@@@	D%	 	  "s4yy!!!Kr   c                  ~    e Zd ZdZ	 	 	 	 	 	 	 	 	 d$ddd%dZed&d            Zej        d'd             Zd(d"Zd)d#Z	dS )*DynamoDBChatMessageHistorya  Chat message history that stores history in AWS DynamoDB.

    This class expects that a DynamoDB table exists with name `table_name`

    Args:
        table_name: name of the DynamoDB table
        session_id: arbitrary key that is used to store the messages
            of a single chat session.
        endpoint_url: URL of the AWS endpoint to connect to. This argument
            is optional and useful for test purposes, like using Localstack.
            If you plan to use AWS cloud service, you normally don't have to
            worry about setting the endpoint_url.
        primary_key_name: name of the primary key of the DynamoDB table. This argument
            is optional, defaulting to "SessionId".
        key: an optional dictionary with a custom primary and secondary key.
            This argument is optional, but useful when using composite dynamodb keys, or
            isolating records based off of application details such as a user id.
            This may also contain global and local secondary index keys.
        kms_key_id: an optional AWS KMS Key ID, AWS KMS Key ARN, or AWS KMS Alias for
            client-side encryption
        ttl: Optional Time-to-live (TTL) in seconds. Allows you to define a per-item
            expiration timestamp that indicates when an item can be deleted from the
            table. DynamoDB handles deletion of expired items without consuming
            write throughput. To enable this feature on the table, follow the
            [AWS DynamoDB documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html)
        history_size: Maximum number of messages to store. If None then there is no
            limit. If not None then only the latest `history_size` messages are stored.
        history_messages_key: Key for the chat history where the messages
            are stored and updated
        coerce_float_to_decimal: If True, all float values in the messages will be
            converted to Decimal.
    N	SessionIdexpireAtHistoryF)coerce_float_to_decimal
table_namer$   
session_idendpoint_urlOptional[str]primary_key_namekeyOptional[Dict[str, str]]boto3_sessionOptional[Session]
kms_key_idttlOptional[int]ttl_key_namehistory_sizehistory_messages_keyr*   boolc                  |r|                     d|          }nW	 dd l}n"# t          $ r}t          d          |d }~ww xY w|r|                     d|          }n|                     d          }|                    |          | _        || _        |p||i| _        || _        |	| _        |
| _	        || _
        || _        |r	 ddlm} ddlm} ddlm} ddlm} n"# t          $ r}t          d	          |d }~ww xY w ||j        | j
        |j        i
          } ||          } || j        ||d          | _        d S d S )Ndynamodb)r-   r   z@Unable to import boto3, please install with `pip install boto3`.)EncryptedTable)CryptoAction)$AwsKmsCryptographicMaterialsProvider)AttributeActionszdUnable to import dynamodb_encryption_sdk, please install with `pip install dynamodb-encryption-sdk`.)default_actionattribute_actions)key_idF)tablematerials_providerrB   auto_refresh_table_indexes)resourceboto3ImportErrorTablerD   r,   r0   r5   r7   r8   r9   r*   'dynamodb_encryption_sdk.encrypted.tabler=   #dynamodb_encryption_sdk.identifiersr>   2dynamodb_encryption_sdk.material_providers.aws_kmsr?   "dynamodb_encryption_sdk.structuresr@   
DO_NOTHINGENCRYPT_AND_SIGN)selfr+   r,   r-   r/   r0   r2   r4   r5   r7   r8   r9   r*   clientrH   er=   r>   r?   r@   actionsaws_kms_cmps                         r   __init__z#DynamoDBChatMessageHistory.__init__=   s      	4"++J\+RRFF   !V   4
NN
33\\*--
$>!1: >(($8!'>$ 	RRRRRRLLLLLL      POOOOOO   !=   '&+6-|/L#  G ?>jQQQK'j#.")+0	  DJJJ+	 	s*   ! 
A ;A C 
C<'C77C<r   List[BaseMessage]c                    d}| j                             | j                  }|rd|v r|d         | j                 }ng }t	          |          }|S )z#Retrieve the messages from DynamoDBNKeyItem)rD   get_itemr0   r9   r   )rQ   responser"   messagess       r   r^   z#DynamoDBChatMessageHistory.messages   s`     :&&48&44 	(**V$T%>?EEE%e,,r   r^   Nonec                     t          d          )NzODirect assignment to 'messages' is not allowed. Use the 'add_messages' instead.)NotImplementedError)rQ   r^   s     r   r^   z#DynamoDBChatMessageHistory.messages   s    !/
 
 	
r   Sequence[BaseMessage]c                   t          | j                  }|                    t          |                     | j        rt	          |          }| j        r|| j         d         }| j        rgddl}t          |                                          | j        z   }| j	        
                    i | j        d| j         d| j         d||d           dS | j	        
                    i | j        d| j         dd	|i           dS )
z,Append the message to the record in DynamoDBNr   zset z = :h, z = :t):hz:t)rZ   UpdateExpressionExpressionAttributeValuesz = :hrd   )r   r^   extendr*   r   r8   r5   timeintrD   update_itemr0   r9   r7   )rQ   r^   existing_messagesrh   r(   s        r   add_messagesz'DynamoDBChatMessageHistory.add_messages   sC   ,T];;  !1(!;!;<<<' 	D 01B C C 	H 143D2D2F2F G8 	KKK499;;''$(2HJ"" txLU44UUT=NUUU1B(*S*S #      J"" txL!H(A!H!H!H+/1B*C #     r   c                F    | j                             | j                   dS )z"Clear session memory from DynamoDBrY   N)rD   delete_itemr0   )rQ   s    r   clearz DynamoDBChatMessageHistory.clear   s#    
48,,,,,r   )	Nr'   NNNNr(   Nr)   )r+   r$   r,   r$   r-   r.   r/   r$   r0   r1   r2   r3   r4   r.   r5   r6   r7   r$   r8   r6   r9   r.   r*   r:   )r   rW   )r^   rW   r   r_   )r^   rb   r   r_   )r   r_   )
__name__
__module____qualname____doc__rV   propertyr^   setterrl   ro   r   r   r   r&   r&      s         J '+ +(,+/$(!&&*.7@ ).@ @ @ @ @ @D    X _
 
 
 _
   8- - - - - -r   r&   N)r   r   r   r   )
__future__r   decimalr   typingr   r   r   r   r	   langchain_core.chat_historyr
   langchain_core.messagesr   r   r   boto3.sessionr   r   r&   r   r   r   <module>r|      s   " " " " " "       @ @ @ @ @ @ @ @ @ @ @ @ @ @ > > > > > >           &%%%%%%   W- W- W- W- W-!7 W- W- W- W- W-r   