
    3fi7                        d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	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  ej&                  e      ZddZdd	Zdd
ZddZddZ G d de      Zy)zClient for persisting chat message history in a Postgres database.

This client provides support for both sync and async via psycopg 3.
    )annotationsN)ListOptionalSequence)BaseChatMessageHistory)BaseMessagemessage_to_dictmessages_from_dict)sqlc                   d|  d}t        j                  d      j                  t        j                  |             t        j                  d      j                  t        j                  |       t        j                  |            g}|S )z#Make a SQL query to create a table.idx__session_ida	  
            CREATE TABLE IF NOT EXISTS {table_name} (
                id SERIAL PRIMARY KEY,
                session_id UUID NOT NULL,
                message JSONB NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
            );
            
table_namez_
            CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} (session_id);
            )r   
index_namer   SQLformat
Identifier)r   r   
statementss      g/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_postgres/chat_message_histories.py_create_table_and_indexr      s    
|;/J		
 &CNN:6&
7	
 &~~j1cnnZ>X  
J&     c                r    t        j                  d      j                  t        j                  |             S )z5Make a SQL query to get messages for a given session.zOSELECT message FROM {table_name} WHERE session_id = %(session_id)s ORDER BY id;r   r   r   s    r   _get_messages_queryr   /   s/    77	
 fz2f34r   c                r    t        j                  d      j                  t        j                  |             S )z8Make a SQL query to delete messages for a given session.z;DELETE FROM {table_name} WHERE session_id = %(session_id)s;r   r   r   s    r   _delete_by_session_id_queryr   9   s+    77Efz2f34r   c                r    t        j                  d      j                  t        j                  |             S )z#Make a SQL query to delete a table.z"DROP TABLE IF EXISTS {table_name};r   r   r   s    r   _delete_table_queryr   @   s1    7778??>>*- @  r   c                r    t        j                  d      j                  t        j                  |             S )z%Make a SQL query to insert a message.z>INSERT INTO {table_name} (session_id, message) VALUES (%s, %s)r   r   r   s    r   _insert_message_queryr!   G   s+    77Hfz2f34r   c                     e Zd Zddd	 	 	 	 	 	 	 	 	 ddZe	 	 	 	 	 	 dd       Ze	 	 	 	 	 	 dd       Zedd       Ze	 	 	 	 	 	 dd       ZddZ	dd	Z
dd
ZddZedd       Zej                  dd       ZddZddZy)PostgresChatMessageHistoryN)sync_connectionasync_connectionc                  |s|st        d      || _        || _        	 t        j                  |       || _        t        j                  d|      st        d      || _        y# t         $ r t        d|       w xY w)ar  Client for persisting chat message history in a Postgres database,

        This client provides support for both sync and async via psycopg >=3.

        The client can create schema in the database and provides methods to
        add messages, get messages, and clear the chat message history.

        The schema has the following columns:

        - id: A serial primary key.
        - session_id: The session ID for the chat message history.
        - message: The JSONB message content.
        - created_at: The timestamp of when the message was created.

        Messages are retrieved for a given session_id and are sorted by
        the id (which should be increasing monotonically), and correspond
        to the order in which the messages were added to the history.

        The "created_at" column is not returned by the interface, but
        has been added for the schema so the information is available in the database.

        A session_id can be used to separate different chat histories in the same table,
        the session_id should be provided when initializing the client.

        This chat history client takes in a psycopg connection object (either
        Connection or AsyncConnection) and uses it to interact with the database.

        This design allows to reuse the underlying connection object across
        multiple instantiations of this class, making instantiation fast.

        This chat history client is designed for prototyping applications that
        involve chat and are based on Postgres.

        As your application grows, you will likely need to extend the schema to
        handle more complex queries. For example, a chat application
        may involve multiple tables like a user table, a table for storing
        chat sessions / conversations, and this table for storing chat messages
        for a given session. The application will require access to additional
        endpoints like deleting messages by user id, listing conversations by
        user id or ordering them based on last message time, etc.

        Feel free to adapt this implementation to suit your application's needs.

        Args:
            session_id: The session ID to use for the chat message history
            table_name: The name of the database table to use
            sync_connection: An existing psycopg connection instance
            async_connection: An existing psycopg async connection instance

        Usage:
            - Use the create_tables or acreate_tables method to set up the table
              schema in the database.
            - Initialize the class with the appropriate session ID, table name,
              and database connection.
            - Add messages to the database using add_messages or aadd_messages.
            - Retrieve messages with get_messages or aget_messages.
            - Clear the session history with clear or aclear when needed.

        Note:
            - At least one of sync_connection or async_connection must be provided.

        Examples:

        .. code-block:: python

            import uuid

            from langchain_core.messages import SystemMessage, AIMessage, HumanMessage
            from langchain_postgres import PostgresChatMessageHistory
            import psycopg

            # Establish a synchronous connection to the database
            # (or use psycopg.AsyncConnection for async)
            sync_connection = psycopg2.connect(conn_info)

            # Create the table schema (only needs to be done once)
            table_name = "chat_history"
            PostgresChatMessageHistory.create_tables(sync_connection, table_name)

            session_id = str(uuid.uuid4())

            # Initialize the chat history manager
            chat_history = PostgresChatMessageHistory(
                table_name,
                session_id,
                sync_connection=sync_connection
            )

            # Add messages to the chat history
            chat_history.add_messages([
                SystemMessage(content="Meow"),
                AIMessage(content="woof"),
                HumanMessage(content="bark"),
            ])

            print(chat_history.messages)
        z0Must provide sync_connection or async_connectionz9Invalid session id. Session id must be a valid UUID. Got z^\w+$zYInvalid table name. Table name must contain only alphanumeric characters and underscores.N)	
