From a23d6c7b350e3bc8e9cafe17f3a31b07ac6b44a2 Mon Sep 17 00:00:00 2001 From: Nicola Procopio Date: Sat, 10 Feb 2024 11:27:36 +0100 Subject: [PATCH] add Fastembed Embeddings integration (#383) * created project * added parallel param * updated test * version 0.0.1 * renamed folder * removed print * updated readme * added fastembed.yml * fix typos * python version to 3.9 for lint * updated file * force install black * return to original file * try to fix workflow * retry * add missing info to pyproject * add hatch-vcs to check version * Update pyproject.toml * fixed typos * removed python 3.9 * Update fastembed.yml * Update fastembed_document_embedder.py * Update fastembed_text_embedder.py * ignore errors for bool arguments * fix * try moving noqa * move noqa * formatted with black * added numpy dependency * removed numpy * removed numpy * make mypy happy * Update fastembed_backend.py * removed classvar * fix * Update pyproject.toml * added import numpy lint * skip docs generation for the time being * Update README.md * added config.yml * generate docs * Update fastembed.yml * Update config.yml * rm unnecessary from_dict * final touch --------- Co-authored-by: Stefano Fiorucci --- .github/workflows/fastembed.yml | 45 ++++ integrations/fastembed/LICENSE.txt | 73 ++++++ integrations/fastembed/README.md | 47 ++++ integrations/fastembed/pydoc/config.yml | 30 +++ integrations/fastembed/pyproject.toml | 185 ++++++++++++++ .../embedders/fastembed/__init__.py | 7 + .../fastembed/embedding_backend/__init__.py | 3 + .../embedding_backend/fastembed_backend.py | 42 ++++ .../fastembed/fastembed_document_embedder.py | 135 ++++++++++ .../fastembed/fastembed_text_embedder.py | 89 +++++++ integrations/fastembed/tests/__init__.py | 3 + .../fastembed/tests/test_fastembed_backend.py | 44 ++++ .../tests/test_fastembed_document_embedder.py | 231 ++++++++++++++++++ .../tests/test_fastembed_text_embedder.py | 169 +++++++++++++ 14 files changed, 1103 insertions(+) create mode 100644 .github/workflows/fastembed.yml create mode 100644 integrations/fastembed/LICENSE.txt create mode 100644 integrations/fastembed/README.md create mode 100644 integrations/fastembed/pydoc/config.yml create mode 100644 integrations/fastembed/pyproject.toml create mode 100644 integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/__init__.py create mode 100644 integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/__init__.py create mode 100644 integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/fastembed_backend.py create mode 100644 integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_document_embedder.py create mode 100644 integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_text_embedder.py create mode 100644 integrations/fastembed/tests/__init__.py create mode 100644 integrations/fastembed/tests/test_fastembed_backend.py create mode 100644 integrations/fastembed/tests/test_fastembed_document_embedder.py create mode 100644 integrations/fastembed/tests/test_fastembed_text_embedder.py diff --git a/.github/workflows/fastembed.yml b/.github/workflows/fastembed.yml new file mode 100644 index 000000000..fe736029a --- /dev/null +++ b/.github/workflows/fastembed.yml @@ -0,0 +1,45 @@ +name: Test / fastembed + +on: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "integrations/fastembed/**" + - ".github/workflows/fastembed.yml" + +defaults: + run: + working-directory: integrations/fastembed + +jobs: + run: + name: Python ${{ matrix.python-version }} on ${{ startsWith(matrix.os, 'macos-') && 'macOS' || startsWith(matrix.os, 'windows-') && 'Windows' || 'Linux' }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] + python-version: ["3.9","3.10","3.11"] + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Hatch + run: pip install --upgrade hatch + + - name: Lint + if: matrix.python-version == '3.9' + run: hatch run lint:all + + - name: Generate docs + if: matrix.python-version == '3.9' && runner.os == 'Linux' + run: hatch run docs + + - name: Run tests + run: hatch run cov diff --git a/integrations/fastembed/LICENSE.txt b/integrations/fastembed/LICENSE.txt new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/integrations/fastembed/LICENSE.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"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. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"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. + +"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). + +"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. + +"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." + +"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. + +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. + +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. + +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: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (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 + + (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. + + 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. + +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. + +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. + +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. + +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. + +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. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +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. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/integrations/fastembed/README.md b/integrations/fastembed/README.md new file mode 100644 index 000000000..94a86d85e --- /dev/null +++ b/integrations/fastembed/README.md @@ -0,0 +1,47 @@ +# fastembed-haystack + +[![PyPI - Version](https://img.shields.io/pypi/v/fastembed-haystack.svg)](https://pypi.org/project/fastembed-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fastembed-haystack.svg)](https://pypi.org/project/fastembed-haystack) + +----- + +**Table of Contents** + +- [Installation](#installation) +- [License](#license) + +## Installation + +```console +pip install fastembed-haystack +``` + +## Usage + +You can use `FastembedTextEmbedder` and `FastembedDocumentEmbedder` by importing as: + +```python +from fastembed_haystack.fastembed_text_embedder import FastembedTextEmbedder + +text = "fastembed is supported by and maintained by Qdrant." +text_embedder = FastembedTextEmbedder( + model="BAAI/bge-small-en-v1.5" +) +embedding = text_embedder.run(text) +``` + +```python +from fastembed_haystack.fastembed__document_embedder import FastembedDocumentEmbedder +from haystack.dataclasses import Document + +embedder = FastembedDocumentEmbedder( + model="BAAI/bge-small-en-v1.5", +) +embedder.warm_up() +doc = Document(content="fastembed is supported by and maintained by Qdrant.", meta={"long_answer": "no",}) +result = embedder.run(documents=[doc]) +``` + +## License + +`fastembed-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license. diff --git a/integrations/fastembed/pydoc/config.yml b/integrations/fastembed/pydoc/config.yml new file mode 100644 index 000000000..3e491eac2 --- /dev/null +++ b/integrations/fastembed/pydoc/config.yml @@ -0,0 +1,30 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../src] + modules: + [ + "haystack_integrations.components.embedders.fastembed", + "haystack_integrations.components.embedders.fastembed.embedding_backend", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmePreviewRenderer + excerpt: Embedders integration for Haystack + category_slug: haystack-integrations + title: Embedders + slug: fastembed-embedders + order: 300 + markdown: + descriptive_class_title: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: _readme_fastembed.md diff --git a/integrations/fastembed/pyproject.toml b/integrations/fastembed/pyproject.toml new file mode 100644 index 000000000..6ebb99142 --- /dev/null +++ b/integrations/fastembed/pyproject.toml @@ -0,0 +1,185 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "fastembed-haystack" +dynamic = ["version"] +description = "Haystack 2.x component to embed strings and Documents using fastembed embedding model" +readme = "README.md" +requires-python = ">=3.8" +license = "Apache-2.0" +keywords = [] +authors = [ + { name = "deepset GmbH", email = "info@deepset.ai" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = [ +"haystack-ai", +"fastembed>=0.2", +] + +[project.urls] +Source = "https://github.com/deepset-ai/haystack-core-integrations" +Documentation = "https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/README.md" +Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues" + +[tool.hatch.build.targets.wheel] +packages = ["src/haystack_integrations"] + +[tool.hatch.version] +source = "vcs" +tag-pattern = 'integrations\/fastembed-v(?P.*)' + +[tool.hatch.version.raw-options] +root = "../.." +git_describe_command = 'git describe --tags --match="integrations/fastembed-v[0-9]*"' + +[tool.hatch.envs.default] +dependencies = [ + "coverage[toml]>=6.5", + "pytest", + "ipython", + "haystack-pydoc-tools", +] +[tool.hatch.envs.default.scripts] +test = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = [ + "- coverage combine", + "coverage report", +] +cov = [ + "test-cov", + "cov-report", +] +docs = [ + "pydoc-markdown pydoc/config.yml" +] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11", "3.12"] + +[tool.hatch.envs.lint] +detached = true +dependencies = [ + "black>=23.1.0", + "mypy>=1.0.0", + "ruff>=0.0.243", + "numpy" +] +[tool.hatch.envs.lint.scripts] +typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}" +style = [ + "ruff {args:.}", + "black --check --diff {args:.}", +] +fmt = [ + "black {args:.}", + "ruff --fix {args:.}", + "style", +] +all = [ + "style", + "typing", +] + +[tool.black] +target-version = ["py37"] +line-length = 120 +skip-string-normalization = true + +[tool.ruff] +target-version = "py37" +line-length = 120 +select = [ + "A", + "ARG", + "B", + "C", + "DTZ", + "E", + "EM", + "F", + "FBT", + "I", + "ICN", + "ISC", + "N", + "PLC", + "PLE", + "PLR", + "PLW", + "Q", + "RUF", + "S", + "T", + "TID", + "UP", + "W", + "YTT", +] +ignore = [ + # Allow non-abstract empty methods in abstract base classes + "B027", + # Allow boolean positional values in function calls, like `dict.get(... True)` + "FBT003", + "FBT001", "FBT002", + # Ignore checks for possible passwords + "S105", "S106", "S107", + # Ignore complexity + "C901", "PLR0911", "PLR0912", "PLR0913", "PLR0915", +] +unfixable = [ + # Don't touch unused imports + "F401", +] + +[tool.ruff.isort] +known-first-party = ["src"] + +[tool.ruff.flake8-tidy-imports] +ban-relative-imports = "parents" + +[tool.ruff.per-file-ignores] +# Tests can use magic values, assertions, and relative imports +"tests/**/*" = ["PLR2004", "S101", "TID252"] +# examples can contain "print" commands +"examples/**/*" = ["T201"] + +[tool.coverage.run] +source_pkgs = ["src", "tests"] +branch = true +parallel = true + + +[tool.coverage.paths] +fastembed_haystack = ["src/haystack_integrations", "*/fastembed-haystack/src"] +tests = ["tests", "*/fastembed-haystack/tests"] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] + +[[tool.mypy.overrides]] +module = [ + "haystack.*", + "haystack_integrations.*", + "fastembed.*", + "pytest.*", + "numpy.*" +] +ignore_missing_imports = true diff --git a/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/__init__.py b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/__init__.py new file mode 100644 index 000000000..fdf4dd8de --- /dev/null +++ b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2024-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from .fastembed_document_embedder import FastembedDocumentEmbedder +from .fastembed_text_embedder import FastembedTextEmbedder + +__all__ = ["FastembedDocumentEmbedder", "FastembedTextEmbedder"] diff --git a/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/__init__.py b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/__init__.py new file mode 100644 index 000000000..e873bc332 --- /dev/null +++ b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/fastembed_backend.py b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/fastembed_backend.py new file mode 100644 index 000000000..392f9d32d --- /dev/null +++ b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/embedding_backend/fastembed_backend.py @@ -0,0 +1,42 @@ +from typing import ClassVar, Dict, List + +from fastembed import TextEmbedding + + +class _FastembedEmbeddingBackendFactory: + """ + Factory class to create instances of fastembed embedding backends. + """ + + _instances: ClassVar[Dict[str, "_FastembedEmbeddingBackend"]] = {} + + @staticmethod + def get_embedding_backend( + model_name: str, + ): + embedding_backend_id = f"{model_name}" + + if embedding_backend_id in _FastembedEmbeddingBackendFactory._instances: + return _FastembedEmbeddingBackendFactory._instances[embedding_backend_id] + + embedding_backend = _FastembedEmbeddingBackend( + model_name=model_name, + ) + _FastembedEmbeddingBackendFactory._instances[embedding_backend_id] = embedding_backend + return embedding_backend + + +class _FastembedEmbeddingBackend: + """ + Class to manage fastembed embeddings. + """ + + def __init__( + self, + model_name: str, + ): + self.model = TextEmbedding(model_name=model_name) + + def embed(self, data: List[List[str]], **kwargs) -> List[List[float]]: + embeddings = list(self.model.embed(data, **kwargs)) + return embeddings diff --git a/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_document_embedder.py b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_document_embedder.py new file mode 100644 index 000000000..24da783fd --- /dev/null +++ b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_document_embedder.py @@ -0,0 +1,135 @@ +from typing import Any, Dict, List, Optional + +from haystack import Document, component, default_to_dict + +from .embedding_backend.fastembed_backend import _FastembedEmbeddingBackendFactory + + +@component +class FastembedDocumentEmbedder: + """ + A component for computing Document embeddings using Fastembed embedding models. + The embedding of each Document is stored in the `embedding` field of the Document. + + Usage example: + ```python + # To use this component, install the "fastembed-haystack" package. + # pip install fastembed-haystack + + from fastembed_haystack.fastembed__document_embedder import FastembedDocumentEmbedder + from haystack.dataclasses import Document + + doc_embedder = FastembedDocumentEmbedder( + model="BAAI/bge-small-en-v1.5", + batch_size=256, + ) + + doc_embedder.warm_up() + + # Text taken from PubMed QA Dataset (https://huggingface.co/datasets/pubmed_qa) + document_list = [ + Document( + 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.", + meta={ + "pubid": "25,445,628", + "long_answer": "yes", + }, + ), + Document( + 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.", + meta={ + "pubid": "25,445,712", + "long_answer": "yes", + }, + ), + ] + + result = doc_embedder.run(document_list) + print(f"Document Text: {result['documents'][0].content}") + print(f"Document Embedding: {result['documents'][0].embedding}") + print(f"Embedding Dimension: {len(result['documents'][0].embedding)}") + """ # noqa: E501 + + def __init__( + self, + model: str = "BAAI/bge-small-en-v1.5", + batch_size: int = 256, + progress_bar: bool = True, + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + ): + """ + Create an FastembedDocumentEmbedder component. + + :param model: Local path or name of the model in Hugging Face's model hub, + such as ``'BAAI/bge-small-en-v1.5'``. + :param batch_size: Number of strings to encode at once. + :param progress_bar: If true, displays progress bar during embedding. + :param meta_fields_to_embed: List of meta fields that should be embedded along with the Document content. + :param embedding_separator: Separator used to concatenate the meta fields to the Document content. + """ + + self.model_name = model + self.batch_size = batch_size + self.progress_bar = progress_bar + self.meta_fields_to_embed = meta_fields_to_embed or [] + self.embedding_separator = embedding_separator + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + """ + return default_to_dict( + self, + model=self.model_name, + batch_size=self.batch_size, + progress_bar=self.progress_bar, + meta_fields_to_embed=self.meta_fields_to_embed, + embedding_separator=self.embedding_separator, + ) + + def warm_up(self): + """ + Load the embedding backend. + """ + if not hasattr(self, "embedding_backend"): + self.embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name=self.model_name) + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document]): + """ + Embed a list of Documents. + The embedding of each Document is stored in the `embedding` field of the Document. + """ + if not isinstance(documents, list) or documents and not isinstance(documents[0], Document): + msg = ( + "FastembedDocumentEmbedder expects a list of Documents as input. " + "In case you want to embed a list of strings, please use the FastembedTextEmbedder." + ) + raise TypeError(msg) + if not hasattr(self, "embedding_backend"): + msg = "The embedding model has not been loaded. Please call warm_up() before running." + raise RuntimeError(msg) + + # TODO: once non textual Documents are properly supported, we should also prepare them for embedding here + + texts_to_embed = [] + for doc in documents: + meta_values_to_embed = [ + str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None + ] + text_to_embed = [ + self.embedding_separator.join([*meta_values_to_embed, doc.content or ""]), + ] + + texts_to_embed.append(text_to_embed[0]) + embeddings = self.embedding_backend.embed( + texts_to_embed, + batch_size=self.batch_size, + show_progress_bar=self.progress_bar, + ) + + for doc, emb in zip(documents, embeddings): + doc.embedding = list(emb) + + return {"documents": documents} diff --git a/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_text_embedder.py b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_text_embedder.py new file mode 100644 index 000000000..832d1240f --- /dev/null +++ b/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_text_embedder.py @@ -0,0 +1,89 @@ +from typing import Any, Dict, List + +from haystack import component, default_to_dict + +from .embedding_backend.fastembed_backend import _FastembedEmbeddingBackendFactory + + +@component +class FastembedTextEmbedder: + """ + A component for embedding strings using fastembed embedding models. + + Usage example: + ```python + # To use this component, install the "fastembed" package. + # pip install fastembed + + from fastembed_haystack.fastembed_text_embedder import FastembedTextEmbedder + + 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!!" + + text_embedder = FastembedTextEmbedder( + model="BAAI/bge-small-en-v1.5" + ) + + embedding = text_embedder.run(text) + ``` + """ # noqa: E501 + + def __init__( + self, + model: str = "BAAI/bge-small-en-v1.5", + batch_size: int = 256, + progress_bar: bool = True, + ): + """ + Create a FastembedTextEmbedder component. + + :param model: Local path or name of the model in Fastembed's model hub, + such as ``'BAAI/bge-small-en-v1.5'``. + :param batch_size: Number of strings to encode at once. + """ + + # TODO add parallel + + self.model_name = model + self.batch_size = batch_size + self.progress_bar = progress_bar + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + """ + return default_to_dict( + self, + model=self.model_name, + batch_size=self.batch_size, + progress_bar=self.progress_bar, + ) + + def warm_up(self): + """ + Load the embedding backend. + """ + if not hasattr(self, "embedding_backend"): + self.embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name=self.model_name) + + @component.output_types(embedding=List[float]) + def run(self, text: str): + """Embed a string.""" + if not isinstance(text, str): + msg = ( + "FastembedTextEmbedder expects a string as input. " + "In case you want to embed a list of Documents, please use the FastembedDocumentEmbedder." + ) + raise TypeError(msg) + if not hasattr(self, "embedding_backend"): + msg = "The embedding model has not been loaded. Please call warm_up() before running." + raise RuntimeError(msg) + + text_to_embed = [text] + embedding = list( + self.embedding_backend.embed( + text_to_embed, + batch_size=self.batch_size, + show_progress_bar=self.progress_bar, + )[0] + ) + return {"embedding": embedding} diff --git a/integrations/fastembed/tests/__init__.py b/integrations/fastembed/tests/__init__.py new file mode 100644 index 000000000..6b5e14dc1 --- /dev/null +++ b/integrations/fastembed/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2024-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/fastembed/tests/test_fastembed_backend.py b/integrations/fastembed/tests/test_fastembed_backend.py new file mode 100644 index 000000000..c564c72bf --- /dev/null +++ b/integrations/fastembed/tests/test_fastembed_backend.py @@ -0,0 +1,44 @@ +from unittest.mock import patch + +from haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend import ( + _FastembedEmbeddingBackendFactory, +) + + +@patch("haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend.TextEmbedding") +def test_factory_behavior(mock_instructor): # noqa: ARG001 + embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name="BAAI/bge-small-en-v1.5") + same_embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend("BAAI/bge-small-en-v1.5") + another_embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend( + model_name="BAAI/bge-base-en-v1.5" + ) + + assert same_embedding_backend is embedding_backend + assert another_embedding_backend is not embedding_backend + + # restore the factory state + _FastembedEmbeddingBackendFactory._instances = {} + + +@patch("haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend.TextEmbedding") +def test_model_initialization(mock_instructor): + _FastembedEmbeddingBackendFactory.get_embedding_backend( + model_name="BAAI/bge-small-en-v1.5", + ) + mock_instructor.assert_called_once_with( + model_name="BAAI/bge-small-en-v1.5", + ) + # restore the factory state + _FastembedEmbeddingBackendFactory._instances = {} + + +@patch("haystack_integrations.components.embedders.fastembed.embedding_backend.fastembed_backend.TextEmbedding") +def test_embedding_function_with_kwargs(mock_instructor): # noqa: ARG001 + embedding_backend = _FastembedEmbeddingBackendFactory.get_embedding_backend(model_name="BAAI/bge-small-en-v1.5") + + data = ["sentence1", "sentence2"] + embedding_backend.embed(data=data) + + embedding_backend.model.embed.assert_called_once_with(data) + # restore the factory stateTrue + _FastembedEmbeddingBackendFactory._instances = {} diff --git a/integrations/fastembed/tests/test_fastembed_document_embedder.py b/integrations/fastembed/tests/test_fastembed_document_embedder.py new file mode 100644 index 000000000..be182183c --- /dev/null +++ b/integrations/fastembed/tests/test_fastembed_document_embedder.py @@ -0,0 +1,231 @@ +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest +from haystack import Document, default_from_dict +from haystack_integrations.components.embedders.fastembed.fastembed_document_embedder import ( + FastembedDocumentEmbedder, +) + + +class TestFastembedDocumentEmbedder: + def test_init_default(self): + """ + Test default initialization parameters for FastembedDocumentEmbedder. + """ + embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5") + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 256 + assert embedder.progress_bar is True + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + + def test_init_with_parameters(self): + """ + Test custom initialization parameters for FastembedDocumentEmbedder. + """ + embedder = FastembedDocumentEmbedder( + model="BAAI/bge-small-en-v1.5", + batch_size=64, + progress_bar=False, + meta_fields_to_embed=["test_field"], + embedding_separator=" | ", + ) + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + assert embedder.meta_fields_to_embed == ["test_field"] + assert embedder.embedding_separator == " | " + + def test_to_dict(self): + """ + Test serialization of FastembedDocumentEmbedder to a dictionary, using default initialization parameters. + """ + embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5") + embedder_dict = embedder.to_dict() + assert embedder_dict == { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 256, + "progress_bar": True, + "embedding_separator": "\n", + "meta_fields_to_embed": [], + }, + } + + def test_to_dict_with_custom_init_parameters(self): + """ + Test serialization of FastembedDocumentEmbedder to a dictionary, using custom initialization parameters. + """ + embedder = FastembedDocumentEmbedder( + model="BAAI/bge-small-en-v1.5", + batch_size=64, + progress_bar=False, + meta_fields_to_embed=["test_field"], + embedding_separator=" | ", + ) + embedder_dict = embedder.to_dict() + assert embedder_dict == { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 64, + "progress_bar": False, + "meta_fields_to_embed": ["test_field"], + "embedding_separator": " | ", + }, + } + + def test_from_dict(self): + """ + Test deserialization of FastembedDocumentEmbedder from a dictionary, using default initialization parameters. + """ + embedder_dict = { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 256, + "progress_bar": True, + "meta_fields_to_embed": [], + "embedding_separator": "\n", + }, + } + embedder = default_from_dict(FastembedDocumentEmbedder, embedder_dict) + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 256 + assert embedder.progress_bar is True + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + + def test_from_dict_with_custom_init_parameters(self): + """ + Test deserialization of FastembedDocumentEmbedder from a dictionary, using custom initialization parameters. + """ + embedder_dict = { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 64, + "progress_bar": False, + "meta_fields_to_embed": ["test_field"], + "embedding_separator": " | ", + }, + } + embedder = default_from_dict(FastembedDocumentEmbedder, embedder_dict) + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + assert embedder.meta_fields_to_embed == ["test_field"] + assert embedder.embedding_separator == " | " + + @patch( + "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder._FastembedEmbeddingBackendFactory" + ) + def test_warmup(self, mocked_factory): + """ + Test for checking embedder instances after warm-up. + """ + embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5") + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + mocked_factory.get_embedding_backend.assert_called_once_with( + model_name="BAAI/bge-small-en-v1.5", + ) + + @patch( + "haystack_integrations.components.embedders.fastembed.fastembed_document_embedder._FastembedEmbeddingBackendFactory" + ) + def test_warmup_does_not_reload(self, mocked_factory): + """ + Test for checking backend instances after multiple warm-ups. + """ + embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5") + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + embedder.warm_up() + mocked_factory.get_embedding_backend.assert_called_once() + + def test_embed(self): + """ + Test for checking output dimensions and embedding dimensions. + """ + embedder = FastembedDocumentEmbedder(model="BAAI/bge-base-en-v1.5") + embedder.embedding_backend = MagicMock() + embedder.embedding_backend.embed = lambda x, **kwargs: np.random.rand(len(x), 16).tolist() # noqa: ARG005 + + documents = [Document(content=f"Sample-document text {i}") for i in range(5)] + + result = embedder.run(documents=documents) + + assert isinstance(result["documents"], list) + assert len(result["documents"]) == len(documents) + for doc in result["documents"]: + assert isinstance(doc, Document) + assert isinstance(doc.embedding, list) + assert isinstance(doc.embedding[0], float) + + def test_embed_incorrect_input_format(self): + """ + Test for checking incorrect input format when creating embedding. + """ + embedder = FastembedDocumentEmbedder(model="BAAI/bge-small-en-v1.5") + + string_input = "text" + list_integers_input = [1, 2, 3] + + with pytest.raises( + TypeError, + match="FastembedDocumentEmbedder expects a list of Documents as input.", + ): + embedder.run(documents=string_input) + + with pytest.raises( + TypeError, + match="FastembedDocumentEmbedder expects a list of Documents as input.", + ): + embedder.run(documents=list_integers_input) + + def test_embed_metadata(self): + """ + Test for checking output dimensions and embedding dimensions for documents + with a custom instruction and metadata. + """ + embedder = FastembedDocumentEmbedder( + model="model", + meta_fields_to_embed=["meta_field"], + embedding_separator="\n", + ) + embedder.embedding_backend = MagicMock() + + documents = [Document(content=f"document-number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)] + + embedder.run(documents=documents) + + embedder.embedding_backend.embed.assert_called_once_with( + [ + "meta_value 0\ndocument-number 0", + "meta_value 1\ndocument-number 1", + "meta_value 2\ndocument-number 2", + "meta_value 3\ndocument-number 3", + "meta_value 4\ndocument-number 4", + ], + batch_size=256, + show_progress_bar=True, + ) + + @pytest.mark.integration + def test_run(self): + embedder = FastembedDocumentEmbedder( + model="BAAI/bge-small-en-v1.5", + ) + embedder.warm_up() + + doc = Document(content="Parton energy loss in QCD matter") + + result = embedder.run(documents=[doc]) + embedding = result["documents"][0].embedding + + assert isinstance(embedding, list) + assert len(embedding) == 384 + assert all(isinstance(emb.item(), float) for emb in embedding) diff --git a/integrations/fastembed/tests/test_fastembed_text_embedder.py b/integrations/fastembed/tests/test_fastembed_text_embedder.py new file mode 100644 index 000000000..6327532e1 --- /dev/null +++ b/integrations/fastembed/tests/test_fastembed_text_embedder.py @@ -0,0 +1,169 @@ +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest +from haystack import default_from_dict +from haystack_integrations.components.embedders.fastembed.fastembed_text_embedder import ( + FastembedTextEmbedder, +) + + +class TestFastembedTextEmbedder: + def test_init_default(self): + """ + Test default initialization parameters for FastembedTextEmbedder. + """ + embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5") + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 256 + assert embedder.progress_bar is True + + def test_init_with_parameters(self): + """ + Test custom initialization parameters for FastembedTextEmbedder. + """ + embedder = FastembedTextEmbedder( + model="BAAI/bge-small-en-v1.5", + batch_size=64, + progress_bar=False, + ) + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + + def test_to_dict(self): + """ + Test serialization of FastembedTextEmbedder to a dictionary, using default initialization parameters. + """ + embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5") + embedder_dict = embedder.to_dict() + assert embedder_dict == { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 256, + "progress_bar": True, + }, + } + + def test_to_dict_with_custom_init_parameters(self): + """ + Test serialization of FastembedTextEmbedder to a dictionary, using custom initialization parameters. + """ + embedder = FastembedTextEmbedder( + model="BAAI/bge-small-en-v1.5", + batch_size=64, + progress_bar=False, + ) + embedder_dict = embedder.to_dict() + assert embedder_dict == { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 64, + "progress_bar": False, + }, + } + + def test_from_dict(self): + """ + Test deserialization of FastembedTextEmbedder from a dictionary, using default initialization parameters. + """ + embedder_dict = { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 256, + "progress_bar": True, + }, + } + embedder = default_from_dict(FastembedTextEmbedder, embedder_dict) + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 256 + assert embedder.progress_bar is True + + def test_from_dict_with_custom_init_parameters(self): + """ + Test deserialization of FastembedTextEmbedder from a dictionary, using custom initialization parameters. + """ + embedder_dict = { + "type": "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder", # noqa + "init_parameters": { + "model": "BAAI/bge-small-en-v1.5", + "batch_size": 64, + "progress_bar": False, + }, + } + embedder = default_from_dict(FastembedTextEmbedder, embedder_dict) + assert embedder.model_name == "BAAI/bge-small-en-v1.5" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + + @patch( + "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder._FastembedEmbeddingBackendFactory" + ) + def test_warmup(self, mocked_factory): + """ + Test for checking embedder instances after warm-up. + """ + embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5") + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + mocked_factory.get_embedding_backend.assert_called_once_with(model_name="BAAI/bge-small-en-v1.5") + + @patch( + "haystack_integrations.components.embedders.fastembed.fastembed_text_embedder._FastembedEmbeddingBackendFactory" + ) + def test_warmup_does_not_reload(self, mocked_factory): + """ + Test for checking backend instances after multiple warm-ups. + """ + embedder = FastembedTextEmbedder(model="BAAI/bge-small-en-v1.5") + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + embedder.warm_up() + mocked_factory.get_embedding_backend.assert_called_once() + + def test_embed(self): + """ + Test for checking output dimensions and embedding dimensions. + """ + embedder = FastembedTextEmbedder(model="BAAI/bge-base-en-v1.5") + embedder.embedding_backend = MagicMock() + embedder.embedding_backend.embed = lambda x, **kwargs: np.random.rand(len(x), 16).tolist() # noqa: ARG005 + + text = "Good text to embed" + + result = embedder.run(text=text) + embedding = result["embedding"] + + assert isinstance(embedding, list) + assert all(isinstance(emb, float) for emb in embedding) + + def test_run_wrong_incorrect_format(self): + """ + Test for checking incorrect input format when creating embedding. + """ + embedder = FastembedTextEmbedder(model="BAAI/bge-base-en-v1.5") + embedder.embedding_backend = MagicMock() + + list_integers_input = [1, 2, 3] + + with pytest.raises(TypeError, match="FastembedTextEmbedder expects a string as input"): + embedder.run(text=list_integers_input) + + @pytest.mark.integration + def test_run(self): + embedder = FastembedTextEmbedder( + model="BAAI/bge-small-en-v1.5", + ) + embedder.warm_up() + + text = "Parton energy loss in QCD matter" + + result = embedder.run(text=text) + embedding = result["embedding"] + + assert isinstance(embedding, list) + assert len(embedding) == 384 + assert all(isinstance(emb.item(), float) for emb in embedding)