-
Notifications
You must be signed in to change notification settings - Fork 123
/
qdrant_fastembed.py
688 lines (594 loc) · 25.5 KB
/
qdrant_fastembed.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
import uuid
import warnings
from itertools import tee
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from qdrant_client.client_base import QdrantBase
from qdrant_client.conversions import common_types as types
from qdrant_client.fastembed_common import QueryResponse
from qdrant_client.http import models
from qdrant_client.hybrid.fusion import reciprocal_rank_fusion
try:
from fastembed import TextEmbedding
from fastembed.sparse.sparse_text_embedding import SparseTextEmbedding
except ImportError:
TextEmbedding = None
SparseTextEmbedding = None
SUPPORTED_EMBEDDING_MODELS: Dict[str, Tuple[int, models.Distance]] = (
{
model["model"]: (model["dim"], models.Distance.COSINE)
for model in TextEmbedding.list_supported_models()
}
if TextEmbedding
else {}
)
SUPPORTED_SPARSE_EMBEDDING_MODELS: Dict[str, Tuple[int, models.Distance]] = (
{model["model"]: model for model in SparseTextEmbedding.list_supported_models()}
if SparseTextEmbedding
else {}
)
class QdrantFastembedMixin(QdrantBase):
DEFAULT_EMBEDDING_MODEL = "BAAI/bge-small-en"
embedding_models: Dict[str, "TextEmbedding"] = {}
sparse_embedding_models: Dict[str, "SparseTextEmbedding"] = {}
_FASTEMBED_INSTALLED: bool
def __init__(self, **kwargs: Any):
self._embedding_model_name: Optional[str] = None
self._sparse_embedding_model_name: Optional[str] = None
try:
from fastembed import TextEmbedding # noqa: F401
from fastembed.sparse.sparse_text_embedding import SparseTextEmbedding
self.__class__._FASTEMBED_INSTALLED = True
except ImportError:
self.__class__._FASTEMBED_INSTALLED = False
super().__init__(**kwargs)
@property
def embedding_model_name(self) -> str:
if self._embedding_model_name is None:
self._embedding_model_name = self.DEFAULT_EMBEDDING_MODEL
return self._embedding_model_name
@property
def sparse_embedding_model_name(self) -> Optional[str]:
return self._sparse_embedding_model_name
def set_model(
self,
embedding_model_name: str,
max_length: Optional[int] = None,
cache_dir: Optional[str] = None,
threads: Optional[int] = None,
**kwargs: Any,
) -> None:
"""
Set embedding model to use for encoding documents and queries.
Args:
embedding_model_name: One of the supported embedding models. See `SUPPORTED_EMBEDDING_MODELS` for details.
max_length (int, optional): Deprecated. Defaults to None.
cache_dir (str, optional): The path to the cache directory.
Can be set using the `FASTEMBED_CACHE_PATH` env variable.
Defaults to `fastembed_cache` in the system's temp directory.
threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None.
Raises:
ValueError: If embedding model is not supported.
ImportError: If fastembed is not installed.
Returns:
None
"""
if max_length is not None:
warnings.warn(
"max_length parameter is deprecated and will be removed in the future. "
"It's not used by fastembed models.",
DeprecationWarning,
stacklevel=2,
)
self._get_or_init_model(
model_name=embedding_model_name,
cache_dir=cache_dir,
threads=threads,
**kwargs,
)
self._embedding_model_name = embedding_model_name
def set_sparse_model(
self,
embedding_model_name: Optional[str],
cache_dir: Optional[str] = None,
threads: Optional[int] = None,
) -> None:
"""
Set sparse embedding model to use for hybrid search over documents in combination with dense embeddings.
Args:
embedding_model_name: One of the supported sparse embedding models. See `SUPPORTED_SPARSE_EMBEDDING_MODELS` for details.
If None, sparse embeddings will not be used.
cache_dir (str, optional): The path to the cache directory.
Can be set using the `FASTEMBED_CACHE_PATH` env variable.
Defaults to `fastembed_cache` in the system's temp directory.
threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None.
Raises:
ValueError: If embedding model is not supported.
ImportError: If fastembed is not installed.
Returns:
None
"""
if embedding_model_name is not None:
self._get_or_init_sparse_model(
model_name=embedding_model_name,
cache_dir=cache_dir,
threads=threads,
)
self._sparse_embedding_model_name = embedding_model_name
@classmethod
def _import_fastembed(cls) -> None:
if cls._FASTEMBED_INSTALLED:
return
# If it's not, ask the user to install it
raise ImportError(
"fastembed is not installed."
" Please install it to enable fast vector indexing with `pip install fastembed`."
)
@classmethod
def _get_model_params(cls, model_name: str) -> Tuple[int, models.Distance]:
cls._import_fastembed()
if model_name not in SUPPORTED_EMBEDDING_MODELS:
raise ValueError(
f"Unsupported embedding model: {model_name}. Supported models: {SUPPORTED_EMBEDDING_MODELS}"
)
return SUPPORTED_EMBEDDING_MODELS[model_name]
@classmethod
def _get_or_init_model(
cls,
model_name: str,
cache_dir: Optional[str] = None,
threads: Optional[int] = None,
**kwargs: Any,
) -> "TextEmbedding":
if model_name in cls.embedding_models:
return cls.embedding_models[model_name]
cls._import_fastembed()
if model_name not in SUPPORTED_EMBEDDING_MODELS:
raise ValueError(
f"Unsupported embedding model: {model_name}. Supported models: {SUPPORTED_EMBEDDING_MODELS}"
)
cls.embedding_models[model_name] = TextEmbedding(
model_name=model_name,
cache_dir=cache_dir,
threads=threads,
**kwargs,
)
return cls.embedding_models[model_name]
@classmethod
def _get_or_init_sparse_model(
cls,
model_name: str,
cache_dir: Optional[str] = None,
threads: Optional[int] = None,
**kwargs: Any,
) -> "SparseTextEmbedding":
if model_name in cls.sparse_embedding_models:
return cls.sparse_embedding_models[model_name]
cls._import_fastembed()
if model_name not in SUPPORTED_SPARSE_EMBEDDING_MODELS:
raise ValueError(
f"Unsupported embedding model: {model_name}. Supported models: {SUPPORTED_SPARSE_EMBEDDING_MODELS}"
)
cls.sparse_embedding_models[model_name] = SparseTextEmbedding(
model_name=model_name,
cache_dir=cache_dir,
threads=threads,
**kwargs,
)
return cls.sparse_embedding_models[model_name]
def _embed_documents(
self,
documents: Iterable[str],
embedding_model_name: str = DEFAULT_EMBEDDING_MODEL,
batch_size: int = 32,
embed_type: str = "default",
parallel: Optional[int] = None,
) -> Iterable[Tuple[str, List[float]]]:
embedding_model = self._get_or_init_model(model_name=embedding_model_name)
documents_a, documents_b = tee(documents, 2)
if embed_type == "passage":
vectors_iter = embedding_model.passage_embed(
documents_a, batch_size=batch_size, parallel=parallel
)
elif embed_type == "query":
vectors_iter = (
list(embedding_model.query_embed(query=query))[0] for query in documents_a
)
elif embed_type == "default":
vectors_iter = embedding_model.embed(
documents_a, batch_size=batch_size, parallel=parallel
)
else:
raise ValueError(f"Unknown embed type: {embed_type}")
for vector, doc in zip(vectors_iter, documents_b):
yield doc, vector.tolist()
def _sparse_embed_documents(
self,
documents: Iterable[str],
embedding_model_name: str = DEFAULT_EMBEDDING_MODEL,
batch_size: int = 32,
parallel: Optional[int] = None,
) -> Iterable[types.SparseVector]:
sparse_embedding_model = self._get_or_init_sparse_model(model_name=embedding_model_name)
vectors_iter = sparse_embedding_model.embed(
documents, batch_size=batch_size, parallel=parallel
)
for sparse_vector in vectors_iter:
yield types.SparseVector(
indices=sparse_vector.indices.tolist(),
values=sparse_vector.values.tolist(),
)
def get_vector_field_name(self) -> str:
"""
Returns name of the vector field in qdrant collection, used by current fastembed model.
Returns:
Name of the vector field.
"""
model_name = self.embedding_model_name.split("/")[-1].lower()
return f"fast-{model_name}"
def get_sparse_vector_field_name(self) -> Optional[str]:
"""
Returns name of the vector field in qdrant collection, used by current fastembed model.
Returns:
Name of the vector field.
"""
if self.sparse_embedding_model_name is not None:
model_name = self.sparse_embedding_model_name.split("/")[-1].lower()
return f"fast-sparse-{model_name}"
return None
def _scored_points_to_query_responses(
self,
scored_points: List[types.ScoredPoint],
) -> List[QueryResponse]:
response = []
vector_field_name = self.get_vector_field_name()
sparse_vector_field_name = self.get_sparse_vector_field_name()
for scored_point in scored_points:
embedding = (
scored_point.vector.get(vector_field_name, None)
if isinstance(scored_point.vector, Dict)
else None
)
sparse_embedding = None
if sparse_vector_field_name is not None:
sparse_embedding = (
scored_point.vector.get(sparse_vector_field_name, None)
if isinstance(scored_point.vector, Dict)
else None
)
response.append(
QueryResponse(
id=scored_point.id,
embedding=embedding,
sparse_embedding=sparse_embedding,
metadata=scored_point.payload,
document=scored_point.payload.get("document", ""),
score=scored_point.score,
)
)
return response
def _points_iterator(
self,
ids: Optional[Iterable[models.ExtendedPointId]],
metadata: Optional[Iterable[Dict[str, Any]]],
encoded_docs: Iterable[Tuple[str, List[float]]],
ids_accumulator: list,
sparse_vectors: Optional[Iterable[types.SparseVector]] = None,
) -> Iterable[models.PointStruct]:
if ids is None:
ids = iter(lambda: uuid.uuid4().hex, None)
if metadata is None:
metadata = iter(lambda: {}, None)
if sparse_vectors is None:
sparse_vectors = iter(lambda: None, True)
vector_name = self.get_vector_field_name()
sparse_vector_name = self.get_sparse_vector_field_name()
for idx, meta, (doc, vector), sparse_vector in zip(
ids, metadata, encoded_docs, sparse_vectors
):
ids_accumulator.append(idx)
payload = {"document": doc, **meta}
point_vector: Dict[str, models.Vector] = {vector_name: vector}
if sparse_vector_name is not None and sparse_vector is not None:
point_vector[sparse_vector_name] = sparse_vector
yield models.PointStruct(id=idx, payload=payload, vector=point_vector)
def _validate_collection_info(self, collection_info: models.CollectionInfo) -> None:
embeddings_size, distance = self._get_model_params(model_name=self.embedding_model_name)
vector_field_name = self.get_vector_field_name()
# Check if collection has compatible vector params
assert isinstance(
collection_info.config.params.vectors, dict
), f"Collection have incompatible vector params: {collection_info.config.params.vectors}"
assert (
vector_field_name in collection_info.config.params.vectors
), f"Collection have incompatible vector params: {collection_info.config.params.vectors}, expected {vector_field_name}"
vector_params = collection_info.config.params.vectors[vector_field_name]
assert (
embeddings_size == vector_params.size
), f"Embedding size mismatch: {embeddings_size} != {vector_params.size}"
assert (
distance == vector_params.distance
), f"Distance mismatch: {distance} != {vector_params.distance}"
sparse_vector_field_name = self.get_sparse_vector_field_name()
if sparse_vector_field_name is not None:
assert (
sparse_vector_field_name in collection_info.config.params.sparse_vectors
), f"Collection have incompatible vector params: {collection_info.config.params.vectors}"
def get_fastembed_vector_params(
self,
on_disk: Optional[bool] = None,
quantization_config: Optional[models.QuantizationConfig] = None,
hnsw_config: Optional[models.HnswConfigDiff] = None,
) -> Dict[str, models.VectorParams]:
"""
Generates vector configuration, compatible with fastembed models.
Args:
on_disk: if True, vectors will be stored on disk. If None, default value will be used.
quantization_config: Quantization configuration. If None, quantization will be disabled.
hnsw_config: HNSW configuration. If None, default configuration will be used.
Returns:
Configuration for `vectors_config` argument in `create_collection` method.
"""
vector_field_name = self.get_vector_field_name()
embeddings_size, distance = self._get_model_params(model_name=self.embedding_model_name)
return {
vector_field_name: models.VectorParams(
size=embeddings_size,
distance=distance,
on_disk=on_disk,
quantization_config=quantization_config,
hnsw_config=hnsw_config,
)
}
def get_fastembed_sparse_vector_params(
self,
on_disk: Optional[bool] = None,
) -> Optional[Dict[str, models.SparseVectorParams]]:
"""
Generates vector configuration, compatible with fastembed sparse models.
Args:
on_disk: if True, vectors will be stored on disk. If None, default value will be used.
Returns:
Configuration for `vectors_config` argument in `create_collection` method.
"""
vector_field_name = self.get_sparse_vector_field_name()
if vector_field_name is None:
return None
return {
vector_field_name: models.SparseVectorParams(
index=models.SparseIndexParams(
on_disk=on_disk,
)
)
}
def add(
self,
collection_name: str,
documents: Iterable[str],
metadata: Optional[Iterable[Dict[str, Any]]] = None,
ids: Optional[Iterable[models.ExtendedPointId]] = None,
batch_size: int = 32,
parallel: Optional[int] = None,
**kwargs: Any,
) -> List[Union[str, int]]:
"""
Adds text documents into qdrant collection.
If collection does not exist, it will be created with default parameters.
Metadata in combination with documents will be added as payload.
Documents will be embedded using the specified embedding model.
If you want to use your own vectors, use `upsert` method instead.
Args:
collection_name (str):
Name of the collection to add documents to.
documents (Iterable[str]):
List of documents to embed and add to the collection.
metadata (Iterable[Dict[str, Any]], optional):
List of metadata dicts. Defaults to None.
ids (Iterable[models.ExtendedPointId], optional):
List of ids to assign to documents.
If not specified, UUIDs will be generated. Defaults to None.
batch_size (int, optional):
How many documents to embed and upload in single request. Defaults to 32.
parallel (Optional[int], optional):
How many parallel workers to use for embedding. Defaults to None.
If number is specified, data-parallel process will be used.
Raises:
ImportError: If fastembed is not installed.
Returns:
List of IDs of added documents. If no ids provided, UUIDs will be randomly generated on client side.
"""
# check if we have fastembed installed
encoded_docs = self._embed_documents(
documents=documents,
embedding_model_name=self.embedding_model_name,
batch_size=batch_size,
embed_type="passage",
parallel=parallel,
)
encoded_sparse_docs = None
if self.sparse_embedding_model_name is not None:
encoded_sparse_docs = self._sparse_embed_documents(
documents=documents,
embedding_model_name=self.sparse_embedding_model_name,
batch_size=batch_size,
parallel=parallel,
)
# Check if collection by same name exists, if not, create it
try:
collection_info = self.get_collection(collection_name=collection_name)
except Exception:
self.create_collection(
collection_name=collection_name,
vectors_config=self.get_fastembed_vector_params(),
sparse_vectors_config=self.get_fastembed_sparse_vector_params(),
)
collection_info = self.get_collection(collection_name=collection_name)
self._validate_collection_info(collection_info)
inserted_ids: list = []
points = self._points_iterator(
ids=ids,
metadata=metadata,
encoded_docs=encoded_docs,
ids_accumulator=inserted_ids,
sparse_vectors=encoded_sparse_docs,
)
self.upload_points(
collection_name=collection_name,
points=points,
wait=True,
parallel=parallel or 1,
batch_size=batch_size,
**kwargs,
)
return inserted_ids
def query(
self,
collection_name: str,
query_text: str,
query_filter: Optional[models.Filter] = None,
limit: int = 10,
**kwargs: Any,
) -> List[QueryResponse]:
"""
Search for documents in a collection.
This method automatically embeds the query text using the specified embedding model.
If you want to use your own query vector, use `search` method instead.
Args:
collection_name: Collection to search in
query_text:
Text to search for. This text will be embedded using the specified embedding model.
And then used as a query vector.
query_filter:
- Exclude vectors which doesn't fit given conditions.
- If `None` - search among all vectors
limit: How many results return
**kwargs: Additional search parameters. See `qdrant_client.models.SearchRequest` for details.
Returns:
List[types.ScoredPoint]: List of scored points.
"""
embedding_model_inst = self._get_or_init_model(model_name=self.embedding_model_name)
embeddings = list(embedding_model_inst.query_embed(query=query_text))
query_vector = embeddings[0].tolist()
if self.sparse_embedding_model_name is None:
return self._scored_points_to_query_responses(
self.search(
collection_name=collection_name,
query_vector=models.NamedVector(
name=self.get_vector_field_name(), vector=query_vector
),
query_filter=query_filter,
limit=limit,
with_payload=True,
**kwargs,
)
)
sparse_embedding_model_inst = self._get_or_init_sparse_model(
model_name=self.sparse_embedding_model_name
)
sparse_vector = list(sparse_embedding_model_inst.embed(documents=query_text))[0]
sparse_query_vector = models.SparseVector(
indices=sparse_vector.indices.tolist(),
values=sparse_vector.values.tolist(),
)
dense_request = models.SearchRequest(
vector=models.NamedVector(
name=self.get_vector_field_name(),
vector=query_vector,
),
filter=query_filter,
limit=limit,
with_payload=True,
**kwargs,
)
sparse_request = models.SearchRequest(
vector=models.NamedSparseVector(
name=self.get_sparse_vector_field_name(),
vector=sparse_query_vector,
),
filter=query_filter,
limit=limit,
with_payload=True,
**kwargs,
)
dense_request_response, sparse_request_response = self.search_batch(
collection_name=collection_name, requests=[dense_request, sparse_request]
)
return self._scored_points_to_query_responses(
reciprocal_rank_fusion([dense_request_response, sparse_request_response], limit=limit)
)
def query_batch(
self,
collection_name: str,
query_texts: List[str],
query_filter: Optional[models.Filter] = None,
limit: int = 10,
**kwargs: Any,
) -> List[List[QueryResponse]]:
"""
Search for documents in a collection with batched query.
This method automatically embeds the query text using the specified embedding model.
Args:
collection_name: Collection to search in
query_texts:
A list of texts to search for. Each text will be embedded using the specified embedding model.
And then used as a query vector for a separate search requests.
query_filter:
- Exclude vectors which doesn't fit given conditions.
- If `None` - search among all vectors
This filter will be applied to all search requests.
limit: How many results return
**kwargs: Additional search parameters. See `qdrant_client.models.SearchRequest` for details.
Returns:
List[List[QueryResponse]]: List of lists of responses for each query text.
"""
embedding_model_inst = self._get_or_init_model(model_name=self.embedding_model_name)
query_vectors = list(embedding_model_inst.query_embed(query=query_texts))
requests = []
for vector in query_vectors:
request = models.SearchRequest(
vector=models.NamedVector(
name=self.get_vector_field_name(), vector=vector.tolist()
),
filter=query_filter,
limit=limit,
with_payload=True,
**kwargs,
)
requests.append(request)
if self.sparse_embedding_model_name is None:
responses = self.search_batch(
collection_name=collection_name,
requests=requests,
)
return [self._scored_points_to_query_responses(response) for response in responses]
sparse_embedding_model_inst = self._get_or_init_sparse_model(
model_name=self.sparse_embedding_model_name
)
sparse_query_vectors = [
models.SparseVector(
indices=sparse_vector.indices.tolist(), values=sparse_vector.values.tolist()
)
for sparse_vector in sparse_embedding_model_inst.embed(documents=query_texts)
]
for sparse_vector in sparse_query_vectors:
request = models.SearchRequest(
vector=models.NamedSparseVector(
name=self.get_sparse_vector_field_name(),
vector=sparse_vector,
),
filter=query_filter,
limit=limit,
with_payload=True,
**kwargs,
)
requests.append(request)
responses = self.search_batch(
collection_name=collection_name,
requests=requests,
)
dense_responses = responses[: len(query_texts)]
sparse_responses = responses[len(query_texts) :]
responses = [
reciprocal_rank_fusion([dense_response, sparse_response], limit=limit)
for dense_response, sparse_response in zip(dense_responses, sparse_responses)
]
return [self._scored_points_to_query_responses(response) for response in responses]