|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import json |
| 15 | +from typing import List |
| 16 | + |
| 17 | +import sqlalchemy |
| 18 | +from langchain_core.chat_history import BaseChatMessageHistory |
| 19 | +from langchain_core.messages import BaseMessage, messages_from_dict |
| 20 | + |
| 21 | +from langchain_google_cloud_sql_mssql.mssql_engine import MSSQLEngine |
| 22 | + |
| 23 | + |
| 24 | +class MSSQLChatMessageHistory(BaseChatMessageHistory): |
| 25 | + """Chat message history stored in a Cloud SQL MSSQL database. |
| 26 | +
|
| 27 | + Args: |
| 28 | + engine (MSSQLEngine): SQLAlchemy connection pool engine for managing |
| 29 | + connections to Cloud SQL for SQL Server. |
| 30 | + session_id (str): Arbitrary key that is used to store the messages |
| 31 | + of a single chat session. |
| 32 | + table_name (str): The name of the table to use for storing/retrieving |
| 33 | + the chat message history. |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, |
| 38 | + engine: MSSQLEngine, |
| 39 | + session_id: str, |
| 40 | + table_name: str, |
| 41 | + ) -> None: |
| 42 | + self.engine = engine |
| 43 | + self.session_id = session_id |
| 44 | + self.table_name = table_name |
| 45 | + self._verify_schema() |
| 46 | + |
| 47 | + def _verify_schema(self) -> None: |
| 48 | + """Verify table exists with required schema for MSSQLChatMessageHistory class. |
| 49 | +
|
| 50 | + Use helper method MSSQLEngine.create_chat_history_table(...) to create |
| 51 | + table with valid schema. |
| 52 | + """ |
| 53 | + insp = sqlalchemy.inspect(self.engine.engine) |
| 54 | + # check table exists |
| 55 | + if insp.has_table(self.table_name): |
| 56 | + # check that all required columns are present |
| 57 | + required_columns = ["id", "session_id", "data", "type"] |
| 58 | + column_names = [ |
| 59 | + c["name"] for c in insp.get_columns(table_name=self.table_name) |
| 60 | + ] |
| 61 | + if not (all(x in column_names for x in required_columns)): |
| 62 | + raise IndexError( |
| 63 | + f"Table '{self.table_name}' has incorrect schema. Got " |
| 64 | + f"column names '{column_names}' but required column names " |
| 65 | + f"'{required_columns}'.\nPlease create table with following schema:" |
| 66 | + f"\nCREATE TABLE {self.table_name} (" |
| 67 | + "\n id INT IDENTITY(1,1) PRIMARY KEY," |
| 68 | + "\n session_id NVARCHAR(MAX) NOT NULL," |
| 69 | + "\n data NVARCHAR(MAX) NOT NULL," |
| 70 | + "\n type NVARCHAR(MAX) NOT NULL" |
| 71 | + "\n);" |
| 72 | + ) |
| 73 | + else: |
| 74 | + raise AttributeError( |
| 75 | + f"Table '{self.table_name}' does not exist. Please create " |
| 76 | + "it before initializing MSSQLChatMessageHistory. See " |
| 77 | + "MSSQLEngine.create_chat_history_table() for a helper method." |
| 78 | + ) |
| 79 | + |
| 80 | + @property |
| 81 | + def messages(self) -> List[BaseMessage]: # type: ignore |
| 82 | + """Retrieve the messages from Cloud SQL""" |
| 83 | + query = f'SELECT data, type FROM "{self.table_name}" WHERE session_id = :session_id ORDER BY id;' |
| 84 | + with self.engine.connect() as conn: |
| 85 | + results = conn.execute( |
| 86 | + sqlalchemy.text(query), {"session_id": self.session_id} |
| 87 | + ).fetchall() |
| 88 | + # load SQLAlchemy row objects into dicts |
| 89 | + items = [{"data": json.loads(r[0]), "type": r[1]} for r in results] |
| 90 | + messages = messages_from_dict(items) |
| 91 | + return messages |
| 92 | + |
| 93 | + def add_message(self, message: BaseMessage) -> None: |
| 94 | + """Append the message to the record in Cloud SQL""" |
| 95 | + query = f'INSERT INTO "{self.table_name}" (session_id, data, type) VALUES (:session_id, :data, :type);' |
| 96 | + with self.engine.connect() as conn: |
| 97 | + conn.execute( |
| 98 | + sqlalchemy.text(query), |
| 99 | + { |
| 100 | + "session_id": self.session_id, |
| 101 | + "data": json.dumps(message.dict()), |
| 102 | + "type": message.type, |
| 103 | + }, |
| 104 | + ) |
| 105 | + conn.commit() |
| 106 | + |
| 107 | + def clear(self) -> None: |
| 108 | + """Clear session memory from Cloud SQL""" |
| 109 | + query = f'DELETE FROM "{self.table_name}" WHERE session_id = :session_id;' |
| 110 | + with self.engine.connect() as conn: |
| 111 | + conn.execute(sqlalchemy.text(query), {"session_id": self.session_id}) |
| 112 | + conn.commit() |
0 commit comments