[docs]@deprecated(since="0.0.31",message=("This class is deprecated and will be removed in a future version. ""You can swap to using the `PostgresChatMessageHistory`"" implementation in `langchain_postgres`. ""Please do not submit further PRs to this class.""See <https://github.com/langchain-ai/langchain-postgres>"),alternative="from langchain_postgres import PostgresChatMessageHistory;",pending=True,)classPostgresChatMessageHistory(BaseChatMessageHistory):"""Chat message history stored in a Postgres database. **DEPRECATED**: This class is deprecated and will be removed in a future version. Use the `PostgresChatMessageHistory` implementation in `langchain_postgres`. """
def_create_table_if_not_exists(self)->None:create_table_query=f"""CREATE TABLE IF NOT EXISTS {self.table_name} ( id SERIAL PRIMARY KEY, session_id TEXT NOT NULL, message JSONB NOT NULL );"""self.cursor.execute(create_table_query)self.connection.commit()@propertydefmessages(self)->List[BaseMessage]:# type: ignore"""Retrieve the messages from PostgreSQL"""query=(f"SELECT message FROM {self.table_name} WHERE session_id = %s ORDER BY id;")self.cursor.execute(query,(self.session_id,))items=[record["message"]forrecordinself.cursor.fetchall()]messages=messages_from_dict(items)returnmessages
[docs]defadd_message(self,message:BaseMessage)->None:"""Append the message to the record in PostgreSQL"""frompsycopgimportsqlquery=sql.SQL("INSERT INTO {} (session_id, message) VALUES (%s, %s);").format(sql.Identifier(self.table_name))self.cursor.execute(query,(self.session_id,json.dumps(message_to_dict(message))))self.connection.commit()
[docs]defclear(self)->None:"""Clear session memory from PostgreSQL"""query=f"DELETE FROM {self.table_name} WHERE session_id = %s;"self.cursor.execute(query,(self.session_id,))self.connection.commit()