From 59cacc50c8e8ba4517a67b49c47931d4ef71f347 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Thu, 19 Feb 2026 19:50:01 +0100 Subject: [PATCH 01/21] feat: create pyversity integration --- integrations/pyversity/CHANGELOG.md | 9 + integrations/pyversity/LICENSE.txt | 73 +++++++++ integrations/pyversity/README.md | 13 ++ integrations/pyversity/examples/pipeline.py | 52 ++++++ integrations/pyversity/examples/standalone.py | 26 +++ .../pyversity/pydoc/config_docusaurus.yml | 13 ++ integrations/pyversity/pyproject.toml | 154 ++++++++++++++++++ .../components/rankers/pyversity/__init__.py | 7 + .../components/rankers/pyversity/reranker.py | 73 +++++++++ integrations/pyversity/tests/__init__.py | 3 + integrations/pyversity/tests/test_reranker.py | 140 ++++++++++++++++ 11 files changed, 563 insertions(+) create mode 100644 integrations/pyversity/CHANGELOG.md create mode 100644 integrations/pyversity/LICENSE.txt create mode 100644 integrations/pyversity/README.md create mode 100644 integrations/pyversity/examples/pipeline.py create mode 100644 integrations/pyversity/examples/standalone.py create mode 100644 integrations/pyversity/pydoc/config_docusaurus.yml create mode 100644 integrations/pyversity/pyproject.toml create mode 100644 integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py create mode 100644 integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py create mode 100644 integrations/pyversity/tests/__init__.py create mode 100644 integrations/pyversity/tests/test_reranker.py diff --git a/integrations/pyversity/CHANGELOG.md b/integrations/pyversity/CHANGELOG.md new file mode 100644 index 0000000000..be1bc3ca6b --- /dev/null +++ b/integrations/pyversity/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changelog + +## [integrations/pyversity-v0.1.0] - 2026-02-19 + +### 🚀 Features + +- Add `PyversityReranker` component wrapping pyversity's diversification algorithms + + diff --git a/integrations/pyversity/LICENSE.txt b/integrations/pyversity/LICENSE.txt new file mode 100644 index 0000000000..137069b823 --- /dev/null +++ b/integrations/pyversity/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/pyversity/README.md b/integrations/pyversity/README.md new file mode 100644 index 0000000000..3e85c31853 --- /dev/null +++ b/integrations/pyversity/README.md @@ -0,0 +1,13 @@ +# pyversity-haystack + +[![PyPI - Version](https://img.shields.io/pypi/v/pyversity-haystack.svg)](https://pypi.org/project/pyversity-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pyversity-haystack.svg)](https://pypi.org/project/pyversity-haystack) + +- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/pyversity/CHANGELOG.md) + + +--- + +## Contributing + +Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md). diff --git a/integrations/pyversity/examples/pipeline.py b/integrations/pyversity/examples/pipeline.py new file mode 100644 index 0000000000..2df9dab463 --- /dev/null +++ b/integrations/pyversity/examples/pipeline.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2026-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack import Document, Pipeline +from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder +from haystack.components.retrievers import InMemoryEmbeddingRetriever +from haystack.document_stores.in_memory import InMemoryDocumentStore +from pyversity import Strategy + +from haystack_integrations.components.rankers.pyversity import PyversityReranker + +# --- Index documents --- +document_store = InMemoryDocumentStore() + +raw_documents = [ + Document(content="Paris is the capital of France."), + Document(content="The Eiffel Tower is located in Paris."), + Document(content="Berlin is the capital of Germany."), + Document(content="The Brandenburg Gate is in Berlin."), + Document(content="France borders Spain to the south."), + Document(content="The Louvre is the world's largest art museum and is in Paris."), + Document(content="Munich is the capital of Bavaria."), + Document(content="The Rhine river flows through Germany and France."), +] + +doc_embedder = SentenceTransformersDocumentEmbedder() +doc_embedder.warm_up() +documents_with_embeddings = doc_embedder.run(raw_documents)["documents"] +document_store.write_documents(documents_with_embeddings) + +# --- Build pipeline --- +pipeline = Pipeline() +pipeline.add_component("text_embedder", SentenceTransformersTextEmbedder()) +pipeline.add_component( + "retriever", + InMemoryEmbeddingRetriever(document_store=document_store, top_k=6, return_embedding=True), +) +pipeline.add_component("reranker", PyversityReranker(k=3, strategy=Strategy.MMR, diversity=0.7)) + +pipeline.connect("text_embedder.embedding", "retriever.query_embedding") +pipeline.connect("retriever.documents", "reranker.documents") + +# --- Run --- +result = pipeline.run({"text_embedder": {"text": "What are the famous landmarks in France?"}}) + +for doc in result["reranker"]["documents"]: + print(f"{doc.score:.4f} {doc.content}") + +# 0.xxxx Paris is the capital of France. +# 0.xxxx The Eiffel Tower is located in Paris. +# 0.xxxx France borders Spain to the south. diff --git a/integrations/pyversity/examples/standalone.py b/integrations/pyversity/examples/standalone.py new file mode 100644 index 0000000000..2f1efa2464 --- /dev/null +++ b/integrations/pyversity/examples/standalone.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: 2026-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack import Document +from pyversity import Strategy + +from haystack_integrations.components.rankers.pyversity import PyversityReranker + +documents = [ + Document(content="Paris is the capital of France.", score=0.95, embedding=[0.9, 0.1, 0.0, 0.0]), + Document(content="The Eiffel Tower is located in Paris.", score=0.90, embedding=[0.8, 0.2, 0.0, 0.0]), + Document(content="Berlin is the capital of Germany.", score=0.85, embedding=[0.0, 0.0, 0.9, 0.1]), + Document(content="The Brandenburg Gate is in Berlin.", score=0.80, embedding=[0.0, 0.0, 0.8, 0.2]), + Document(content="France borders Spain to the south.", score=0.75, embedding=[0.5, 0.5, 0.0, 0.0]), +] + +reranker = PyversityReranker(k=3, strategy=Strategy.MMR, diversity=0.7) +result = reranker.run(documents=documents) + +for doc in result["documents"]: + print(f"{doc.score:.2f} {doc.content}") + +# 0.95 Paris is the capital of France. +# 0.85 Berlin is the capital of Germany. +# 0.75 France borders Spain to the south. diff --git a/integrations/pyversity/pydoc/config_docusaurus.yml b/integrations/pyversity/pydoc/config_docusaurus.yml new file mode 100644 index 0000000000..74d50921c4 --- /dev/null +++ b/integrations/pyversity/pydoc/config_docusaurus.yml @@ -0,0 +1,13 @@ +loaders: + - modules: + - haystack_integrations.components.rankers.pyversity.reranker + search_path: [../src] +processors: + - type: filter + documented_only: true + skip_empty_modules: true +renderer: + description: pyversity integration for Haystack + id: integrations-pyversity + filename: pyversity.md + title: pyversity diff --git a/integrations/pyversity/pyproject.toml b/integrations/pyversity/pyproject.toml new file mode 100644 index 0000000000..ef235b71da --- /dev/null +++ b/integrations/pyversity/pyproject.toml @@ -0,0 +1,154 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "pyversity-haystack" +dynamic = ["version"] +description = 'Haystack component wrapping pyversity for result diversification in retrieval pipelines' +readme = "README.md" +requires-python = ">=3.10" +license = "Apache-2.0" +keywords = [] +authors = [ + { name = "Kacper Łukawski", email = "kacper.lukawski@deepset.ai" }, + { name = "deepset GmbH", email = "info@deepset.ai" }, +] +classifiers = [ + "License :: OSI Approved :: Apache Software License", + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = [ + "haystack-ai>=2.24.1", + "pyversity>=0.2.0", +] + +[project.urls] +Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/pyversity#readme" +Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues" +Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/pyversity" + +[tool.hatch.build.targets.wheel] +packages = ["src/haystack_integrations"] + +[tool.hatch.version] +source = "vcs" +tag-pattern = 'integrations\/pyversity-v(?P.*)' + +[tool.hatch.version.raw-options] +root = "../.." +git_describe_command = 'git describe --tags --match="integrations/pyversity-v[0-9]*"' + +[tool.hatch.envs.default] +installer = "uv" +dependencies = ["haystack-pydoc-tools", "ruff"] + +[tool.hatch.envs.default.scripts] +docs = ["haystack-pydoc pydoc/config_docusaurus.yml"] +fmt = "ruff check --fix {args}; ruff format {args}" +fmt-check = "ruff check {args} && ruff format --check {args}" + +[tool.hatch.envs.test] +dependencies = [ + "pytest", + "pytest-asyncio", + "pytest-cov", + "pytest-rerunfailures", + "mypy", + "pip", +] + +[tool.hatch.envs.test.scripts] +unit = 'pytest -m "not integration" {args:tests}' +integration = 'pytest -m "integration" {args:tests}' +all = 'pytest {args:tests}' +cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x {args:tests}' +types = "mypy -p haystack_integrations.components.rankers.pyversity {args}" + +[tool.mypy] +install_types = true +non_interactive = true +check_untyped_defs = true +disallow_incomplete_defs = true + +[tool.ruff] +line-length = 120 + +[tool.ruff.lint] +select = [ + "A", + "ARG", + "B", + "C", + "DTZ", + "E", + "EM", + "F", + "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", + # Ignore checks for possible passwords + "S105", + "S106", + "S107", + # Ignore complexity + "C901", + "PLR0911", + "PLR0912", + "PLR0913", + "PLR0915", + # Misc + "B008", + "S101", +] + +[tool.ruff.lint.isort] +known-first-party = ["haystack_integrations"] + +[tool.ruff.lint.flake8-tidy-imports] +ban-relative-imports = "parents" + +[tool.ruff.lint.per-file-ignores] +# Tests can use magic values, assertions, and relative imports +"tests/**/*" = ["PLR2004", "S101", "TID252"] + +[tool.coverage.run] +source = ["haystack_integrations"] +branch = true +parallel = false + +[tool.coverage.report] +omit = ["*/tests/*", "*/__init__.py"] +show_missing = true +exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] + +[tool.pytest.ini_options] +addopts = "--strict-markers" +markers = ["integration: integration tests"] +log_cli = true +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "class" diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py new file mode 100644 index 0000000000..deda1ab08b --- /dev/null +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2026-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack_integrations.components.rankers.pyversity.reranker import PyversityReranker + +__all__ = ["PyversityReranker"] diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py new file mode 100644 index 0000000000..31e60ee550 --- /dev/null +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2026-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +"""Haystack integration for `pyversity `_. + +Wraps pyversity's diversification algorithms as a Haystack ``@component``, +making it easy to drop result diversification into any Haystack pipeline. +""" + +import logging + +import numpy as np +from haystack import Document, component + +from pyversity import Strategy, diversify + +logger = logging.getLogger(__name__) + + +@component +class PyversityReranker: + """Rerank documents using pyversity's diversification algorithms. + + Balances relevance and diversity in a ranked list of documents. Documents + must have both ``score`` and ``embedding`` populated (e.g. as returned by + a dense retriever with ``return_embedding=True``). + + Args: + k: Number of documents to return after diversification. + strategy: Pyversity diversification strategy (e.g. ``Strategy.MMR``). + diversity: Trade-off between relevance and diversity in [0, 1]. + ``0.0`` keeps only the most relevant documents; ``1.0`` maximises + diversity regardless of relevance. Defaults to ``0.5``. + """ + + def __init__(self, k: int, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: + if k <= 0: + raise ValueError(f"k must be a positive integer, got {k}") + if not 0.0 <= diversity <= 1.0: + raise ValueError(f"diversity must be in [0, 1], got {diversity}") + self._k = k + self._strategy = strategy + self._diversity = diversity + + @component.output_types(documents=list[Document]) + def run(self, documents: list[Document]) -> dict: + if not documents: + return {"documents": []} + + valid_docs = [doc for doc in documents if doc.score is not None and doc.embedding is not None] + skipped = len(documents) - len(valid_docs) + if skipped: + logger.warning( + "%d document(s) are missing 'score' or 'embedding' and will be skipped.", + skipped, + ) + + if not valid_docs: + return {"documents": []} + + embeddings = np.array([doc.embedding for doc in valid_docs]) + scores = np.array([doc.score for doc in valid_docs]) + + result = diversify( + embeddings=embeddings, + scores=scores, + k=min(self._k, len(valid_docs)), + strategy=self._strategy, + diversity=self._diversity, + ) + + return {"documents": [valid_docs[i] for i in result.indices]} diff --git a/integrations/pyversity/tests/__init__.py b/integrations/pyversity/tests/__init__.py new file mode 100644 index 0000000000..1872f673d7 --- /dev/null +++ b/integrations/pyversity/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2026-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/pyversity/tests/test_reranker.py b/integrations/pyversity/tests/test_reranker.py new file mode 100644 index 0000000000..e87396245f --- /dev/null +++ b/integrations/pyversity/tests/test_reranker.py @@ -0,0 +1,140 @@ +# SPDX-FileCopyrightText: 2026-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np +import pytest +from haystack import Document, Pipeline +from haystack.components.retrievers import InMemoryEmbeddingRetriever +from haystack.document_stores.in_memory import InMemoryDocumentStore +from pyversity import Strategy + +from haystack_integrations.components.rankers.pyversity import PyversityReranker + +EMBEDDING_DIM = 16 +RNG = np.random.default_rng(42) + + +@pytest.fixture() +def documents(): + docs = [] + for i in range(20): + vec = RNG.standard_normal(EMBEDDING_DIM) + vec /= np.linalg.norm(vec) + docs.append(Document(content=f"Document {i}", embedding=vec.tolist())) + return docs + + +@pytest.fixture() +def query_embedding(): + vec = RNG.standard_normal(EMBEDDING_DIM) + return (vec / np.linalg.norm(vec)).tolist() + + +@pytest.fixture() +def pipeline(documents, request): + strategy = getattr(request, "param", Strategy.MMR) + store = InMemoryDocumentStore() + store.write_documents(documents) + + p = Pipeline() + p.add_component( + "retriever", + InMemoryEmbeddingRetriever(document_store=store, top_k=15, return_embedding=True), + ) + p.add_component("reranker", PyversityReranker(k=5, strategy=strategy, diversity=0.7)) + p.connect("retriever.documents", "reranker.documents") + return p + + +class TestPyversityReranker: + def test_init_defaults(self): + reranker = PyversityReranker(k=5) + assert reranker._k == 5 + assert reranker._strategy == Strategy.DPP + assert reranker._diversity == 0.5 + + def test_init_custom_params(self): + reranker = PyversityReranker(k=10, strategy=Strategy.MMR, diversity=0.3) + assert reranker._k == 10 + assert reranker._strategy == Strategy.MMR + assert reranker._diversity == 0.3 + + def test_init_invalid_k_zero(self): + with pytest.raises(ValueError, match="k must be a positive integer"): + PyversityReranker(k=0) + + def test_init_invalid_k_negative(self): + with pytest.raises(ValueError, match="k must be a positive integer"): + PyversityReranker(k=-1) + + def test_init_invalid_diversity_above_one(self): + with pytest.raises(ValueError, match="diversity must be in"): + PyversityReranker(k=5, diversity=1.1) + + def test_init_invalid_diversity_below_zero(self): + with pytest.raises(ValueError, match="diversity must be in"): + PyversityReranker(k=5, diversity=-0.1) + + def test_run_empty_documents(self): + reranker = PyversityReranker(k=5) + result = reranker.run(documents=[]) + assert result == {"documents": []} + + def test_run_skips_docs_without_score(self): + rng = np.random.default_rng(0) + docs = [ + Document(content="has score and embedding", score=0.9, embedding=rng.standard_normal(4).tolist()), + Document(content="missing score", embedding=rng.standard_normal(4).tolist()), + ] + reranker = PyversityReranker(k=5) + result = reranker.run(documents=docs) + assert len(result["documents"]) == 1 + + def test_run_skips_docs_without_embedding(self): + docs = [ + Document(content="has score and embedding", score=0.9, embedding=[0.1, 0.2, 0.3, 0.4]), + Document(content="missing embedding", score=0.5), + ] + reranker = PyversityReranker(k=5) + result = reranker.run(documents=docs) + assert len(result["documents"]) == 1 + + def test_run_all_docs_invalid_returns_empty(self): + docs = [ + Document(content="no score", embedding=[0.1, 0.2]), + Document(content="no embedding", score=0.5), + ] + reranker = PyversityReranker(k=5) + result = reranker.run(documents=docs) + assert result == {"documents": []} + + def test_run_returns_at_most_k_documents(self): + rng = np.random.default_rng(1) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(10) + ] + reranker = PyversityReranker(k=3) + result = reranker.run(documents=docs) + assert len(result["documents"]) <= 3 + + def test_run_returns_fewer_than_k_if_not_enough_valid(self): + rng = np.random.default_rng(2) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(2) + ] + reranker = PyversityReranker(k=5) + result = reranker.run(documents=docs) + assert len(result["documents"]) == 2 + + +@pytest.mark.parametrize( + "pipeline", + [Strategy.DPP, Strategy.MMR, Strategy.MSD, Strategy.SSD, Strategy.COVER], + indirect=True, +) +def test_pipeline_returns_k_documents(pipeline, query_embedding): + result = pipeline.run({"retriever": {"query_embedding": query_embedding}}) + assert len(result["reranker"]["documents"]) == 5 From 103d8bf42ed6c7fba806b5f002c82b5a3e8ca16a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Thu, 19 Feb 2026 19:51:26 +0100 Subject: [PATCH 02/21] chore: format pyversity reranker --- .../components/rankers/pyversity/reranker.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py index 31e60ee550..385af7a239 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py @@ -36,9 +36,11 @@ class PyversityReranker: def __init__(self, k: int, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: if k <= 0: - raise ValueError(f"k must be a positive integer, got {k}") + msg = f"k must be a positive integer, got {k}" + raise ValueError(msg) if not 0.0 <= diversity <= 1.0: - raise ValueError(f"diversity must be in [0, 1], got {diversity}") + msg = f"diversity must be in [0, 1], got {diversity}" + raise ValueError(msg) self._k = k self._strategy = strategy self._diversity = diversity From 880f8686d349e252c6c3e41235640784475dd8bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Thu, 19 Feb 2026 20:03:14 +0100 Subject: [PATCH 03/21] chore: improve pyversity pipeline comments --- integrations/pyversity/examples/pipeline.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/integrations/pyversity/examples/pipeline.py b/integrations/pyversity/examples/pipeline.py index 2df9dab463..bc47686232 100644 --- a/integrations/pyversity/examples/pipeline.py +++ b/integrations/pyversity/examples/pipeline.py @@ -10,7 +10,7 @@ from haystack_integrations.components.rankers.pyversity import PyversityReranker -# --- Index documents --- +# Index documents document_store = InMemoryDocumentStore() raw_documents = [ @@ -25,11 +25,10 @@ ] doc_embedder = SentenceTransformersDocumentEmbedder() -doc_embedder.warm_up() documents_with_embeddings = doc_embedder.run(raw_documents)["documents"] document_store.write_documents(documents_with_embeddings) -# --- Build pipeline --- +# Build pipeline pipeline = Pipeline() pipeline.add_component("text_embedder", SentenceTransformersTextEmbedder()) pipeline.add_component( @@ -41,7 +40,7 @@ pipeline.connect("text_embedder.embedding", "retriever.query_embedding") pipeline.connect("retriever.documents", "reranker.documents") -# --- Run --- +# Run result = pipeline.run({"text_embedder": {"text": "What are the famous landmarks in France?"}}) for doc in result["reranker"]["documents"]: From 403fd39c872cc0777fd7aef41a9600336370abec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Thu, 19 Feb 2026 20:09:21 +0100 Subject: [PATCH 04/21] docs: rewrite the docstrings in pyversity-haystack --- .../components/rankers/pyversity/reranker.py | 51 +++++++++++++++---- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py index 385af7a239..7bb76101e4 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py @@ -20,21 +20,42 @@ @component class PyversityReranker: - """Rerank documents using pyversity's diversification algorithms. + """ + Reranks documents using [pyversity](https://github.com/Pringled/pyversity)'s diversification algorithms. Balances relevance and diversity in a ranked list of documents. Documents - must have both ``score`` and ``embedding`` populated (e.g. as returned by - a dense retriever with ``return_embedding=True``). - - Args: - k: Number of documents to return after diversification. - strategy: Pyversity diversification strategy (e.g. ``Strategy.MMR``). - diversity: Trade-off between relevance and diversity in [0, 1]. - ``0.0`` keeps only the most relevant documents; ``1.0`` maximises - diversity regardless of relevance. Defaults to ``0.5``. + must have both `score` and `embedding` populated (e.g. as returned by + a dense retriever with `return_embedding=True`). + + Usage example: + ```python + from haystack import Document + from haystack_integrations.components.rankers.pyversity import PyversityReranker + from pyversity import Strategy + + ranker = PyversityReranker(k=5, strategy=Strategy.MMR, diversity=0.5) + + docs = [ + Document(content="Paris", score=0.9, embedding=[0.1, 0.2]), + Document(content="Berlin", score=0.8, embedding=[0.3, 0.4]), + ] + output = ranker.run(documents=docs) + docs = output["documents"] + ``` """ def __init__(self, k: int, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: + """ + Creates an instance of PyversityReranker. + + :param k: Number of documents to return after diversification. + :param strategy: Pyversity diversification strategy (e.g. `Strategy.MMR`). Defaults to `Strategy.DPP`. + :param diversity: Trade-off between relevance and diversity in [0, 1]. + `0.0` keeps only the most relevant documents; `1.0` maximises + diversity regardless of relevance. Defaults to `0.5`. + + :raises ValueError: If `k` is not a positive integer or `diversity` is not in [0, 1]. + """ if k <= 0: msg = f"k must be a positive integer, got {k}" raise ValueError(msg) @@ -47,6 +68,16 @@ def __init__(self, k: int, *, strategy: Strategy = Strategy.DPP, diversity: floa @component.output_types(documents=list[Document]) def run(self, documents: list[Document]) -> dict: + """ + Rerank the list of documents using pyversity's diversification algorithm. + + Documents missing `score` or `embedding` are skipped with a warning. + + :param documents: List of Documents to rerank. Each document must have `score` and `embedding` set. + :returns: + A dictionary with the following keys: + - `documents`: List of up to `k` reranked Documents, ordered by the diversification algorithm. + """ if not documents: return {"documents": []} From 3cf854378f5c5c98415347105c90eb23a8535adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Thu, 19 Feb 2026 20:36:27 +0100 Subject: [PATCH 05/21] chore: repo-wide changes for pyversity --- .github/labeler.yml | 5 +++ .github/workflows/pyversity.yml | 63 +++++++++++++++++++++++++++++++++ README.md | 1 + 3 files changed, 69 insertions(+) create mode 100644 .github/workflows/pyversity.yml diff --git a/.github/labeler.yml b/.github/labeler.yml index 7b3657adb2..912cb581de 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -167,6 +167,11 @@ integration:pinecone: - any-glob-to-any-file: "integrations/pinecone/**/*" - any-glob-to-any-file: ".github/workflows/pinecone.yml" +integration:pyversity: + - changed-files: + - any-glob-to-any-file: "integrations/pyversity/**/*" + - any-glob-to-any-file: ".github/workflows/pyversity.yml" + integration:qdrant: - changed-files: - any-glob-to-any-file: "integrations/qdrant/**/*" diff --git a/.github/workflows/pyversity.yml b/.github/workflows/pyversity.yml new file mode 100644 index 0000000000..cc99bdf263 --- /dev/null +++ b/.github/workflows/pyversity.yml @@ -0,0 +1,63 @@ +name: Test / pyversity + +on: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "integrations/pyversity/**" + - "!integrations/pyversity/*.md" + - ".github/workflows/pyversity.yml" + +defaults: + run: + working-directory: integrations/pyversity + +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, windows-latest, macos-latest] + python-version: ["3.10", "3.13"] + + steps: + - uses: actions/checkout@v6 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Hatch + run: pip install --upgrade hatch + + - name: Lint + if: matrix.python-version == '3.10' && runner.os == 'Linux' + run: hatch run fmt-check && hatch run test:types + + - name: Run tests + run: hatch run test:cov-retry + + - name: Run unit tests with lowest direct dependencies + run: | + hatch run uv pip compile pyproject.toml --resolution lowest-direct --output-file requirements_lowest_direct.txt + hatch -e test env run -- uv pip install -r requirements_lowest_direct.txt + hatch run test:unit + + - name: Nightly - run unit tests with Haystack main branch + if: github.event_name == 'schedule' + run: | + hatch env prune + hatch -e test env run -- uv pip install git+https://github.com/deepset-ai/haystack.git@main + hatch run test:unit + + - name: Send event to Datadog for nightly failures + if: failure() && github.event_name == 'schedule' + uses: ./.github/actions/send_failure + with: + title: | + Core integrations nightly tests failure: ${{ github.workflow }} + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} diff --git a/README.md b/README.md index b52153e7fa..bf9c8c6cab 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ Please check out our [Contribution Guidelines](CONTRIBUTING.md) for all the deta | [paddleocr-haystack](integrations/paddleocr/) | Converter | [![PyPI - Version](https://img.shields.io/pypi/v/paddleocr-haystack.svg)](https://pypi.org/project/paddleocr-haystack) | [![Test / paddleocr](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/paddleocr.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/paddleocr.yml) | | [pinecone-haystack](integrations/pinecone/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/pinecone-haystack.svg?color=orange)](https://pypi.org/project/pinecone-haystack) | [![Test / pinecone](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/pinecone.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/pinecone.yml) | | [pgvector-haystack](integrations/pgvector/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/pgvector-haystack.svg?color=orange)](https://pypi.org/project/pgvector-haystack) | [![Test / pgvector](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/pgvector.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/pgvector.yml) | +| [pyversity-haystack](integrations/pyversity/) | Ranker | [![PyPI - Version](https://img.shields.io/pypi/v/pyversity-haystack.svg)](https://pypi.org/project/pyversity-haystack) | [![Test / pyversity](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/pyversity.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/pyversity.yml) | | [qdrant-haystack](integrations/qdrant/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/qdrant-haystack.svg?color=orange)](https://pypi.org/project/qdrant-haystack) | [![Test / qdrant](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/qdrant.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/qdrant.yml) | | [ragas-haystack](integrations/ragas/) | Evaluator | [![PyPI - Version](https://img.shields.io/pypi/v/ragas-haystack.svg)](https://pypi.org/project/ragas-haystack) | [![Test / ragas](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/ragas.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/ragas.yml) | | [snowflake-haystack](integrations/snowflake/) | Retriever | [![PyPI - Version](https://img.shields.io/pypi/v/snowflake-haystack.svg)](https://pypi.org/project/snowflake-haystack) | [![Test / snowflake](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/snowflake.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/snowflake.yml) | From fdce1149c5d7fce18943ea853e911c64ad22bff7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Thu, 19 Feb 2026 20:47:27 +0100 Subject: [PATCH 06/21] chore: allow print statements in pyversity examples --- integrations/pyversity/pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/integrations/pyversity/pyproject.toml b/integrations/pyversity/pyproject.toml index ef235b71da..4af4bec446 100644 --- a/integrations/pyversity/pyproject.toml +++ b/integrations/pyversity/pyproject.toml @@ -135,6 +135,8 @@ ban-relative-imports = "parents" [tool.ruff.lint.per-file-ignores] # Tests can use magic values, assertions, and relative imports "tests/**/*" = ["PLR2004", "S101", "TID252"] +# Examples can use print statements +"examples/**/*" = ["T201"] [tool.coverage.run] source = ["haystack_integrations"] From e503c7aaaaf2a0bd87a44e93b9788319d14f9e60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Thu, 19 Feb 2026 21:12:37 +0100 Subject: [PATCH 07/21] chore: add py.typed --- .../haystack_integrations/components/rankers/pyversity/py.typed | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/py.typed diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/py.typed b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/py.typed new file mode 100644 index 0000000000..e69de29bb2 From 382a9266cd3f32fbf70aa36b0217100615ca67bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Fri, 20 Feb 2026 16:20:28 +0100 Subject: [PATCH 08/21] chore: rename k to top_k --- integrations/pyversity/examples/pipeline.py | 2 +- integrations/pyversity/examples/standalone.py | 2 +- .../components/rankers/pyversity/reranker.py | 18 +++++----- integrations/pyversity/tests/test_reranker.py | 34 +++++++++---------- 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/integrations/pyversity/examples/pipeline.py b/integrations/pyversity/examples/pipeline.py index bc47686232..5f4e2b4a2c 100644 --- a/integrations/pyversity/examples/pipeline.py +++ b/integrations/pyversity/examples/pipeline.py @@ -35,7 +35,7 @@ "retriever", InMemoryEmbeddingRetriever(document_store=document_store, top_k=6, return_embedding=True), ) -pipeline.add_component("reranker", PyversityReranker(k=3, strategy=Strategy.MMR, diversity=0.7)) +pipeline.add_component("reranker", PyversityReranker(top_k=3, strategy=Strategy.MMR, diversity=0.7)) pipeline.connect("text_embedder.embedding", "retriever.query_embedding") pipeline.connect("retriever.documents", "reranker.documents") diff --git a/integrations/pyversity/examples/standalone.py b/integrations/pyversity/examples/standalone.py index 2f1efa2464..717bf72444 100644 --- a/integrations/pyversity/examples/standalone.py +++ b/integrations/pyversity/examples/standalone.py @@ -15,7 +15,7 @@ Document(content="France borders Spain to the south.", score=0.75, embedding=[0.5, 0.5, 0.0, 0.0]), ] -reranker = PyversityReranker(k=3, strategy=Strategy.MMR, diversity=0.7) +reranker = PyversityReranker(top_k=3, strategy=Strategy.MMR, diversity=0.7) result = reranker.run(documents=documents) for doc in result["documents"]: diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py index 7bb76101e4..8ca57314e4 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py @@ -33,7 +33,7 @@ class PyversityReranker: from haystack_integrations.components.rankers.pyversity import PyversityReranker from pyversity import Strategy - ranker = PyversityReranker(k=5, strategy=Strategy.MMR, diversity=0.5) + ranker = PyversityReranker(top_k=5, strategy=Strategy.MMR, diversity=0.5) docs = [ Document(content="Paris", score=0.9, embedding=[0.1, 0.2]), @@ -44,25 +44,25 @@ class PyversityReranker: ``` """ - def __init__(self, k: int, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: + def __init__(self, top_k: int, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: """ Creates an instance of PyversityReranker. - :param k: Number of documents to return after diversification. + :param top_k: Number of documents to return after diversification. :param strategy: Pyversity diversification strategy (e.g. `Strategy.MMR`). Defaults to `Strategy.DPP`. :param diversity: Trade-off between relevance and diversity in [0, 1]. `0.0` keeps only the most relevant documents; `1.0` maximises diversity regardless of relevance. Defaults to `0.5`. - :raises ValueError: If `k` is not a positive integer or `diversity` is not in [0, 1]. + :raises ValueError: If `top_k` is not a positive integer or `diversity` is not in [0, 1]. """ - if k <= 0: - msg = f"k must be a positive integer, got {k}" + if top_k <= 0: + msg = f"top_k must be a positive integer, got {top_k}" raise ValueError(msg) if not 0.0 <= diversity <= 1.0: msg = f"diversity must be in [0, 1], got {diversity}" raise ValueError(msg) - self._k = k + self._top_k = top_k self._strategy = strategy self._diversity = diversity @@ -76,7 +76,7 @@ def run(self, documents: list[Document]) -> dict: :param documents: List of Documents to rerank. Each document must have `score` and `embedding` set. :returns: A dictionary with the following keys: - - `documents`: List of up to `k` reranked Documents, ordered by the diversification algorithm. + - `documents`: List of up to `top_k` reranked Documents, ordered by the diversification algorithm. """ if not documents: return {"documents": []} @@ -98,7 +98,7 @@ def run(self, documents: list[Document]) -> dict: result = diversify( embeddings=embeddings, scores=scores, - k=min(self._k, len(valid_docs)), + k=min(self._top_k, len(valid_docs)), strategy=self._strategy, diversity=self._diversity, ) diff --git a/integrations/pyversity/tests/test_reranker.py b/integrations/pyversity/tests/test_reranker.py index e87396245f..47195e75b4 100644 --- a/integrations/pyversity/tests/test_reranker.py +++ b/integrations/pyversity/tests/test_reranker.py @@ -42,42 +42,42 @@ def pipeline(documents, request): "retriever", InMemoryEmbeddingRetriever(document_store=store, top_k=15, return_embedding=True), ) - p.add_component("reranker", PyversityReranker(k=5, strategy=strategy, diversity=0.7)) + p.add_component("reranker", PyversityReranker(top_k=5, strategy=strategy, diversity=0.7)) p.connect("retriever.documents", "reranker.documents") return p class TestPyversityReranker: def test_init_defaults(self): - reranker = PyversityReranker(k=5) - assert reranker._k == 5 + reranker = PyversityReranker(top_k=5) + assert reranker._top_k == 5 assert reranker._strategy == Strategy.DPP assert reranker._diversity == 0.5 def test_init_custom_params(self): - reranker = PyversityReranker(k=10, strategy=Strategy.MMR, diversity=0.3) - assert reranker._k == 10 + reranker = PyversityReranker(top_k=10, strategy=Strategy.MMR, diversity=0.3) + assert reranker._top_k == 10 assert reranker._strategy == Strategy.MMR assert reranker._diversity == 0.3 def test_init_invalid_k_zero(self): - with pytest.raises(ValueError, match="k must be a positive integer"): - PyversityReranker(k=0) + with pytest.raises(ValueError, match="top_k must be a positive integer"): + PyversityReranker(top_k=0) def test_init_invalid_k_negative(self): - with pytest.raises(ValueError, match="k must be a positive integer"): - PyversityReranker(k=-1) + with pytest.raises(ValueError, match="top_k must be a positive integer"): + PyversityReranker(top_k=-1) def test_init_invalid_diversity_above_one(self): with pytest.raises(ValueError, match="diversity must be in"): - PyversityReranker(k=5, diversity=1.1) + PyversityReranker(top_k=5, diversity=1.1) def test_init_invalid_diversity_below_zero(self): with pytest.raises(ValueError, match="diversity must be in"): - PyversityReranker(k=5, diversity=-0.1) + PyversityReranker(top_k=5, diversity=-0.1) def test_run_empty_documents(self): - reranker = PyversityReranker(k=5) + reranker = PyversityReranker(top_k=5) result = reranker.run(documents=[]) assert result == {"documents": []} @@ -87,7 +87,7 @@ def test_run_skips_docs_without_score(self): Document(content="has score and embedding", score=0.9, embedding=rng.standard_normal(4).tolist()), Document(content="missing score", embedding=rng.standard_normal(4).tolist()), ] - reranker = PyversityReranker(k=5) + reranker = PyversityReranker(top_k=5) result = reranker.run(documents=docs) assert len(result["documents"]) == 1 @@ -96,7 +96,7 @@ def test_run_skips_docs_without_embedding(self): Document(content="has score and embedding", score=0.9, embedding=[0.1, 0.2, 0.3, 0.4]), Document(content="missing embedding", score=0.5), ] - reranker = PyversityReranker(k=5) + reranker = PyversityReranker(top_k=5) result = reranker.run(documents=docs) assert len(result["documents"]) == 1 @@ -105,7 +105,7 @@ def test_run_all_docs_invalid_returns_empty(self): Document(content="no score", embedding=[0.1, 0.2]), Document(content="no embedding", score=0.5), ] - reranker = PyversityReranker(k=5) + reranker = PyversityReranker(top_k=5) result = reranker.run(documents=docs) assert result == {"documents": []} @@ -115,7 +115,7 @@ def test_run_returns_at_most_k_documents(self): Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) for i in range(10) ] - reranker = PyversityReranker(k=3) + reranker = PyversityReranker(top_k=3) result = reranker.run(documents=docs) assert len(result["documents"]) <= 3 @@ -125,7 +125,7 @@ def test_run_returns_fewer_than_k_if_not_enough_valid(self): Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) for i in range(2) ] - reranker = PyversityReranker(k=5) + reranker = PyversityReranker(top_k=5) result = reranker.run(documents=docs) assert len(result["documents"]) == 2 From 9010cab914a1e6897ec918fd89308f823ba56afd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Fri, 20 Feb 2026 16:23:13 +0100 Subject: [PATCH 09/21] chore: rename object attrs (remove leading underscores) --- .../components/rankers/pyversity/reranker.py | 12 ++++++------ integrations/pyversity/tests/test_reranker.py | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py index 8ca57314e4..ff77ba465f 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py @@ -62,9 +62,9 @@ def __init__(self, top_k: int, *, strategy: Strategy = Strategy.DPP, diversity: if not 0.0 <= diversity <= 1.0: msg = f"diversity must be in [0, 1], got {diversity}" raise ValueError(msg) - self._top_k = top_k - self._strategy = strategy - self._diversity = diversity + self.top_k = top_k + self.strategy = strategy + self.diversity = diversity @component.output_types(documents=list[Document]) def run(self, documents: list[Document]) -> dict: @@ -98,9 +98,9 @@ def run(self, documents: list[Document]) -> dict: result = diversify( embeddings=embeddings, scores=scores, - k=min(self._top_k, len(valid_docs)), - strategy=self._strategy, - diversity=self._diversity, + k=min(self.top_k, len(valid_docs)), + strategy=self.strategy, + diversity=self.diversity, ) return {"documents": [valid_docs[i] for i in result.indices]} diff --git a/integrations/pyversity/tests/test_reranker.py b/integrations/pyversity/tests/test_reranker.py index 47195e75b4..b1032bf680 100644 --- a/integrations/pyversity/tests/test_reranker.py +++ b/integrations/pyversity/tests/test_reranker.py @@ -50,15 +50,15 @@ def pipeline(documents, request): class TestPyversityReranker: def test_init_defaults(self): reranker = PyversityReranker(top_k=5) - assert reranker._top_k == 5 - assert reranker._strategy == Strategy.DPP - assert reranker._diversity == 0.5 + assert reranker.top_k == 5 + assert reranker.strategy == Strategy.DPP + assert reranker.diversity == 0.5 def test_init_custom_params(self): reranker = PyversityReranker(top_k=10, strategy=Strategy.MMR, diversity=0.3) - assert reranker._top_k == 10 - assert reranker._strategy == Strategy.MMR - assert reranker._diversity == 0.3 + assert reranker.top_k == 10 + assert reranker.strategy == Strategy.MMR + assert reranker.diversity == 0.3 def test_init_invalid_k_zero(self): with pytest.raises(ValueError, match="top_k must be a positive integer"): From ee1e00a3fbe7941919ce7cc52e3786bf1e87bcfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:03:49 +0100 Subject: [PATCH 10/21] chore: remove CHANGELOG.md for pyversity integration --- integrations/pyversity/CHANGELOG.md | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 integrations/pyversity/CHANGELOG.md diff --git a/integrations/pyversity/CHANGELOG.md b/integrations/pyversity/CHANGELOG.md deleted file mode 100644 index be1bc3ca6b..0000000000 --- a/integrations/pyversity/CHANGELOG.md +++ /dev/null @@ -1,9 +0,0 @@ -# Changelog - -## [integrations/pyversity-v0.1.0] - 2026-02-19 - -### 🚀 Features - -- Add `PyversityReranker` component wrapping pyversity's diversification algorithms - - From 9363c34802a26568852b3f8572e38a78baa58456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:08:15 +0100 Subject: [PATCH 11/21] chore: update copyright year and owner in LICENSE.txt --- integrations/pyversity/LICENSE.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/pyversity/LICENSE.txt b/integrations/pyversity/LICENSE.txt index 137069b823..c6086717c9 100644 --- a/integrations/pyversity/LICENSE.txt +++ b/integrations/pyversity/LICENSE.txt @@ -58,7 +58,7 @@ 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] +Copyright 2026 deepset GmbH Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From 75cc052d51c241adae81f6c3e086c0c0d785e5ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:10:22 +0100 Subject: [PATCH 12/21] chore: move py.typed to rankers --- .../components/rankers/{pyversity => }/py.typed | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename integrations/pyversity/src/haystack_integrations/components/rankers/{pyversity => }/py.typed (100%) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/py.typed b/integrations/pyversity/src/haystack_integrations/components/rankers/py.typed similarity index 100% rename from integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/py.typed rename to integrations/pyversity/src/haystack_integrations/components/rankers/py.typed From be854138ba8af603a005e89cc1e6470c548255bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:15:57 +0100 Subject: [PATCH 13/21] chore: downgrade haystack-ai dependency version to >=2.2.0 --- integrations/pyversity/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/pyversity/pyproject.toml b/integrations/pyversity/pyproject.toml index 4af4bec446..7807e6cca4 100644 --- a/integrations/pyversity/pyproject.toml +++ b/integrations/pyversity/pyproject.toml @@ -26,7 +26,7 @@ classifiers = [ "Programming Language :: Python :: Implementation :: PyPy", ] dependencies = [ - "haystack-ai>=2.24.1", + "haystack-ai>=2.2.0", "pyversity>=0.2.0", ] From 501a46ce04f2223a128b313037f584dd81e01327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:17:38 +0100 Subject: [PATCH 14/21] refactor: rename PyversityReranker to PyversityRanker --- integrations/pyversity/examples/pipeline.py | 4 +-- integrations/pyversity/examples/standalone.py | 4 +-- .../components/rankers/pyversity/__init__.py | 4 +-- .../components/rankers/pyversity/reranker.py | 8 ++--- integrations/pyversity/tests/test_reranker.py | 30 +++++++++---------- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/integrations/pyversity/examples/pipeline.py b/integrations/pyversity/examples/pipeline.py index 5f4e2b4a2c..6070f72fb2 100644 --- a/integrations/pyversity/examples/pipeline.py +++ b/integrations/pyversity/examples/pipeline.py @@ -8,7 +8,7 @@ from haystack.document_stores.in_memory import InMemoryDocumentStore from pyversity import Strategy -from haystack_integrations.components.rankers.pyversity import PyversityReranker +from haystack_integrations.components.rankers.pyversity import PyversityRanker # Index documents document_store = InMemoryDocumentStore() @@ -35,7 +35,7 @@ "retriever", InMemoryEmbeddingRetriever(document_store=document_store, top_k=6, return_embedding=True), ) -pipeline.add_component("reranker", PyversityReranker(top_k=3, strategy=Strategy.MMR, diversity=0.7)) +pipeline.add_component("reranker", PyversityRanker(top_k=3, strategy=Strategy.MMR, diversity=0.7)) pipeline.connect("text_embedder.embedding", "retriever.query_embedding") pipeline.connect("retriever.documents", "reranker.documents") diff --git a/integrations/pyversity/examples/standalone.py b/integrations/pyversity/examples/standalone.py index 717bf72444..c5531d510e 100644 --- a/integrations/pyversity/examples/standalone.py +++ b/integrations/pyversity/examples/standalone.py @@ -5,7 +5,7 @@ from haystack import Document from pyversity import Strategy -from haystack_integrations.components.rankers.pyversity import PyversityReranker +from haystack_integrations.components.rankers.pyversity import PyversityRanker documents = [ Document(content="Paris is the capital of France.", score=0.95, embedding=[0.9, 0.1, 0.0, 0.0]), @@ -15,7 +15,7 @@ Document(content="France borders Spain to the south.", score=0.75, embedding=[0.5, 0.5, 0.0, 0.0]), ] -reranker = PyversityReranker(top_k=3, strategy=Strategy.MMR, diversity=0.7) +reranker = PyversityRanker(top_k=3, strategy=Strategy.MMR, diversity=0.7) result = reranker.run(documents=documents) for doc in result["documents"]: diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py index deda1ab08b..564c8a5c7a 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py @@ -2,6 +2,6 @@ # # SPDX-License-Identifier: Apache-2.0 -from haystack_integrations.components.rankers.pyversity.reranker import PyversityReranker +from haystack_integrations.components.rankers.pyversity.reranker import PyversityRanker -__all__ = ["PyversityReranker"] +__all__ = ["PyversityRanker"] diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py index ff77ba465f..fed8a54827 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py @@ -19,7 +19,7 @@ @component -class PyversityReranker: +class PyversityRanker: """ Reranks documents using [pyversity](https://github.com/Pringled/pyversity)'s diversification algorithms. @@ -30,10 +30,10 @@ class PyversityReranker: Usage example: ```python from haystack import Document - from haystack_integrations.components.rankers.pyversity import PyversityReranker + from haystack_integrations.components.rankers.pyversity import PyversityRanker from pyversity import Strategy - ranker = PyversityReranker(top_k=5, strategy=Strategy.MMR, diversity=0.5) + ranker = PyversityRanker(top_k=5, strategy=Strategy.MMR, diversity=0.5) docs = [ Document(content="Paris", score=0.9, embedding=[0.1, 0.2]), @@ -46,7 +46,7 @@ class PyversityReranker: def __init__(self, top_k: int, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: """ - Creates an instance of PyversityReranker. + Creates an instance of PyversityRanker. :param top_k: Number of documents to return after diversification. :param strategy: Pyversity diversification strategy (e.g. `Strategy.MMR`). Defaults to `Strategy.DPP`. diff --git a/integrations/pyversity/tests/test_reranker.py b/integrations/pyversity/tests/test_reranker.py index b1032bf680..2cb2e5d38c 100644 --- a/integrations/pyversity/tests/test_reranker.py +++ b/integrations/pyversity/tests/test_reranker.py @@ -9,7 +9,7 @@ from haystack.document_stores.in_memory import InMemoryDocumentStore from pyversity import Strategy -from haystack_integrations.components.rankers.pyversity import PyversityReranker +from haystack_integrations.components.rankers.pyversity import PyversityRanker EMBEDDING_DIM = 16 RNG = np.random.default_rng(42) @@ -42,42 +42,42 @@ def pipeline(documents, request): "retriever", InMemoryEmbeddingRetriever(document_store=store, top_k=15, return_embedding=True), ) - p.add_component("reranker", PyversityReranker(top_k=5, strategy=strategy, diversity=0.7)) + p.add_component("reranker", PyversityRanker(top_k=5, strategy=strategy, diversity=0.7)) p.connect("retriever.documents", "reranker.documents") return p -class TestPyversityReranker: +class TestPyversityRanker: def test_init_defaults(self): - reranker = PyversityReranker(top_k=5) + reranker = PyversityRanker(top_k=5) assert reranker.top_k == 5 assert reranker.strategy == Strategy.DPP assert reranker.diversity == 0.5 def test_init_custom_params(self): - reranker = PyversityReranker(top_k=10, strategy=Strategy.MMR, diversity=0.3) + reranker = PyversityRanker(top_k=10, strategy=Strategy.MMR, diversity=0.3) assert reranker.top_k == 10 assert reranker.strategy == Strategy.MMR assert reranker.diversity == 0.3 def test_init_invalid_k_zero(self): with pytest.raises(ValueError, match="top_k must be a positive integer"): - PyversityReranker(top_k=0) + PyversityRanker(top_k=0) def test_init_invalid_k_negative(self): with pytest.raises(ValueError, match="top_k must be a positive integer"): - PyversityReranker(top_k=-1) + PyversityRanker(top_k=-1) def test_init_invalid_diversity_above_one(self): with pytest.raises(ValueError, match="diversity must be in"): - PyversityReranker(top_k=5, diversity=1.1) + PyversityRanker(top_k=5, diversity=1.1) def test_init_invalid_diversity_below_zero(self): with pytest.raises(ValueError, match="diversity must be in"): - PyversityReranker(top_k=5, diversity=-0.1) + PyversityRanker(top_k=5, diversity=-0.1) def test_run_empty_documents(self): - reranker = PyversityReranker(top_k=5) + reranker = PyversityRanker(top_k=5) result = reranker.run(documents=[]) assert result == {"documents": []} @@ -87,7 +87,7 @@ def test_run_skips_docs_without_score(self): Document(content="has score and embedding", score=0.9, embedding=rng.standard_normal(4).tolist()), Document(content="missing score", embedding=rng.standard_normal(4).tolist()), ] - reranker = PyversityReranker(top_k=5) + reranker = PyversityRanker(top_k=5) result = reranker.run(documents=docs) assert len(result["documents"]) == 1 @@ -96,7 +96,7 @@ def test_run_skips_docs_without_embedding(self): Document(content="has score and embedding", score=0.9, embedding=[0.1, 0.2, 0.3, 0.4]), Document(content="missing embedding", score=0.5), ] - reranker = PyversityReranker(top_k=5) + reranker = PyversityRanker(top_k=5) result = reranker.run(documents=docs) assert len(result["documents"]) == 1 @@ -105,7 +105,7 @@ def test_run_all_docs_invalid_returns_empty(self): Document(content="no score", embedding=[0.1, 0.2]), Document(content="no embedding", score=0.5), ] - reranker = PyversityReranker(top_k=5) + reranker = PyversityRanker(top_k=5) result = reranker.run(documents=docs) assert result == {"documents": []} @@ -115,7 +115,7 @@ def test_run_returns_at_most_k_documents(self): Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) for i in range(10) ] - reranker = PyversityReranker(top_k=3) + reranker = PyversityRanker(top_k=3) result = reranker.run(documents=docs) assert len(result["documents"]) <= 3 @@ -125,7 +125,7 @@ def test_run_returns_fewer_than_k_if_not_enough_valid(self): Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) for i in range(2) ] - reranker = PyversityReranker(top_k=5) + reranker = PyversityRanker(top_k=5) result = reranker.run(documents=docs) assert len(result["documents"]) == 2 From f610726573541ba353dc6450daf3b971dbcfe156 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:23:15 +0100 Subject: [PATCH 15/21] feat: add serialization methods to PyversityRanker for dict conversion --- .../components/rankers/pyversity/reranker.py | 31 ++++++++++- integrations/pyversity/tests/test_reranker.py | 55 +++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py index fed8a54827..aeb1bfc79f 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py @@ -9,9 +9,10 @@ """ import logging +from typing import Any import numpy as np -from haystack import Document, component +from haystack import Document, component, default_from_dict, default_to_dict from pyversity import Strategy, diversify @@ -66,6 +67,34 @@ def __init__(self, top_k: int, *, strategy: Strategy = Strategy.DPP, diversity: self.strategy = strategy self.diversity = diversity + def to_dict(self) -> dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + top_k=self.top_k, + strategy=self.strategy.value, + diversity=self.diversity, + ) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> "PyversityRanker": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component instance. + """ + if strategy := data.get("init_parameters", {}).get("strategy"): + data["init_parameters"]["strategy"] = Strategy(strategy) + return default_from_dict(cls, data) + @component.output_types(documents=list[Document]) def run(self, documents: list[Document]) -> dict: """ diff --git a/integrations/pyversity/tests/test_reranker.py b/integrations/pyversity/tests/test_reranker.py index 2cb2e5d38c..84f73f0c5c 100644 --- a/integrations/pyversity/tests/test_reranker.py +++ b/integrations/pyversity/tests/test_reranker.py @@ -129,6 +129,61 @@ def test_run_returns_fewer_than_k_if_not_enough_valid(self): result = reranker.run(documents=docs) assert len(result["documents"]) == 2 + def test_to_dict_defaults(self): + reranker = PyversityRanker(top_k=5) + data = reranker.to_dict() + assert data == { + "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "init_parameters": { + "top_k": 5, + "strategy": "dpp", + "diversity": 0.5, + }, + } + + def test_to_dict_custom_params(self): + reranker = PyversityRanker(top_k=10, strategy=Strategy.MMR, diversity=0.3) + data = reranker.to_dict() + assert data == { + "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "init_parameters": { + "top_k": 10, + "strategy": "mmr", + "diversity": 0.3, + }, + } + + def test_from_dict(self): + data = { + "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "init_parameters": { + "top_k": 7, + "strategy": "mmr", + "diversity": 0.8, + }, + } + reranker = PyversityRanker.from_dict(data) + assert reranker.top_k == 7 + assert reranker.strategy == Strategy.MMR + assert reranker.diversity == 0.8 + + def test_from_dict_defaults(self): + data = { + "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "init_parameters": {"top_k": 3}, + } + reranker = PyversityRanker.from_dict(data) + assert reranker.top_k == 3 + assert reranker.strategy == Strategy.DPP + assert reranker.diversity == 0.5 + + def test_to_dict_from_dict_roundtrip(self): + original = PyversityRanker(top_k=4, strategy=Strategy.SSD, diversity=0.2) + restored = PyversityRanker.from_dict(original.to_dict()) + assert restored.top_k == original.top_k + assert restored.strategy == original.strategy + assert restored.diversity == original.diversity + @pytest.mark.parametrize( "pipeline", From d578f0826045857a84d082997919e66ff610365b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:29:35 +0100 Subject: [PATCH 16/21] chore: rename package to ranker from reranker --- .../components/rankers/pyversity/__init__.py | 2 +- .../rankers/pyversity/{reranker.py => ranker.py} | 0 .../pyversity/tests/{test_reranker.py => test_ranker.py} | 8 ++++---- 3 files changed, 5 insertions(+), 5 deletions(-) rename integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/{reranker.py => ranker.py} (100%) rename integrations/pyversity/tests/{test_reranker.py => test_ranker.py} (98%) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py index 564c8a5c7a..c15332ccc0 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/__init__.py @@ -2,6 +2,6 @@ # # SPDX-License-Identifier: Apache-2.0 -from haystack_integrations.components.rankers.pyversity.reranker import PyversityRanker +from haystack_integrations.components.rankers.pyversity.ranker import PyversityRanker __all__ = ["PyversityRanker"] diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py similarity index 100% rename from integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/reranker.py rename to integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py diff --git a/integrations/pyversity/tests/test_reranker.py b/integrations/pyversity/tests/test_ranker.py similarity index 98% rename from integrations/pyversity/tests/test_reranker.py rename to integrations/pyversity/tests/test_ranker.py index 84f73f0c5c..1f07540edf 100644 --- a/integrations/pyversity/tests/test_reranker.py +++ b/integrations/pyversity/tests/test_ranker.py @@ -133,7 +133,7 @@ def test_to_dict_defaults(self): reranker = PyversityRanker(top_k=5) data = reranker.to_dict() assert data == { - "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker", "init_parameters": { "top_k": 5, "strategy": "dpp", @@ -145,7 +145,7 @@ def test_to_dict_custom_params(self): reranker = PyversityRanker(top_k=10, strategy=Strategy.MMR, diversity=0.3) data = reranker.to_dict() assert data == { - "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker", "init_parameters": { "top_k": 10, "strategy": "mmr", @@ -155,7 +155,7 @@ def test_to_dict_custom_params(self): def test_from_dict(self): data = { - "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker", "init_parameters": { "top_k": 7, "strategy": "mmr", @@ -169,7 +169,7 @@ def test_from_dict(self): def test_from_dict_defaults(self): data = { - "type": "haystack_integrations.components.rankers.pyversity.reranker.PyversityRanker", + "type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker", "init_parameters": {"top_k": 3}, } reranker = PyversityRanker.from_dict(data) From 116376d318cb028f0eab9cd93e4baa69a99a031c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 12:32:03 +0100 Subject: [PATCH 17/21] fix: update module reference from reranker to ranker in Docusaurus config --- integrations/pyversity/pydoc/config_docusaurus.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/pyversity/pydoc/config_docusaurus.yml b/integrations/pyversity/pydoc/config_docusaurus.yml index 74d50921c4..b01f332e68 100644 --- a/integrations/pyversity/pydoc/config_docusaurus.yml +++ b/integrations/pyversity/pydoc/config_docusaurus.yml @@ -1,6 +1,6 @@ loaders: - modules: - - haystack_integrations.components.rankers.pyversity.reranker + - haystack_integrations.components.rankers.pyversity.ranker search_path: [../src] processors: - type: filter From ab2b682d37b9c16597283ae49c9a3907205a4201 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 13:43:43 +0100 Subject: [PATCH 18/21] feat: update PyversityRanker to support None for top_k, returning all documents when None --- .../components/rankers/pyversity/ranker.py | 11 ++++-- integrations/pyversity/tests/test_ranker.py | 39 ++++++++++++++++++- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py index aeb1bfc79f..bf86376773 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py @@ -45,11 +45,12 @@ class PyversityRanker: ``` """ - def __init__(self, top_k: int, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: + def __init__(self, top_k: int | None = None, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None: """ Creates an instance of PyversityRanker. :param top_k: Number of documents to return after diversification. + If `None`, all documents are returned in diversified order. :param strategy: Pyversity diversification strategy (e.g. `Strategy.MMR`). Defaults to `Strategy.DPP`. :param diversity: Trade-off between relevance and diversity in [0, 1]. `0.0` keeps only the most relevant documents; `1.0` maximises @@ -57,7 +58,7 @@ def __init__(self, top_k: int, *, strategy: Strategy = Strategy.DPP, diversity: :raises ValueError: If `top_k` is not a positive integer or `diversity` is not in [0, 1]. """ - if top_k <= 0: + if top_k is not None and top_k <= 0: msg = f"top_k must be a positive integer, got {top_k}" raise ValueError(msg) if not 0.0 <= diversity <= 1.0: @@ -124,10 +125,14 @@ def run(self, documents: list[Document]) -> dict: embeddings = np.array([doc.embedding for doc in valid_docs]) scores = np.array([doc.score for doc in valid_docs]) + if self.top_k is not None: + k = min(self.top_k, len(valid_docs)) + else: + k = len(valid_docs) result = diversify( embeddings=embeddings, scores=scores, - k=min(self.top_k, len(valid_docs)), + k=k, strategy=self.strategy, diversity=self.diversity, ) diff --git a/integrations/pyversity/tests/test_ranker.py b/integrations/pyversity/tests/test_ranker.py index 1f07540edf..7ac704f393 100644 --- a/integrations/pyversity/tests/test_ranker.py +++ b/integrations/pyversity/tests/test_ranker.py @@ -49,11 +49,19 @@ def pipeline(documents, request): class TestPyversityRanker: def test_init_defaults(self): - reranker = PyversityRanker(top_k=5) - assert reranker.top_k == 5 + reranker = PyversityRanker() + assert reranker.top_k is None assert reranker.strategy == Strategy.DPP assert reranker.diversity == 0.5 + def test_init_top_k_none(self): + reranker = PyversityRanker(top_k=None) + assert reranker.top_k is None + + def test_init_explicit_top_k(self): + reranker = PyversityRanker(top_k=5) + assert reranker.top_k == 5 + def test_init_custom_params(self): reranker = PyversityRanker(top_k=10, strategy=Strategy.MMR, diversity=0.3) assert reranker.top_k == 10 @@ -119,6 +127,16 @@ def test_run_returns_at_most_k_documents(self): result = reranker.run(documents=docs) assert len(result["documents"]) <= 3 + def test_run_returns_all_documents_when_top_k_is_none(self): + rng = np.random.default_rng(3) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(10) + ] + reranker = PyversityRanker(top_k=None) + result = reranker.run(documents=docs) + assert len(result["documents"]) == 10 + def test_run_returns_fewer_than_k_if_not_enough_valid(self): rng = np.random.default_rng(2) docs = [ @@ -129,6 +147,18 @@ def test_run_returns_fewer_than_k_if_not_enough_valid(self): result = reranker.run(documents=docs) assert len(result["documents"]) == 2 + def test_to_dict_top_k_none(self): + reranker = PyversityRanker(top_k=None) + data = reranker.to_dict() + assert data == { + "type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker", + "init_parameters": { + "top_k": None, + "strategy": "dpp", + "diversity": 0.5, + }, + } + def test_to_dict_defaults(self): reranker = PyversityRanker(top_k=5) data = reranker.to_dict() @@ -184,6 +214,11 @@ def test_to_dict_from_dict_roundtrip(self): assert restored.strategy == original.strategy assert restored.diversity == original.diversity + def test_to_dict_from_dict_roundtrip_top_k_none(self): + original = PyversityRanker(top_k=None) + restored = PyversityRanker.from_dict(original.to_dict()) + assert restored.top_k is None + @pytest.mark.parametrize( "pipeline", From 5e199de45c90289b24c92dd8ee11143a36fc09c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 14:00:46 +0100 Subject: [PATCH 19/21] feat: pass diversification scores to the documents --- integrations/pyversity/examples/pipeline.py | 6 ++--- integrations/pyversity/examples/standalone.py | 6 ++--- .../components/rankers/pyversity/ranker.py | 8 +++++- integrations/pyversity/tests/test_ranker.py | 25 +++++++++++++++++++ 4 files changed, 38 insertions(+), 7 deletions(-) diff --git a/integrations/pyversity/examples/pipeline.py b/integrations/pyversity/examples/pipeline.py index 6070f72fb2..d77f8bf7eb 100644 --- a/integrations/pyversity/examples/pipeline.py +++ b/integrations/pyversity/examples/pipeline.py @@ -46,6 +46,6 @@ for doc in result["reranker"]["documents"]: print(f"{doc.score:.4f} {doc.content}") -# 0.xxxx Paris is the capital of France. -# 0.xxxx The Eiffel Tower is located in Paris. -# 0.xxxx France borders Spain to the south. +# 0.1846 Paris is the capital of France. +# -0.1647 The Rhine river flows through Germany and France. +# -0.1775 The Brandenburg Gate is in Berlin. diff --git a/integrations/pyversity/examples/standalone.py b/integrations/pyversity/examples/standalone.py index c5531d510e..33765d528f 100644 --- a/integrations/pyversity/examples/standalone.py +++ b/integrations/pyversity/examples/standalone.py @@ -21,6 +21,6 @@ for doc in result["documents"]: print(f"{doc.score:.2f} {doc.content}") -# 0.95 Paris is the capital of France. -# 0.85 Berlin is the capital of Germany. -# 0.75 France borders Spain to the south. +# 0.28 Paris is the capital of France. +# 0.26 Berlin is the capital of Germany. +# -0.32 France borders Spain to the south. diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py index bf86376773..245017ca77 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py @@ -9,6 +9,7 @@ """ import logging +from dataclasses import replace from typing import Any import numpy as np @@ -137,4 +138,9 @@ def run(self, documents: list[Document]) -> dict: diversity=self.diversity, ) - return {"documents": [valid_docs[i] for i in result.indices]} + return { + "documents": [ + replace(valid_docs[i], score=float(score)) + for i, score in zip(result.indices, result.selection_scores, strict=True) # type: ignore[call-overload] + ] + } diff --git a/integrations/pyversity/tests/test_ranker.py b/integrations/pyversity/tests/test_ranker.py index 7ac704f393..f28b6c7bfe 100644 --- a/integrations/pyversity/tests/test_ranker.py +++ b/integrations/pyversity/tests/test_ranker.py @@ -147,6 +147,31 @@ def test_run_returns_fewer_than_k_if_not_enough_valid(self): result = reranker.run(documents=docs) assert len(result["documents"]) == 2 + def test_run_sets_selection_scores_on_output(self): + rng = np.random.default_rng(7) + original_scores = [float(i) / 10 for i in range(1, 6)] + docs = [ + Document(content=f"doc {i}", score=s, embedding=rng.standard_normal(8).tolist()) + for i, s in enumerate(original_scores) + ] + reranker = PyversityRanker(top_k=3) + result = reranker.run(documents=docs) + for doc in result["documents"]: + assert doc.score is not None + assert isinstance(doc.score, float) + + def test_run_does_not_mutate_input_documents(self): + rng = np.random.default_rng(8) + original_scores = [float(i) / 10 for i in range(1, 6)] + docs = [ + Document(content=f"doc {i}", score=s, embedding=rng.standard_normal(8).tolist()) + for i, s in enumerate(original_scores) + ] + reranker = PyversityRanker(top_k=3) + reranker.run(documents=docs) + for doc, original_score in zip(docs, original_scores, strict=False): # type: ignore[call-overload] + assert doc.score == original_score + def test_to_dict_top_k_none(self): reranker = PyversityRanker(top_k=None) data = reranker.to_dict() From 57120013b194b73e71d9babd0f709271224475fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 15:32:09 +0100 Subject: [PATCH 20/21] chore: apply suggestions from code review Co-authored-by: Sebastian Husch Lee <10526848+sjrl@users.noreply.github.com> --- .../components/rankers/pyversity/ranker.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py index 245017ca77..8125bb52d4 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py @@ -8,12 +8,11 @@ making it easy to drop result diversification into any Haystack pipeline. """ -import logging from dataclasses import replace from typing import Any import numpy as np -from haystack import Document, component, default_from_dict, default_to_dict +from haystack import Document, component, default_from_dict, default_to_dict, logging from pyversity import Strategy, diversify @@ -98,7 +97,7 @@ def from_dict(cls, data: dict[str, Any]) -> "PyversityRanker": return default_from_dict(cls, data) @component.output_types(documents=list[Document]) - def run(self, documents: list[Document]) -> dict: + def run(self, documents: list[Document]) -> dict[str, list[Document]]: """ Rerank the list of documents using pyversity's diversification algorithm. @@ -116,8 +115,8 @@ def run(self, documents: list[Document]) -> dict: skipped = len(documents) - len(valid_docs) if skipped: logger.warning( - "%d document(s) are missing 'score' or 'embedding' and will be skipped.", - skipped, + "{skipped} document(s) are missing 'score' or 'embedding' and will be skipped.", + skipped=skipped, ) if not valid_docs: From 6291f80b306fcdc48c64e09469b0bc95ecad1cbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20=C5=81ukawski?= Date: Mon, 23 Feb 2026 16:27:00 +0100 Subject: [PATCH 21/21] feat: support runtime overrides for top_k, strategy, and diversity parameters --- .../components/rankers/pyversity/ranker.py | 32 +++++- integrations/pyversity/tests/test_ranker.py | 106 ++++++++++++++++++ 2 files changed, 133 insertions(+), 5 deletions(-) diff --git a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py index 8125bb52d4..622ae11da3 100644 --- a/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py +++ b/integrations/pyversity/src/haystack_integrations/components/rankers/pyversity/ranker.py @@ -97,17 +97,39 @@ def from_dict(cls, data: dict[str, Any]) -> "PyversityRanker": return default_from_dict(cls, data) @component.output_types(documents=list[Document]) - def run(self, documents: list[Document]) -> dict[str, list[Document]]: + def run( + self, + documents: list[Document], + top_k: int | None = None, + strategy: Strategy | None = None, + diversity: float | None = None, + ) -> dict[str, list[Document]]: """ Rerank the list of documents using pyversity's diversification algorithm. Documents missing `score` or `embedding` are skipped with a warning. :param documents: List of Documents to rerank. Each document must have `score` and `embedding` set. + :param top_k: Overrides the initialized `top_k` for this call. `None` falls back to the initialized value. + :param strategy: Overrides the initialized `strategy` for this call. `None` falls back to the initialized value. + :param diversity: Overrides the initialized `diversity` for this call. + `None` falls back to the initialized value. :returns: A dictionary with the following keys: - `documents`: List of up to `top_k` reranked Documents, ordered by the diversification algorithm. + :raises ValueError: If `top_k` is not a positive integer or `diversity` is not in [0, 1]. """ + if top_k is not None and top_k <= 0: + msg = f"top_k must be a positive integer, got {top_k}" + raise ValueError(msg) + if diversity is not None and not 0.0 <= diversity <= 1.0: + msg = f"diversity must be in [0, 1], got {diversity}" + raise ValueError(msg) + + effective_top_k = top_k if top_k is not None else self.top_k + effective_strategy = strategy if strategy is not None else self.strategy + effective_diversity = diversity if diversity is not None else self.diversity + if not documents: return {"documents": []} @@ -125,16 +147,16 @@ def run(self, documents: list[Document]) -> dict[str, list[Document]]: embeddings = np.array([doc.embedding for doc in valid_docs]) scores = np.array([doc.score for doc in valid_docs]) - if self.top_k is not None: - k = min(self.top_k, len(valid_docs)) + if effective_top_k is not None: + k = min(effective_top_k, len(valid_docs)) else: k = len(valid_docs) result = diversify( embeddings=embeddings, scores=scores, k=k, - strategy=self.strategy, - diversity=self.diversity, + strategy=effective_strategy, + diversity=effective_diversity, ) return { diff --git a/integrations/pyversity/tests/test_ranker.py b/integrations/pyversity/tests/test_ranker.py index f28b6c7bfe..7bc4cc21b3 100644 --- a/integrations/pyversity/tests/test_ranker.py +++ b/integrations/pyversity/tests/test_ranker.py @@ -244,6 +244,112 @@ def test_to_dict_from_dict_roundtrip_top_k_none(self): restored = PyversityRanker.from_dict(original.to_dict()) assert restored.top_k is None + def test_run_top_k_runtime_overrides_init(self): + rng = np.random.default_rng(10) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(10) + ] + reranker = PyversityRanker(top_k=10) + result = reranker.run(documents=docs, top_k=3) + assert len(result["documents"]) == 3 + + def test_run_top_k_runtime_none_falls_back_to_init(self): + rng = np.random.default_rng(11) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(10) + ] + reranker = PyversityRanker(top_k=3) + result = reranker.run(documents=docs, top_k=None) + assert len(result["documents"]) == 3 + + def test_run_top_k_runtime_invalid_zero(self): + reranker = PyversityRanker() + docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])] + with pytest.raises(ValueError, match="top_k must be a positive integer"): + reranker.run(documents=docs, top_k=0) + + def test_run_top_k_runtime_invalid_negative(self): + reranker = PyversityRanker() + docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])] + with pytest.raises(ValueError, match="top_k must be a positive integer"): + reranker.run(documents=docs, top_k=-1) + + def test_run_top_k_runtime_with_init_top_k_none(self): + rng = np.random.default_rng(12) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(10) + ] + reranker = PyversityRanker(top_k=None) + result = reranker.run(documents=docs, top_k=5) + assert len(result["documents"]) == 5 + + def test_run_diversity_runtime_none_falls_back_to_init(self): + rng = np.random.default_rng(13) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(5) + ] + reranker = PyversityRanker(diversity=0.9) + result_default = reranker.run(documents=docs) + result_none = reranker.run(documents=docs, diversity=None) + assert [d.score for d in result_default["documents"]] == [d.score for d in result_none["documents"]] + + def test_run_diversity_runtime_invalid_above_one(self): + reranker = PyversityRanker() + docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])] + with pytest.raises(ValueError, match="diversity must be in"): + reranker.run(documents=docs, diversity=1.1) + + def test_run_diversity_runtime_invalid_below_zero(self): + reranker = PyversityRanker() + docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])] + with pytest.raises(ValueError, match="diversity must be in"): + reranker.run(documents=docs, diversity=-0.1) + + def test_run_both_params_overridden_at_runtime(self): + rng = np.random.default_rng(14) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(10) + ] + reranker = PyversityRanker(top_k=10, diversity=0.9) + result = reranker.run(documents=docs, top_k=4, diversity=0.1) + assert len(result["documents"]) == 4 + + def test_run_strategy_runtime_overrides_init(self): + rng = np.random.default_rng(15) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(5) + ] + reranker = PyversityRanker(strategy=Strategy.DPP) + result = reranker.run(documents=docs, strategy=Strategy.MMR) + assert len(result["documents"]) == 5 + + def test_run_strategy_runtime_none_falls_back_to_init(self): + rng = np.random.default_rng(16) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(5) + ] + reranker = PyversityRanker(strategy=Strategy.MMR) + result_default = reranker.run(documents=docs) + result_none = reranker.run(documents=docs, strategy=None) + assert [d.score for d in result_default["documents"]] == [d.score for d in result_none["documents"]] + + def test_run_all_params_overridden_at_runtime(self): + rng = np.random.default_rng(17) + docs = [ + Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist()) + for i in range(10) + ] + reranker = PyversityRanker(top_k=10, strategy=Strategy.DPP, diversity=0.9) + result = reranker.run(documents=docs, top_k=4, strategy=Strategy.MMR, diversity=0.1) + assert len(result["documents"]) == 4 + @pytest.mark.parametrize( "pipeline",