fastembed-haystack 1.2.0__tar.gz → 1.4.0__tar.gz
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.
- fastembed_haystack-1.4.0/CHANGELOG.md +72 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/PKG-INFO +3 -4
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/examples/example.py +1 -0
- fastembed_haystack-1.4.0/examples/ranker_example.py +22 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/examples/sparse_example.py +1 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/pydoc/config.yml +2 -1
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/pyproject.toml +19 -9
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/src/haystack_integrations/components/embedders/fastembed/embedding_backend/fastembed_backend.py +16 -4
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/src/haystack_integrations/components/embedders/fastembed/fastembed_sparse_document_embedder.py +5 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/src/haystack_integrations/components/embedders/fastembed/fastembed_sparse_text_embedder.py +5 -0
- fastembed_haystack-1.4.0/src/haystack_integrations/components/rankers/fastembed/__init__.py +3 -0
- fastembed_haystack-1.4.0/src/haystack_integrations/components/rankers/fastembed/ranker.py +202 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/tests/test_fastembed_backend.py +26 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/tests/test_fastembed_document_embedder.py +1 -0
- fastembed_haystack-1.4.0/tests/test_fastembed_ranker.py +292 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/tests/test_fastembed_sparse_document_embedder.py +54 -1
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/tests/test_fastembed_sparse_text_embedder.py +56 -1
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/tests/test_fastembed_text_embedder.py +1 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/.gitignore +0 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/LICENSE.txt +0 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/README.md +0 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/src/haystack_integrations/components/embedders/fastembed/__init__.py +0 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/src/haystack_integrations/components/embedders/fastembed/embedding_backend/__init__.py +0 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/src/haystack_integrations/components/embedders/fastembed/fastembed_document_embedder.py +0 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/src/haystack_integrations/components/embedders/fastembed/fastembed_text_embedder.py +0 -0
- {fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/tests/__init__.py +0 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [integrations/fastembed-v1.3.0] - 2024-10-07
|
|
4
|
+
|
|
5
|
+
### 🚀 Features
|
|
6
|
+
|
|
7
|
+
- Introduce `model_kwargs` in Sparse Embedders (can be used for BM25 parameters) (#1126)
|
|
8
|
+
|
|
9
|
+
### 🧪 Testing
|
|
10
|
+
|
|
11
|
+
- Do not retry tests in `hatch run test` command (#954)
|
|
12
|
+
|
|
13
|
+
### ⚙️ Miscellaneous Tasks
|
|
14
|
+
|
|
15
|
+
- Retry tests to reduce flakyness (#836)
|
|
16
|
+
- Update ruff invocation to include check parameter (#853)
|
|
17
|
+
- Update ruff linting scripts and settings (#1105)
|
|
18
|
+
|
|
19
|
+
### Fix
|
|
20
|
+
|
|
21
|
+
- Typo on Sparse embedders. The parameter should be "progress_bar" … (#814)
|
|
22
|
+
|
|
23
|
+
## [integrations/fastembed-v1.1.0] - 2024-05-15
|
|
24
|
+
|
|
25
|
+
## [integrations/fastembed-v1.0.0] - 2024-05-06
|
|
26
|
+
|
|
27
|
+
## [integrations/fastembed-v0.1.0] - 2024-04-10
|
|
28
|
+
|
|
29
|
+
### 🚀 Features
|
|
30
|
+
|
|
31
|
+
- *(FastEmbed)* Support for SPLADE Sparse Embedder (#579)
|
|
32
|
+
|
|
33
|
+
### 📚 Documentation
|
|
34
|
+
|
|
35
|
+
- Disable-class-def (#556)
|
|
36
|
+
|
|
37
|
+
## [integrations/fastembed-v0.0.6] - 2024-03-07
|
|
38
|
+
|
|
39
|
+
### 📚 Documentation
|
|
40
|
+
|
|
41
|
+
- Review and normalize docstrings - `integrations.fastembed` (#519)
|
|
42
|
+
- Small consistency improvements (#536)
|
|
43
|
+
|
|
44
|
+
## [integrations/fastembed-v0.0.5] - 2024-02-20
|
|
45
|
+
|
|
46
|
+
### 🐛 Bug Fixes
|
|
47
|
+
|
|
48
|
+
- Fix order of API docs (#447)
|
|
49
|
+
|
|
50
|
+
This PR will also push the docs to Readme
|
|
51
|
+
|
|
52
|
+
### 📚 Documentation
|
|
53
|
+
|
|
54
|
+
- Update category slug (#442)
|
|
55
|
+
|
|
56
|
+
## [integrations/fastembed-v0.0.4] - 2024-02-16
|
|
57
|
+
|
|
58
|
+
## [integrations/fastembed-v0.0.3] - 2024-02-12
|
|
59
|
+
|
|
60
|
+
### 🐛 Bug Fixes
|
|
61
|
+
|
|
62
|
+
- From numpy float to float (#391)
|
|
63
|
+
|
|
64
|
+
### 📚 Documentation
|
|
65
|
+
|
|
66
|
+
- Update paths and titles (#397)
|
|
67
|
+
|
|
68
|
+
## [integrations/fastembed-v0.0.2] - 2024-02-11
|
|
69
|
+
|
|
70
|
+
## [integrations/fastembed-v0.0.1] - 2024-02-10
|
|
71
|
+
|
|
72
|
+
<!-- generated by git-cliff -->
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: fastembed-haystack
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
4
|
Summary: Haystack 2.x component to embed strings and Documents using fastembed embedding model
|
|
5
5
|
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations
|
|
6
6
|
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/README.md
|
|
7
7
|
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
8
8
|
Author-email: deepset GmbH <info@deepset.ai>
|
|
9
|
-
License
|
|
10
|
-
License-File: LICENSE.txt
|
|
9
|
+
License: Apache-2.0
|
|
11
10
|
Classifier: Development Status :: 4 - Beta
|
|
12
11
|
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
12
|
Classifier: Programming Language :: Python
|
|
@@ -19,7 +18,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
19
18
|
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
20
19
|
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
21
20
|
Requires-Python: >=3.8
|
|
22
|
-
Requires-Dist: fastembed>=0.2
|
|
21
|
+
Requires-Dist: fastembed>=0.4.2
|
|
23
22
|
Requires-Dist: haystack-ai>=2.0.1
|
|
24
23
|
Description-Content-Type: text/markdown
|
|
25
24
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from haystack import Document, Pipeline
|
|
2
2
|
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
|
|
3
3
|
from haystack.document_stores.in_memory import InMemoryDocumentStore
|
|
4
|
+
|
|
4
5
|
from haystack_integrations.components.embedders.fastembed import FastembedDocumentEmbedder, FastembedTextEmbedder
|
|
5
6
|
|
|
6
7
|
document_store = InMemoryDocumentStore(embedding_similarity_function="cosine")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from haystack import Document
|
|
2
|
+
|
|
3
|
+
from haystack_integrations.components.rankers.fastembed import FastembedRanker
|
|
4
|
+
|
|
5
|
+
query = "Who is maintaining Qdrant?"
|
|
6
|
+
documents = [
|
|
7
|
+
Document(
|
|
8
|
+
content="This is built to be faster and lighter than other embedding libraries e.g. Transformers, Sentence-Transformers, etc."
|
|
9
|
+
),
|
|
10
|
+
Document(content="fastembed is supported by and maintained by Qdrant."),
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
ranker = FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-6-v2")
|
|
14
|
+
ranker.warm_up()
|
|
15
|
+
reranked_documents = ranker.run(query=query, documents=documents)["documents"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
print(reranked_documents["documents"][0])
|
|
19
|
+
|
|
20
|
+
# Document(id=...,
|
|
21
|
+
# content: 'fastembed is supported by and maintained by Qdrant.',
|
|
22
|
+
# score: 5.472434997558594..)
|
|
@@ -6,7 +6,8 @@ loaders:
|
|
|
6
6
|
"haystack_integrations.components.embedders.fastembed.fastembed_document_embedder",
|
|
7
7
|
"haystack_integrations.components.embedders.fastembed.fastembed_text_embedder",
|
|
8
8
|
"haystack_integrations.components.embedders.fastembed.fastembed_sparse_document_embedder",
|
|
9
|
-
"haystack_integrations.components.embedders.fastembed.fastembed_sparse_text_embedder"
|
|
9
|
+
"haystack_integrations.components.embedders.fastembed.fastembed_sparse_text_embedder",
|
|
10
|
+
"haystack_integrations.components.rankers.fastembed.ranker"
|
|
10
11
|
]
|
|
11
12
|
ignore_when_discovered: ["__init__"]
|
|
12
13
|
processors:
|
|
@@ -23,7 +23,7 @@ classifiers = [
|
|
|
23
23
|
"Programming Language :: Python :: Implementation :: CPython",
|
|
24
24
|
"Programming Language :: Python :: Implementation :: PyPy",
|
|
25
25
|
]
|
|
26
|
-
dependencies = ["haystack-ai>=2.0.1", "fastembed>=0.2
|
|
26
|
+
dependencies = ["haystack-ai>=2.0.1", "fastembed>=0.4.2"]
|
|
27
27
|
|
|
28
28
|
[project.urls]
|
|
29
29
|
Source = "https://github.com/deepset-ai/haystack-core-integrations"
|
|
@@ -42,6 +42,7 @@ root = "../.."
|
|
|
42
42
|
git_describe_command = 'git describe --tags --match="integrations/fastembed-v[0-9]*"'
|
|
43
43
|
|
|
44
44
|
[tool.hatch.envs.default]
|
|
45
|
+
installer = "uv"
|
|
45
46
|
dependencies = [
|
|
46
47
|
"coverage[toml]>=6.5",
|
|
47
48
|
"pytest",
|
|
@@ -50,22 +51,25 @@ dependencies = [
|
|
|
50
51
|
"haystack-pydoc-tools",
|
|
51
52
|
]
|
|
52
53
|
[tool.hatch.envs.default.scripts]
|
|
53
|
-
test = "pytest
|
|
54
|
-
test-cov = "coverage run -m pytest
|
|
54
|
+
test = "pytest {args:tests}"
|
|
55
|
+
test-cov = "coverage run -m pytest {args:tests}"
|
|
56
|
+
test-cov-retry = "test-cov --reruns 3 --reruns-delay 30 -x"
|
|
55
57
|
cov-report = ["- coverage combine", "coverage report"]
|
|
56
58
|
cov = ["test-cov", "cov-report"]
|
|
59
|
+
cov-retry = ["test-cov-retry", "cov-report"]
|
|
57
60
|
docs = ["pydoc-markdown pydoc/config.yml"]
|
|
58
61
|
|
|
59
62
|
[[tool.hatch.envs.all.matrix]]
|
|
60
63
|
python = ["3.8", "3.9", "3.10", "3.11", "3.12"]
|
|
61
64
|
|
|
62
65
|
[tool.hatch.envs.lint]
|
|
66
|
+
installer = "uv"
|
|
63
67
|
detached = true
|
|
64
|
-
dependencies = ["black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243", "numpy"]
|
|
68
|
+
dependencies = ["pip", "black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243", "numpy"]
|
|
65
69
|
[tool.hatch.envs.lint.scripts]
|
|
66
70
|
typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}"
|
|
67
71
|
style = ["ruff check {args:.}", "black --check --diff {args:.}"]
|
|
68
|
-
fmt = ["black {args:.}", "ruff --fix {args:.}", "style"]
|
|
72
|
+
fmt = ["black {args:.}", "ruff check --fix {args:.}", "style"]
|
|
69
73
|
all = ["style", "typing"]
|
|
70
74
|
|
|
71
75
|
[tool.black]
|
|
@@ -76,6 +80,8 @@ skip-string-normalization = true
|
|
|
76
80
|
[tool.ruff]
|
|
77
81
|
target-version = "py38"
|
|
78
82
|
line-length = 120
|
|
83
|
+
|
|
84
|
+
[tool.ruff.lint]
|
|
79
85
|
select = [
|
|
80
86
|
"A",
|
|
81
87
|
"ARG",
|
|
@@ -126,13 +132,13 @@ unfixable = [
|
|
|
126
132
|
"F401",
|
|
127
133
|
]
|
|
128
134
|
|
|
129
|
-
[tool.ruff.isort]
|
|
130
|
-
known-first-party = ["
|
|
135
|
+
[tool.ruff.lint.isort]
|
|
136
|
+
known-first-party = ["haystack_integrations"]
|
|
131
137
|
|
|
132
|
-
[tool.ruff.flake8-tidy-imports]
|
|
138
|
+
[tool.ruff.lint.flake8-tidy-imports]
|
|
133
139
|
ban-relative-imports = "parents"
|
|
134
140
|
|
|
135
|
-
[tool.ruff.per-file-ignores]
|
|
141
|
+
[tool.ruff.lint.per-file-ignores]
|
|
136
142
|
# Tests can use magic values, assertions, and relative imports
|
|
137
143
|
"tests/**/*" = ["PLR2004", "S101", "TID252"]
|
|
138
144
|
# examples can contain "print" commands
|
|
@@ -148,6 +154,10 @@ omit = ["*/tests/*", "*/__init__.py"]
|
|
|
148
154
|
show_missing = true
|
|
149
155
|
exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
|
|
150
156
|
|
|
157
|
+
[tool.pytest.ini_options]
|
|
158
|
+
minversion = "6.0"
|
|
159
|
+
markers = ["unit: unit tests", "integration: integration tests"]
|
|
160
|
+
|
|
151
161
|
[[tool.mypy.overrides]]
|
|
152
162
|
module = [
|
|
153
163
|
"haystack.*",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
from typing import ClassVar, Dict, List, Optional
|
|
1
|
+
from typing import Any, ClassVar, Dict, List, Optional
|
|
2
2
|
|
|
3
3
|
from haystack.dataclasses.sparse_embedding import SparseEmbedding
|
|
4
4
|
from tqdm import tqdm
|
|
@@ -73,14 +73,19 @@ class _FastembedSparseEmbeddingBackendFactory:
|
|
|
73
73
|
cache_dir: Optional[str] = None,
|
|
74
74
|
threads: Optional[int] = None,
|
|
75
75
|
local_files_only: bool = False,
|
|
76
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
76
77
|
):
|
|
77
|
-
embedding_backend_id = f"{model_name}{cache_dir}{threads}"
|
|
78
|
+
embedding_backend_id = f"{model_name}{cache_dir}{threads}{local_files_only}{model_kwargs}"
|
|
78
79
|
|
|
79
80
|
if embedding_backend_id in _FastembedSparseEmbeddingBackendFactory._instances:
|
|
80
81
|
return _FastembedSparseEmbeddingBackendFactory._instances[embedding_backend_id]
|
|
81
82
|
|
|
82
83
|
embedding_backend = _FastembedSparseEmbeddingBackend(
|
|
83
|
-
model_name=model_name,
|
|
84
|
+
model_name=model_name,
|
|
85
|
+
cache_dir=cache_dir,
|
|
86
|
+
threads=threads,
|
|
87
|
+
local_files_only=local_files_only,
|
|
88
|
+
model_kwargs=model_kwargs,
|
|
84
89
|
)
|
|
85
90
|
_FastembedSparseEmbeddingBackendFactory._instances[embedding_backend_id] = embedding_backend
|
|
86
91
|
return embedding_backend
|
|
@@ -97,9 +102,16 @@ class _FastembedSparseEmbeddingBackend:
|
|
|
97
102
|
cache_dir: Optional[str] = None,
|
|
98
103
|
threads: Optional[int] = None,
|
|
99
104
|
local_files_only: bool = False,
|
|
105
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
100
106
|
):
|
|
107
|
+
model_kwargs = model_kwargs or {}
|
|
108
|
+
|
|
101
109
|
self.model = SparseTextEmbedding(
|
|
102
|
-
model_name=model_name,
|
|
110
|
+
model_name=model_name,
|
|
111
|
+
cache_dir=cache_dir,
|
|
112
|
+
threads=threads,
|
|
113
|
+
local_files_only=local_files_only,
|
|
114
|
+
**model_kwargs,
|
|
103
115
|
)
|
|
104
116
|
|
|
105
117
|
def embed(self, data: List[List[str]], progress_bar=True, **kwargs) -> List[SparseEmbedding]:
|
|
@@ -62,6 +62,7 @@ class FastembedSparseDocumentEmbedder:
|
|
|
62
62
|
local_files_only: bool = False,
|
|
63
63
|
meta_fields_to_embed: Optional[List[str]] = None,
|
|
64
64
|
embedding_separator: str = "\n",
|
|
65
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
65
66
|
):
|
|
66
67
|
"""
|
|
67
68
|
Create an FastembedDocumentEmbedder component.
|
|
@@ -81,6 +82,7 @@ class FastembedSparseDocumentEmbedder:
|
|
|
81
82
|
:param local_files_only: If `True`, only use the model files in the `cache_dir`.
|
|
82
83
|
:param meta_fields_to_embed: List of meta fields that should be embedded along with the Document content.
|
|
83
84
|
:param embedding_separator: Separator used to concatenate the meta fields to the Document content.
|
|
85
|
+
:param model_kwargs: Dictionary containing model parameters such as `k`, `b`, `avg_len`, `language`.
|
|
84
86
|
"""
|
|
85
87
|
|
|
86
88
|
self.model_name = model
|
|
@@ -92,6 +94,7 @@ class FastembedSparseDocumentEmbedder:
|
|
|
92
94
|
self.local_files_only = local_files_only
|
|
93
95
|
self.meta_fields_to_embed = meta_fields_to_embed or []
|
|
94
96
|
self.embedding_separator = embedding_separator
|
|
97
|
+
self.model_kwargs = model_kwargs
|
|
95
98
|
|
|
96
99
|
def to_dict(self) -> Dict[str, Any]:
|
|
97
100
|
"""
|
|
@@ -110,6 +113,7 @@ class FastembedSparseDocumentEmbedder:
|
|
|
110
113
|
local_files_only=self.local_files_only,
|
|
111
114
|
meta_fields_to_embed=self.meta_fields_to_embed,
|
|
112
115
|
embedding_separator=self.embedding_separator,
|
|
116
|
+
model_kwargs=self.model_kwargs,
|
|
113
117
|
)
|
|
114
118
|
|
|
115
119
|
def warm_up(self):
|
|
@@ -122,6 +126,7 @@ class FastembedSparseDocumentEmbedder:
|
|
|
122
126
|
cache_dir=self.cache_dir,
|
|
123
127
|
threads=self.threads,
|
|
124
128
|
local_files_only=self.local_files_only,
|
|
129
|
+
model_kwargs=self.model_kwargs,
|
|
125
130
|
)
|
|
126
131
|
|
|
127
132
|
def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]:
|
|
@@ -35,6 +35,7 @@ class FastembedSparseTextEmbedder:
|
|
|
35
35
|
progress_bar: bool = True,
|
|
36
36
|
parallel: Optional[int] = None,
|
|
37
37
|
local_files_only: bool = False,
|
|
38
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
38
39
|
):
|
|
39
40
|
"""
|
|
40
41
|
Create a FastembedSparseTextEmbedder component.
|
|
@@ -50,6 +51,7 @@ class FastembedSparseTextEmbedder:
|
|
|
50
51
|
If 0, use all available cores.
|
|
51
52
|
If None, don't use data-parallel processing, use default onnxruntime threading instead.
|
|
52
53
|
:param local_files_only: If `True`, only use the model files in the `cache_dir`.
|
|
54
|
+
:param model_kwargs: Dictionary containing model parameters such as `k`, `b`, `avg_len`, `language`.
|
|
53
55
|
"""
|
|
54
56
|
|
|
55
57
|
self.model_name = model
|
|
@@ -58,6 +60,7 @@ class FastembedSparseTextEmbedder:
|
|
|
58
60
|
self.progress_bar = progress_bar
|
|
59
61
|
self.parallel = parallel
|
|
60
62
|
self.local_files_only = local_files_only
|
|
63
|
+
self.model_kwargs = model_kwargs
|
|
61
64
|
|
|
62
65
|
def to_dict(self) -> Dict[str, Any]:
|
|
63
66
|
"""
|
|
@@ -74,6 +77,7 @@ class FastembedSparseTextEmbedder:
|
|
|
74
77
|
progress_bar=self.progress_bar,
|
|
75
78
|
parallel=self.parallel,
|
|
76
79
|
local_files_only=self.local_files_only,
|
|
80
|
+
model_kwargs=self.model_kwargs,
|
|
77
81
|
)
|
|
78
82
|
|
|
79
83
|
def warm_up(self):
|
|
@@ -86,6 +90,7 @@ class FastembedSparseTextEmbedder:
|
|
|
86
90
|
cache_dir=self.cache_dir,
|
|
87
91
|
threads=self.threads,
|
|
88
92
|
local_files_only=self.local_files_only,
|
|
93
|
+
model_kwargs=self.model_kwargs,
|
|
89
94
|
)
|
|
90
95
|
|
|
91
96
|
@component.output_types(sparse_embedding=SparseEmbedding)
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Optional
|
|
2
|
+
|
|
3
|
+
from haystack import Document, component, default_from_dict, default_to_dict, logging
|
|
4
|
+
|
|
5
|
+
from fastembed.rerank.cross_encoder import TextCrossEncoder
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@component
|
|
11
|
+
class FastembedRanker:
|
|
12
|
+
"""
|
|
13
|
+
Ranks Documents based on their similarity to the query using
|
|
14
|
+
[Fastembed models](https://qdrant.github.io/fastembed/examples/Supported_Models/).
|
|
15
|
+
|
|
16
|
+
Documents are indexed from most to least semantically relevant to the query.
|
|
17
|
+
|
|
18
|
+
Usage example:
|
|
19
|
+
```python
|
|
20
|
+
from haystack import Document
|
|
21
|
+
from haystack_integrations.components.rankers.fastembed import FastembedRanker
|
|
22
|
+
|
|
23
|
+
ranker = FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-6-v2", top_k=2)
|
|
24
|
+
|
|
25
|
+
docs = [Document(content="Paris"), Document(content="Berlin")]
|
|
26
|
+
query = "What is the capital of germany?"
|
|
27
|
+
output = ranker.run(query=query, documents=docs)
|
|
28
|
+
print(output["documents"][0].content)
|
|
29
|
+
|
|
30
|
+
# Berlin
|
|
31
|
+
```
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
model_name: str = "Xenova/ms-marco-MiniLM-L-6-v2",
|
|
37
|
+
top_k: int = 10,
|
|
38
|
+
cache_dir: Optional[str] = None,
|
|
39
|
+
threads: Optional[int] = None,
|
|
40
|
+
batch_size: int = 64,
|
|
41
|
+
parallel: Optional[int] = None,
|
|
42
|
+
local_files_only: bool = False,
|
|
43
|
+
meta_fields_to_embed: Optional[List[str]] = None,
|
|
44
|
+
meta_data_separator: str = "\n",
|
|
45
|
+
):
|
|
46
|
+
"""
|
|
47
|
+
Creates an instance of the 'FastembedRanker'.
|
|
48
|
+
|
|
49
|
+
:param model_name: Fastembed model name. Check the list of supported models in the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/).
|
|
50
|
+
:param top_k: The maximum number of documents to return.
|
|
51
|
+
:param cache_dir: The path to the cache directory.
|
|
52
|
+
Can be set using the `FASTEMBED_CACHE_PATH` env variable.
|
|
53
|
+
Defaults to `fastembed_cache` in the system's temp directory.
|
|
54
|
+
:param threads: The number of threads single onnxruntime session can use. Defaults to None.
|
|
55
|
+
:param batch_size: Number of strings to encode at once.
|
|
56
|
+
:param parallel:
|
|
57
|
+
If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets.
|
|
58
|
+
If 0, use all available cores.
|
|
59
|
+
If None, don't use data-parallel processing, use default onnxruntime threading instead.
|
|
60
|
+
:param local_files_only: If `True`, only use the model files in the `cache_dir`.
|
|
61
|
+
:param meta_fields_to_embed: List of meta fields that should be concatenated
|
|
62
|
+
with the document content for reranking.
|
|
63
|
+
:param meta_data_separator: Separator used to concatenate the meta fields
|
|
64
|
+
to the Document content.
|
|
65
|
+
"""
|
|
66
|
+
if top_k <= 0:
|
|
67
|
+
msg = f"top_k must be > 0, but got {top_k}"
|
|
68
|
+
raise ValueError(msg)
|
|
69
|
+
|
|
70
|
+
self.model_name = model_name
|
|
71
|
+
self.top_k = top_k
|
|
72
|
+
self.cache_dir = cache_dir
|
|
73
|
+
self.threads = threads
|
|
74
|
+
self.batch_size = batch_size
|
|
75
|
+
self.parallel = parallel
|
|
76
|
+
self.local_files_only = local_files_only
|
|
77
|
+
self.meta_fields_to_embed = meta_fields_to_embed or []
|
|
78
|
+
self.meta_data_separator = meta_data_separator
|
|
79
|
+
self._model = None
|
|
80
|
+
|
|
81
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
82
|
+
"""
|
|
83
|
+
Serializes the component to a dictionary.
|
|
84
|
+
|
|
85
|
+
:returns:
|
|
86
|
+
Dictionary with serialized data.
|
|
87
|
+
"""
|
|
88
|
+
return default_to_dict(
|
|
89
|
+
self,
|
|
90
|
+
model_name=self.model_name,
|
|
91
|
+
top_k=self.top_k,
|
|
92
|
+
cache_dir=self.cache_dir,
|
|
93
|
+
threads=self.threads,
|
|
94
|
+
batch_size=self.batch_size,
|
|
95
|
+
parallel=self.parallel,
|
|
96
|
+
local_files_only=self.local_files_only,
|
|
97
|
+
meta_fields_to_embed=self.meta_fields_to_embed,
|
|
98
|
+
meta_data_separator=self.meta_data_separator,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def from_dict(cls, data: Dict[str, Any]) -> "FastembedRanker":
|
|
103
|
+
"""
|
|
104
|
+
Deserializes the component from a dictionary.
|
|
105
|
+
|
|
106
|
+
:param data:
|
|
107
|
+
The dictionary to deserialize from.
|
|
108
|
+
:returns:
|
|
109
|
+
The deserialized component.
|
|
110
|
+
"""
|
|
111
|
+
return default_from_dict(cls, data)
|
|
112
|
+
|
|
113
|
+
def warm_up(self):
|
|
114
|
+
"""
|
|
115
|
+
Initializes the component.
|
|
116
|
+
"""
|
|
117
|
+
if self._model is None:
|
|
118
|
+
self._model = TextCrossEncoder(
|
|
119
|
+
model_name=self.model_name,
|
|
120
|
+
cache_dir=self.cache_dir,
|
|
121
|
+
threads=self.threads,
|
|
122
|
+
local_files_only=self.local_files_only,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def _prepare_fastembed_input_docs(self, documents: List[Document]) -> List[str]:
|
|
126
|
+
"""
|
|
127
|
+
Prepare the input by concatenating the document text with the metadata fields specified.
|
|
128
|
+
:param documents: The list of Document objects.
|
|
129
|
+
|
|
130
|
+
:return: A list of strings to be given as input to Fastembed model.
|
|
131
|
+
"""
|
|
132
|
+
concatenated_input_list = []
|
|
133
|
+
for doc in documents:
|
|
134
|
+
meta_values_to_embed = [
|
|
135
|
+
str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta.get(key)
|
|
136
|
+
]
|
|
137
|
+
concatenated_input = self.meta_data_separator.join([*meta_values_to_embed, doc.content or ""])
|
|
138
|
+
concatenated_input_list.append(concatenated_input)
|
|
139
|
+
|
|
140
|
+
return concatenated_input_list
|
|
141
|
+
|
|
142
|
+
@component.output_types(documents=List[Document])
|
|
143
|
+
def run(self, query: str, documents: List[Document], top_k: Optional[int] = None):
|
|
144
|
+
"""
|
|
145
|
+
Returns a list of documents ranked by their similarity to the given query, using FastEmbed.
|
|
146
|
+
|
|
147
|
+
:param query:
|
|
148
|
+
The input query to compare the documents to.
|
|
149
|
+
:param documents:
|
|
150
|
+
A list of documents to be ranked.
|
|
151
|
+
:param top_k:
|
|
152
|
+
The maximum number of documents to return.
|
|
153
|
+
|
|
154
|
+
:returns:
|
|
155
|
+
A dictionary with the following keys:
|
|
156
|
+
- `documents`: A list of documents closest to the query, sorted from most similar to least similar.
|
|
157
|
+
|
|
158
|
+
:raises ValueError: If `top_k` is not > 0.
|
|
159
|
+
"""
|
|
160
|
+
if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):
|
|
161
|
+
msg = "FastembedRanker expects a list of Documents as input. "
|
|
162
|
+
raise TypeError(msg)
|
|
163
|
+
if query == "":
|
|
164
|
+
msg = "No query provided"
|
|
165
|
+
raise ValueError(msg)
|
|
166
|
+
|
|
167
|
+
if not documents:
|
|
168
|
+
return {"documents": []}
|
|
169
|
+
|
|
170
|
+
top_k = top_k or self.top_k
|
|
171
|
+
if top_k <= 0:
|
|
172
|
+
msg = f"top_k must be > 0, but got {top_k}"
|
|
173
|
+
raise ValueError(msg)
|
|
174
|
+
|
|
175
|
+
if self._model is None:
|
|
176
|
+
msg = "The ranker model has not been loaded. Please call warm_up() before running."
|
|
177
|
+
raise RuntimeError(msg)
|
|
178
|
+
|
|
179
|
+
fastembed_input_docs = self._prepare_fastembed_input_docs(documents)
|
|
180
|
+
|
|
181
|
+
scores = list(
|
|
182
|
+
self._model.rerank(
|
|
183
|
+
query=query,
|
|
184
|
+
documents=fastembed_input_docs,
|
|
185
|
+
batch_size=self.batch_size,
|
|
186
|
+
parallel=self.parallel,
|
|
187
|
+
)
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
# Combine the two lists into a single list of tuples
|
|
191
|
+
doc_scores = list(zip(documents, scores))
|
|
192
|
+
|
|
193
|
+
# Sort the list of tuples by the score in descending order
|
|
194
|
+
sorted_doc_scores = sorted(doc_scores, key=lambda x: x[1], reverse=True)
|
|
195
|
+
|
|
196
|
+
# Get the top_k documents
|
|
197
|
+
top_k_documents = []
|
|
198
|
+
for doc, score in sorted_doc_scores[:top_k]:
|
|
199
|
+
doc.score = score
|
|
200
|
+
top_k_documents.append(doc)
|
|
201
|
+
|
|
202
|
+
return {"documents": top_k_documents}
|
|
@@ -2,6 +2,7 @@ from unittest.mock import patch
|
|
|
2
2
|
|
|
3
3
|
from haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend import (
|
|
4
4
|
_FastembedEmbeddingBackendFactory,
|
|
5
|
+
_FastembedSparseEmbeddingBackendFactory,
|
|
5
6
|
)
|
|
6
7
|
|
|
7
8
|
|
|
@@ -44,3 +45,28 @@ def test_embedding_function_with_kwargs(mock_instructor): # noqa: ARG001
|
|
|
44
45
|
embedding_backend.model.embed.assert_called_once_with(data)
|
|
45
46
|
# restore the factory stateTrue
|
|
46
47
|
_FastembedEmbeddingBackendFactory._instances = {}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@patch("haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend.SparseTextEmbedding")
|
|
51
|
+
def test_model_kwargs_initialization(mock_instructor):
|
|
52
|
+
bm25_config = {
|
|
53
|
+
"k": 1.2,
|
|
54
|
+
"b": 0.75,
|
|
55
|
+
"avg_len": 300.0,
|
|
56
|
+
"language": "english",
|
|
57
|
+
"token_max_length": 40,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
# Invoke the backend factory with the BM25 configuration
|
|
61
|
+
_FastembedSparseEmbeddingBackendFactory.get_embedding_backend(
|
|
62
|
+
model_name="Qdrant/bm25",
|
|
63
|
+
model_kwargs=bm25_config,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Check if SparseTextEmbedding was called with the correct arguments
|
|
67
|
+
mock_instructor.assert_called_once_with(
|
|
68
|
+
model_name="Qdrant/bm25", cache_dir=None, threads=None, local_files_only=False, **bm25_config
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
# Restore factory state after the test
|
|
72
|
+
_FastembedSparseEmbeddingBackendFactory._instances = {}
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
from unittest.mock import MagicMock
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from haystack import Document, default_from_dict
|
|
5
|
+
|
|
6
|
+
from haystack_integrations.components.rankers.fastembed.ranker import (
|
|
7
|
+
FastembedRanker,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TestFastembedRanker:
|
|
12
|
+
def test_init_default(self):
|
|
13
|
+
"""
|
|
14
|
+
Test default initialization parameters for FastembedRanker.
|
|
15
|
+
"""
|
|
16
|
+
ranker = FastembedRanker(model_name="BAAI/bge-reranker-base")
|
|
17
|
+
assert ranker.model_name == "BAAI/bge-reranker-base"
|
|
18
|
+
assert ranker.top_k == 10
|
|
19
|
+
assert ranker.cache_dir is None
|
|
20
|
+
assert ranker.threads is None
|
|
21
|
+
assert ranker.batch_size == 64
|
|
22
|
+
assert ranker.parallel is None
|
|
23
|
+
assert not ranker.local_files_only
|
|
24
|
+
assert ranker.meta_fields_to_embed == []
|
|
25
|
+
assert ranker.meta_data_separator == "\n"
|
|
26
|
+
|
|
27
|
+
def test_init_with_parameters(self):
|
|
28
|
+
"""
|
|
29
|
+
Test custom initialization parameters for FastembedRanker.
|
|
30
|
+
"""
|
|
31
|
+
ranker = FastembedRanker(
|
|
32
|
+
model_name="BAAI/bge-reranker-base",
|
|
33
|
+
top_k=64,
|
|
34
|
+
cache_dir="fake_dir",
|
|
35
|
+
threads=2,
|
|
36
|
+
batch_size=50,
|
|
37
|
+
parallel=1,
|
|
38
|
+
local_files_only=True,
|
|
39
|
+
meta_fields_to_embed=["test_field"],
|
|
40
|
+
meta_data_separator=" | ",
|
|
41
|
+
)
|
|
42
|
+
assert ranker.model_name == "BAAI/bge-reranker-base"
|
|
43
|
+
assert ranker.top_k == 64
|
|
44
|
+
assert ranker.cache_dir == "fake_dir"
|
|
45
|
+
assert ranker.threads == 2
|
|
46
|
+
assert ranker.batch_size == 50
|
|
47
|
+
assert ranker.parallel == 1
|
|
48
|
+
assert ranker.local_files_only
|
|
49
|
+
assert ranker.meta_fields_to_embed == ["test_field"]
|
|
50
|
+
assert ranker.meta_data_separator == " | "
|
|
51
|
+
|
|
52
|
+
def test_init_with_incorrect_input(self):
|
|
53
|
+
"""
|
|
54
|
+
Test for checking incorrect input format on init
|
|
55
|
+
"""
|
|
56
|
+
with pytest.raises(
|
|
57
|
+
ValueError,
|
|
58
|
+
match="top_k must be > 0, but got 0",
|
|
59
|
+
):
|
|
60
|
+
FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-12-v2", top_k=0)
|
|
61
|
+
|
|
62
|
+
with pytest.raises(
|
|
63
|
+
ValueError,
|
|
64
|
+
match="top_k must be > 0, but got -3",
|
|
65
|
+
):
|
|
66
|
+
FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-12-v2", top_k=-3)
|
|
67
|
+
|
|
68
|
+
def test_to_dict(self):
|
|
69
|
+
"""
|
|
70
|
+
Test serialization of FastembedRanker to a dictionary, using default initialization parameters.
|
|
71
|
+
"""
|
|
72
|
+
ranker = FastembedRanker(model_name="BAAI/bge-reranker-base")
|
|
73
|
+
ranker_dict = ranker.to_dict()
|
|
74
|
+
assert ranker_dict == {
|
|
75
|
+
"type": "haystack_integrations.components.rankers.fastembed.ranker.FastembedRanker",
|
|
76
|
+
"init_parameters": {
|
|
77
|
+
"model_name": "BAAI/bge-reranker-base",
|
|
78
|
+
"top_k": 10,
|
|
79
|
+
"cache_dir": None,
|
|
80
|
+
"threads": None,
|
|
81
|
+
"batch_size": 64,
|
|
82
|
+
"parallel": None,
|
|
83
|
+
"local_files_only": False,
|
|
84
|
+
"meta_fields_to_embed": [],
|
|
85
|
+
"meta_data_separator": "\n",
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
def test_to_dict_with_custom_init_parameters(self):
|
|
90
|
+
"""
|
|
91
|
+
Test serialization of FastembedRanker to a dictionary, using custom initialization parameters.
|
|
92
|
+
"""
|
|
93
|
+
ranker = FastembedRanker(
|
|
94
|
+
model_name="BAAI/bge-reranker-base",
|
|
95
|
+
cache_dir="fake_dir",
|
|
96
|
+
threads=2,
|
|
97
|
+
top_k=5,
|
|
98
|
+
batch_size=50,
|
|
99
|
+
parallel=1,
|
|
100
|
+
local_files_only=True,
|
|
101
|
+
meta_fields_to_embed=["test_field"],
|
|
102
|
+
meta_data_separator=" | ",
|
|
103
|
+
)
|
|
104
|
+
ranker_dict = ranker.to_dict()
|
|
105
|
+
assert ranker_dict == {
|
|
106
|
+
"type": "haystack_integrations.components.rankers.fastembed.ranker.FastembedRanker",
|
|
107
|
+
"init_parameters": {
|
|
108
|
+
"model_name": "BAAI/bge-reranker-base",
|
|
109
|
+
"cache_dir": "fake_dir",
|
|
110
|
+
"threads": 2,
|
|
111
|
+
"top_k": 5,
|
|
112
|
+
"batch_size": 50,
|
|
113
|
+
"parallel": 1,
|
|
114
|
+
"local_files_only": True,
|
|
115
|
+
"meta_fields_to_embed": ["test_field"],
|
|
116
|
+
"meta_data_separator": " | ",
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
def test_from_dict(self):
|
|
121
|
+
"""
|
|
122
|
+
Test deserialization of FastembedRanker from a dictionary, using default initialization parameters.
|
|
123
|
+
"""
|
|
124
|
+
ranker_dict = {
|
|
125
|
+
"type": "haystack_integrations.components.rankers.fastembed.ranker.FastembedRanker",
|
|
126
|
+
"init_parameters": {
|
|
127
|
+
"model_name": "BAAI/bge-reranker-base",
|
|
128
|
+
"cache_dir": None,
|
|
129
|
+
"threads": None,
|
|
130
|
+
"top_k": 5,
|
|
131
|
+
"batch_size": 50,
|
|
132
|
+
"parallel": None,
|
|
133
|
+
"local_files_only": False,
|
|
134
|
+
"meta_fields_to_embed": [],
|
|
135
|
+
"meta_data_separator": "\n",
|
|
136
|
+
},
|
|
137
|
+
}
|
|
138
|
+
ranker = default_from_dict(FastembedRanker, ranker_dict)
|
|
139
|
+
assert ranker.model_name == "BAAI/bge-reranker-base"
|
|
140
|
+
assert ranker.cache_dir is None
|
|
141
|
+
assert ranker.threads is None
|
|
142
|
+
assert ranker.top_k == 5
|
|
143
|
+
assert ranker.batch_size == 50
|
|
144
|
+
assert ranker.parallel is None
|
|
145
|
+
assert not ranker.local_files_only
|
|
146
|
+
assert ranker.meta_fields_to_embed == []
|
|
147
|
+
assert ranker.meta_data_separator == "\n"
|
|
148
|
+
|
|
149
|
+
def test_from_dict_with_custom_init_parameters(self):
|
|
150
|
+
"""
|
|
151
|
+
Test deserialization of FastembedRanker from a dictionary, using custom initialization parameters.
|
|
152
|
+
"""
|
|
153
|
+
ranker_dict = {
|
|
154
|
+
"type": "haystack_integrations.components.rankers.fastembed.ranker.FastembedRanker",
|
|
155
|
+
"init_parameters": {
|
|
156
|
+
"model_name": "BAAI/bge-reranker-base",
|
|
157
|
+
"cache_dir": "fake_dir",
|
|
158
|
+
"threads": 2,
|
|
159
|
+
"top_k": 5,
|
|
160
|
+
"batch_size": 50,
|
|
161
|
+
"parallel": 1,
|
|
162
|
+
"local_files_only": True,
|
|
163
|
+
"meta_fields_to_embed": ["test_field"],
|
|
164
|
+
"meta_data_separator": " | ",
|
|
165
|
+
},
|
|
166
|
+
}
|
|
167
|
+
ranker = default_from_dict(FastembedRanker, ranker_dict)
|
|
168
|
+
assert ranker.model_name == "BAAI/bge-reranker-base"
|
|
169
|
+
assert ranker.cache_dir == "fake_dir"
|
|
170
|
+
assert ranker.threads == 2
|
|
171
|
+
assert ranker.top_k == 5
|
|
172
|
+
assert ranker.batch_size == 50
|
|
173
|
+
assert ranker.parallel == 1
|
|
174
|
+
assert ranker.local_files_only
|
|
175
|
+
assert ranker.meta_fields_to_embed == ["test_field"]
|
|
176
|
+
assert ranker.meta_data_separator == " | "
|
|
177
|
+
|
|
178
|
+
def test_run_incorrect_input_format(self):
|
|
179
|
+
"""
|
|
180
|
+
Test for checking incorrect input format.
|
|
181
|
+
"""
|
|
182
|
+
ranker = FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-12-v2")
|
|
183
|
+
ranker._model = "mock_model"
|
|
184
|
+
|
|
185
|
+
query = "query"
|
|
186
|
+
string_input = "text"
|
|
187
|
+
list_integers_input = [1, 2, 3]
|
|
188
|
+
list_document = [Document("Document 1")]
|
|
189
|
+
|
|
190
|
+
with pytest.raises(
|
|
191
|
+
TypeError,
|
|
192
|
+
match="FastembedRanker expects a list of Documents as input.",
|
|
193
|
+
):
|
|
194
|
+
ranker.run(query=query, documents=string_input)
|
|
195
|
+
|
|
196
|
+
with pytest.raises(
|
|
197
|
+
TypeError,
|
|
198
|
+
match="FastembedRanker expects a list of Documents as input.",
|
|
199
|
+
):
|
|
200
|
+
ranker.run(query=query, documents=list_integers_input)
|
|
201
|
+
|
|
202
|
+
with pytest.raises(
|
|
203
|
+
ValueError,
|
|
204
|
+
match="No query provided",
|
|
205
|
+
):
|
|
206
|
+
ranker.run(query="", documents=list_document)
|
|
207
|
+
|
|
208
|
+
with pytest.raises(
|
|
209
|
+
ValueError,
|
|
210
|
+
match="top_k must be > 0, but got -3",
|
|
211
|
+
):
|
|
212
|
+
ranker.run(query=query, documents=list_document, top_k=-3)
|
|
213
|
+
|
|
214
|
+
def test_run_no_warmup(self):
|
|
215
|
+
"""
|
|
216
|
+
Test for checking error when calling without a warmup.
|
|
217
|
+
"""
|
|
218
|
+
ranker = FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-12-v2")
|
|
219
|
+
|
|
220
|
+
query = "query"
|
|
221
|
+
list_document = [Document("Document 1")]
|
|
222
|
+
|
|
223
|
+
with pytest.raises(
|
|
224
|
+
RuntimeError,
|
|
225
|
+
):
|
|
226
|
+
ranker.run(query=query, documents=list_document)
|
|
227
|
+
|
|
228
|
+
def test_run_empty_document_list(self):
|
|
229
|
+
"""
|
|
230
|
+
Test for no error when sending no documents.
|
|
231
|
+
"""
|
|
232
|
+
ranker = FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-12-v2")
|
|
233
|
+
ranker._model = "mock_model"
|
|
234
|
+
|
|
235
|
+
query = "query"
|
|
236
|
+
list_document = []
|
|
237
|
+
|
|
238
|
+
result = ranker.run(query=query, documents=list_document)
|
|
239
|
+
assert len(result["documents"]) == 0
|
|
240
|
+
|
|
241
|
+
def test_embed_metadata(self):
|
|
242
|
+
"""
|
|
243
|
+
Tests the embedding of metadata fields in document content for ranking.
|
|
244
|
+
"""
|
|
245
|
+
ranker = FastembedRanker(
|
|
246
|
+
model_name="model_name",
|
|
247
|
+
meta_fields_to_embed=["meta_field"],
|
|
248
|
+
)
|
|
249
|
+
ranker._model = MagicMock()
|
|
250
|
+
|
|
251
|
+
documents = [Document(content=f"document-number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)]
|
|
252
|
+
query = "test"
|
|
253
|
+
ranker.run(query=query, documents=documents)
|
|
254
|
+
|
|
255
|
+
ranker._model.rerank.assert_called_once_with(
|
|
256
|
+
query=query,
|
|
257
|
+
documents=[
|
|
258
|
+
"meta_value 0\ndocument-number 0",
|
|
259
|
+
"meta_value 1\ndocument-number 1",
|
|
260
|
+
"meta_value 2\ndocument-number 2",
|
|
261
|
+
"meta_value 3\ndocument-number 3",
|
|
262
|
+
"meta_value 4\ndocument-number 4",
|
|
263
|
+
],
|
|
264
|
+
batch_size=64,
|
|
265
|
+
parallel=None,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
@pytest.mark.integration
|
|
269
|
+
def test_run(self):
|
|
270
|
+
ranker = FastembedRanker(model_name="Xenova/ms-marco-MiniLM-L-6-v2", top_k=2)
|
|
271
|
+
ranker.warm_up()
|
|
272
|
+
|
|
273
|
+
query = "Who is maintaining Qdrant?"
|
|
274
|
+
documents = [
|
|
275
|
+
Document(
|
|
276
|
+
content="This is built to be faster and lighter than other embedding \
|
|
277
|
+
libraries e.g. Transformers, Sentence-Transformers, etc."
|
|
278
|
+
),
|
|
279
|
+
Document(content="This is some random input"),
|
|
280
|
+
Document(content="fastembed is supported by and maintained by Qdrant."),
|
|
281
|
+
]
|
|
282
|
+
|
|
283
|
+
result = ranker.run(query=query, documents=documents)
|
|
284
|
+
|
|
285
|
+
assert len(result["documents"]) == 2
|
|
286
|
+
first_document = result["documents"][0]
|
|
287
|
+
second_document = result["documents"][1]
|
|
288
|
+
|
|
289
|
+
assert isinstance(first_document, Document)
|
|
290
|
+
assert isinstance(second_document, Document)
|
|
291
|
+
assert first_document.content == "fastembed is supported by and maintained by Qdrant."
|
|
292
|
+
assert first_document.score > second_document.score
|
|
@@ -4,6 +4,7 @@ import numpy as np
|
|
|
4
4
|
import pytest
|
|
5
5
|
from haystack import Document, default_from_dict
|
|
6
6
|
from haystack.dataclasses.sparse_embedding import SparseEmbedding
|
|
7
|
+
|
|
7
8
|
from haystack_integrations.components.embedders.fastembed.fastembed_sparse_document_embedder import (
|
|
8
9
|
FastembedSparseDocumentEmbedder,
|
|
9
10
|
)
|
|
@@ -68,6 +69,7 @@ class TestFastembedSparseDocumentEmbedderDoc:
|
|
|
68
69
|
"local_files_only": False,
|
|
69
70
|
"embedding_separator": "\n",
|
|
70
71
|
"meta_fields_to_embed": [],
|
|
72
|
+
"model_kwargs": None,
|
|
71
73
|
},
|
|
72
74
|
}
|
|
73
75
|
|
|
@@ -99,6 +101,7 @@ class TestFastembedSparseDocumentEmbedderDoc:
|
|
|
99
101
|
"local_files_only": True,
|
|
100
102
|
"meta_fields_to_embed": ["test_field"],
|
|
101
103
|
"embedding_separator": " | ",
|
|
104
|
+
"model_kwargs": None,
|
|
102
105
|
},
|
|
103
106
|
}
|
|
104
107
|
|
|
@@ -173,7 +176,11 @@ class TestFastembedSparseDocumentEmbedderDoc:
|
|
|
173
176
|
mocked_factory.get_embedding_backend.assert_not_called()
|
|
174
177
|
embedder.warm_up()
|
|
175
178
|
mocked_factory.get_embedding_backend.assert_called_once_with(
|
|
176
|
-
model_name="prithvida/Splade_PP_en_v1",
|
|
179
|
+
model_name="prithvida/Splade_PP_en_v1",
|
|
180
|
+
cache_dir=None,
|
|
181
|
+
threads=None,
|
|
182
|
+
local_files_only=False,
|
|
183
|
+
model_kwargs=None,
|
|
177
184
|
)
|
|
178
185
|
|
|
179
186
|
@patch(
|
|
@@ -274,6 +281,52 @@ class TestFastembedSparseDocumentEmbedderDoc:
|
|
|
274
281
|
parallel=None,
|
|
275
282
|
)
|
|
276
283
|
|
|
284
|
+
def test_init_with_model_kwargs_parameters(self):
|
|
285
|
+
"""
|
|
286
|
+
Test initialization of FastembedSparseDocumentEmbedder with model_kwargs parameters.
|
|
287
|
+
"""
|
|
288
|
+
bm25_config = {
|
|
289
|
+
"k": 1.2,
|
|
290
|
+
"b": 0.75,
|
|
291
|
+
"avg_len": 300.0,
|
|
292
|
+
"language": "english",
|
|
293
|
+
"token_max_length": 50,
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
embedder = FastembedSparseDocumentEmbedder(
|
|
297
|
+
model="Qdrant/bm25",
|
|
298
|
+
model_kwargs=bm25_config,
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
assert embedder.model_kwargs == bm25_config
|
|
302
|
+
|
|
303
|
+
@pytest.mark.integration
|
|
304
|
+
def test_run_with_model_kwargs(self):
|
|
305
|
+
"""
|
|
306
|
+
Integration test to check the embedding with model_kwargs parameters.
|
|
307
|
+
"""
|
|
308
|
+
bm42_config = {
|
|
309
|
+
"alpha": 0.2,
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
embedder = FastembedSparseDocumentEmbedder(
|
|
313
|
+
model="Qdrant/bm42-all-minilm-l6-v2-attentions",
|
|
314
|
+
model_kwargs=bm42_config,
|
|
315
|
+
)
|
|
316
|
+
embedder.warm_up()
|
|
317
|
+
|
|
318
|
+
doc = Document(content="Example content using BM42")
|
|
319
|
+
|
|
320
|
+
result = embedder.run(documents=[doc])
|
|
321
|
+
embedding = result["documents"][0].sparse_embedding
|
|
322
|
+
embedding_dict = embedding.to_dict()
|
|
323
|
+
|
|
324
|
+
assert isinstance(embedding, SparseEmbedding)
|
|
325
|
+
assert isinstance(embedding_dict["indices"], list)
|
|
326
|
+
assert isinstance(embedding_dict["values"], list)
|
|
327
|
+
assert isinstance(embedding_dict["indices"][0], int)
|
|
328
|
+
assert isinstance(embedding_dict["values"][0], float)
|
|
329
|
+
|
|
277
330
|
@pytest.mark.integration
|
|
278
331
|
def test_run(self):
|
|
279
332
|
embedder = FastembedSparseDocumentEmbedder(
|
{fastembed_haystack-1.2.0 → fastembed_haystack-1.4.0}/tests/test_fastembed_sparse_text_embedder.py
RENAMED
|
@@ -4,6 +4,7 @@ import numpy as np
|
|
|
4
4
|
import pytest
|
|
5
5
|
from haystack import default_from_dict
|
|
6
6
|
from haystack.dataclasses.sparse_embedding import SparseEmbedding
|
|
7
|
+
|
|
7
8
|
from haystack_integrations.components.embedders.fastembed.fastembed_sparse_text_embedder import (
|
|
8
9
|
FastembedSparseTextEmbedder,
|
|
9
10
|
)
|
|
@@ -53,6 +54,7 @@ class TestFastembedSparseTextEmbedder:
|
|
|
53
54
|
"progress_bar": True,
|
|
54
55
|
"parallel": None,
|
|
55
56
|
"local_files_only": False,
|
|
57
|
+
"model_kwargs": None,
|
|
56
58
|
},
|
|
57
59
|
}
|
|
58
60
|
|
|
@@ -78,6 +80,7 @@ class TestFastembedSparseTextEmbedder:
|
|
|
78
80
|
"progress_bar": False,
|
|
79
81
|
"parallel": 1,
|
|
80
82
|
"local_files_only": True,
|
|
83
|
+
"model_kwargs": None,
|
|
81
84
|
},
|
|
82
85
|
}
|
|
83
86
|
|
|
@@ -134,7 +137,11 @@ class TestFastembedSparseTextEmbedder:
|
|
|
134
137
|
mocked_factory.get_embedding_backend.assert_not_called()
|
|
135
138
|
embedder.warm_up()
|
|
136
139
|
mocked_factory.get_embedding_backend.assert_called_once_with(
|
|
137
|
-
model_name="prithvida/Splade_PP_en_v1",
|
|
140
|
+
model_name="prithvida/Splade_PP_en_v1",
|
|
141
|
+
cache_dir=None,
|
|
142
|
+
threads=None,
|
|
143
|
+
local_files_only=False,
|
|
144
|
+
model_kwargs=None,
|
|
138
145
|
)
|
|
139
146
|
|
|
140
147
|
@patch(
|
|
@@ -194,6 +201,54 @@ class TestFastembedSparseTextEmbedder:
|
|
|
194
201
|
with pytest.raises(TypeError, match="FastembedSparseTextEmbedder expects a string as input"):
|
|
195
202
|
embedder.run(text=list_integers_input)
|
|
196
203
|
|
|
204
|
+
def test_init_with_model_kwargs_parameters(self):
|
|
205
|
+
"""
|
|
206
|
+
Test initialization of FastembedSparseTextEmbedder with model_kwargs parameters.
|
|
207
|
+
"""
|
|
208
|
+
bm25_config = {
|
|
209
|
+
"k": 1.2,
|
|
210
|
+
"b": 0.75,
|
|
211
|
+
"avg_len": 300.0,
|
|
212
|
+
"language": "english",
|
|
213
|
+
"token_max_length": 50,
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
embedder = FastembedSparseTextEmbedder(
|
|
217
|
+
model="Qdrant/bm25",
|
|
218
|
+
model_kwargs=bm25_config,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
assert embedder.model_kwargs == bm25_config
|
|
222
|
+
|
|
223
|
+
@pytest.mark.integration
|
|
224
|
+
def test_run_with_model_kwargs(self):
|
|
225
|
+
"""
|
|
226
|
+
Integration test to check the embedding with model_kwargs parameters.
|
|
227
|
+
"""
|
|
228
|
+
bm25_config = {
|
|
229
|
+
"k": 1.2,
|
|
230
|
+
"b": 0.75,
|
|
231
|
+
"avg_len": 256.0,
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
embedder = FastembedSparseTextEmbedder(
|
|
235
|
+
model="Qdrant/bm25",
|
|
236
|
+
model_kwargs=bm25_config,
|
|
237
|
+
)
|
|
238
|
+
embedder.warm_up()
|
|
239
|
+
|
|
240
|
+
text = "Example content using BM25"
|
|
241
|
+
|
|
242
|
+
result = embedder.run(text=text)
|
|
243
|
+
embedding = result["sparse_embedding"]
|
|
244
|
+
embedding_dict = embedding.to_dict()
|
|
245
|
+
|
|
246
|
+
assert isinstance(embedding, SparseEmbedding)
|
|
247
|
+
assert isinstance(embedding_dict["indices"], list)
|
|
248
|
+
assert isinstance(embedding_dict["values"], list)
|
|
249
|
+
assert isinstance(embedding_dict["indices"][0], int)
|
|
250
|
+
assert isinstance(embedding_dict["values"][0], float)
|
|
251
|
+
|
|
197
252
|
@pytest.mark.integration
|
|
198
253
|
def test_run(self):
|
|
199
254
|
embedder = FastembedSparseTextEmbedder(
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|