fastembed-haystack 0.0.1__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.
@@ -0,0 +1,136 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ volumes/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96
+ __pypackages__/
97
+
98
+ # Celery stuff
99
+ celerybeat-schedule
100
+ celerybeat.pid
101
+
102
+ # SageMath parsed files
103
+ *.sage.py
104
+
105
+ # Environments
106
+ .env
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+
114
+ # Spyder project settings
115
+ .spyderproject
116
+ .spyproject
117
+
118
+ # Rope project settings
119
+ .ropeproject
120
+
121
+ # mkdocs documentation
122
+ /site
123
+
124
+ # mypy
125
+ .mypy_cache/
126
+ .dmypy.json
127
+ dmypy.json
128
+
129
+ # Pyre type checker
130
+ .pyre/
131
+
132
+ # IDEs
133
+ .vscode
134
+
135
+ # Docs generation artifacts
136
+ _readme_*.md
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.1
2
+ Name: fastembed-haystack
3
+ Version: 0.0.1
4
+ Summary: Haystack 2.x component to embed strings and Documents using fastembed embedding model
5
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations
6
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/README.md
7
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: Implementation :: CPython
19
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
20
+ Requires-Python: >=3.8
21
+ Requires-Dist: fastembed>=0.2
22
+ Requires-Dist: haystack-ai
23
+ Description-Content-Type: text/markdown
24
+
25
+ # fastembed-haystack
26
+
27
+ [![PyPI - Version](https://img.shields.io/pypi/v/fastembed-haystack.svg)](https://pypi.org/project/fastembed-haystack)
28
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastembed-haystack.svg)](https://pypi.org/project/fastembed-haystack)
29
+
30
+ -----
31
+
32
+ **Table of Contents**
33
+
34
+ - [Installation](#installation)
35
+ - [License](#license)
36
+
37
+ ## Installation
38
+
39
+ ```console
40
+ pip install fastembed-haystack
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ You can use `FastembedTextEmbedder` and `FastembedDocumentEmbedder` by importing as:
46
+
47
+ ```python
48
+ from fastembed_haystack.fastembed_text_embedder import FastembedTextEmbedder
49
+
50
+ text = "fastembed is supported by and maintained by Qdrant."
51
+ text_embedder = FastembedTextEmbedder(
52
+ model="BAAI/bge-small-en-v1.5"
53
+ )
54
+ embedding = text_embedder.run(text)
55
+ ```
56
+
57
+ ```python
58
+ from fastembed_haystack.fastembed__document_embedder import FastembedDocumentEmbedder
59
+ from haystack.dataclasses import Document
60
+
61
+ embedder = FastembedDocumentEmbedder(
62
+ model="BAAI/bge-small-en-v1.5",
63
+ )
64
+ embedder.warm_up()
65
+ doc = Document(content="fastembed is supported by and maintained by Qdrant.", meta={"long_answer": "no",})
66
+ result = embedder.run(documents=[doc])
67
+ ```
68
+
69
+ ## License
70
+
71
+ `fastembed-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,47 @@
1
+ # fastembed-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/fastembed-haystack.svg)](https://pypi.org/project/fastembed-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastembed-haystack.svg)](https://pypi.org/project/fastembed-haystack)
5
+
6
+ -----
7
+
8
+ **Table of Contents**
9
+
10
+ - [Installation](#installation)
11
+ - [License](#license)
12
+
13
+ ## Installation
14
+
15
+ ```console
16
+ pip install fastembed-haystack
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ You can use `FastembedTextEmbedder` and `FastembedDocumentEmbedder` by importing as:
22
+
23
+ ```python
24
+ from fastembed_haystack.fastembed_text_embedder import FastembedTextEmbedder
25
+
26
+ text = "fastembed is supported by and maintained by Qdrant."
27
+ text_embedder = FastembedTextEmbedder(
28
+ model="BAAI/bge-small-en-v1.5"
29
+ )
30
+ embedding = text_embedder.run(text)
31
+ ```
32
+
33
+ ```python
34
+ from fastembed_haystack.fastembed__document_embedder import FastembedDocumentEmbedder
35
+ from haystack.dataclasses import Document
36
+
37
+ embedder = FastembedDocumentEmbedder(
38
+ model="BAAI/bge-small-en-v1.5",
39
+ )
40
+ embedder.warm_up()
41
+ doc = Document(content="fastembed is supported by and maintained by Qdrant.", meta={"long_answer": "no",})
42
+ result = embedder.run(documents=[doc])
43
+ ```
44
+
45
+ ## License
46
+
47
+ `fastembed-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,30 @@
1
+ loaders:
2
+ - type: haystack_pydoc_tools.loaders.CustomPythonLoader
3
+ search_path: [../src]
4
+ modules:
5
+ [
6
+ "haystack_integrations.components.embedders.fastembed",
7
+ "haystack_integrations.components.embedders.fastembed.embedding_backend",
8
+ ]
9
+ ignore_when_discovered: ["__init__"]
10
+ processors:
11
+ - type: filter
12
+ expression:
13
+ documented_only: true
14
+ do_not_filter_modules: false
15
+ skip_empty_modules: true
16
+ - type: smart
17
+ - type: crossref
18
+ renderer:
19
+ type: haystack_pydoc_tools.renderers.ReadmePreviewRenderer
20
+ excerpt: Embedders integration for Haystack
21
+ category_slug: haystack-integrations
22
+ title: Embedders
23
+ slug: fastembed-embedders
24
+ order: 300
25
+ markdown:
26
+ descriptive_class_title: false
27
+ descriptive_module_title: true
28
+ add_method_class_prefix: true
29
+ add_member_class_prefix: false
30
+ filename: _readme_fastembed.md
@@ -0,0 +1,185 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "fastembed-haystack"
7
+ dynamic = ["version"]
8
+ description = "Haystack 2.x component to embed strings and Documents using fastembed embedding model"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "Apache-2.0"
12
+ keywords = []
13
+ authors = [
14
+ { name = "deepset GmbH", email = "info@deepset.ai" },
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Programming Language :: Python",
19
+ "Programming Language :: Python :: 3.8",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: Implementation :: CPython",
25
+ "Programming Language :: Python :: Implementation :: PyPy",
26
+ ]
27
+ dependencies = [
28
+ "haystack-ai",
29
+ "fastembed>=0.2",
30
+ ]
31
+
32
+ [project.urls]
33
+ Source = "https://github.com/deepset-ai/haystack-core-integrations"
34
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/README.md"
35
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/haystack_integrations"]
39
+
40
+ [tool.hatch.version]
41
+ source = "vcs"
42
+ tag-pattern = 'integrations\/fastembed-v(?P<version>.*)'
43
+
44
+ [tool.hatch.version.raw-options]
45
+ root = "../.."
46
+ git_describe_command = 'git describe --tags --match="integrations/fastembed-v[0-9]*"'
47
+
48
+ [tool.hatch.envs.default]
49
+ dependencies = [
50
+ "coverage[toml]>=6.5",
51
+ "pytest",
52
+ "ipython",
53
+ "haystack-pydoc-tools",
54
+ ]
55
+ [tool.hatch.envs.default.scripts]
56
+ test = "pytest {args:tests}"
57
+ test-cov = "coverage run -m pytest {args:tests}"
58
+ cov-report = [
59
+ "- coverage combine",
60
+ "coverage report",
61
+ ]
62
+ cov = [
63
+ "test-cov",
64
+ "cov-report",
65
+ ]
66
+ docs = [
67
+ "pydoc-markdown pydoc/config.yml"
68
+ ]
69
+
70
+ [[tool.hatch.envs.all.matrix]]
71
+ python = ["3.8", "3.9", "3.10", "3.11", "3.12"]
72
+
73
+ [tool.hatch.envs.lint]
74
+ detached = true
75
+ dependencies = [
76
+ "black>=23.1.0",
77
+ "mypy>=1.0.0",
78
+ "ruff>=0.0.243",
79
+ "numpy"
80
+ ]
81
+ [tool.hatch.envs.lint.scripts]
82
+ typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}"
83
+ style = [
84
+ "ruff {args:.}",
85
+ "black --check --diff {args:.}",
86
+ ]
87
+ fmt = [
88
+ "black {args:.}",
89
+ "ruff --fix {args:.}",
90
+ "style",
91
+ ]
92
+ all = [
93
+ "style",
94
+ "typing",
95
+ ]
96
+
97
+ [tool.black]
98
+ target-version = ["py37"]
99
+ line-length = 120
100
+ skip-string-normalization = true
101
+
102
+ [tool.ruff]
103
+ target-version = "py37"
104
+ line-length = 120
105
+ select = [
106
+ "A",
107
+ "ARG",
108
+ "B",
109
+ "C",
110
+ "DTZ",
111
+ "E",
112
+ "EM",
113
+ "F",
114
+ "FBT",
115
+ "I",
116
+ "ICN",
117
+ "ISC",
118
+ "N",
119
+ "PLC",
120
+ "PLE",
121
+ "PLR",
122
+ "PLW",
123
+ "Q",
124
+ "RUF",
125
+ "S",
126
+ "T",
127
+ "TID",
128
+ "UP",
129
+ "W",
130
+ "YTT",
131
+ ]
132
+ ignore = [
133
+ # Allow non-abstract empty methods in abstract base classes
134
+ "B027",
135
+ # Allow boolean positional values in function calls, like `dict.get(... True)`
136
+ "FBT003",
137
+ "FBT001", "FBT002",
138
+ # Ignore checks for possible passwords
139
+ "S105", "S106", "S107",
140
+ # Ignore complexity
141
+ "C901", "PLR0911", "PLR0912", "PLR0913", "PLR0915",
142
+ ]
143
+ unfixable = [
144
+ # Don't touch unused imports
145
+ "F401",
146
+ ]
147
+
148
+ [tool.ruff.isort]
149
+ known-first-party = ["src"]
150
+
151
+ [tool.ruff.flake8-tidy-imports]
152
+ ban-relative-imports = "parents"
153
+
154
+ [tool.ruff.per-file-ignores]
155
+ # Tests can use magic values, assertions, and relative imports
156
+ "tests/**/*" = ["PLR2004", "S101", "TID252"]
157
+ # examples can contain "print" commands
158
+ "examples/**/*" = ["T201"]
159
+
160
+ [tool.coverage.run]
161
+ source_pkgs = ["src", "tests"]
162
+ branch = true
163
+ parallel = true
164
+
165
+
166
+ [tool.coverage.paths]
167
+ fastembed_haystack = ["src/haystack_integrations", "*/fastembed-haystack/src"]
168
+ tests = ["tests", "*/fastembed-haystack/tests"]
169
+
170
+ [tool.coverage.report]
171
+ exclude_lines = [
172
+ "no cov",
173
+ "if __name__ == .__main__.:",
174
+ "if TYPE_CHECKING:",
175
+ ]
176
+
177
+ [[tool.mypy.overrides]]
178
+ module = [
179
+ "haystack.*",
180
+ "haystack_integrations.*",
181
+ "fastembed.*",
182
+ "pytest.*",
183
+ "numpy.*"
184
+ ]
185
+ ignore_missing_imports = true
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2024-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from .fastembed_document_embedder import FastembedDocumentEmbedder
5
+ from .fastembed_text_embedder import FastembedTextEmbedder
6
+
7
+ __all__ = ["FastembedDocumentEmbedder", "FastembedTextEmbedder"]
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,42 @@
1
+ from typing import ClassVar, Dict, List
2
+
3
+ from fastembed import TextEmbedding
4
+
5
+
6
+ class _FastembedEmbeddingBackendFactory:
7
+ """
8
+ Factory class to create instances of fastembed embedding backends.
9
+ """
10
+
11
+ _instances: ClassVar[Dict[str, "_FastembedEmbeddingBackend"]] = {}
12
+
13
+ @staticmethod
14
+ def get_embedding_backend(
15
+ model_name: str,
16
+ ):
17
+ embedding_backend_id = f"{model_name}"
18
+
19
+ if embedding_backend_id in _FastembedEmbeddingBackendFactory._instances:
20
+ return _FastembedEmbeddingBackendFactory._instances[embedding_backend_id]
21
+
22
+ embedding_backend = _FastembedEmbeddingBackend(
23
+ model_name=model_name,
24
+ )
25
+ _FastembedEmbeddingBackendFactory._instances[embedding_backend_id] = embedding_backend
26
+ return embedding_backend
27
+
28
+
29
+ class _FastembedEmbeddingBackend:
30
+ """
31
+ Class to manage fastembed embeddings.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ model_name: str,
37
+ ):
38
+ self.model = TextEmbedding(model_name=model_name)
39
+
40
+ def embed(self, data: List[List[str]], **kwargs) -> List[List[float]]:
41
+ embeddings = list(self.model.embed(data, **kwargs))
42
+ return embeddings
@@ -0,0 +1,135 @@
1
+ from typing import Any, Dict, List, Optional
2
+
3
+ from haystack import Document, component, default_to_dict
4
+
5
+ from .embedding_backend.fastembed_backend import _FastembedEmbeddingBackendFactory
6
+
7
+
8
+ @component
9
+ class FastembedDocumentEmbedder:
10
+ """
11
+ A component for computing Document embeddings using Fastembed embedding models.
12
+ The embedding of each Document is stored in the `embedding` field of the Document.
13
+
14
+ Usage example:
15
+ ```python
16
+ # To use this component, install the "fastembed-haystack" package.
17
+ # pip install fastembed-haystack
18
+
19
+ from fastembed_haystack.fastembed__document_embedder import FastembedDocumentEmbedder
20
+ from haystack.dataclasses import Document
21
+
22
+ doc_embedder = FastembedDocumentEmbedder(
23
+ model="BAAI/bge-small-en-v1.5",
24
+ batch_size=256,
25
+ )
26
+
27
+ doc_embedder.warm_up()
28
+
29
+ # Text taken from PubMed QA Dataset (https://huggingface.co/datasets/pubmed_qa)
30
+ document_list = [
31
+ Document(
32
+ content="Oxidative stress generated within inflammatory joints can produce autoimmune phenomena and joint destruction. Radical species with oxidative activity, including reactive nitrogen species, represent mediators of inflammation and cartilage damage.",
33
+ meta={
34
+ "pubid": "25,445,628",
35
+ "long_answer": "yes",
36
+ },
37
+ ),
38
+ Document(
39
+ content="Plasma levels of pancreatic polypeptide (PP) rise upon food intake. Although other pancreatic islet hormones, such as insulin and glucagon, have been extensively investigated, PP secretion and actions are still poorly understood.",
40
+ meta={
41
+ "pubid": "25,445,712",
42
+ "long_answer": "yes",
43
+ },
44
+ ),
45
+ ]
46
+
47
+ result = doc_embedder.run(document_list)
48
+ print(f"Document Text: {result['documents'][0].content}")
49
+ print(f"Document Embedding: {result['documents'][0].embedding}")
50
+ print(f"Embedding Dimension: {len(result['documents'][0].embedding)}")
51
+ """ # noqa: E501
52
+
53
+ def __init__(
54
+ self,
55
+ model: str = "BAAI/bge-small-en-v1.5",
56
+ batch_size: int = 256,
57
+ progress_bar: bool = True,
58
+ meta_fields_to_embed: Optional[List[str]] = None,
59
+ embedding_separator: str = "\n",
60
+ ):
61
+ """
62
+ Create an FastembedDocumentEmbedder component.
63
+
64
+ :param model: Local path or name of the model in Hugging Face's model hub,
65
+ such as ``'BAAI/bge-small-en-v1.5'``.
66
+ :param batch_size: Number of strings to encode at once.
67
+ :param progress_bar: If true, displays progress bar during embedding.
68
+ :param meta_fields_to_embed: List of meta fields that should be embedded along with the Document content.
69
+ :param embedding_separator: Separator used to concatenate the meta fields to the Document content.
70
+ """
71
+
72
+ self.model_name = model
73
+ self.batch_size = batch_size
74
+ self.progress_bar = progress_bar
75
+ self.meta_fields_to_embed = meta_fields_to_embed or []
76
+ self.embedding_separator = embedding_separator
77
+
78
+ def to_dict(self) -> Dict[str, Any]:
79
+ """
80
+ Serialize this component to a dictionary.
81
+ """
82
+ return default_to_dict(
83
+ self,
84
+ model=self.model_name,
85
+ batch_size=self.batch_size,
86
+ progress_bar=self.progress_bar,
87
+ meta_fields_to_embed=self.meta_fields_to_embed,
88
+ embedding_separator=self.embedding_separator,
89
+ )
90
+
91
+ def warm_up(self):
92
+ """
93
+ Load the embedding backend.
94
+ """
95
+ if not hasattr(self, "embedding_backend"):
96
+ self.embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name=self.model_name)
97
+
98
+ @component.output_types(documents=List[Document])
99
+ def run(self, documents: List[Document]):
100
+ """
101
+ Embed a list of Documents.
102
+ The embedding of each Document is stored in the `embedding` field of the Document.
103
+ """
104
+ if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):
105
+ msg = (
106
+ "FastembedDocumentEmbedder expects a list of Documents as input. "
107
+ "In case you want to embed a list of strings, please use the FastembedTextEmbedder."
108
+ )
109
+ raise TypeError(msg)
110
+ if not hasattr(self, "embedding_backend"):
111
+ msg = "The embedding model has not been loaded. Please call warm_up() before running."
112
+ raise RuntimeError(msg)
113
+
114
+ # TODO: once non textual Documents are properly supported, we should also prepare them for embedding here
115
+
116
+ texts_to_embed = []
117
+ for doc in documents:
118
+ meta_values_to_embed = [
119
+ str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None
120
+ ]
121
+ text_to_embed = [
122
+ self.embedding_separator.join([*meta_values_to_embed, doc.content or ""]),
123
+ ]
124
+
125
+ texts_to_embed.append(text_to_embed[0])
126
+ embeddings = self.embedding_backend.embed(
127
+ texts_to_embed,
128
+ batch_size=self.batch_size,
129
+ show_progress_bar=self.progress_bar,
130
+ )
131
+
132
+ for doc, emb in zip(documents, embeddings):
133
+ doc.embedding = list(emb)
134
+
135
+ return {"documents": documents}
@@ -0,0 +1,89 @@
1
+ from typing import Any, Dict, List
2
+
3
+ from haystack import component, default_to_dict
4
+
5
+ from .embedding_backend.fastembed_backend import _FastembedEmbeddingBackendFactory
6
+
7
+
8
+ @component
9
+ class FastembedTextEmbedder:
10
+ """
11
+ A component for embedding strings using fastembed embedding models.
12
+
13
+ Usage example:
14
+ ```python
15
+ # To use this component, install the "fastembed" package.
16
+ # pip install fastembed
17
+
18
+ from fastembed_haystack.fastembed_text_embedder import FastembedTextEmbedder
19
+
20
+ text = "It clearly says online this will work on a Mac OS system. The disk comes and it does not, only Windows. Do Not order this if you have a Mac!!"
21
+
22
+ text_embedder = FastembedTextEmbedder(
23
+ model="BAAI/bge-small-en-v1.5"
24
+ )
25
+
26
+ embedding = text_embedder.run(text)
27
+ ```
28
+ """ # noqa: E501
29
+
30
+ def __init__(
31
+ self,
32
+ model: str = "BAAI/bge-small-en-v1.5",
33
+ batch_size: int = 256,
34
+ progress_bar: bool = True,
35
+ ):
36
+ """
37
+ Create a FastembedTextEmbedder component.
38
+
39
+ :param model: Local path or name of the model in Fastembed's model hub,
40
+ such as ``'BAAI/bge-small-en-v1.5'``.
41
+ :param batch_size: Number of strings to encode at once.
42
+ """
43
+
44
+ # TODO add parallel
45
+
46
+ self.model_name = model
47
+ self.batch_size = batch_size
48
+ self.progress_bar = progress_bar
49
+
50
+ def to_dict(self) -> Dict[str, Any]:
51
+ """
52
+ Serialize this component to a dictionary.
53
+ """
54
+ return default_to_dict(
55
+ self,
56
+ model=self.model_name,
57
+ batch_size=self.batch_size,
58
+ progress_bar=self.progress_bar,
59
+ )
60
+
61
+ def warm_up(self):
62
+ """
63
+ Load the embedding backend.
64
+ """
65
+ if not hasattr(self, "embedding_backend"):
66
+ self.embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name=self.model_name)
67
+
68
+ @component.output_types(embedding=List[float])
69
+ def run(self, text: str):
70
+ """Embed a string."""
71
+ if not isinstance(text, str):
72
+ msg = (
73
+ "FastembedTextEmbedder expects a string as input. "
74
+ "In case you want to embed a list of Documents, please use the FastembedDocumentEmbedder."
75
+ )
76
+ raise TypeError(msg)
77
+ if not hasattr(self, "embedding_backend"):
78
+ msg = "The embedding model has not been loaded. Please call warm_up() before running."
79
+ raise RuntimeError(msg)
80
+
81
+ text_to_embed = [text]
82
+ embedding = list(
83
+ self.embedding_backend.embed(
84
+ text_to_embed,
85
+ batch_size=self.batch_size,
86
+ show_progress_bar=self.progress_bar,
87
+ )[0]
88
+ )
89
+ return {"embedding": embedding}
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2024-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,44 @@
1
+ from unittest.mock import patch
2
+
3
+ from haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend import (
4
+ _FastembedEmbeddingBackendFactory,
5
+ )
6
+
7
+
8
+ @patch("haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend.TextEmbedding")
9
+ def test_factory_behavior(mock_instructor): # noqa: ARG001
10
+ embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name="BAAI/bge-small-en-v1.5")
11
+ same_embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend("BAAI/bge-small-en-v1.5")
12
+ another_embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(
13
+ model_name="BAAI/bge-base-en-v1.5"
14
+ )
15
+
16
+ assert same_embedding_backend is embedding_backend
17
+ assert another_embedding_backend is not embedding_backend
18
+
19
+ # restore the factory state
20
+ _FastembedEmbeddingBackendFactory._instances = {}
21
+
22
+
23
+ @patch("haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend.TextEmbedding")
24
+ def test_model_initialization(mock_instructor):
25
+ _FastembedEmbeddingBackendFactory.get_embedding_backend(
26
+ model_name="BAAI/bge-small-en-v1.5",
27
+ )
28
+ mock_instructor.assert_called_once_with(
29
+ model_name="BAAI/bge-small-en-v1.5",
30
+ )
31
+ # restore the factory state
32
+ _FastembedEmbeddingBackendFactory._instances = {}
33
+
34
+
35
+ @patch("haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend.TextEmbedding")
36
+ def test_embedding_function_with_kwargs(mock_instructor): # noqa: ARG001
37
+ embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name="BAAI/bge-small-en-v1.5")
38
+
39
+ data = ["sentence1", "sentence2"]
40
+ embedding_backend.embed(data=data)
41
+
42
+ embedding_backend.model.embed.assert_called_once_with(data)
43
+ # restore the factory stateTrue
44
+ _FastembedEmbeddingBackendFactory._instances = {}
@@ -0,0 +1,231 @@
1
+ from unittest.mock import MagicMock, patch
2
+
3
+ import numpy as np
4
+ import pytest
5
+ from haystack import Document, default_from_dict
6
+ from haystack_integrations.components.embedders.fastembed.fastembed_document_embedder import (
7
+ FastembedDocumentEmbedder,
8
+ )
9
+
10
+
11
+ class TestFastembedDocumentEmbedder:
12
+ def test_init_default(self):
13
+ """
14
+ Test default initialization parameters for FastembedDocumentEmbedder.
15
+ """
16
+ embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5")
17
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
18
+ assert embedder.batch_size == 256
19
+ assert embedder.progress_bar is True
20
+ assert embedder.meta_fields_to_embed == []
21
+ assert embedder.embedding_separator == "\n"
22
+
23
+ def test_init_with_parameters(self):
24
+ """
25
+ Test custom initialization parameters for FastembedDocumentEmbedder.
26
+ """
27
+ embedder = FastembedDocumentEmbedder(
28
+ model="BAAI/bge-small-en-v1.5",
29
+ batch_size=64,
30
+ progress_bar=False,
31
+ meta_fields_to_embed=["test_field"],
32
+ embedding_separator=" | ",
33
+ )
34
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
35
+ assert embedder.batch_size == 64
36
+ assert embedder.progress_bar is False
37
+ assert embedder.meta_fields_to_embed == ["test_field"]
38
+ assert embedder.embedding_separator == " | "
39
+
40
+ def test_to_dict(self):
41
+ """
42
+ Test serialization of FastembedDocumentEmbedder to a dictionary, using default initialization parameters.
43
+ """
44
+ embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5")
45
+ embedder_dict = embedder.to_dict()
46
+ assert embedder_dict == {
47
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa
48
+ "init_parameters": {
49
+ "model": "BAAI/bge-small-en-v1.5",
50
+ "batch_size": 256,
51
+ "progress_bar": True,
52
+ "embedding_separator": "\n",
53
+ "meta_fields_to_embed": [],
54
+ },
55
+ }
56
+
57
+ def test_to_dict_with_custom_init_parameters(self):
58
+ """
59
+ Test serialization of FastembedDocumentEmbedder to a dictionary, using custom initialization parameters.
60
+ """
61
+ embedder = FastembedDocumentEmbedder(
62
+ model="BAAI/bge-small-en-v1.5",
63
+ batch_size=64,
64
+ progress_bar=False,
65
+ meta_fields_to_embed=["test_field"],
66
+ embedding_separator=" | ",
67
+ )
68
+ embedder_dict = embedder.to_dict()
69
+ assert embedder_dict == {
70
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa
71
+ "init_parameters": {
72
+ "model": "BAAI/bge-small-en-v1.5",
73
+ "batch_size": 64,
74
+ "progress_bar": False,
75
+ "meta_fields_to_embed": ["test_field"],
76
+ "embedding_separator": " | ",
77
+ },
78
+ }
79
+
80
+ def test_from_dict(self):
81
+ """
82
+ Test deserialization of FastembedDocumentEmbedder from a dictionary, using default initialization parameters.
83
+ """
84
+ embedder_dict = {
85
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa
86
+ "init_parameters": {
87
+ "model": "BAAI/bge-small-en-v1.5",
88
+ "batch_size": 256,
89
+ "progress_bar": True,
90
+ "meta_fields_to_embed": [],
91
+ "embedding_separator": "\n",
92
+ },
93
+ }
94
+ embedder = default_from_dict(FastembedDocumentEmbedder, embedder_dict)
95
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
96
+ assert embedder.batch_size == 256
97
+ assert embedder.progress_bar is True
98
+ assert embedder.meta_fields_to_embed == []
99
+ assert embedder.embedding_separator == "\n"
100
+
101
+ def test_from_dict_with_custom_init_parameters(self):
102
+ """
103
+ Test deserialization of FastembedDocumentEmbedder from a dictionary, using custom initialization parameters.
104
+ """
105
+ embedder_dict = {
106
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa
107
+ "init_parameters": {
108
+ "model": "BAAI/bge-small-en-v1.5",
109
+ "batch_size": 64,
110
+ "progress_bar": False,
111
+ "meta_fields_to_embed": ["test_field"],
112
+ "embedding_separator": " | ",
113
+ },
114
+ }
115
+ embedder = default_from_dict(FastembedDocumentEmbedder, embedder_dict)
116
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
117
+ assert embedder.batch_size == 64
118
+ assert embedder.progress_bar is False
119
+ assert embedder.meta_fields_to_embed == ["test_field"]
120
+ assert embedder.embedding_separator == " | "
121
+
122
+ @patch(
123
+ "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder._FastembedEmbeddingBackendFactory"
124
+ )
125
+ def test_warmup(self, mocked_factory):
126
+ """
127
+ Test for checking embedder instances after warm-up.
128
+ """
129
+ embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5")
130
+ mocked_factory.get_embedding_backend.assert_not_called()
131
+ embedder.warm_up()
132
+ mocked_factory.get_embedding_backend.assert_called_once_with(
133
+ model_name="BAAI/bge-small-en-v1.5",
134
+ )
135
+
136
+ @patch(
137
+ "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder._FastembedEmbeddingBackendFactory"
138
+ )
139
+ def test_warmup_does_not_reload(self, mocked_factory):
140
+ """
141
+ Test for checking backend instances after multiple warm-ups.
142
+ """
143
+ embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5")
144
+ mocked_factory.get_embedding_backend.assert_not_called()
145
+ embedder.warm_up()
146
+ embedder.warm_up()
147
+ mocked_factory.get_embedding_backend.assert_called_once()
148
+
149
+ def test_embed(self):
150
+ """
151
+ Test for checking output dimensions and embedding dimensions.
152
+ """
153
+ embedder = FastembedDocumentEmbedder(model="BAAI/bge-base-en-v1.5")
154
+ embedder.embedding_backend = MagicMock()
155
+ embedder.embedding_backend.embed = lambda x, **kwargs: np.random.rand(len(x), 16).tolist() # noqa: ARG005
156
+
157
+ documents = [Document(content=f"Sample-document text {i}") for i in range(5)]
158
+
159
+ result = embedder.run(documents=documents)
160
+
161
+ assert isinstance(result["documents"], list)
162
+ assert len(result["documents"]) == len(documents)
163
+ for doc in result["documents"]:
164
+ assert isinstance(doc, Document)
165
+ assert isinstance(doc.embedding, list)
166
+ assert isinstance(doc.embedding[0], float)
167
+
168
+ def test_embed_incorrect_input_format(self):
169
+ """
170
+ Test for checking incorrect input format when creating embedding.
171
+ """
172
+ embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5")
173
+
174
+ string_input = "text"
175
+ list_integers_input = [1, 2, 3]
176
+
177
+ with pytest.raises(
178
+ TypeError,
179
+ match="FastembedDocumentEmbedder expects a list of Documents as input.",
180
+ ):
181
+ embedder.run(documents=string_input)
182
+
183
+ with pytest.raises(
184
+ TypeError,
185
+ match="FastembedDocumentEmbedder expects a list of Documents as input.",
186
+ ):
187
+ embedder.run(documents=list_integers_input)
188
+
189
+ def test_embed_metadata(self):
190
+ """
191
+ Test for checking output dimensions and embedding dimensions for documents
192
+ with a custom instruction and metadata.
193
+ """
194
+ embedder = FastembedDocumentEmbedder(
195
+ model="model",
196
+ meta_fields_to_embed=["meta_field"],
197
+ embedding_separator="\n",
198
+ )
199
+ embedder.embedding_backend = MagicMock()
200
+
201
+ documents = [Document(content=f"document-number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)]
202
+
203
+ embedder.run(documents=documents)
204
+
205
+ embedder.embedding_backend.embed.assert_called_once_with(
206
+ [
207
+ "meta_value 0\ndocument-number 0",
208
+ "meta_value 1\ndocument-number 1",
209
+ "meta_value 2\ndocument-number 2",
210
+ "meta_value 3\ndocument-number 3",
211
+ "meta_value 4\ndocument-number 4",
212
+ ],
213
+ batch_size=256,
214
+ show_progress_bar=True,
215
+ )
216
+
217
+ @pytest.mark.integration
218
+ def test_run(self):
219
+ embedder = FastembedDocumentEmbedder(
220
+ model="BAAI/bge-small-en-v1.5",
221
+ )
222
+ embedder.warm_up()
223
+
224
+ doc = Document(content="Parton energy loss in QCD matter")
225
+
226
+ result = embedder.run(documents=[doc])
227
+ embedding = result["documents"][0].embedding
228
+
229
+ assert isinstance(embedding, list)
230
+ assert len(embedding) == 384
231
+ assert all(isinstance(emb.item(), float) for emb in embedding)
@@ -0,0 +1,169 @@
1
+ from unittest.mock import MagicMock, patch
2
+
3
+ import numpy as np
4
+ import pytest
5
+ from haystack import default_from_dict
6
+ from haystack_integrations.components.embedders.fastembed.fastembed_text_embedder import (
7
+ FastembedTextEmbedder,
8
+ )
9
+
10
+
11
+ class TestFastembedTextEmbedder:
12
+ def test_init_default(self):
13
+ """
14
+ Test default initialization parameters for FastembedTextEmbedder.
15
+ """
16
+ embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5")
17
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
18
+ assert embedder.batch_size == 256
19
+ assert embedder.progress_bar is True
20
+
21
+ def test_init_with_parameters(self):
22
+ """
23
+ Test custom initialization parameters for FastembedTextEmbedder.
24
+ """
25
+ embedder = FastembedTextEmbedder(
26
+ model="BAAI/bge-small-en-v1.5",
27
+ batch_size=64,
28
+ progress_bar=False,
29
+ )
30
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
31
+ assert embedder.batch_size == 64
32
+ assert embedder.progress_bar is False
33
+
34
+ def test_to_dict(self):
35
+ """
36
+ Test serialization of FastembedTextEmbedder to a dictionary, using default initialization parameters.
37
+ """
38
+ embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5")
39
+ embedder_dict = embedder.to_dict()
40
+ assert embedder_dict == {
41
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa
42
+ "init_parameters": {
43
+ "model": "BAAI/bge-small-en-v1.5",
44
+ "batch_size": 256,
45
+ "progress_bar": True,
46
+ },
47
+ }
48
+
49
+ def test_to_dict_with_custom_init_parameters(self):
50
+ """
51
+ Test serialization of FastembedTextEmbedder to a dictionary, using custom initialization parameters.
52
+ """
53
+ embedder = FastembedTextEmbedder(
54
+ model="BAAI/bge-small-en-v1.5",
55
+ batch_size=64,
56
+ progress_bar=False,
57
+ )
58
+ embedder_dict = embedder.to_dict()
59
+ assert embedder_dict == {
60
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa
61
+ "init_parameters": {
62
+ "model": "BAAI/bge-small-en-v1.5",
63
+ "batch_size": 64,
64
+ "progress_bar": False,
65
+ },
66
+ }
67
+
68
+ def test_from_dict(self):
69
+ """
70
+ Test deserialization of FastembedTextEmbedder from a dictionary, using default initialization parameters.
71
+ """
72
+ embedder_dict = {
73
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa
74
+ "init_parameters": {
75
+ "model": "BAAI/bge-small-en-v1.5",
76
+ "batch_size": 256,
77
+ "progress_bar": True,
78
+ },
79
+ }
80
+ embedder = default_from_dict(FastembedTextEmbedder, embedder_dict)
81
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
82
+ assert embedder.batch_size == 256
83
+ assert embedder.progress_bar is True
84
+
85
+ def test_from_dict_with_custom_init_parameters(self):
86
+ """
87
+ Test deserialization of FastembedTextEmbedder from a dictionary, using custom initialization parameters.
88
+ """
89
+ embedder_dict = {
90
+ "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa
91
+ "init_parameters": {
92
+ "model": "BAAI/bge-small-en-v1.5",
93
+ "batch_size": 64,
94
+ "progress_bar": False,
95
+ },
96
+ }
97
+ embedder = default_from_dict(FastembedTextEmbedder, embedder_dict)
98
+ assert embedder.model_name == "BAAI/bge-small-en-v1.5"
99
+ assert embedder.batch_size == 64
100
+ assert embedder.progress_bar is False
101
+
102
+ @patch(
103
+ "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder._FastembedEmbeddingBackendFactory"
104
+ )
105
+ def test_warmup(self, mocked_factory):
106
+ """
107
+ Test for checking embedder instances after warm-up.
108
+ """
109
+ embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5")
110
+ mocked_factory.get_embedding_backend.assert_not_called()
111
+ embedder.warm_up()
112
+ mocked_factory.get_embedding_backend.assert_called_once_with(model_name="BAAI/bge-small-en-v1.5")
113
+
114
+ @patch(
115
+ "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder._FastembedEmbeddingBackendFactory"
116
+ )
117
+ def test_warmup_does_not_reload(self, mocked_factory):
118
+ """
119
+ Test for checking backend instances after multiple warm-ups.
120
+ """
121
+ embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5")
122
+ mocked_factory.get_embedding_backend.assert_not_called()
123
+ embedder.warm_up()
124
+ embedder.warm_up()
125
+ mocked_factory.get_embedding_backend.assert_called_once()
126
+
127
+ def test_embed(self):
128
+ """
129
+ Test for checking output dimensions and embedding dimensions.
130
+ """
131
+ embedder = FastembedTextEmbedder(model="BAAI/bge-base-en-v1.5")
132
+ embedder.embedding_backend = MagicMock()
133
+ embedder.embedding_backend.embed = lambda x, **kwargs: np.random.rand(len(x), 16).tolist() # noqa: ARG005
134
+
135
+ text = "Good text to embed"
136
+
137
+ result = embedder.run(text=text)
138
+ embedding = result["embedding"]
139
+
140
+ assert isinstance(embedding, list)
141
+ assert all(isinstance(emb, float) for emb in embedding)
142
+
143
+ def test_run_wrong_incorrect_format(self):
144
+ """
145
+ Test for checking incorrect input format when creating embedding.
146
+ """
147
+ embedder = FastembedTextEmbedder(model="BAAI/bge-base-en-v1.5")
148
+ embedder.embedding_backend = MagicMock()
149
+
150
+ list_integers_input = [1, 2, 3]
151
+
152
+ with pytest.raises(TypeError, match="FastembedTextEmbedder expects a string as input"):
153
+ embedder.run(text=list_integers_input)
154
+
155
+ @pytest.mark.integration
156
+ def test_run(self):
157
+ embedder = FastembedTextEmbedder(
158
+ model="BAAI/bge-small-en-v1.5",
159
+ )
160
+ embedder.warm_up()
161
+
162
+ text = "Parton energy loss in QCD matter"
163
+
164
+ result = embedder.run(text=text)
165
+ embedding = result["embedding"]
166
+
167
+ assert isinstance(embedding, list)
168
+ assert len(embedding) == 384
169
+ assert all(isinstance(emb.item(), float) for emb in embedding)