ValueError_connection_aconnectionuuidUUIDr   rematch_table_name)selfr   
session_idr$   r%   s        r   __init__z#PostgresChatMessageHistory.__init__O   s    T '7OPP*,	IIj! &xx*-.  &  	KJ<X 	s   A$ $A<c                   t        |      }t        j                  d|       | j                         5 }|D ]  }|j	                  |        	 ddd       | j                          y# 1 sw Y   xY wzDCreate the table schema in the database and create relevant indexes.zCreating schema for table %sNr   loggerinfocursorexecutecommit)
connectionr   queriesr7   querys        r   create_tablesz(PostgresChatMessageHistory.create_tables   si     **52J?  	&F  &u%&	& 		& 	&s   A%%A.c               J  K   t        |      }t        j                  d|       | j                         4 d{   }|D ]  }|j	                  |       d{     ddd      d{    | j                          d{    y7 M7 17 !# 1 d{  7  sw Y   1xY w7  wr3   r4   )r:   r   r;   curr<   s        r   acreate_tablesz)PostgresChatMessageHistory.acreate_tables   s     
 **52J?$$& 	) 	)#  )kk%((()	) 	) !!!	)(	) 	) 	) 	) 	"sb   6B#BB#BBBB#(B
)B# B!B#B
B#BBBB#c                   t        |      }t        j                  d|       | j                         5 }|j	                  |       ddd       | j                          y# 1 sw Y   xY w)aL  Delete the table schema in the database.

        WARNING:
            This will delete the given table from the database including
            all the database in the table and the schema of the table.

        Args:
            connection: The database connection.
            table_name: The name of the table to create.
        Dropping table %sNr   r5   r6   r7   r8   r9   )r:   r   r<   r7   s       r   
