pyversity-haystack 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyversity_haystack-1.0.0/.gitignore +146 -0
- pyversity_haystack-1.0.0/LICENSE.txt +73 -0
- pyversity_haystack-1.0.0/PKG-INFO +37 -0
- pyversity_haystack-1.0.0/README.md +13 -0
- pyversity_haystack-1.0.0/examples/pipeline.py +51 -0
- pyversity_haystack-1.0.0/examples/standalone.py +26 -0
- pyversity_haystack-1.0.0/pydoc/config_docusaurus.yml +13 -0
- pyversity_haystack-1.0.0/pyproject.toml +156 -0
- pyversity_haystack-1.0.0/src/haystack_integrations/components/rankers/py.typed +0 -0
- pyversity_haystack-1.0.0/src/haystack_integrations/components/rankers/pyversity/__init__.py +7 -0
- pyversity_haystack-1.0.0/src/haystack_integrations/components/rankers/pyversity/ranker.py +167 -0
- pyversity_haystack-1.0.0/tests/__init__.py +3 -0
- pyversity_haystack-1.0.0/tests/test_ranker.py +361 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
pip-wheel-metadata/
|
|
24
|
+
share/python-wheels/
|
|
25
|
+
*.egg-info/
|
|
26
|
+
.installed.cfg
|
|
27
|
+
*.egg
|
|
28
|
+
MANIFEST
|
|
29
|
+
|
|
30
|
+
# PyInstaller
|
|
31
|
+
# Usually these files are written by a python script from a template
|
|
32
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
33
|
+
*.manifest
|
|
34
|
+
*.spec
|
|
35
|
+
|
|
36
|
+
# Installer logs
|
|
37
|
+
pip-log.txt
|
|
38
|
+
pip-delete-this-directory.txt
|
|
39
|
+
|
|
40
|
+
# Unit test / coverage reports
|
|
41
|
+
htmlcov/
|
|
42
|
+
.tox/
|
|
43
|
+
.nox/
|
|
44
|
+
.coverage
|
|
45
|
+
.coverage.*
|
|
46
|
+
.cache
|
|
47
|
+
nosetests.xml
|
|
48
|
+
coverage.xml
|
|
49
|
+
*.cover
|
|
50
|
+
*.py,cover
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
volumes/
|
|
54
|
+
|
|
55
|
+
# Translations
|
|
56
|
+
*.mo
|
|
57
|
+
*.pot
|
|
58
|
+
|
|
59
|
+
# Django stuff:
|
|
60
|
+
*.log
|
|
61
|
+
local_settings.py
|
|
62
|
+
db.sqlite3
|
|
63
|
+
db.sqlite3-journal
|
|
64
|
+
|
|
65
|
+
# Flask stuff:
|
|
66
|
+
instance/
|
|
67
|
+
.webassets-cache
|
|
68
|
+
|
|
69
|
+
# Scrapy stuff:
|
|
70
|
+
.scrapy
|
|
71
|
+
|
|
72
|
+
# Sphinx documentation
|
|
73
|
+
docs/_build/
|
|
74
|
+
|
|
75
|
+
# PyBuilder
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
.python-version
|
|
87
|
+
|
|
88
|
+
# pipenv
|
|
89
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
90
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
91
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
92
|
+
# install all needed dependencies.
|
|
93
|
+
#Pipfile.lock
|
|
94
|
+
|
|
95
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
96
|
+
__pypackages__/
|
|
97
|
+
|
|
98
|
+
# Celery stuff
|
|
99
|
+
celerybeat-schedule
|
|
100
|
+
celerybeat.pid
|
|
101
|
+
|
|
102
|
+
# SageMath parsed files
|
|
103
|
+
*.sage.py
|
|
104
|
+
|
|
105
|
+
# Environments
|
|
106
|
+
.env
|
|
107
|
+
.venv
|
|
108
|
+
env/
|
|
109
|
+
venv/
|
|
110
|
+
ENV/
|
|
111
|
+
env.bak/
|
|
112
|
+
venv.bak/
|
|
113
|
+
|
|
114
|
+
# Spyder project settings
|
|
115
|
+
.spyderproject
|
|
116
|
+
.spyproject
|
|
117
|
+
|
|
118
|
+
# Rope project settings
|
|
119
|
+
.ropeproject
|
|
120
|
+
|
|
121
|
+
# mkdocs documentation
|
|
122
|
+
/site
|
|
123
|
+
|
|
124
|
+
# mypy
|
|
125
|
+
.mypy_cache/
|
|
126
|
+
.dmypy.json
|
|
127
|
+
dmypy.json
|
|
128
|
+
|
|
129
|
+
# Pyre type checker
|
|
130
|
+
.pyre/
|
|
131
|
+
|
|
132
|
+
# IDEs
|
|
133
|
+
.vscode
|
|
134
|
+
|
|
135
|
+
# Docs generation artifacts
|
|
136
|
+
_readme_*.md
|
|
137
|
+
.idea
|
|
138
|
+
|
|
139
|
+
# macOS
|
|
140
|
+
.DS_Store
|
|
141
|
+
|
|
142
|
+
# http cache (requests-cache)
|
|
143
|
+
**/http_cache.sqlite
|
|
144
|
+
|
|
145
|
+
# ruff
|
|
146
|
+
.ruff_cache
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright 2026 deepset GmbH
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyversity-haystack
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Haystack component wrapping pyversity for result diversification in retrieval pipelines
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/pyversity#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/pyversity
|
|
8
|
+
Author-email: Kacper Łukawski <kacper.lukawski@deepset.ai>, deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: haystack-ai>=2.2.0
|
|
22
|
+
Requires-Dist: pyversity>=0.2.0
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# pyversity-haystack
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/pyversity-haystack)
|
|
28
|
+
[](https://pypi.org/project/pyversity-haystack)
|
|
29
|
+
|
|
30
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/pyversity/CHANGELOG.md)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Contributing
|
|
36
|
+
|
|
37
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# pyversity-haystack
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/pyversity-haystack)
|
|
4
|
+
[](https://pypi.org/project/pyversity-haystack)
|
|
5
|
+
|
|
6
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/pyversity/CHANGELOG.md)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Contributing
|
|
12
|
+
|
|
13
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from haystack import Document, Pipeline
|
|
6
|
+
from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder
|
|
7
|
+
from haystack.components.retrievers import InMemoryEmbeddingRetriever
|
|
8
|
+
from haystack.document_stores.in_memory import InMemoryDocumentStore
|
|
9
|
+
from pyversity import Strategy
|
|
10
|
+
|
|
11
|
+
from haystack_integrations.components.rankers.pyversity import PyversityRanker
|
|
12
|
+
|
|
13
|
+
# Index documents
|
|
14
|
+
document_store = InMemoryDocumentStore()
|
|
15
|
+
|
|
16
|
+
raw_documents = [
|
|
17
|
+
Document(content="Paris is the capital of France."),
|
|
18
|
+
Document(content="The Eiffel Tower is located in Paris."),
|
|
19
|
+
Document(content="Berlin is the capital of Germany."),
|
|
20
|
+
Document(content="The Brandenburg Gate is in Berlin."),
|
|
21
|
+
Document(content="France borders Spain to the south."),
|
|
22
|
+
Document(content="The Louvre is the world's largest art museum and is in Paris."),
|
|
23
|
+
Document(content="Munich is the capital of Bavaria."),
|
|
24
|
+
Document(content="The Rhine river flows through Germany and France."),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
doc_embedder = SentenceTransformersDocumentEmbedder()
|
|
28
|
+
documents_with_embeddings = doc_embedder.run(raw_documents)["documents"]
|
|
29
|
+
document_store.write_documents(documents_with_embeddings)
|
|
30
|
+
|
|
31
|
+
# Build pipeline
|
|
32
|
+
pipeline = Pipeline()
|
|
33
|
+
pipeline.add_component("text_embedder", SentenceTransformersTextEmbedder())
|
|
34
|
+
pipeline.add_component(
|
|
35
|
+
"retriever",
|
|
36
|
+
InMemoryEmbeddingRetriever(document_store=document_store, top_k=6, return_embedding=True),
|
|
37
|
+
)
|
|
38
|
+
pipeline.add_component("reranker", PyversityRanker(top_k=3, strategy=Strategy.MMR, diversity=0.7))
|
|
39
|
+
|
|
40
|
+
pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
|
|
41
|
+
pipeline.connect("retriever.documents", "reranker.documents")
|
|
42
|
+
|
|
43
|
+
# Run
|
|
44
|
+
result = pipeline.run({"text_embedder": {"text": "What are the famous landmarks in France?"}})
|
|
45
|
+
|
|
46
|
+
for doc in result["reranker"]["documents"]:
|
|
47
|
+
print(f"{doc.score:.4f} {doc.content}")
|
|
48
|
+
|
|
49
|
+
# 0.1846 Paris is the capital of France.
|
|
50
|
+
# -0.1647 The Rhine river flows through Germany and France.
|
|
51
|
+
# -0.1775 The Brandenburg Gate is in Berlin.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from haystack import Document
|
|
6
|
+
from pyversity import Strategy
|
|
7
|
+
|
|
8
|
+
from haystack_integrations.components.rankers.pyversity import PyversityRanker
|
|
9
|
+
|
|
10
|
+
documents = [
|
|
11
|
+
Document(content="Paris is the capital of France.", score=0.95, embedding=[0.9, 0.1, 0.0, 0.0]),
|
|
12
|
+
Document(content="The Eiffel Tower is located in Paris.", score=0.90, embedding=[0.8, 0.2, 0.0, 0.0]),
|
|
13
|
+
Document(content="Berlin is the capital of Germany.", score=0.85, embedding=[0.0, 0.0, 0.9, 0.1]),
|
|
14
|
+
Document(content="The Brandenburg Gate is in Berlin.", score=0.80, embedding=[0.0, 0.0, 0.8, 0.2]),
|
|
15
|
+
Document(content="France borders Spain to the south.", score=0.75, embedding=[0.5, 0.5, 0.0, 0.0]),
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
reranker = PyversityRanker(top_k=3, strategy=Strategy.MMR, diversity=0.7)
|
|
19
|
+
result = reranker.run(documents=documents)
|
|
20
|
+
|
|
21
|
+
for doc in result["documents"]:
|
|
22
|
+
print(f"{doc.score:.2f} {doc.content}")
|
|
23
|
+
|
|
24
|
+
# 0.28 Paris is the capital of France.
|
|
25
|
+
# 0.26 Berlin is the capital of Germany.
|
|
26
|
+
# -0.32 France borders Spain to the south.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
loaders:
|
|
2
|
+
- modules:
|
|
3
|
+
- haystack_integrations.components.rankers.pyversity.ranker
|
|
4
|
+
search_path: [../src]
|
|
5
|
+
processors:
|
|
6
|
+
- type: filter
|
|
7
|
+
documented_only: true
|
|
8
|
+
skip_empty_modules: true
|
|
9
|
+
renderer:
|
|
10
|
+
description: pyversity integration for Haystack
|
|
11
|
+
id: integrations-pyversity
|
|
12
|
+
filename: pyversity.md
|
|
13
|
+
title: pyversity
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling", "hatch-vcs"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pyversity-haystack"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = 'Haystack component wrapping pyversity for result diversification in retrieval pipelines'
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
keywords = []
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Kacper Łukawski", email = "kacper.lukawski@deepset.ai" },
|
|
15
|
+
{ name = "deepset GmbH", email = "info@deepset.ai" },
|
|
16
|
+
]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"License :: OSI Approved :: Apache Software License",
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Programming Language :: Python",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
26
|
+
"Programming Language :: Python :: Implementation :: PyPy",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"haystack-ai>=2.2.0",
|
|
30
|
+
"pyversity>=0.2.0",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/pyversity#readme"
|
|
35
|
+
Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
|
|
36
|
+
Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/pyversity"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/haystack_integrations"]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.version]
|
|
42
|
+
source = "vcs"
|
|
43
|
+
tag-pattern = 'integrations\/pyversity-v(?P<version>.*)'
|
|
44
|
+
|
|
45
|
+
[tool.hatch.version.raw-options]
|
|
46
|
+
root = "../.."
|
|
47
|
+
git_describe_command = 'git describe --tags --match="integrations/pyversity-v[0-9]*"'
|
|
48
|
+
|
|
49
|
+
[tool.hatch.envs.default]
|
|
50
|
+
installer = "uv"
|
|
51
|
+
dependencies = ["haystack-pydoc-tools", "ruff"]
|
|
52
|
+
|
|
53
|
+
[tool.hatch.envs.default.scripts]
|
|
54
|
+
docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
|
|
55
|
+
fmt = "ruff check --fix {args}; ruff format {args}"
|
|
56
|
+
fmt-check = "ruff check {args} && ruff format --check {args}"
|
|
57
|
+
|
|
58
|
+
[tool.hatch.envs.test]
|
|
59
|
+
dependencies = [
|
|
60
|
+
"pytest",
|
|
61
|
+
"pytest-asyncio",
|
|
62
|
+
"pytest-cov",
|
|
63
|
+
"pytest-rerunfailures",
|
|
64
|
+
"mypy",
|
|
65
|
+
"pip",
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
[tool.hatch.envs.test.scripts]
|
|
69
|
+
unit = 'pytest -m "not integration" {args:tests}'
|
|
70
|
+
integration = 'pytest -m "integration" {args:tests}'
|
|
71
|
+
all = 'pytest {args:tests}'
|
|
72
|
+
cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x {args:tests}'
|
|
73
|
+
types = "mypy -p haystack_integrations.components.rankers.pyversity {args}"
|
|
74
|
+
|
|
75
|
+
[tool.mypy]
|
|
76
|
+
install_types = true
|
|
77
|
+
non_interactive = true
|
|
78
|
+
check_untyped_defs = true
|
|
79
|
+
disallow_incomplete_defs = true
|
|
80
|
+
|
|
81
|
+
[tool.ruff]
|
|
82
|
+
line-length = 120
|
|
83
|
+
|
|
84
|
+
[tool.ruff.lint]
|
|
85
|
+
select = [
|
|
86
|
+
"A",
|
|
87
|
+
"ARG",
|
|
88
|
+
"B",
|
|
89
|
+
"C",
|
|
90
|
+
"DTZ",
|
|
91
|
+
"E",
|
|
92
|
+
"EM",
|
|
93
|
+
"F",
|
|
94
|
+
"I",
|
|
95
|
+
"ICN",
|
|
96
|
+
"ISC",
|
|
97
|
+
"N",
|
|
98
|
+
"PLC",
|
|
99
|
+
"PLE",
|
|
100
|
+
"PLR",
|
|
101
|
+
"PLW",
|
|
102
|
+
"Q",
|
|
103
|
+
"RUF",
|
|
104
|
+
"S",
|
|
105
|
+
"T",
|
|
106
|
+
"TID",
|
|
107
|
+
"UP",
|
|
108
|
+
"W",
|
|
109
|
+
"YTT",
|
|
110
|
+
]
|
|
111
|
+
ignore = [
|
|
112
|
+
# Allow non-abstract empty methods in abstract base classes
|
|
113
|
+
"B027",
|
|
114
|
+
# Ignore checks for possible passwords
|
|
115
|
+
"S105",
|
|
116
|
+
"S106",
|
|
117
|
+
"S107",
|
|
118
|
+
# Ignore complexity
|
|
119
|
+
"C901",
|
|
120
|
+
"PLR0911",
|
|
121
|
+
"PLR0912",
|
|
122
|
+
"PLR0913",
|
|
123
|
+
"PLR0915",
|
|
124
|
+
# Misc
|
|
125
|
+
"B008",
|
|
126
|
+
"S101",
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
[tool.ruff.lint.isort]
|
|
130
|
+
known-first-party = ["haystack_integrations"]
|
|
131
|
+
|
|
132
|
+
[tool.ruff.lint.flake8-tidy-imports]
|
|
133
|
+
ban-relative-imports = "parents"
|
|
134
|
+
|
|
135
|
+
[tool.ruff.lint.per-file-ignores]
|
|
136
|
+
# Tests can use magic values, assertions, and relative imports
|
|
137
|
+
"tests/**/*" = ["PLR2004", "S101", "TID252"]
|
|
138
|
+
# Examples can use print statements
|
|
139
|
+
"examples/**/*" = ["T201"]
|
|
140
|
+
|
|
141
|
+
[tool.coverage.run]
|
|
142
|
+
source = ["haystack_integrations"]
|
|
143
|
+
branch = true
|
|
144
|
+
parallel = false
|
|
145
|
+
|
|
146
|
+
[tool.coverage.report]
|
|
147
|
+
omit = ["*/tests/*", "*/__init__.py"]
|
|
148
|
+
show_missing = true
|
|
149
|
+
exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
|
|
150
|
+
|
|
151
|
+
[tool.pytest.ini_options]
|
|
152
|
+
addopts = "--strict-markers"
|
|
153
|
+
markers = ["integration: integration tests"]
|
|
154
|
+
log_cli = true
|
|
155
|
+
asyncio_mode = "auto"
|
|
156
|
+
asyncio_default_fixture_loop_scope = "class"
|
|
File without changes
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
"""Haystack integration for `pyversity <https://github.com/Pringled/pyversity>`_.
|
|
6
|
+
|
|
7
|
+
Wraps pyversity's diversification algorithms as a Haystack ``@component``,
|
|
8
|
+
making it easy to drop result diversification into any Haystack pipeline.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from dataclasses import replace
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
from haystack import Document, component, default_from_dict, default_to_dict, logging
|
|
16
|
+
|
|
17
|
+
from pyversity import Strategy, diversify
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@component
|
|
23
|
+
class PyversityRanker:
|
|
24
|
+
"""
|
|
25
|
+
Reranks documents using [pyversity](https://github.com/Pringled/pyversity)'s diversification algorithms.
|
|
26
|
+
|
|
27
|
+
Balances relevance and diversity in a ranked list of documents. Documents
|
|
28
|
+
must have both `score` and `embedding` populated (e.g. as returned by
|
|
29
|
+
a dense retriever with `return_embedding=True`).
|
|
30
|
+
|
|
31
|
+
Usage example:
|
|
32
|
+
```python
|
|
33
|
+
from haystack import Document
|
|
34
|
+
from haystack_integrations.components.rankers.pyversity import PyversityRanker
|
|
35
|
+
from pyversity import Strategy
|
|
36
|
+
|
|
37
|
+
ranker = PyversityRanker(top_k=5, strategy=Strategy.MMR, diversity=0.5)
|
|
38
|
+
|
|
39
|
+
docs = [
|
|
40
|
+
Document(content="Paris", score=0.9, embedding=[0.1, 0.2]),
|
|
41
|
+
Document(content="Berlin", score=0.8, embedding=[0.3, 0.4]),
|
|
42
|
+
]
|
|
43
|
+
output = ranker.run(documents=docs)
|
|
44
|
+
docs = output["documents"]
|
|
45
|
+
```
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, top_k: int | None = None, *, strategy: Strategy = Strategy.DPP, diversity: float = 0.5) -> None:
|
|
49
|
+
"""
|
|
50
|
+
Creates an instance of PyversityRanker.
|
|
51
|
+
|
|
52
|
+
:param top_k: Number of documents to return after diversification.
|
|
53
|
+
If `None`, all documents are returned in diversified order.
|
|
54
|
+
:param strategy: Pyversity diversification strategy (e.g. `Strategy.MMR`). Defaults to `Strategy.DPP`.
|
|
55
|
+
:param diversity: Trade-off between relevance and diversity in [0, 1].
|
|
56
|
+
`0.0` keeps only the most relevant documents; `1.0` maximises
|
|
57
|
+
diversity regardless of relevance. Defaults to `0.5`.
|
|
58
|
+
|
|
59
|
+
:raises ValueError: If `top_k` is not a positive integer or `diversity` is not in [0, 1].
|
|
60
|
+
"""
|
|
61
|
+
if top_k is not None and top_k <= 0:
|
|
62
|
+
msg = f"top_k must be a positive integer, got {top_k}"
|
|
63
|
+
raise ValueError(msg)
|
|
64
|
+
if not 0.0 <= diversity <= 1.0:
|
|
65
|
+
msg = f"diversity must be in [0, 1], got {diversity}"
|
|
66
|
+
raise ValueError(msg)
|
|
67
|
+
self.top_k = top_k
|
|
68
|
+
self.strategy = strategy
|
|
69
|
+
self.diversity = diversity
|
|
70
|
+
|
|
71
|
+
def to_dict(self) -> dict[str, Any]:
|
|
72
|
+
"""
|
|
73
|
+
Serializes the component to a dictionary.
|
|
74
|
+
|
|
75
|
+
:returns:
|
|
76
|
+
Dictionary with serialized data.
|
|
77
|
+
"""
|
|
78
|
+
return default_to_dict(
|
|
79
|
+
self,
|
|
80
|
+
top_k=self.top_k,
|
|
81
|
+
strategy=self.strategy.value,
|
|
82
|
+
diversity=self.diversity,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def from_dict(cls, data: dict[str, Any]) -> "PyversityRanker":
|
|
87
|
+
"""
|
|
88
|
+
Deserializes the component from a dictionary.
|
|
89
|
+
|
|
90
|
+
:param data:
|
|
91
|
+
The dictionary to deserialize from.
|
|
92
|
+
:returns:
|
|
93
|
+
The deserialized component instance.
|
|
94
|
+
"""
|
|
95
|
+
if strategy := data.get("init_parameters", {}).get("strategy"):
|
|
96
|
+
data["init_parameters"]["strategy"] = Strategy(strategy)
|
|
97
|
+
return default_from_dict(cls, data)
|
|
98
|
+
|
|
99
|
+
@component.output_types(documents=list[Document])
|
|
100
|
+
def run(
|
|
101
|
+
self,
|
|
102
|
+
documents: list[Document],
|
|
103
|
+
top_k: int | None = None,
|
|
104
|
+
strategy: Strategy | None = None,
|
|
105
|
+
diversity: float | None = None,
|
|
106
|
+
) -> dict[str, list[Document]]:
|
|
107
|
+
"""
|
|
108
|
+
Rerank the list of documents using pyversity's diversification algorithm.
|
|
109
|
+
|
|
110
|
+
Documents missing `score` or `embedding` are skipped with a warning.
|
|
111
|
+
|
|
112
|
+
:param documents: List of Documents to rerank. Each document must have `score` and `embedding` set.
|
|
113
|
+
:param top_k: Overrides the initialized `top_k` for this call. `None` falls back to the initialized value.
|
|
114
|
+
:param strategy: Overrides the initialized `strategy` for this call. `None` falls back to the initialized value.
|
|
115
|
+
:param diversity: Overrides the initialized `diversity` for this call.
|
|
116
|
+
`None` falls back to the initialized value.
|
|
117
|
+
:returns:
|
|
118
|
+
A dictionary with the following keys:
|
|
119
|
+
- `documents`: List of up to `top_k` reranked Documents, ordered by the diversification algorithm.
|
|
120
|
+
:raises ValueError: If `top_k` is not a positive integer or `diversity` is not in [0, 1].
|
|
121
|
+
"""
|
|
122
|
+
if top_k is not None and top_k <= 0:
|
|
123
|
+
msg = f"top_k must be a positive integer, got {top_k}"
|
|
124
|
+
raise ValueError(msg)
|
|
125
|
+
if diversity is not None and not 0.0 <= diversity <= 1.0:
|
|
126
|
+
msg = f"diversity must be in [0, 1], got {diversity}"
|
|
127
|
+
raise ValueError(msg)
|
|
128
|
+
|
|
129
|
+
effective_top_k = top_k if top_k is not None else self.top_k
|
|
130
|
+
effective_strategy = strategy if strategy is not None else self.strategy
|
|
131
|
+
effective_diversity = diversity if diversity is not None else self.diversity
|
|
132
|
+
|
|
133
|
+
if not documents:
|
|
134
|
+
return {"documents": []}
|
|
135
|
+
|
|
136
|
+
valid_docs = [doc for doc in documents if doc.score is not None and doc.embedding is not None]
|
|
137
|
+
skipped = len(documents) - len(valid_docs)
|
|
138
|
+
if skipped:
|
|
139
|
+
logger.warning(
|
|
140
|
+
"{skipped} document(s) are missing 'score' or 'embedding' and will be skipped.",
|
|
141
|
+
skipped=skipped,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
if not valid_docs:
|
|
145
|
+
return {"documents": []}
|
|
146
|
+
|
|
147
|
+
embeddings = np.array([doc.embedding for doc in valid_docs])
|
|
148
|
+
scores = np.array([doc.score for doc in valid_docs])
|
|
149
|
+
|
|
150
|
+
if effective_top_k is not None:
|
|
151
|
+
k = min(effective_top_k, len(valid_docs))
|
|
152
|
+
else:
|
|
153
|
+
k = len(valid_docs)
|
|
154
|
+
result = diversify(
|
|
155
|
+
embeddings=embeddings,
|
|
156
|
+
scores=scores,
|
|
157
|
+
k=k,
|
|
158
|
+
strategy=effective_strategy,
|
|
159
|
+
diversity=effective_diversity,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
"documents": [
|
|
164
|
+
replace(valid_docs[i], score=float(score))
|
|
165
|
+
for i, score in zip(result.indices, result.selection_scores, strict=True) # type: ignore[call-overload]
|
|
166
|
+
]
|
|
167
|
+
}
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pytest
|
|
7
|
+
from haystack import Document, Pipeline
|
|
8
|
+
from haystack.components.retrievers import InMemoryEmbeddingRetriever
|
|
9
|
+
from haystack.document_stores.in_memory import InMemoryDocumentStore
|
|
10
|
+
from pyversity import Strategy
|
|
11
|
+
|
|
12
|
+
from haystack_integrations.components.rankers.pyversity import PyversityRanker
|
|
13
|
+
|
|
14
|
+
EMBEDDING_DIM = 16
|
|
15
|
+
RNG = np.random.default_rng(42)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@pytest.fixture()
|
|
19
|
+
def documents():
|
|
20
|
+
docs = []
|
|
21
|
+
for i in range(20):
|
|
22
|
+
vec = RNG.standard_normal(EMBEDDING_DIM)
|
|
23
|
+
vec /= np.linalg.norm(vec)
|
|
24
|
+
docs.append(Document(content=f"Document {i}", embedding=vec.tolist()))
|
|
25
|
+
return docs
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.fixture()
|
|
29
|
+
def query_embedding():
|
|
30
|
+
vec = RNG.standard_normal(EMBEDDING_DIM)
|
|
31
|
+
return (vec / np.linalg.norm(vec)).tolist()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.fixture()
|
|
35
|
+
def pipeline(documents, request):
|
|
36
|
+
strategy = getattr(request, "param", Strategy.MMR)
|
|
37
|
+
store = InMemoryDocumentStore()
|
|
38
|
+
store.write_documents(documents)
|
|
39
|
+
|
|
40
|
+
p = Pipeline()
|
|
41
|
+
p.add_component(
|
|
42
|
+
"retriever",
|
|
43
|
+
InMemoryEmbeddingRetriever(document_store=store, top_k=15, return_embedding=True),
|
|
44
|
+
)
|
|
45
|
+
p.add_component("reranker", PyversityRanker(top_k=5, strategy=strategy, diversity=0.7))
|
|
46
|
+
p.connect("retriever.documents", "reranker.documents")
|
|
47
|
+
return p
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class TestPyversityRanker:
|
|
51
|
+
def test_init_defaults(self):
|
|
52
|
+
reranker = PyversityRanker()
|
|
53
|
+
assert reranker.top_k is None
|
|
54
|
+
assert reranker.strategy == Strategy.DPP
|
|
55
|
+
assert reranker.diversity == 0.5
|
|
56
|
+
|
|
57
|
+
def test_init_top_k_none(self):
|
|
58
|
+
reranker = PyversityRanker(top_k=None)
|
|
59
|
+
assert reranker.top_k is None
|
|
60
|
+
|
|
61
|
+
def test_init_explicit_top_k(self):
|
|
62
|
+
reranker = PyversityRanker(top_k=5)
|
|
63
|
+
assert reranker.top_k == 5
|
|
64
|
+
|
|
65
|
+
def test_init_custom_params(self):
|
|
66
|
+
reranker = PyversityRanker(top_k=10, strategy=Strategy.MMR, diversity=0.3)
|
|
67
|
+
assert reranker.top_k == 10
|
|
68
|
+
assert reranker.strategy == Strategy.MMR
|
|
69
|
+
assert reranker.diversity == 0.3
|
|
70
|
+
|
|
71
|
+
def test_init_invalid_k_zero(self):
|
|
72
|
+
with pytest.raises(ValueError, match="top_k must be a positive integer"):
|
|
73
|
+
PyversityRanker(top_k=0)
|
|
74
|
+
|
|
75
|
+
def test_init_invalid_k_negative(self):
|
|
76
|
+
with pytest.raises(ValueError, match="top_k must be a positive integer"):
|
|
77
|
+
PyversityRanker(top_k=-1)
|
|
78
|
+
|
|
79
|
+
def test_init_invalid_diversity_above_one(self):
|
|
80
|
+
with pytest.raises(ValueError, match="diversity must be in"):
|
|
81
|
+
PyversityRanker(top_k=5, diversity=1.1)
|
|
82
|
+
|
|
83
|
+
def test_init_invalid_diversity_below_zero(self):
|
|
84
|
+
with pytest.raises(ValueError, match="diversity must be in"):
|
|
85
|
+
PyversityRanker(top_k=5, diversity=-0.1)
|
|
86
|
+
|
|
87
|
+
def test_run_empty_documents(self):
|
|
88
|
+
reranker = PyversityRanker(top_k=5)
|
|
89
|
+
result = reranker.run(documents=[])
|
|
90
|
+
assert result == {"documents": []}
|
|
91
|
+
|
|
92
|
+
def test_run_skips_docs_without_score(self):
|
|
93
|
+
rng = np.random.default_rng(0)
|
|
94
|
+
docs = [
|
|
95
|
+
Document(content="has score and embedding", score=0.9, embedding=rng.standard_normal(4).tolist()),
|
|
96
|
+
Document(content="missing score", embedding=rng.standard_normal(4).tolist()),
|
|
97
|
+
]
|
|
98
|
+
reranker = PyversityRanker(top_k=5)
|
|
99
|
+
result = reranker.run(documents=docs)
|
|
100
|
+
assert len(result["documents"]) == 1
|
|
101
|
+
|
|
102
|
+
def test_run_skips_docs_without_embedding(self):
|
|
103
|
+
docs = [
|
|
104
|
+
Document(content="has score and embedding", score=0.9, embedding=[0.1, 0.2, 0.3, 0.4]),
|
|
105
|
+
Document(content="missing embedding", score=0.5),
|
|
106
|
+
]
|
|
107
|
+
reranker = PyversityRanker(top_k=5)
|
|
108
|
+
result = reranker.run(documents=docs)
|
|
109
|
+
assert len(result["documents"]) == 1
|
|
110
|
+
|
|
111
|
+
def test_run_all_docs_invalid_returns_empty(self):
|
|
112
|
+
docs = [
|
|
113
|
+
Document(content="no score", embedding=[0.1, 0.2]),
|
|
114
|
+
Document(content="no embedding", score=0.5),
|
|
115
|
+
]
|
|
116
|
+
reranker = PyversityRanker(top_k=5)
|
|
117
|
+
result = reranker.run(documents=docs)
|
|
118
|
+
assert result == {"documents": []}
|
|
119
|
+
|
|
120
|
+
def test_run_returns_at_most_k_documents(self):
|
|
121
|
+
rng = np.random.default_rng(1)
|
|
122
|
+
docs = [
|
|
123
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
124
|
+
for i in range(10)
|
|
125
|
+
]
|
|
126
|
+
reranker = PyversityRanker(top_k=3)
|
|
127
|
+
result = reranker.run(documents=docs)
|
|
128
|
+
assert len(result["documents"]) <= 3
|
|
129
|
+
|
|
130
|
+
def test_run_returns_all_documents_when_top_k_is_none(self):
|
|
131
|
+
rng = np.random.default_rng(3)
|
|
132
|
+
docs = [
|
|
133
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
134
|
+
for i in range(10)
|
|
135
|
+
]
|
|
136
|
+
reranker = PyversityRanker(top_k=None)
|
|
137
|
+
result = reranker.run(documents=docs)
|
|
138
|
+
assert len(result["documents"]) == 10
|
|
139
|
+
|
|
140
|
+
def test_run_returns_fewer_than_k_if_not_enough_valid(self):
|
|
141
|
+
rng = np.random.default_rng(2)
|
|
142
|
+
docs = [
|
|
143
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
144
|
+
for i in range(2)
|
|
145
|
+
]
|
|
146
|
+
reranker = PyversityRanker(top_k=5)
|
|
147
|
+
result = reranker.run(documents=docs)
|
|
148
|
+
assert len(result["documents"]) == 2
|
|
149
|
+
|
|
150
|
+
def test_run_sets_selection_scores_on_output(self):
|
|
151
|
+
rng = np.random.default_rng(7)
|
|
152
|
+
original_scores = [float(i) / 10 for i in range(1, 6)]
|
|
153
|
+
docs = [
|
|
154
|
+
Document(content=f"doc {i}", score=s, embedding=rng.standard_normal(8).tolist())
|
|
155
|
+
for i, s in enumerate(original_scores)
|
|
156
|
+
]
|
|
157
|
+
reranker = PyversityRanker(top_k=3)
|
|
158
|
+
result = reranker.run(documents=docs)
|
|
159
|
+
for doc in result["documents"]:
|
|
160
|
+
assert doc.score is not None
|
|
161
|
+
assert isinstance(doc.score, float)
|
|
162
|
+
|
|
163
|
+
def test_run_does_not_mutate_input_documents(self):
|
|
164
|
+
rng = np.random.default_rng(8)
|
|
165
|
+
original_scores = [float(i) / 10 for i in range(1, 6)]
|
|
166
|
+
docs = [
|
|
167
|
+
Document(content=f"doc {i}", score=s, embedding=rng.standard_normal(8).tolist())
|
|
168
|
+
for i, s in enumerate(original_scores)
|
|
169
|
+
]
|
|
170
|
+
reranker = PyversityRanker(top_k=3)
|
|
171
|
+
reranker.run(documents=docs)
|
|
172
|
+
for doc, original_score in zip(docs, original_scores, strict=False): # type: ignore[call-overload]
|
|
173
|
+
assert doc.score == original_score
|
|
174
|
+
|
|
175
|
+
def test_to_dict_top_k_none(self):
|
|
176
|
+
reranker = PyversityRanker(top_k=None)
|
|
177
|
+
data = reranker.to_dict()
|
|
178
|
+
assert data == {
|
|
179
|
+
"type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker",
|
|
180
|
+
"init_parameters": {
|
|
181
|
+
"top_k": None,
|
|
182
|
+
"strategy": "dpp",
|
|
183
|
+
"diversity": 0.5,
|
|
184
|
+
},
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
def test_to_dict_defaults(self):
|
|
188
|
+
reranker = PyversityRanker(top_k=5)
|
|
189
|
+
data = reranker.to_dict()
|
|
190
|
+
assert data == {
|
|
191
|
+
"type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker",
|
|
192
|
+
"init_parameters": {
|
|
193
|
+
"top_k": 5,
|
|
194
|
+
"strategy": "dpp",
|
|
195
|
+
"diversity": 0.5,
|
|
196
|
+
},
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
def test_to_dict_custom_params(self):
|
|
200
|
+
reranker = PyversityRanker(top_k=10, strategy=Strategy.MMR, diversity=0.3)
|
|
201
|
+
data = reranker.to_dict()
|
|
202
|
+
assert data == {
|
|
203
|
+
"type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker",
|
|
204
|
+
"init_parameters": {
|
|
205
|
+
"top_k": 10,
|
|
206
|
+
"strategy": "mmr",
|
|
207
|
+
"diversity": 0.3,
|
|
208
|
+
},
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
def test_from_dict(self):
|
|
212
|
+
data = {
|
|
213
|
+
"type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker",
|
|
214
|
+
"init_parameters": {
|
|
215
|
+
"top_k": 7,
|
|
216
|
+
"strategy": "mmr",
|
|
217
|
+
"diversity": 0.8,
|
|
218
|
+
},
|
|
219
|
+
}
|
|
220
|
+
reranker = PyversityRanker.from_dict(data)
|
|
221
|
+
assert reranker.top_k == 7
|
|
222
|
+
assert reranker.strategy == Strategy.MMR
|
|
223
|
+
assert reranker.diversity == 0.8
|
|
224
|
+
|
|
225
|
+
def test_from_dict_defaults(self):
|
|
226
|
+
data = {
|
|
227
|
+
"type": "haystack_integrations.components.rankers.pyversity.ranker.PyversityRanker",
|
|
228
|
+
"init_parameters": {"top_k": 3},
|
|
229
|
+
}
|
|
230
|
+
reranker = PyversityRanker.from_dict(data)
|
|
231
|
+
assert reranker.top_k == 3
|
|
232
|
+
assert reranker.strategy == Strategy.DPP
|
|
233
|
+
assert reranker.diversity == 0.5
|
|
234
|
+
|
|
235
|
+
def test_to_dict_from_dict_roundtrip(self):
|
|
236
|
+
original = PyversityRanker(top_k=4, strategy=Strategy.SSD, diversity=0.2)
|
|
237
|
+
restored = PyversityRanker.from_dict(original.to_dict())
|
|
238
|
+
assert restored.top_k == original.top_k
|
|
239
|
+
assert restored.strategy == original.strategy
|
|
240
|
+
assert restored.diversity == original.diversity
|
|
241
|
+
|
|
242
|
+
def test_to_dict_from_dict_roundtrip_top_k_none(self):
|
|
243
|
+
original = PyversityRanker(top_k=None)
|
|
244
|
+
restored = PyversityRanker.from_dict(original.to_dict())
|
|
245
|
+
assert restored.top_k is None
|
|
246
|
+
|
|
247
|
+
def test_run_top_k_runtime_overrides_init(self):
|
|
248
|
+
rng = np.random.default_rng(10)
|
|
249
|
+
docs = [
|
|
250
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
251
|
+
for i in range(10)
|
|
252
|
+
]
|
|
253
|
+
reranker = PyversityRanker(top_k=10)
|
|
254
|
+
result = reranker.run(documents=docs, top_k=3)
|
|
255
|
+
assert len(result["documents"]) == 3
|
|
256
|
+
|
|
257
|
+
def test_run_top_k_runtime_none_falls_back_to_init(self):
|
|
258
|
+
rng = np.random.default_rng(11)
|
|
259
|
+
docs = [
|
|
260
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
261
|
+
for i in range(10)
|
|
262
|
+
]
|
|
263
|
+
reranker = PyversityRanker(top_k=3)
|
|
264
|
+
result = reranker.run(documents=docs, top_k=None)
|
|
265
|
+
assert len(result["documents"]) == 3
|
|
266
|
+
|
|
267
|
+
def test_run_top_k_runtime_invalid_zero(self):
|
|
268
|
+
reranker = PyversityRanker()
|
|
269
|
+
docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])]
|
|
270
|
+
with pytest.raises(ValueError, match="top_k must be a positive integer"):
|
|
271
|
+
reranker.run(documents=docs, top_k=0)
|
|
272
|
+
|
|
273
|
+
def test_run_top_k_runtime_invalid_negative(self):
|
|
274
|
+
reranker = PyversityRanker()
|
|
275
|
+
docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])]
|
|
276
|
+
with pytest.raises(ValueError, match="top_k must be a positive integer"):
|
|
277
|
+
reranker.run(documents=docs, top_k=-1)
|
|
278
|
+
|
|
279
|
+
def test_run_top_k_runtime_with_init_top_k_none(self):
|
|
280
|
+
rng = np.random.default_rng(12)
|
|
281
|
+
docs = [
|
|
282
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
283
|
+
for i in range(10)
|
|
284
|
+
]
|
|
285
|
+
reranker = PyversityRanker(top_k=None)
|
|
286
|
+
result = reranker.run(documents=docs, top_k=5)
|
|
287
|
+
assert len(result["documents"]) == 5
|
|
288
|
+
|
|
289
|
+
def test_run_diversity_runtime_none_falls_back_to_init(self):
|
|
290
|
+
rng = np.random.default_rng(13)
|
|
291
|
+
docs = [
|
|
292
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
293
|
+
for i in range(5)
|
|
294
|
+
]
|
|
295
|
+
reranker = PyversityRanker(diversity=0.9)
|
|
296
|
+
result_default = reranker.run(documents=docs)
|
|
297
|
+
result_none = reranker.run(documents=docs, diversity=None)
|
|
298
|
+
assert [d.score for d in result_default["documents"]] == [d.score for d in result_none["documents"]]
|
|
299
|
+
|
|
300
|
+
def test_run_diversity_runtime_invalid_above_one(self):
|
|
301
|
+
reranker = PyversityRanker()
|
|
302
|
+
docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])]
|
|
303
|
+
with pytest.raises(ValueError, match="diversity must be in"):
|
|
304
|
+
reranker.run(documents=docs, diversity=1.1)
|
|
305
|
+
|
|
306
|
+
def test_run_diversity_runtime_invalid_below_zero(self):
|
|
307
|
+
reranker = PyversityRanker()
|
|
308
|
+
docs = [Document(content="doc", score=0.5, embedding=[0.1, 0.2, 0.3, 0.4])]
|
|
309
|
+
with pytest.raises(ValueError, match="diversity must be in"):
|
|
310
|
+
reranker.run(documents=docs, diversity=-0.1)
|
|
311
|
+
|
|
312
|
+
def test_run_both_params_overridden_at_runtime(self):
|
|
313
|
+
rng = np.random.default_rng(14)
|
|
314
|
+
docs = [
|
|
315
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
316
|
+
for i in range(10)
|
|
317
|
+
]
|
|
318
|
+
reranker = PyversityRanker(top_k=10, diversity=0.9)
|
|
319
|
+
result = reranker.run(documents=docs, top_k=4, diversity=0.1)
|
|
320
|
+
assert len(result["documents"]) == 4
|
|
321
|
+
|
|
322
|
+
def test_run_strategy_runtime_overrides_init(self):
|
|
323
|
+
rng = np.random.default_rng(15)
|
|
324
|
+
docs = [
|
|
325
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
326
|
+
for i in range(5)
|
|
327
|
+
]
|
|
328
|
+
reranker = PyversityRanker(strategy=Strategy.DPP)
|
|
329
|
+
result = reranker.run(documents=docs, strategy=Strategy.MMR)
|
|
330
|
+
assert len(result["documents"]) == 5
|
|
331
|
+
|
|
332
|
+
def test_run_strategy_runtime_none_falls_back_to_init(self):
|
|
333
|
+
rng = np.random.default_rng(16)
|
|
334
|
+
docs = [
|
|
335
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
336
|
+
for i in range(5)
|
|
337
|
+
]
|
|
338
|
+
reranker = PyversityRanker(strategy=Strategy.MMR)
|
|
339
|
+
result_default = reranker.run(documents=docs)
|
|
340
|
+
result_none = reranker.run(documents=docs, strategy=None)
|
|
341
|
+
assert [d.score for d in result_default["documents"]] == [d.score for d in result_none["documents"]]
|
|
342
|
+
|
|
343
|
+
def test_run_all_params_overridden_at_runtime(self):
|
|
344
|
+
rng = np.random.default_rng(17)
|
|
345
|
+
docs = [
|
|
346
|
+
Document(content=f"doc {i}", score=float(i) / 10, embedding=rng.standard_normal(8).tolist())
|
|
347
|
+
for i in range(10)
|
|
348
|
+
]
|
|
349
|
+
reranker = PyversityRanker(top_k=10, strategy=Strategy.DPP, diversity=0.9)
|
|
350
|
+
result = reranker.run(documents=docs, top_k=4, strategy=Strategy.MMR, diversity=0.1)
|
|
351
|
+
assert len(result["documents"]) == 4
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
@pytest.mark.parametrize(
|
|
355
|
+
"pipeline",
|
|
356
|
+
[Strategy.DPP, Strategy.MMR, Strategy.MSD, Strategy.SSD, Strategy.COVER],
|
|
357
|
+
indirect=True,
|
|
358
|
+
)
|
|
359
|
+
def test_pipeline_returns_k_documents(pipeline, query_embedding):
|
|
360
|
+
result = pipeline.run({"retriever": {"query_embedding": query_embedding}})
|
|
361
|
+
assert len(result["reranker"]["documents"]) == 5
|