Repository navigation
Expand file tree
/
Copy pathmongodb.py
More file actions
635 lines (569 loc) · 25 KB
/
Copy pathmongodb.py
File metadata and controls
635 lines (569 loc) · 25 KB
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
# Copyright (c) Microsoft. All rights reserved.
import ast
import logging
import sys
from collections.abc import MutableSequence, Sequence
from importlib import metadata
from typing import Any, ClassVar, Final, Generic, TypeVar
from pydantic import SecretStr, ValidationError
from pymongo import AsyncMongoClient, ReplaceOne
from pymongo.asynchronous.collection import AsyncCollection
from pymongo.asynchronous.database import AsyncDatabase
from pymongo.driver_info import DriverInfo
from pymongo.operations import SearchIndexModel
from semantic_kernel.connectors.ai.embedding_generator_base import EmbeddingGeneratorBase
from semantic_kernel.data.vector import (
DistanceFunction,
GetFilteredRecordOptions,
KernelSearchResults,
SearchType,
TModel,
VectorSearch,
VectorSearchOptions,
VectorSearchResult,
VectorStore,
VectorStoreCollection,
VectorStoreCollectionDefinition,
VectorStoreField,
_get_collection_name_from_model,
)
from semantic_kernel.exceptions import (
VectorSearchExecutionException,
VectorStoreInitializationException,
VectorStoreOperationException,
)
from semantic_kernel.exceptions.vector_store_exceptions import VectorStoreModelException
from semantic_kernel.kernel_pydantic import KernelBaseSettings
from semantic_kernel.utils.feature_stage_decorator import release_candidate
from semantic_kernel.utils.telemetry.user_agent import SEMANTIC_KERNEL_USER_AGENT
if sys.version_info >= (3, 11):
from typing import Self # pragma: no cover
else:
from typing_extensions import Self # pragma: no cover
if sys.version_info >= (3, 12):
from typing import override # pragma: no cover
else:
from typing_extensions import override
TKey = TypeVar("TKey", bound=str)
DEFAULT_DB_NAME: Final[str] = "default"
DEFAULT_SEARCH_INDEX_NAME: Final[str] = "default"
MONGODB_ID_FIELD: Final[str] = "_id"
MONGODB_SCORE_FIELD: Final[str] = "score"
NUM_CANDIDATES_SCALAR: Final[int] = 10
DISTANCE_FUNCTION_MAP: Final[dict[DistanceFunction, str]] = {
DistanceFunction.EUCLIDEAN_DISTANCE: "euclidean",
DistanceFunction.COSINE_SIMILARITY: "cosine",
DistanceFunction.DOT_PROD: "dotProduct",
DistanceFunction.DEFAULT: "euclidean",
}
DRIVER_METADATA = DriverInfo(SEMANTIC_KERNEL_USER_AGENT, metadata.version("semantic-kernel"))
logger = logging.getLogger(__name__)
@release_candidate
class MongoDBAtlasSettings(KernelBaseSettings):
"""MongoDB Atlas model settings.
Args:
- connection_string: str - MongoDB Atlas connection string
(Env var MONGODB_ATLAS_CONNECTION_STRING)
- database_name: str - MongoDB Atlas database name, defaults to 'default'
(Env var MONGODB_ATLAS_DATABASE_NAME)
- index_name: str - MongoDB Atlas search index name, defaults to 'default'
(Env var MONGODB_ATLAS_INDEX_NAME)
"""
env_prefix: ClassVar[str] = "MONGODB_ATLAS_"
connection_string: SecretStr
database_name: str = DEFAULT_DB_NAME
index_name: str = DEFAULT_SEARCH_INDEX_NAME
def _create_vector_field(field: VectorStoreField) -> dict:
"""Create a vector field.
Args:
field (VectorStoreRecordVectorField): The vector field.
Returns:
dict: The vector field.
"""
if field.distance_function not in DISTANCE_FUNCTION_MAP:
raise VectorStoreInitializationException(
f"Distance function {field.distance_function} is not supported. "
f"Supported distance functions are: {list(DISTANCE_FUNCTION_MAP.keys())}"
)
return {
"type": "vector",
"numDimensions": field.dimensions,
"path": field.storage_name or field.name,
"similarity": DISTANCE_FUNCTION_MAP[field.distance_function],
}
def _create_index_definitions(
record_definition: VectorStoreCollectionDefinition, index_name: str
) -> list[SearchIndexModel]:
"""Create the index definitions."""
indexes = []
if record_definition.vector_fields:
vector_fields = [_create_vector_field(field) for field in record_definition.vector_fields]
filterable_fields = [
{"path": field.storage_name or field.name, "type": "filter"}
for field in record_definition.data_fields
if field.is_indexed
]
filterable_fields.append({"path": record_definition.key_field.name, "type": "filter"})
indexes.append(
SearchIndexModel(
type="vectorSearch",
name=index_name,
definition={"fields": vector_fields + filterable_fields},
)
)
if record_definition.data_fields:
ft_indexed_fields = [
{field.storage_name or field.name: {"type": "string"}}
for field in record_definition.data_fields
if field.is_full_text_indexed
]
if ft_indexed_fields:
indexes.append(
SearchIndexModel(
type="search",
name=f"{index_name}_ft",
definition={
"mapping": {"dynamic": True, "fields": ft_indexed_fields},
},
)
)
return indexes
@release_candidate
class MongoDBAtlasCollection(
VectorStoreCollection[TKey, TModel],
VectorSearch[TKey, TModel],
Generic[TKey, TModel],
):
"""MongoDB Atlas collection implementation."""
mongo_client: AsyncMongoClient
database_name: str
index_name: str
supported_key_types: ClassVar[set[str] | None] = {"str"}
supported_vector_types: ClassVar[set[str] | None] = {"float", "int"}
supported_search_types: ClassVar[set[SearchType]] = {SearchType.VECTOR, SearchType.KEYWORD_HYBRID}
def __init__(
self,
record_type: type[TModel],
definition: VectorStoreCollectionDefinition | None = None,
collection_name: str | None = None,
embedding_generator: EmbeddingGeneratorBase | None = None,
index_name: str | None = None,
mongo_client: AsyncMongoClient | None = None,
connection_string: str | None = None,
database_name: str | None = None,
env_file_path: str | None = None,
env_file_encoding: str | None = None,
**kwargs: Any,
) -> None:
"""Initializes a new instance of the MongoDBAtlasCollection class.
Args:
record_type: The type of the data model.
definition: The model definition, optional.
collection_name: The name of the collection, optional.
embedding_generator: The embedding generator, optional.
index_name: The name of the index to use for searching, when not passed, will use <collection_name>_idx.
mongo_client: The MongoDB client for interacting with MongoDB Atlas,
used for creating and deleting collections.
connection_string: The connection string for MongoDB Atlas, optional.
Can be read from environment variables.
database_name: The name of the database, will be filled from the env when this is not set.
connection_string: str | None = None,
env_file_path: str | None = None,
env_file_encoding: str | None = None
**kwargs: Additional keyword arguments
"""
if not collection_name:
collection_name = _get_collection_name_from_model(record_type, definition)
managed_client = kwargs.get("managed_client", not mongo_client)
if mongo_client:
super().__init__(
record_type=record_type,
definition=definition,
mongo_client=mongo_client,
collection_name=collection_name,
database_name=database_name or DEFAULT_DB_NAME,
index_name=index_name or DEFAULT_SEARCH_INDEX_NAME,
managed_client=managed_client,
embedding_generator=embedding_generator,
)
if callable(mongo_client.append_metadata):
mongo_client.append_metadata(DRIVER_METADATA)
return
try:
mongodb_atlas_settings = MongoDBAtlasSettings(
env_file_path=env_file_path,
env_file_encoding=env_file_encoding,
connection_string=connection_string,
database_name=database_name,
index_name=index_name,
)
except ValidationError as exc:
raise VectorStoreInitializationException("Failed to create MongoDB Atlas settings.") from exc
mongo_client = AsyncMongoClient(
mongodb_atlas_settings.connection_string.get_secret_value(),
driver=DRIVER_METADATA,
)
super().__init__(
record_type=record_type,
definition=definition,
collection_name=collection_name,
mongo_client=mongo_client,
managed_client=managed_client,
database_name=mongodb_atlas_settings.database_name,
index_name=mongodb_atlas_settings.index_name,
embedding_generator=embedding_generator,
)
def _get_database(self) -> AsyncDatabase:
"""Get the database.
If you need control over things like read preference, you can override this method.
"""
return self.mongo_client.get_database(self.database_name)
def _get_collection(self) -> AsyncCollection:
"""Get the collection.
If you need control over things like read preference, you can override this method.
"""
return self.mongo_client.get_database(self.database_name).get_collection(self.collection_name)
@override
async def _inner_upsert(
self,
records: Sequence[Any],
**kwargs: Any,
) -> Sequence[TKey]:
operations: MutableSequence[ReplaceOne] = []
for record in records:
operations.append(
ReplaceOne(
filter={MONGODB_ID_FIELD: record[MONGODB_ID_FIELD]},
replacement=record,
upsert=True,
)
)
result = await self._get_collection().bulk_write(operations, ordered=False)
return [str(value) for _, value in result.upserted_ids.items()] # type: ignore
@override
async def _inner_get(
self,
keys: Sequence[TKey] | None = None,
options: GetFilteredRecordOptions | None = None,
**kwargs: Any,
) -> Sequence[dict[str, Any]] | None:
if not keys:
if options is not None:
raise NotImplementedError("Get without keys is not yet implemented.")
return None
result = self._get_collection().find({MONGODB_ID_FIELD: {"$in": keys}})
return await result.to_list(length=len(keys))
@override
async def _inner_delete(self, keys: Sequence[TKey], **kwargs: Any) -> None:
collection = self._get_collection()
await collection.delete_many({MONGODB_ID_FIELD: {"$in": keys}})
def _replace_key_field(self, record: dict[str, Any]) -> dict[str, Any]:
if self._key_field_name == MONGODB_ID_FIELD:
return record
return {
MONGODB_ID_FIELD: record.pop(self._key_field_name, None),
**record,
}
def _reset_key_field(self, record: dict[str, Any]) -> dict[str, Any]:
if self._key_field_name == MONGODB_ID_FIELD:
return record
return {
self._key_field_name: record.pop(MONGODB_ID_FIELD, None),
**record,
}
@override
def _serialize_dicts_to_store_models(self, records: Sequence[dict[str, Any]], **kwargs: Any) -> Sequence[Any]:
return [self._replace_key_field(record) for record in records]
@override
def _deserialize_store_models_to_dicts(self, records: Sequence[Any], **kwargs: Any) -> Sequence[dict[str, Any]]:
return [self._reset_key_field(record) for record in records]
@override
async def ensure_collection_exists(self, **kwargs) -> None:
"""Create a new collection in MongoDB.
This first creates a collection, with the kwargs.
Then creates a search index based on the data model definition.
Args:
**kwargs: Additional keyword arguments.
"""
collection = await self._get_database().create_collection(self.collection_name, **kwargs)
await collection.create_search_indexes(models=_create_index_definitions(self.definition, self.index_name))
@override
async def collection_exists(self, **kwargs) -> bool:
return bool(await self._get_database().list_collection_names(filter={"name": self.collection_name}))
@override
async def ensure_collection_deleted(self, **kwargs) -> None:
await self._get_database().drop_collection(self.collection_name, **kwargs)
@override
async def _inner_search(
self,
search_type: SearchType,
options: VectorSearchOptions,
values: Any | None = None,
vector: Sequence[float | int] | None = None,
**kwargs: Any,
) -> KernelSearchResults[VectorSearchResult[TModel]]:
if search_type == SearchType.VECTOR:
return await self._inner_vector_search(options, values, vector, **kwargs)
if search_type == SearchType.KEYWORD_HYBRID:
return await self._inner_keyword_hybrid_search(options, values, vector, **kwargs)
raise VectorStoreOperationException("Vector is required for search.")
async def _inner_vector_search(
self,
options: VectorSearchOptions,
values: Any | None = None,
vector: Sequence[float | int] | None = None,
**kwargs: Any,
) -> KernelSearchResults[VectorSearchResult[TModel]]:
collection = self._get_collection()
vector_field = self.definition.try_get_vector_field(options.vector_property_name)
if not vector_field:
raise VectorStoreModelException(
f"Vector field '{options.vector_property_name}' not found in the data model definition."
)
if not vector:
vector = await self._generate_vector_from_values(values, options)
vector_search_query: dict[str, Any] = {
"limit": options.top + options.skip,
"index": self.index_name,
"queryVector": vector,
"path": vector_field.storage_name or vector_field.name,
}
if filter := self._build_filter(options.filter):
vector_search_query["filter"] = filter if isinstance(filter, dict) else {"$and": filter}
projection_query: dict[str, int | dict] = {
field: 1
for field in self.definition.get_names(
include_vector_fields=options.include_vectors,
include_key_field=False, # _id is always included
)
}
projection_query[MONGODB_SCORE_FIELD] = {"$meta": "vectorSearchScore"}
try:
raw_results = await collection.aggregate([
{"$vectorSearch": vector_search_query},
{"$project": projection_query},
])
except Exception as exc:
raise VectorSearchExecutionException("Failed to search the collection.") from exc
return KernelSearchResults(
results=self._get_vector_search_results_from_results(raw_results, options),
total_count=None, # no way to get a count before looping through the result cursor
)
async def _inner_keyword_hybrid_search(
self,
options: VectorSearchOptions,
values: Any | None = None,
vector: Sequence[float | int] | None = None,
**kwargs: Any,
) -> KernelSearchResults[VectorSearchResult[TModel]]:
collection = self._get_collection()
vector_field = self.definition.try_get_vector_field(options.vector_property_name)
if not vector_field:
raise VectorStoreModelException(
f"Vector field '{options.vector_property_name}' not found in the data model definition."
)
if not vector:
vector = await self._generate_vector_from_values(values, options)
vector_search_query: dict[str, Any] = {
"limit": options.top + options.skip,
"index": self.index_name,
"queryVector": vector,
"path": vector_field.storage_name or vector_field.name,
}
if filter := self._build_filter(options.filter):
vector_search_query["filter"] = filter if isinstance(filter, dict) else {"$and": filter}
projection_query: dict[str, int | dict] = {
field: 1
for field in self.definition.get_names(
include_vector_fields=options.include_vectors,
include_key_field=False, # _id is always included
)
}
projection_query[MONGODB_SCORE_FIELD] = {"$meta": "vectorSearchScore"}
try:
raw_results = await collection.aggregate([
{"$vectorSearch": vector_search_query},
{"$project": projection_query},
])
except Exception as exc:
raise VectorSearchExecutionException("Failed to search the collection.") from exc
return KernelSearchResults(
results=self._get_vector_search_results_from_results(raw_results, options),
total_count=None, # no way to get a count before looping through the result cursor
)
@override
def _lambda_parser(self, node: ast.AST) -> Any:
# Comparison operations
match node:
case ast.Compare():
if len(node.ops) > 1:
# Chain comparisons (e.g., 1 < x < 3) become $and of each comparison
values = []
for idx in range(len(node.ops)):
left = node.left if idx == 0 else node.comparators[idx - 1]
right = node.comparators[idx]
op = node.ops[idx]
values.append(self._lambda_parser(ast.Compare(left=left, ops=[op], comparators=[right])))
return {"$and": values}
left = self._lambda_parser(node.left)
right = self._lambda_parser(node.comparators[0])
op = node.ops[0]
match op:
case ast.In():
return {left: {"$in": right}}
case ast.NotIn():
return {left: {"$nin": right}}
case ast.Eq():
# MongoDB allows short form: {field: value}
return {left: right}
case ast.NotEq():
return {left: {"$ne": right}}
case ast.Gt():
return {left: {"$gt": right}}
case ast.GtE():
return {left: {"$gte": right}}
case ast.Lt():
return {left: {"$lt": right}}
case ast.LtE():
return {left: {"$lte": right}}
raise NotImplementedError(f"Unsupported operator: {type(op)}")
case ast.BoolOp():
op = node.op # type: ignore
values = [self._lambda_parser(v) for v in node.values]
if isinstance(op, ast.And):
return {"$and": values}
if isinstance(op, ast.Or):
return {"$or": values}
raise NotImplementedError(f"Unsupported BoolOp: {type(op)}")
case ast.UnaryOp():
match node.op:
case ast.Not():
operand = self._lambda_parser(node.operand)
return {"$not": operand}
case ast.UAdd() | ast.USub() | ast.Invert():
raise NotImplementedError("Unary +, -, ~ are not supported in MongoDB filters.")
case ast.Attribute():
# Only allow attributes that are in the data model
if node.attr not in self.definition.storage_names:
raise VectorStoreOperationException(
f"Field '{node.attr}' not in data model (storage property names are used)."
)
return node.attr
case ast.Name():
# Only allow names that are in the data model
if node.id not in self.definition.storage_names:
raise VectorStoreOperationException(
f"Field '{node.id}' not in data model (storage property names are used)."
)
return node.id
case ast.Constant():
return node.value
case ast.List():
return [self._lambda_parser(elt) for elt in node.elts]
raise NotImplementedError(f"Unsupported AST node: {type(node)}")
@override
def _get_record_from_result(self, result: dict[str, Any]) -> dict[str, Any]:
return result
@override
def _get_score_from_result(self, result: dict[str, Any]) -> float | None:
return result.get(MONGODB_SCORE_FIELD)
@override
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
"""Exit the context manager."""
if self.managed_client:
await self.mongo_client.close()
async def __aenter__(self) -> Self:
"""Enter the context manager."""
await self.mongo_client.aconnect()
return self
@release_candidate
class MongoDBAtlasStore(VectorStore):
"""MongoDB Atlas store implementation."""
mongo_client: AsyncMongoClient
database_name: str
def __init__(
self,
connection_string: str | None = None,
database_name: str | None = None,
embedding_generator: EmbeddingGeneratorBase | None = None,
mongo_client: AsyncMongoClient | None = None,
env_file_path: str | None = None,
env_file_encoding: str | None = None,
**kwargs: Any,
) -> None:
"""Initializes a new instance of the MongoDBAtlasStore client.
Args:
connection_string: The connection string for MongoDB Atlas, optional.
Can be read from environment variables.
database_name: The name of the database, optional. Can be read from environment variables.
embedding_generator: The embedding generator, optional.
mongo_client: The MongoDB client, optional.
env_file_path: Use the environment settings file as a fallback
to environment variables.
env_file_encoding: The encoding of the environment settings file.
kwargs: Additional keyword arguments.
"""
managed_client = kwargs.get("managed_client", not mongo_client)
if mongo_client:
super().__init__(
mongo_client=mongo_client,
managed_client=managed_client,
database_name=database_name or DEFAULT_DB_NAME,
embedding_generator=embedding_generator,
)
if callable(mongo_client.append_metadata):
mongo_client.append_metadata(DRIVER_METADATA)
return
try:
mongodb_atlas_settings = MongoDBAtlasSettings(
env_file_path=env_file_path,
connection_string=connection_string,
database_name=database_name,
env_file_encoding=env_file_encoding,
)
except ValidationError as exc:
raise VectorStoreInitializationException("Failed to create MongoDB Atlas settings.") from exc
if not mongodb_atlas_settings.connection_string:
raise VectorStoreInitializationException("The connection string is missing.")
mongo_client = AsyncMongoClient(
mongodb_atlas_settings.connection_string.get_secret_value(),
driver=DRIVER_METADATA,
)
super().__init__(
mongo_client=mongo_client,
managed_client=managed_client,
database_name=mongodb_atlas_settings.database_name,
embedding_generator=embedding_generator,
)
@override
def get_collection(
self,
record_type: type[TModel],
*,
definition: VectorStoreCollectionDefinition | None = None,
collection_name: str | None = None,
embedding_generator: EmbeddingGeneratorBase | None = None,
**kwargs: Any,
) -> MongoDBAtlasCollection:
return MongoDBAtlasCollection(
record_type=record_type,
definition=definition,
collection_name=collection_name,
mongo_client=self.mongo_client,
managed_client=False,
database_name=self.database_name,
embedding_generator=embedding_generator or self.embedding_generator,
**kwargs,
)
@override
async def list_collection_names(self, **kwargs: Any) -> list[str]:
database: AsyncDatabase = self.mongo_client.get_database(self.database_name)
return await database.list_collection_names()
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
"""Exit the context manager."""
if self.managed_client:
await self.mongo_client.close()
async def __aenter__(self) -> Self:
"""Enter the context manager."""
await self.mongo_client.aconnect()
return self