drop_tablez%PostgresChatMessageHistory.drop_table   sX     $J/'4  	"FNN5!	"	" 	"s   AA&c               <  K   t        |      }t        j                  d|       | j                         4 d{   }|j	                  |       d{    ddd      d{    | j                          d{    y7 F7 /7 !# 1 d{  7  sw Y   1xY w7  w)aN  Delete the table schema in the database.

        WARNING:
            This will delete the given table from the database including
            all the database in the table and the schema of the table.

        Args:
            connection: Async database connection.
            table_name: The name of the table to create.
        rB   NrC   )r:   r   r<   acurs       r   adrop_tablez&PostgresChatMessageHistory.adrop_table   s      $J/'4$$& 	& 	&$,,u%%%	& 	&!!!	&%	& 	& 	& 	&!sb   6BA?BBBBB!B"B9B:BBBBBBBc           	        | j                   t        d      |D cg c],  }| j                  t        j                  t        |            f. }}t        | j                        }| j                   j                         5 }|j                  ||       ddd       | j                   j                          yc c}w # 1 sw Y   )xY w))Add messages to the chat message history.NzpPlease initialize the PostgresChatMessageHistory with a sync connection or use the aadd_messages method instead.)r(   r'   r   jsondumpsr	   r!   r.   r7   executemanyr9   r/   messagesmessagevaluesr<   r7   s         r   add_messagesz'PostgresChatMessageHistory.add_messages  s    #R  $
 tzz/'*BCD
 

 &d&6&67$$& 	.&uf-	.!
	. 	.s   1B4>B99Cc           	       K   | j                   t        d      |D cg c],  }| j                  t        j                  t        |            f. }}t        | j                        }| j                   j                         4 d{   }|j                  ||       d{    ddd      d{    | j                   j                          d{    yc c}w 7 V7 >7 0# 1 d{  7  sw Y   @xY w7 %w)rI   NzvPlease initialize the PostgresChatMessageHistory with an async connection or use the sync add_messages method instead.)r)   r'   r   rJ   rK   r	   r!   r.   r7   rL   r9   rM   s         r   aadd_messagesz(PostgresChatMessageHistory.aadd_messages%  s     $X  $
 tzz/'*BCD
 

 &d&6&67$$++- 	4 	4$$UF333	4 	4&&(((
	43	4 	4 	4 	4(sp   C81C5C8CC8C!CC!#C8.C/!C8C6C8C!C8!C3'C*(C3/C8c                X   | j                   t        d      t        | j                        }| j                   j	                         5 }|j                  |d| j                  i       |j                         D cg c]  }|d   	 }}ddd       t              }|S c c}w # 1 sw Y   xY w)0Retrieve messages from the chat message history.NzvPlease initialize the PostgresChatMessageHistory with a sync connection or use the async aget_messages method instead.r0   r   )	r(   r'   r   r.   r7   r8   r   fetchallr
   r/   r<   r7   recorditemsrN   s         r   get_messagesz'PostgresChatMessageHistory.get_messages7  s    #X 
 $D$4$45$$& 	@&NN5<1A1A"BC-3__->?6VAY?E?	@ &e, @	@ 	@s   1B 8BB B  B)c                  K   | j                   t        d      t        | j                        }| j                   j	                         4 d{   }|j                  |d| j                  i       d{    |j                          d{   D cg c]  }|d   	 }}ddd      d{    t              }|S 7 o7 K7 5c c}w 7 # 1 d{  7  sw Y   ,xY ww)rU   NzvPlease initialize the PostgresChatMessageHistory with an async connection or use the sync get_messages method instead.r0   r   )	r)   r'   r   r.   r7   r8   r   rV   r
   rW   s         r   aget_messagesz(PostgresChatMessageHistory.aget_messagesH  s     $X 
 $D$4$45$$++- 	F 	F..t7G7G(HIII39??3D-DE6VAYEEE	F 	F &e,	FI-DE	F 	F 	F 	Fs~   ACB=C"C
3B?4C
CC
CC
 C+C,C?C
C
C
C
CCCCc                "    | j                         S )z$The abstraction required a property.)rZ   )r/   s    r   rN   z#PostgresChatMessageHistory.messagesX  s       ""r   c                F    | j                          | j                  |       y)z9Clear the stored messages and appends a list of messages.N)clearrQ   )r/   values     r   rN   z#PostgresChatMessageHistory.messages]  s     	

% r   c                *   | j                   t        d      t        | j                        }| j                   j	                         5 }|j                  |d| j                  i       ddd       | j                   j                          y# 1 sw Y   $xY w)5Clear the chat message history for the GIVEN session.NznPlease initialize the PostgresChatMessageHistory with a sync connection or use the async clear method instead.r0   )r(   r'   r   r.   r7   r8   r   r9   r/   r<   r7   s      r   r_   z PostgresChatMessageHistory.clearc  s    #P 
 ,D,<,<=$$& 	D&NN5<1A1A"BC	D!	D 	Ds   B		Bc                  K   | j                   t        d      t        | j                        }| j                   j	                         4 d{   }|j                  |d| j                  i       d{    ddd      d{    | j                   j                          d{    y7 ]7 97 +# 1 d{  7  sw Y   ;xY w7  w)rb   NzoPlease initialize the PostgresChatMessageHistory with an async connection or use the sync clear method instead.r0   )r)   r'   r   r.   r7   r8   r   r9   rc   s      r   aclearz!PostgresChatMessageHistory.aclearp  s     $Q 
 ,D,<,<=$$++- 	J 	J..t7G7G(HIII	J 	J&&(((	JI	J 	J 	J 	J(sf   ACB+C"B13B-4B18CB/!C%C&C-B1/C1C7B:8C?C)
r   strr0   rf   r$   zOptional[psycopg.Connection]r%   z!Optional[psycopg.AsyncConnection]returnNone)r:   zpsycopg.Connectionr   rf   rg   rh   )r:   zpsycopg.AsyncConnectionr   rf   rg   rh   )rN   zSequence[BaseMessage]rg   rh   )rg   zList[BaseMessage])r`   zlist[BaseMessage]rg   rh   )rg   rh   )__name__
__module____qualname__r1   staticmethodr=   r@   rD   rG   rQ   rS   rZ   r\   propertyrN   setterr_   re    r   r   r#   r#   N   s*    9=>B&& & 6& <& 
&B & 
	  	"+	"9<	"		" 	"  $ "+"9<"	" "("&)$"  # # __! !
")r   r#   )r   rf   rg   zList[sql.Composed])r   rf   rg   zsql.Composed)__doc__
__future__r   rJ   loggingr,   r*   typingr   r   r   psycopglangchain_core.chat_historyr   langchain_core.messagesr   r	   r
   r   	getLoggerri   r5   r   r   r   r   r!   r#   ro   r   r   <module>rx      sj   
 #   	  + +  > T T 			8	$2444m)!7 m)r   