langchain-postgres 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ from importlib import metadata
2
+
3
+ from langchain_postgres.chat_message_histories import PostgresChatMessageHistory
4
+ from langchain_postgres.checkpoint import (
5
+ CheckpointSerializer,
6
+ PickleCheckpointSerializer,
7
+ PostgresSaver,
8
+ )
9
+ from langchain_postgres.vectorstores import PGVector
10
+
11
+ try:
12
+ __version__ = metadata.version(__package__)
13
+ except metadata.PackageNotFoundError:
14
+ # Case where package metadata is not available.
15
+ __version__ = ""
16
+
17
+ __all__ = [
18
+ "__version__",
19
+ "CheckpointSerializer",
20
+ "PostgresChatMessageHistory",
21
+ "PostgresSaver",
22
+ "PickleCheckpointSerializer",
23
+ "PGVector",
24
+ ]
@@ -0,0 +1,82 @@
1
+ """Copied over from langchain_community.
2
+
3
+ This code should be moved to langchain proper or removed entirely.
4
+ """
5
+
6
+ import logging
7
+ from typing import List, Union
8
+
9
+ import numpy as np
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray]
14
+
15
+
16
+ def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
17
+ """Row-wise cosine similarity between two equal-width matrices."""
18
+ if len(X) == 0 or len(Y) == 0:
19
+ return np.array([])
20
+
21
+ X = np.array(X)
22
+ Y = np.array(Y)
23
+ if X.shape[1] != Y.shape[1]:
24
+ raise ValueError(
25
+ f"Number of columns in X and Y must be the same. X has shape {X.shape} "
26
+ f"and Y has shape {Y.shape}."
27
+ )
28
+ try:
29
+ import simsimd as simd # type: ignore
30
+
31
+ X = np.array(X, dtype=np.float32)
32
+ Y = np.array(Y, dtype=np.float32)
33
+ Z = 1 - simd.cdist(X, Y, metric="cosine")
34
+ if isinstance(Z, float):
35
+ return np.array([Z])
36
+ return np.array(Z)
37
+ except ImportError:
38
+ logger.debug(
39
+ "Unable to import simsimd, defaulting to NumPy implementation. If you want "
40
+ "to use simsimd please install with `pip install simsimd`."
41
+ )
42
+ X_norm = np.linalg.norm(X, axis=1)
43
+ Y_norm = np.linalg.norm(Y, axis=1)
44
+ # Ignore divide by zero errors run time warnings as those are handled below.
45
+ with np.errstate(divide="ignore", invalid="ignore"):
46
+ similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)
47
+ similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
48
+ return similarity
49
+
50
+
51
+ def maximal_marginal_relevance(
52
+ query_embedding: np.ndarray,
53
+ embedding_list: list,
54
+ lambda_mult: float = 0.5,
55
+ k: int = 4,
56
+ ) -> List[int]:
57
+ """Calculate maximal marginal relevance."""
58
+ if min(k, len(embedding_list)) <= 0:
59
+ return []
60
+ if query_embedding.ndim == 1:
61
+ query_embedding = np.expand_dims(query_embedding, axis=0)
62
+ similarity_to_query = cosine_similarity(query_embedding, embedding_list)[0]
63
+ most_similar = int(np.argmax(similarity_to_query))
64
+ idxs = [most_similar]
65
+ selected = np.array([embedding_list[most_similar]])
66
+ while len(idxs) < min(k, len(embedding_list)):
67
+ best_score = -np.inf
68
+ idx_to_add = -1
69
+ similarity_to_selected = cosine_similarity(embedding_list, selected)
70
+ for i, query_score in enumerate(similarity_to_query):
71
+ if i in idxs:
72
+ continue
73
+ redundant_score = max(similarity_to_selected[i])
74
+ equation_score = (
75
+ lambda_mult * query_score - (1 - lambda_mult) * redundant_score
76
+ )
77
+ if equation_score > best_score:
78
+ best_score = equation_score
79
+ idx_to_add = i
80
+ idxs.append(idx_to_add)
81
+ selected = np.append(selected, [embedding_list[idx_to_add]], axis=0)
82
+ return idxs
@@ -0,0 +1,372 @@
1
+ """Client for persisting chat message history in a Postgres database.
2
+
3
+ This client provides support for both sync and async via psycopg 3.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import logging
9
+ import re
10
+ import uuid
11
+ from typing import List, Optional, Sequence
12
+
13
+ import psycopg
14
+ from langchain_core.chat_history import BaseChatMessageHistory
15
+ from langchain_core.messages import BaseMessage, message_to_dict, messages_from_dict
16
+ from psycopg import sql
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def _create_table_and_index(table_name: str) -> List[sql.Composed]:
22
+ """Make a SQL query to create a table."""
23
+ index_name = f"idx_{table_name}_session_id"
24
+ statements = [
25
+ sql.SQL(
26
+ """
27
+ CREATE TABLE IF NOT EXISTS {table_name} (
28
+ id SERIAL PRIMARY KEY,
29
+ session_id UUID NOT NULL,
30
+ message JSONB NOT NULL,
31
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
32
+ );
33
+ """
34
+ ).format(table_name=sql.Identifier(table_name)),
35
+ sql.SQL(
36
+ """
37
+ CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} (session_id);
38
+ """
39
+ ).format(
40
+ table_name=sql.Identifier(table_name), index_name=sql.Identifier(index_name)
41
+ ),
42
+ ]
43
+ return statements
44
+
45
+
46
+ def _get_messages_query(table_name: str) -> sql.Composed:
47
+ """Make a SQL query to get messages for a given session."""
48
+ return sql.SQL(
49
+ "SELECT message "
50
+ "FROM {table_name} "
51
+ "WHERE session_id = %(session_id)s "
52
+ "ORDER BY id;"
53
+ ).format(table_name=sql.Identifier(table_name))
54
+
55
+
56
+ def _delete_by_session_id_query(table_name: str) -> sql.Composed:
57
+ """Make a SQL query to delete messages for a given session."""
58
+ return sql.SQL(
59
+ "DELETE FROM {table_name} WHERE session_id = %(session_id)s;"
60
+ ).format(table_name=sql.Identifier(table_name))
61
+
62
+
63
+ def _delete_table_query(table_name: str) -> sql.Composed:
64
+ """Make a SQL query to delete a table."""
65
+ return sql.SQL("DROP TABLE IF EXISTS {table_name};").format(
66
+ table_name=sql.Identifier(table_name)
67
+ )
68
+
69
+
70
+ def _insert_message_query(table_name: str) -> sql.Composed:
71
+ """Make a SQL query to insert a message."""
72
+ return sql.SQL(
73
+ "INSERT INTO {table_name} (session_id, message) VALUES (%s, %s)"
74
+ ).format(table_name=sql.Identifier(table_name))
75
+
76
+
77
+ class PostgresChatMessageHistory(BaseChatMessageHistory):
78
+ def __init__(
79
+ self,
80
+ table_name: str,
81
+ session_id: str,
82
+ /,
83
+ *,
84
+ sync_connection: Optional[psycopg.Connection] = None,
85
+ async_connection: Optional[psycopg.AsyncConnection] = None,
86
+ ) -> None:
87
+ """Client for persisting chat message history in a Postgres database,
88
+
89
+ This client provides support for both sync and async via psycopg >=3.
90
+
91
+ The client can create schema in the database and provides methods to
92
+ add messages, get messages, and clear the chat message history.
93
+
94
+ The schema has the following columns:
95
+
96
+ - id: A serial primary key.
97
+ - session_id: The session ID for the chat message history.
98
+ - message: The JSONB message content.
99
+ - created_at: The timestamp of when the message was created.
100
+
101
+ Messages are retrieved for a given session_id and are sorted by
102
+ the id (which should be increasing monotonically), and correspond
103
+ to the order in which the messages were added to the history.
104
+
105
+ The "created_at" column is not returned by the interface, but
106
+ has been added for the schema so the information is available in the database.
107
+
108
+ A session_id can be used to separate different chat histories in the same table,
109
+ the session_id should be provided when initializing the client.
110
+
111
+ This chat history client takes in a psycopg connection object (either
112
+ Connection or AsyncConnection) and uses it to interact with the database.
113
+
114
+ This design allows to reuse the underlying connection object across
115
+ multiple instantiations of this class, making instantiation fast.
116
+
117
+ This chat history client is designed for prototyping applications that
118
+ involve chat and are based on Postgres.
119
+
120
+ As your application grows, you will likely need to extend the schema to
121
+ handle more complex queries. For example, a chat application
122
+ may involve multiple tables like a user table, a table for storing
123
+ chat sessions / conversations, and this table for storing chat messages
124
+ for a given session. The application will require access to additional
125
+ endpoints like deleting messages by user id, listing conversations by
126
+ user id or ordering them based on last message time, etc.
127
+
128
+ Feel free to adapt this implementation to suit your application's needs.
129
+
130
+ Args:
131
+ session_id: The session ID to use for the chat message history
132
+ table_name: The name of the database table to use
133
+ sync_connection: An existing psycopg connection instance
134
+ async_connection: An existing psycopg async connection instance
135
+
136
+ Usage:
137
+ - Use the create_tables or acreate_tables method to set up the table
138
+ schema in the database.
139
+ - Initialize the class with the appropriate session ID, table name,
140
+ and database connection.
141
+ - Add messages to the database using add_messages or aadd_messages.
142
+ - Retrieve messages with get_messages or aget_messages.
143
+ - Clear the session history with clear or aclear when needed.
144
+
145
+ Note:
146
+ - At least one of sync_connection or async_connection must be provided.
147
+
148
+ Examples:
149
+
150
+ .. code-block:: python
151
+
152
+ import uuid
153
+
154
+ from langchain_core.messages import SystemMessage, AIMessage, HumanMessage
155
+ from langchain_postgres import PostgresChatMessageHistory
156
+ import psycopg
157
+
158
+ # Establish a synchronous connection to the database
159
+ # (or use psycopg.AsyncConnection for async)
160
+ sync_connection = psycopg2.connect(conn_info)
161
+
162
+ # Create the table schema (only needs to be done once)
163
+ table_name = "chat_history"
164
+ PostgresChatMessageHistory.create_tables(sync_connection, table_name)
165
+
166
+ session_id = str(uuid.uuid4())
167
+
168
+ # Initialize the chat history manager
169
+ chat_history = PostgresChatMessageHistory(
170
+ table_name,
171
+ session_id,
172
+ sync_connection=sync_connection
173
+ )
174
+
175
+ # Add messages to the chat history
176
+ chat_history.add_messages([
177
+ SystemMessage(content="Meow"),
178
+ AIMessage(content="woof"),
179
+ HumanMessage(content="bark"),
180
+ ])
181
+
182
+ print(chat_history.messages)
183
+ """
184
+ if not sync_connection and not async_connection:
185
+ raise ValueError("Must provide sync_connection or async_connection")
186
+
187
+ self._connection = sync_connection
188
+ self._aconnection = async_connection
189
+
190
+ # Validate that session id is a UUID
191
+ try:
192
+ uuid.UUID(session_id)
193
+ except ValueError:
194
+ raise ValueError(
195
+ f"Invalid session id. Session id must be a valid UUID. Got {session_id}"
196
+ )
197
+
198
+ self._session_id = session_id
199
+
200
+ if not re.match(r"^\w+$", table_name):
201
+ raise ValueError(
202
+ "Invalid table name. Table name must contain only alphanumeric "
203
+ "characters and underscores."
204
+ )
205
+ self._table_name = table_name
206
+
207
+ @staticmethod
208
+ def create_tables(
209
+ connection: psycopg.Connection,
210
+ table_name: str,
211
+ /,
212
+ ) -> None:
213
+ """Create the table schema in the database and create relevant indexes."""
214
+ queries = _create_table_and_index(table_name)
215
+ logger.info("Creating schema for table %s", table_name)
216
+ with connection.cursor() as cursor:
217
+ for query in queries:
218
+ cursor.execute(query)
219
+ connection.commit()
220
+
221
+ @staticmethod
222
+ async def acreate_tables(
223
+ connection: psycopg.AsyncConnection, table_name: str, /
224
+ ) -> None:
225
+ """Create the table schema in the database and create relevant indexes."""
226
+ queries = _create_table_and_index(table_name)
227
+ logger.info("Creating schema for table %s", table_name)
228
+ async with connection.cursor() as cur:
229
+ for query in queries:
230
+ await cur.execute(query)
231
+ await connection.commit()
232
+
233
+ @staticmethod
234
+ def drop_table(connection: psycopg.Connection, table_name: str, /) -> None:
235
+ """Delete the table schema in the database.
236
+
237
+ WARNING:
238
+ This will delete the given table from the database including
239
+ all the database in the table and the schema of the table.
240
+
241
+ Args:
242
+ connection: The database connection.
243
+ table_name: The name of the table to create.
244
+ """
245
+
246
+ query = _delete_table_query(table_name)
247
+ logger.info("Dropping table %s", table_name)
248
+ with connection.cursor() as cursor:
249
+ cursor.execute(query)
250
+ connection.commit()
251
+
252
+ @staticmethod
253
+ async def adrop_table(
254
+ connection: psycopg.AsyncConnection, table_name: str, /
255
+ ) -> None:
256
+ """Delete the table schema in the database.
257
+
258
+ WARNING:
259
+ This will delete the given table from the database including
260
+ all the database in the table and the schema of the table.
261
+
262
+ Args:
263
+ connection: Async database connection.
264
+ table_name: The name of the table to create.
265
+ """
266
+ query = _delete_table_query(table_name)
267
+ logger.info("Dropping table %s", table_name)
268
+
269
+ async with connection.cursor() as acur:
270
+ await acur.execute(query)
271
+ await connection.commit()
272
+
273
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
274
+ """Add messages to the chat message history."""
275
+ if self._connection is None:
276
+ raise ValueError(
277
+ "Please initialize the PostgresChatMessageHistory "
278
+ "with a sync connection or use the aadd_messages method instead."
279
+ )
280
+
281
+ values = [
282
+ (self._session_id, json.dumps(message_to_dict(message)))
283
+ for message in messages
284
+ ]
285
+
286
+ query = _insert_message_query(self._table_name)
287
+
288
+ with self._connection.cursor() as cursor:
289
+ cursor.executemany(query, values)
290
+ self._connection.commit()
291
+
292
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
293
+ """Add messages to the chat message history."""
294
+ if self._aconnection is None:
295
+ raise ValueError(
296
+ "Please initialize the PostgresChatMessageHistory "
297
+ "with an async connection or use the sync add_messages method instead."
298
+ )
299
+
300
+ values = [
301
+ (self._session_id, json.dumps(message_to_dict(message)))
302
+ for message in messages
303
+ ]
304
+
305
+ query = _insert_message_query(self._table_name)
306
+ async with self._aconnection.cursor() as cursor:
307
+ await cursor.executemany(query, values)
308
+ await self._aconnection.commit()
309
+
310
+ def get_messages(self) -> List[BaseMessage]:
311
+ """Retrieve messages from the chat message history."""
312
+ if self._connection is None:
313
+ raise ValueError(
314
+ "Please initialize the PostgresChatMessageHistory "
315
+ "with a sync connection or use the async aget_messages method instead."
316
+ )
317
+
318
+ query = _get_messages_query(self._table_name)
319
+
320
+ with self._connection.cursor() as cursor:
321
+ cursor.execute(query, {"session_id": self._session_id})
322
+ items = [record[0] for record in cursor.fetchall()]
323
+
324
+ messages = messages_from_dict(items)
325
+ return messages
326
+
327
+ async def aget_messages(self) -> List[BaseMessage]:
328
+ """Retrieve messages from the chat message history."""
329
+ if self._aconnection is None:
330
+ raise ValueError(
331
+ "Please initialize the PostgresChatMessageHistory "
332
+ "with an async connection or use the sync get_messages method instead."
333
+ )
334
+
335
+ query = _get_messages_query(self._table_name)
336
+ async with self._aconnection.cursor() as cursor:
337
+ await cursor.execute(query, {"session_id": self._session_id})
338
+ items = [record[0] for record in await cursor.fetchall()]
339
+
340
+ messages = messages_from_dict(items)
341
+ return messages
342
+
343
+ @property # type: ignore[override]
344
+ def messages(self) -> List[BaseMessage]:
345
+ """The abstraction required a property."""
346
+ return self.get_messages()
347
+
348
+ def clear(self) -> None:
349
+ """Clear the chat message history for the GIVEN session."""
350
+ if self._connection is None:
351
+ raise ValueError(
352
+ "Please initialize the PostgresChatMessageHistory "
353
+ "with a sync connection or use the async clear method instead."
354
+ )
355
+
356
+ query = _delete_by_session_id_query(self._table_name)
357
+ with self._connection.cursor() as cursor:
358
+ cursor.execute(query, {"session_id": self._session_id})
359
+ self._connection.commit()
360
+
361
+ async def aclear(self) -> None:
362
+ """Clear the chat message history for the GIVEN session."""
363
+ if self._aconnection is None:
364
+ raise ValueError(
365
+ "Please initialize the PostgresChatMessageHistory "
366
+ "with an async connection or use the sync clear method instead."
367
+ )
368
+
369
+ query = _delete_by_session_id_query(self._table_name)
370
+ async with self._aconnection.cursor() as cursor:
371
+ await cursor.execute(query, {"session_id": self._session_id})
372
+ await self._aconnection.commit()