-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathvectorstores.py
2373 lines (2083 loc) · 87.4 KB
/
vectorstores.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=too-many-lines
from __future__ import annotations
import contextlib
import enum
import logging
import uuid
from typing import (
Any,
AsyncGenerator,
Callable,
Dict,
Generator,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from typing import (
cast as typing_cast,
)
import numpy as np
import sqlalchemy
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.indexing import UpsertResponse
from langchain_core.utils import get_from_dict_or_env
from langchain_core.vectorstores import VectorStore
from sqlalchemy import SQLColumnExpression, cast, create_engine, delete, func, select, text
from sqlalchemy.dialects.postgresql import JSON, JSONB, JSONPATH, UUID, insert
from sqlalchemy.engine import Connection, Engine
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import (
Session,
declarative_base,
relationship,
scoped_session,
sessionmaker,
)
from langchain_postgres._utils import maximal_marginal_relevance
class DistanceStrategy(str, enum.Enum):
"""Enumerator of the Distance strategies."""
EUCLIDEAN = "l2"
COSINE = "cosine"
MAX_INNER_PRODUCT = "inner"
DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE
Base = declarative_base() # type: Any
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
_classes: Any = None
COMPARISONS_TO_NATIVE = {
"$eq": "==",
"$ne": "!=",
"$lt": "<",
"$lte": "<=",
"$gt": ">",
"$gte": ">=",
}
SPECIAL_CASED_OPERATORS = {
"$in",
"$nin",
"$between",
"$exists",
}
TEXT_OPERATORS = {
"$like",
"$ilike",
}
LOGICAL_OPERATORS = {"$and", "$or", "$not"}
SUPPORTED_OPERATORS = (
set(COMPARISONS_TO_NATIVE)
.union(TEXT_OPERATORS)
.union(LOGICAL_OPERATORS)
.union(SPECIAL_CASED_OPERATORS)
)
class IndexManager:
"""Manages the creation, listing, and retrieval of indexes for the embedding column in a PostgreSQL database.
This class provides both synchronous and asynchronous methods to interact with the database, allowing for
the creation of different types of indexes (e.g., HNSW, IVFFlat) with various distance functions (e.g., l2, cosine).
Args:
connection (Union[str, Engine, AsyncEngine]): The database connection string or engine instance.
async_mode (bool): Flag to indicate if asynchronous operations should be used. Defaults to False.
"""
def __init__(self, connection: Union[str, Engine, AsyncEngine], async_mode: bool = False):
self.async_mode = async_mode
if isinstance(connection, str):
if async_mode:
self._engine = create_async_engine(connection)
else:
self._engine = create_engine(connection)
elif isinstance(connection, (Engine, AsyncEngine)):
self._engine = connection
else:
raise ValueError("Invalid connection type")
def list_indexes(self) -> List[Dict[str, Any]]:
"""List all indexes."""
with self._engine.connect() as conn:
result = conn.execute(text("SELECT * FROM pg_indexes WHERE tablename = 'langchain_pg_embedding'"))
indexes = [dict(row) for row in result]
return indexes
async def alist_indexes(self) -> List[Dict[str, Any]]:
"""Asynchronously list all indexes."""
async with self._engine.connect() as conn:
result = await conn.execute(text("SELECT * FROM pg_indexes WHERE tablename = 'langchain_pg_embedding'"))
indexes = [dict(row) for row in result]
return indexes
def create_index(self, index_type: str, distance_strategy: DistanceStrategy, **kwargs: Any) -> str:
"""Create an index (HNSW or IVFFlat) on the embedding column.
Args:
index_type: The type of index to create ('hnsw' or 'ivfflat').
distance_strategy: The distance strategy to use (e.g., DistanceStrategy.L2, DistanceStrategy.COSINE).
kwargs: Additional parameters for the index creation (e.g., m, ef_construction, lists).
Returns:
The name of the created index.
"""
index_ops = f"vector_{distance_strategy.value}_ops"
index_name = f"{index_type}_{distance_strategy.value}_index"
index_params = ", ".join(f"{key} = {value}" for key, value in kwargs.items())
with self._engine.connect() as conn:
conn.execute(
text(
f"""
CREATE INDEX {index_name} ON langchain_pg_embedding USING {index_type} (embedding {index_ops})
WITH ({index_params});
"""
)
)
return index_name
async def acreate_index(self, index_type: str, distance_strategy: DistanceStrategy, **kwargs: Any) -> str:
"""Asynchronously create an index (HNSW or IVFFlat) on the embedding column.
Args:
index_type: The type of index to create ('hnsw' or 'ivfflat').
distance_strategy: The distance strategy to use (e.g., DistanceStrategy.L2, DistanceStrategy.COSINE).
kwargs: Additional parameters for the index creation (e.g., m, ef_construction, lists).
Returns:
The name of the created index.
"""
index_ops = f"vector_{distance_strategy.value}_ops"
index_name = f"{index_type}_{distance_strategy.value}_index"
index_params = ", ".join(f"{key} = {value}" for key, value in kwargs.items())
async with self._engine.connect() as conn:
await conn.execute(
text(
f"""
CREATE INDEX {index_name} ON langchain_pg_embedding USING {index_type} (embedding {index_ops})
WITH ({index_params});
"""
)
)
return index_name
def get_index(self, index_name: str, embeddings: Embeddings, collection_name: str) -> Optional[PGVector]:
"""Get details of a specific index and return a PGVector instance."""
with self._engine.connect() as conn:
result = conn.execute(text(f"SELECT * FROM pg_indexes WHERE indexname = :index_name"), {"index_name": index_name})
index = result.fetchone()
if index:
distance_strategy = DistanceStrategy(index['indexdef'].split(' ')[-1].split('_')[1])
return PGVector(
embeddings=embeddings,
connection=self._engine,
collection_name=collection_name,
distance_strategy=distance_strategy,
async_mode=self.async_mode
)
return None
async def aget_index(self, index_name: str, embeddings: Embeddings, collection_name: str) -> Optional[PGVector]:
"""Asynchronously get details of a specific index and return a PGVector instance."""
async with self._engine.connect() as conn:
result = await conn.execute(text(f"SELECT * FROM pg_indexes WHERE indexname = :index_name"), {"index_name": index_name})
index = result.fetchone()
if index:
distance_strategy = DistanceStrategy(index['indexdef'].split(' ')[-1].split('_')[1])
return PGVector(
embeddings=embeddings,
connection=self._engine,
collection_name=collection_name,
distance_strategy=distance_strategy,
async_mode=self.async_mode
)
return None
def _get_embedding_collection_store(vector_dimension: Optional[int] = None) -> Any:
global _classes
if _classes is not None:
return _classes
from pgvector.sqlalchemy import Vector # type: ignore
class CollectionStore(Base):
"""Collection store."""
__tablename__ = "langchain_pg_collection"
uuid = sqlalchemy.Column(
UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
)
name = sqlalchemy.Column(sqlalchemy.String, nullable=False, unique=True)
cmetadata = sqlalchemy.Column(JSON)
embeddings = relationship(
"EmbeddingStore",
back_populates="collection",
passive_deletes=True,
)
@classmethod
def get_by_name(
cls, session: Session, name: str
) -> Optional["CollectionStore"]:
return (
session.query(cls)
.filter(typing_cast(sqlalchemy.Column, cls.name) == name)
.first()
)
@classmethod
async def aget_by_name(
cls, session: AsyncSession, name: str
) -> Optional["CollectionStore"]:
return (
(
await session.execute(
select(CollectionStore).where(
typing_cast(sqlalchemy.Column, cls.name) == name
)
)
)
.scalars()
.first()
)
@classmethod
def get_or_create(
cls,
session: Session,
name: str,
cmetadata: Optional[dict] = None,
) -> Tuple["CollectionStore", bool]:
"""Get or create a collection.
Returns:
Where the bool is True if the collection was created.
""" # noqa: E501
created = False
collection = cls.get_by_name(session, name)
if collection:
return collection, created
collection = cls(name=name, cmetadata=cmetadata)
session.add(collection)
session.commit()
created = True
return collection, created
@classmethod
async def aget_or_create(
cls,
session: AsyncSession,
name: str,
cmetadata: Optional[dict] = None,
) -> Tuple["CollectionStore", bool]:
"""
Get or create a collection.
Returns [Collection, bool] where the bool is True if the collection was created.
""" # noqa: E501
created = False
collection = await cls.aget_by_name(session, name)
if collection:
return collection, created
collection = cls(name=name, cmetadata=cmetadata)
session.add(collection)
await session.commit()
created = True
return collection, created
class EmbeddingStore(Base):
"""Embedding store."""
__tablename__ = "langchain_pg_embedding"
id = sqlalchemy.Column(
sqlalchemy.String, nullable=True, primary_key=True, index=True, unique=True
)
collection_id = sqlalchemy.Column(
UUID(as_uuid=True),
sqlalchemy.ForeignKey(
f"{CollectionStore.__tablename__}.uuid",
ondelete="CASCADE",
),
)
collection = relationship(CollectionStore, back_populates="embeddings")
embedding: Vector = sqlalchemy.Column(Vector(vector_dimension))
document = sqlalchemy.Column(sqlalchemy.String, nullable=True)
cmetadata = sqlalchemy.Column(JSONB, nullable=True)
__table_args__ = (
sqlalchemy.Index(
"ix_cmetadata_gin",
"cmetadata",
postgresql_using="gin",
postgresql_ops={"cmetadata": "jsonb_path_ops"},
),
)
_classes = (EmbeddingStore, CollectionStore)
return _classes
def _results_to_docs(docs_and_scores: Any) -> List[Document]:
"""Return docs from docs and scores."""
return [doc for doc, _ in docs_and_scores]
def _create_vector_extension(conn: Connection) -> None:
statement = sqlalchemy.text(
"SELECT pg_advisory_xact_lock(1573678846307946496);"
"CREATE EXTENSION IF NOT EXISTS vector;"
)
conn.execute(statement)
conn.commit()
DBConnection = Union[sqlalchemy.engine.Engine, str]
class PGVector(VectorStore):
"""Vectorstore implementation using Postgres as the backend.
Currently, there is no mechanism for supporting data migration.
So breaking changes in the vectorstore schema will require the user to recreate
the tables and re-add the documents.
If this is a concern, please use a different vectorstore. If
not, this implementation should be fine for your use case.
To use this vectorstore you need to have the `vector` extension installed.
The `vector` extension is a Postgres extension that provides vector
similarity search capabilities.
```sh
docker run --name pgvector-container -e POSTGRES_PASSWORD=...
-d pgvector/pgvector:pg16
```
Example:
.. code-block:: python
from langchain_postgres.vectorstores import PGVector
from langchain_openai.embeddings import OpenAIEmbeddings
connection_string = "postgresql+psycopg://..."
collection_name = "state_of_the_union_test"
embeddings = OpenAIEmbeddings()
vectorstore = PGVector.from_documents(
embedding=embeddings,
documents=docs,
connection=connection_string,
collection_name=collection_name,
use_jsonb=True,
async_mode=False,
)
This code has been ported over from langchain_community with minimal changes
to allow users to easily transition from langchain_community to langchain_postgres.
Some changes had to be made to address issues with the community implementation:
* langchain_postgres now works with psycopg3. Please update your
connection strings from `postgresql+psycopg2://...` to
`postgresql+psycopg://langchain:langchain@...`
(yes, the driver name is `psycopg` not `psycopg3`)
* The schema of the embedding store and collection have been changed to make
add_documents work correctly with user specified ids, specifically
when overwriting existing documents.
You will need to recreate the tables if you are using an existing database.
* A Connection object has to be provided explicitly. Connections will not be
picked up automatically based on env variables.
* langchain_postgres now accept async connections. If you want to use the async
version, you need to set `async_mode=True` when initializing the store or
use an async engine.
Supported filter operators:
* $eq: Equality operator
* $ne: Not equal operator
* $lt: Less than operator
* $lte: Less than or equal operator
* $gt: Greater than operator
* $gte: Greater than or equal operator
* $in: In operator
* $nin: Not in operator
* $between: Between operator
* $exists: Exists operator
* $like: Like operator
* $ilike: Case insensitive like operator
* $and: Logical AND operator
* $or: Logical OR operator
* $not: Logical NOT operator
Example:
.. code-block:: python
vectorstore.similarity_search('kitty', k=10, filter={
'id': {'$in': [1, 5, 2, 9]}
})
#%% md
If you provide a dict with multiple fields, but no operators,
the top level will be interpreted as a logical **AND** filter
vectorstore.similarity_search('ducks', k=10, filter={
'id': {'$in': [1, 5, 2, 9]},
'location': {'$in': ["pond", "market"]}
})
"""
def __init__(
self,
embeddings: Embeddings,
*,
connection: Union[None, DBConnection, Engine, AsyncEngine, str] = None,
embedding_length: Optional[int] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
collection_metadata: Optional[dict] = None,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
pre_delete_collection: bool = False,
logger: Optional[logging.Logger] = None,
relevance_score_fn: Optional[Callable[[float], float]] = None,
engine_args: Optional[dict[str, Any]] = None,
use_jsonb: bool = True,
create_extension: bool = True,
async_mode: bool = False,
index_type: Optional[str] = None,
index_params: Optional[Dict[str, Any]] = None,
) -> None:
"""Initialize the PGVector store.
For an async version, use `PGVector.acreate()` instead.
Args:
connection: Postgres connection string or (async)engine.
embeddings: Any embedding function implementing
`langchain.embeddings.base.Embeddings` interface.
embedding_length: The length of the embedding vector. (default: None)
NOTE: This is not mandatory. Defining it will prevent vectors of
any other size to be added to the embeddings table but, without it,
the embeddings can't be indexed.
collection_name: The name of the collection to use. (default: langchain)
NOTE: This is not the name of the table, but the name of the collection.
The tables will be created when initializing the store (if not exists)
So, make sure the user has the right permissions to create tables.
distance_strategy: The distance strategy to use. (default: COSINE)
pre_delete_collection: If True, will delete the collection if it exists.
(default: False). Useful for testing.
engine_args: SQLAlchemy's create engine arguments.
use_jsonb: Use JSONB instead of JSON for metadata. (default: True)
Strongly discouraged from using JSON as it's not as efficient
for querying.
It's provided here for backwards compatibility with older versions,
and will be removed in the future.
create_extension: If True, will create the vector extension if it
doesn't exist. disabling creation is useful when using ReadOnly
Databases.
index_type: The type of index to create. (default: None)
index_params: The parameters for the index. (default: None)
"""
self.async_mode = async_mode
self.embedding_function = embeddings
self._embedding_length = embedding_length
self.collection_name = collection_name
self.collection_metadata = collection_metadata
self._distance_strategy = distance_strategy
self.pre_delete_collection = pre_delete_collection
self.logger = logger or logging.getLogger(__name__)
self.override_relevance_score_fn = relevance_score_fn
self._engine: Optional[Engine] = None
self._async_engine: Optional[AsyncEngine] = None
self._async_init = False
self.index_type = index_type
self.index_params = index_params or {}
if isinstance(connection, str):
if async_mode:
self._async_engine = create_async_engine(
connection, **(engine_args or {})
)
else:
self._engine = create_engine(url=connection, **(engine_args or {}))
elif isinstance(connection, Engine):
self.async_mode = False
self._engine = connection
elif isinstance(connection, AsyncEngine):
self.async_mode = True
self._async_engine = connection
else:
raise ValueError(
"connection should be a connection string or an instance of "
"sqlalchemy.engine.Engine or sqlalchemy.ext.asyncio.engine.AsyncEngine"
)
self.session_maker: Union[scoped_session, async_sessionmaker]
if self.async_mode:
self.session_maker = async_sessionmaker(bind=self._async_engine)
else:
self.session_maker = scoped_session(sessionmaker(bind=self._engine))
self.use_jsonb = use_jsonb
self.create_extension = create_extension
if not use_jsonb:
# Replace with a deprecation warning.
raise NotImplementedError("use_jsonb=False is no longer supported.")
self.index_manager = IndexManager(connection=self._engine, async_mode=self.async_mode)
if not self.async_mode:
self.__post_init__()
def __post_init__(
self,
) -> None:
"""Initialize the store."""
if self.create_extension:
self.create_vector_extension()
EmbeddingStore, CollectionStore = _get_embedding_collection_store(
self._embedding_length
)
self.CollectionStore = CollectionStore
self.EmbeddingStore = EmbeddingStore
self.create_tables_if_not_exists()
self.create_collection()
if self.index_type:
self.index_manager.create_index(self.index_type, self._distance_strategy, **self.index_params)
async def __apost_init__(
self,
) -> None:
"""Async initialize the store (use lazy approach)."""
if self._async_init: # Warning: possible race condition
return
self._async_init = True
EmbeddingStore, CollectionStore = _get_embedding_collection_store(
self._embedding_length
)
self.CollectionStore = CollectionStore
self.EmbeddingStore = EmbeddingStore
if self.create_extension:
await self.acreate_vector_extension()
await self.acreate_tables_if_not_exists()
await self.acreate_collection()
if self.index_type:
await self.index_manager.acreate_index(self.index_type, self._distance_strategy, **self.index_params)
@property
def embeddings(self) -> Embeddings:
return self.embedding_function
def create_vector_extension(self) -> None:
assert self._engine, "engine not found"
try:
with self._engine.connect() as conn:
_create_vector_extension(conn)
except Exception as e:
raise Exception(f"Failed to create vector extension: {e}") from e
async def acreate_vector_extension(self) -> None:
assert self._async_engine, "_async_engine not found"
async with self._async_engine.begin() as conn:
await conn.run_sync(_create_vector_extension)
def create_tables_if_not_exists(self) -> None:
with self._make_sync_session() as session:
Base.metadata.create_all(session.get_bind())
session.commit()
async def acreate_tables_if_not_exists(self) -> None:
assert self._async_engine, "This method must be called with async_mode"
async with self._async_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
def drop_tables(self) -> None:
with self._make_sync_session() as session:
Base.metadata.drop_all(session.get_bind())
session.commit()
async def adrop_tables(self) -> None:
assert self._async_engine, "This method must be called with async_mode"
await self.__apost_init__() # Lazy async init
async with self._async_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
def create_collection(self) -> None:
if self.pre_delete_collection:
self.delete_collection()
with self._make_sync_session() as session:
self.CollectionStore.get_or_create(
session, self.collection_name, cmetadata=self.collection_metadata
)
session.commit()
async def acreate_collection(self) -> None:
await self.__apost_init__() # Lazy async init
async with self._make_async_session() as session:
if self.pre_delete_collection:
await self._adelete_collection(session)
await self.CollectionStore.aget_or_create(
session, self.collection_name, cmetadata=self.collection_metadata
)
await session.commit()
def _delete_collection(self, session: Session) -> None:
collection = self.get_collection(session)
if not collection:
self.logger.warning("Collection not found")
return
session.delete(collection)
async def _adelete_collection(self, session: AsyncSession) -> None:
collection = await self.aget_collection(session)
if not collection:
self.logger.warning("Collection not found")
return
await session.delete(collection)
def delete_collection(self) -> None:
with self._make_sync_session() as session:
collection = self.get_collection(session)
if not collection:
self.logger.warning("Collection not found")
return
session.delete(collection)
session.commit()
async def adelete_collection(self) -> None:
await self.__apost_init__() # Lazy async init
async with self._make_async_session() as session:
collection = await self.aget_collection(session)
if not collection:
self.logger.warning("Collection not found")
return
await session.delete(collection)
await session.commit()
def delete(
self,
ids: Optional[List[str]] = None,
collection_only: bool = False,
**kwargs: Any,
) -> None:
"""Delete vectors by ids or uuids.
Args:
ids: List of ids to delete.
collection_only: Only delete ids in the collection.
"""
with self._make_sync_session() as session:
if ids is not None:
self.logger.debug(
"Trying to delete vectors by ids (represented by the model "
"using the custom ids field)"
)
stmt = delete(self.EmbeddingStore)
if collection_only:
collection = self.get_collection(session)
if not collection:
self.logger.warning("Collection not found")
return
stmt = stmt.where(
self.EmbeddingStore.collection_id == collection.uuid
)
stmt = stmt.where(self.EmbeddingStore.id.in_(ids))
session.execute(stmt)
session.commit()
async def adelete(
self,
ids: Optional[List[str]] = None,
collection_only: bool = False,
**kwargs: Any,
) -> None:
"""Async delete vectors by ids or uuids.
Args:
ids: List of ids to delete.
collection_only: Only delete ids in the collection.
"""
await self.__apost_init__() # Lazy async init
async with self._make_async_session() as session:
if ids is not None:
self.logger.debug(
"Trying to delete vectors by ids (represented by the model "
"using the custom ids field)"
)
stmt = delete(self.EmbeddingStore)
if collection_only:
collection = await self.aget_collection(session)
if not collection:
self.logger.warning("Collection not found")
return
stmt = stmt.where(
self.EmbeddingStore.collection_id == collection.uuid
)
stmt = stmt.where(self.EmbeddingStore.id.in_(ids))
await session.execute(stmt)
await session.commit()
def get_collection(self, session: Session) -> Any:
assert not self._async_engine, "This method must be called without async_mode"
return self.CollectionStore.get_by_name(session, self.collection_name)
async def aget_collection(self, session: AsyncSession) -> Any:
assert self._async_engine, "This method must be called with async_mode"
await self.__apost_init__() # Lazy async init
return await self.CollectionStore.aget_by_name(session, self.collection_name)
@classmethod
def __from(
cls,
texts: List[str],
embeddings: List[List[float]],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
connection: Optional[str] = None,
pre_delete_collection: bool = False,
*,
use_jsonb: bool = True,
**kwargs: Any,
) -> PGVector:
if ids is None:
ids = [str(uuid.uuid4()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in texts]
store = cls(
connection=connection,
collection_name=collection_name,
embeddings=embedding,
distance_strategy=distance_strategy,
pre_delete_collection=pre_delete_collection,
use_jsonb=use_jsonb,
**kwargs,
)
store.add_embeddings(
texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs
)
return store
@classmethod
async def __afrom(
cls,
texts: List[str],
embeddings: List[List[float]],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY,
connection: Optional[str] = None,
pre_delete_collection: bool = False,
*,
use_jsonb: bool = True,
**kwargs: Any,
) -> PGVector:
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in texts]
store = cls(
connection=connection,
collection_name=collection_name,
embeddings=embedding,
distance_strategy=distance_strategy,
pre_delete_collection=pre_delete_collection,
use_jsonb=use_jsonb,
async_mode=True,
**kwargs,
)
await store.aadd_embeddings(
texts=texts, embeddings=embeddings, metadatas=metadatas, ids=ids, **kwargs
)
return store
def add_embeddings(
self,
texts: Sequence[str],
embeddings: List[List[float]],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Add embeddings to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
embeddings: List of list of embedding vectors.
metadatas: List of metadatas associated with the texts.
ids: Optional list of ids for the documents.
If not provided, will generate a new id for each document.
kwargs: vectorstore specific parameters
"""
assert not self._async_engine, "This method must be called with sync_mode"
if ids is None:
ids = [str(uuid.uuid4()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in texts]
with self._make_sync_session() as session: # type: ignore[arg-type]
collection = self.get_collection(session)
if not collection:
raise ValueError("Collection not found")
data = [
{
"id": id,
"collection_id": collection.uuid,
"embedding": embedding,
"document": text,
"cmetadata": metadata or {},
}
for text, metadata, embedding, id in zip(
texts, metadatas, embeddings, ids
)
]
stmt = insert(self.EmbeddingStore).values(data)
on_conflict_stmt = stmt.on_conflict_do_update(
index_elements=["id"],
# Conflict detection based on these columns
set_={
"embedding": stmt.excluded.embedding,
"document": stmt.excluded.document,
"cmetadata": stmt.excluded.cmetadata,
},
)
session.execute(on_conflict_stmt)
session.commit()
return ids
async def aadd_embeddings(
self,
texts: Sequence[str],
embeddings: List[List[float]],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
"""Async add embeddings to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
embeddings: List of list of embedding vectors.
metadatas: List of metadatas associated with the texts.
ids: Optional list of ids for the texts.
If not provided, will generate a new id for each text.
kwargs: vectorstore specific parameters
"""
await self.__apost_init__() # Lazy async init
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
if not metadatas:
metadatas = [{} for _ in texts]
async with self._make_async_session() as session: # type: ignore[arg-type]
collection = await self.aget_collection(session)
if not collection:
raise ValueError("Collection not found")
data = [
{
"id": id,
"collection_id": collection.uuid,
"embedding": embedding,
"document": text,
"cmetadata": metadata or {},
}
for text, metadata, embedding, id in zip(
texts, metadatas, embeddings, ids
)
]
stmt = insert(self.EmbeddingStore).values(data)
on_conflict_stmt = stmt.on_conflict_do_update(
index_elements=["id"],
# Conflict detection based on these columns
set_={
"embedding": stmt.excluded.embedding,
"document": stmt.excluded.document,
"cmetadata": stmt.excluded.cmetadata,
},
)
await session.execute(on_conflict_stmt)
await session.commit()
return ids
def similarity_search(
self,
query: str,
k: int = 4,
filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Run similarity search with PGVector with distance.
Args:
query (str): Query text to search for.
k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to the query.
"""
assert not self._async_engine, "This method must be called without async_mode"
embedding = self.embedding_function.embed_query(text=query)
return self.similarity_search_by_vector(
embedding=embedding,
k=k,
filter=filter,
)
async def asimilarity_search(
self,
query: str,
k: int = 4,
filter: Optional[dict] = None,
**kwargs: Any,
) -> List[Document]:
"""Run similarity search with PGVector with distance.
Args:
query (str): Query text to search for.
k (int): Number of results to return. Defaults to 4.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
Returns:
List of Documents most similar to the query.