rager 0.1.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.
- rager-0.1.0/LICENSE +201 -0
- rager-0.1.0/PKG-INFO +67 -0
- rager-0.1.0/README.md +18 -0
- rager-0.1.0/pyproject.toml +144 -0
- rager-0.1.0/src/rager/__init__.py +55 -0
- rager-0.1.0/src/rager/chunkers.py +71 -0
- rager-0.1.0/src/rager/embedders.py +129 -0
- rager-0.1.0/src/rager/fusers.py +53 -0
- rager-0.1.0/src/rager/generators.py +80 -0
- rager-0.1.0/src/rager/indexes.py +262 -0
- rager-0.1.0/src/rager/parsers.py +53 -0
- rager-0.1.0/src/rager/py.typed +0 -0
- rager-0.1.0/src/rager/scorers.py +64 -0
- rager-0.1.0/src/rager/stores.py +103 -0
- rager-0.1.0/src/rager/types.py +23 -0
rager-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Wannes Vantorre
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
rager-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rager
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Caching based RAG primitives
|
|
5
|
+
Keywords: rag,retrieval-augmented-generation,caching,embeddings,faiss,nlp
|
|
6
|
+
Author: Wannes Vantorre
|
|
7
|
+
Author-email: Wannes Vantorre <vantorrewannes@gmail.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Dist: belljar>=3.0.0
|
|
20
|
+
Requires-Dist: blake3>=1.0.9
|
|
21
|
+
Requires-Dist: concresce>=4.0.0
|
|
22
|
+
Requires-Dist: faiss-cpu>=1.14.3
|
|
23
|
+
Requires-Dist: numpy>=2.4.6
|
|
24
|
+
Requires-Dist: semantic-chunker>=0.2.0
|
|
25
|
+
Requires-Dist: sentence-transformers>=5.6.0
|
|
26
|
+
Requires-Dist: tokenizers>=0.22.2
|
|
27
|
+
Requires-Dist: transformers>=5.13.1
|
|
28
|
+
Requires-Dist: unstructured-inference>=1.6.13
|
|
29
|
+
Requires-Dist: unstructured[csv,md,pdf]>=0.24.0
|
|
30
|
+
Requires-Dist: torch>=2.13.0 ; extra == 'cpu'
|
|
31
|
+
Requires-Dist: torchvision>=0.28.0 ; extra == 'cpu'
|
|
32
|
+
Requires-Dist: torch>=2.13.0 ; extra == 'cu130'
|
|
33
|
+
Requires-Dist: torchvision>=0.28.0 ; extra == 'cu130'
|
|
34
|
+
Requires-Dist: torch>=2.13.0 ; extra == 'rocm'
|
|
35
|
+
Requires-Dist: torchvision>=0.28.0 ; extra == 'rocm'
|
|
36
|
+
Requires-Dist: triton>=3.7.1 ; extra == 'rocm'
|
|
37
|
+
Requires-Dist: triton-rocm>=2.13.0 ; extra == 'rocm'
|
|
38
|
+
Maintainer: Wannes Vantorre
|
|
39
|
+
Maintainer-email: Wannes Vantorre <vantorrewannes@gmail.com>
|
|
40
|
+
Requires-Python: >=3.14
|
|
41
|
+
Project-URL: Homepage, https://github.com/VantorreWannes/rager
|
|
42
|
+
Project-URL: Repository, https://github.com/VantorreWannes/rager
|
|
43
|
+
Project-URL: Issues, https://github.com/VantorreWannes/rager/issues
|
|
44
|
+
Project-URL: Changelog, https://github.com/VantorreWannes/rager/releases
|
|
45
|
+
Provides-Extra: cpu
|
|
46
|
+
Provides-Extra: cu130
|
|
47
|
+
Provides-Extra: rocm
|
|
48
|
+
Description-Content-Type: text/markdown
|
|
49
|
+
|
|
50
|
+
# rager
|
|
51
|
+
|
|
52
|
+
Caching based RAG primitives — composable building blocks for retrieval-augmented generation with caching baked in.
|
|
53
|
+
|
|
54
|
+
## Install
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
uv add rager
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Getting started
|
|
61
|
+
|
|
62
|
+
```
|
|
63
|
+
uv run pytest
|
|
64
|
+
uv run prek install
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Add an `--extra` to pin the default device: `rocm` (AMD), `cu130` (NVIDIA), or `cpu`. With `cpu`, torch supplies automatic fallback. For example: `uv run --extra cpu pytest`.
|
rager-0.1.0/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# rager
|
|
2
|
+
|
|
3
|
+
Caching based RAG primitives — composable building blocks for retrieval-augmented generation with caching baked in.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
uv add rager
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Getting started
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
uv run pytest
|
|
15
|
+
uv run prek install
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Add an `--extra` to pin the default device: `rocm` (AMD), `cu130` (NVIDIA), or `cpu`. With `cpu`, torch supplies automatic fallback. For example: `uv run --extra cpu pytest`.
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "rager"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Caching based RAG primitives"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Wannes Vantorre", email = "vantorrewannes@gmail.com" }
|
|
8
|
+
]
|
|
9
|
+
maintainers = [
|
|
10
|
+
{ name = "Wannes Vantorre", email = "vantorrewannes@gmail.com" }
|
|
11
|
+
]
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
keywords = ["rag", "retrieval-augmented-generation", "caching", "embeddings", "faiss", "nlp"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
23
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
requires-python = ">=3.14"
|
|
27
|
+
dependencies = [
|
|
28
|
+
"belljar>=3.0.0",
|
|
29
|
+
"blake3>=1.0.9",
|
|
30
|
+
"concresce>=4.0.0",
|
|
31
|
+
"faiss-cpu>=1.14.3",
|
|
32
|
+
"numpy>=2.4.6",
|
|
33
|
+
"semantic-chunker>=0.2.0",
|
|
34
|
+
"sentence-transformers>=5.6.0",
|
|
35
|
+
"tokenizers>=0.22.2",
|
|
36
|
+
"transformers>=5.13.1",
|
|
37
|
+
"unstructured-inference>=1.6.13",
|
|
38
|
+
"unstructured[csv,md,pdf]>=0.24.0",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://github.com/VantorreWannes/rager"
|
|
43
|
+
Repository = "https://github.com/VantorreWannes/rager"
|
|
44
|
+
Issues = "https://github.com/VantorreWannes/rager/issues"
|
|
45
|
+
Changelog = "https://github.com/VantorreWannes/rager/releases"
|
|
46
|
+
|
|
47
|
+
[build-system]
|
|
48
|
+
requires = ["uv_build>=0.11.28,<0.12.0"]
|
|
49
|
+
build-backend = "uv_build"
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
filterwarnings = [
|
|
53
|
+
"ignore:'asyncio.iscoroutinefunction' is deprecated:DeprecationWarning",
|
|
54
|
+
]
|
|
55
|
+
addopts = "--cov=rager --cov-report=html --cov-report=term-missing"
|
|
56
|
+
markers = [
|
|
57
|
+
"smoke: instant sanity checks that the package imports and its model-free primitives work, with nothing mocked and no model downloads (tests/smoke)",
|
|
58
|
+
"unit: fast, isolated test of a single component with every external dependency mocked (tests/unit)",
|
|
59
|
+
"integration: slower tests requiring external dependencies (tests/integration)",
|
|
60
|
+
"application: end-to-end user journeys composing multiple primitives with real models (tests/application)",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint]
|
|
64
|
+
select = ["ALL"]
|
|
65
|
+
ignore = ["D203", "D213", "COM812", "ISC001"]
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint.per-file-ignores]
|
|
68
|
+
"tests/**" = ["S101"]
|
|
69
|
+
"tests/unit/**" = ["SLF001"]
|
|
70
|
+
|
|
71
|
+
[tool.ty.rules]
|
|
72
|
+
all = "error"
|
|
73
|
+
|
|
74
|
+
[[tool.uv.index]]
|
|
75
|
+
name = "pytorch-rocm"
|
|
76
|
+
url = "https://download.pytorch.org/whl/rocm7.2"
|
|
77
|
+
explicit = true
|
|
78
|
+
|
|
79
|
+
[[tool.uv.index]]
|
|
80
|
+
name = "pytorch-cpu"
|
|
81
|
+
url = "https://download.pytorch.org/whl/cpu"
|
|
82
|
+
explicit = true
|
|
83
|
+
|
|
84
|
+
[[tool.uv.index]]
|
|
85
|
+
name = "pytorch-cu130"
|
|
86
|
+
url = "https://download.pytorch.org/whl/cu130"
|
|
87
|
+
explicit = true
|
|
88
|
+
|
|
89
|
+
[project.optional-dependencies]
|
|
90
|
+
cpu = [
|
|
91
|
+
"torch>=2.13.0",
|
|
92
|
+
"torchvision>=0.28.0",
|
|
93
|
+
]
|
|
94
|
+
cu130 = [
|
|
95
|
+
"torch>=2.13.0",
|
|
96
|
+
"torchvision>=0.28.0",
|
|
97
|
+
]
|
|
98
|
+
rocm = [
|
|
99
|
+
"torch>=2.13.0",
|
|
100
|
+
"torchvision>=0.28.0",
|
|
101
|
+
"triton>=3.7.1",
|
|
102
|
+
"triton-rocm>=2.13.0",
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
[tool.uv.sources]
|
|
106
|
+
torch = [
|
|
107
|
+
{ index = "pytorch-cpu", extra = "cpu" },
|
|
108
|
+
{ index = "pytorch-cu130", extra = "cu130" },
|
|
109
|
+
{ index = "pytorch-rocm", extra = "rocm" },
|
|
110
|
+
]
|
|
111
|
+
torchvision = [
|
|
112
|
+
{ index = "pytorch-cpu", extra = "cpu" },
|
|
113
|
+
{ index = "pytorch-cu130", extra = "cu130" },
|
|
114
|
+
{ index = "pytorch-rocm", extra = "rocm" },
|
|
115
|
+
]
|
|
116
|
+
triton = [
|
|
117
|
+
{ index = "pytorch-rocm", extra = "rocm" },
|
|
118
|
+
]
|
|
119
|
+
triton-rocm = [
|
|
120
|
+
{ index = "pytorch-rocm", extra = "rocm" },
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
[dependency-groups]
|
|
124
|
+
dev = [
|
|
125
|
+
"httpx>=0.28.1",
|
|
126
|
+
"lorem-text>=3.0",
|
|
127
|
+
"prek>=0.4.8",
|
|
128
|
+
"pytest-asyncio>=1.4.0",
|
|
129
|
+
"pytest-cov>=7.1.0",
|
|
130
|
+
"ruff>=0.15.21",
|
|
131
|
+
"ty>=0.0.58",
|
|
132
|
+
]
|
|
133
|
+
|
|
134
|
+
[tool.uv]
|
|
135
|
+
override-dependencies = [
|
|
136
|
+
"python-magic; sys_platform != 'win32'",
|
|
137
|
+
]
|
|
138
|
+
conflicts = [
|
|
139
|
+
[
|
|
140
|
+
{ extra = "cpu" },
|
|
141
|
+
{ extra = "cu130" },
|
|
142
|
+
{ extra = "rocm" },
|
|
143
|
+
],
|
|
144
|
+
]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Caching based RAG primitives."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
from rager.chunkers import Chunker, SemanticChunker
|
|
6
|
+
from rager.embedders import (
|
|
7
|
+
Embedder,
|
|
8
|
+
SentenceTransformerDenseEmbedder,
|
|
9
|
+
SpladeSparseEmbedder,
|
|
10
|
+
)
|
|
11
|
+
from rager.fusers import BordaCountFuser, Fuser, ReciprocalRankFuser
|
|
12
|
+
from rager.generators import Generator, TransformersGenerator
|
|
13
|
+
from rager.indexes import DenseIndex, Index, SparseIndex
|
|
14
|
+
from rager.parsers import (
|
|
15
|
+
CsvFileParser,
|
|
16
|
+
MarkdownFileParser,
|
|
17
|
+
Parser,
|
|
18
|
+
PdfFileParser,
|
|
19
|
+
UnstructuredFileParser,
|
|
20
|
+
)
|
|
21
|
+
from rager.scorers import CrossEncoderScorer, Scorer
|
|
22
|
+
from rager.stores import ChunkStore, MetadataStore, Store
|
|
23
|
+
from rager.types import DenseEmbedding, Hash, Metadata, SparseEmbedding
|
|
24
|
+
|
|
25
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"BordaCountFuser",
|
|
29
|
+
"ChunkStore",
|
|
30
|
+
"Chunker",
|
|
31
|
+
"CrossEncoderScorer",
|
|
32
|
+
"CsvFileParser",
|
|
33
|
+
"DenseEmbedding",
|
|
34
|
+
"DenseIndex",
|
|
35
|
+
"Embedder",
|
|
36
|
+
"Fuser",
|
|
37
|
+
"Generator",
|
|
38
|
+
"Hash",
|
|
39
|
+
"Index",
|
|
40
|
+
"MarkdownFileParser",
|
|
41
|
+
"Metadata",
|
|
42
|
+
"MetadataStore",
|
|
43
|
+
"Parser",
|
|
44
|
+
"PdfFileParser",
|
|
45
|
+
"ReciprocalRankFuser",
|
|
46
|
+
"Scorer",
|
|
47
|
+
"SemanticChunker",
|
|
48
|
+
"SentenceTransformerDenseEmbedder",
|
|
49
|
+
"SparseEmbedding",
|
|
50
|
+
"SparseIndex",
|
|
51
|
+
"SpladeSparseEmbedder",
|
|
52
|
+
"Store",
|
|
53
|
+
"TransformersGenerator",
|
|
54
|
+
"UnstructuredFileParser",
|
|
55
|
+
]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Chunkers for splitting units into smaller chunks."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from functools import cached_property
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING, Protocol, cast
|
|
7
|
+
|
|
8
|
+
import belljar
|
|
9
|
+
from semantic_chunker import get_chunker
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from semantic_text_splitter import TextSplitter
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Chunker(Protocol):
|
|
18
|
+
"""Protocol for chunking units into smaller chunks."""
|
|
19
|
+
|
|
20
|
+
def chunk(self, unit: str) -> list[str]:
|
|
21
|
+
"""Split a unit into smaller chunks."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SemanticChunker:
|
|
26
|
+
"""Chunker that splits units based on semantic boundaries."""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
model_name: str = "gpt-3.5-turbo",
|
|
31
|
+
chunk_size: int = 1000,
|
|
32
|
+
overlap: int = 0,
|
|
33
|
+
) -> None:
|
|
34
|
+
"""Initialize the semantic chunker."""
|
|
35
|
+
self.model_name = model_name
|
|
36
|
+
self.chunk_size = chunk_size
|
|
37
|
+
self.overlap = overlap
|
|
38
|
+
|
|
39
|
+
@cached_property
|
|
40
|
+
def model(self) -> TextSplitter:
|
|
41
|
+
"""Get the text splitter instance."""
|
|
42
|
+
logger.info(
|
|
43
|
+
"Loading semantic chunker for model %r (chunk_size=%d, overlap=%d)",
|
|
44
|
+
self.model_name,
|
|
45
|
+
self.chunk_size,
|
|
46
|
+
self.overlap,
|
|
47
|
+
)
|
|
48
|
+
return cast(
|
|
49
|
+
"TextSplitter",
|
|
50
|
+
get_chunker(
|
|
51
|
+
self.model_name,
|
|
52
|
+
chunking_type="text",
|
|
53
|
+
tree_sitter_language=None,
|
|
54
|
+
max_tokens=self.chunk_size,
|
|
55
|
+
overlap=self.overlap,
|
|
56
|
+
trim=True,
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
@belljar.store(Path(".jar/chunkers"))
|
|
61
|
+
def chunk(self, unit: str) -> list[str]:
|
|
62
|
+
"""Split a unit into semantically meaningful chunks."""
|
|
63
|
+
belljar.include(self.model_name)
|
|
64
|
+
belljar.include(self.chunk_size)
|
|
65
|
+
belljar.include(self.overlap)
|
|
66
|
+
belljar.include(unit)
|
|
67
|
+
belljar.check()
|
|
68
|
+
logger.debug("Cache miss; chunking unit of %d characters", len(unit))
|
|
69
|
+
chunks = self.model.chunks(unit)
|
|
70
|
+
logger.debug("Split unit into %d chunks", len(chunks))
|
|
71
|
+
return chunks
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Embedders for converting text chunks into vector representations."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Protocol
|
|
8
|
+
|
|
9
|
+
import belljar
|
|
10
|
+
import concresce
|
|
11
|
+
from sentence_transformers import SentenceTransformer, SparseEncoder
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Awaitable, Callable, Iterable, Iterator
|
|
15
|
+
|
|
16
|
+
from torch import Tensor
|
|
17
|
+
|
|
18
|
+
from rager import DenseEmbedding
|
|
19
|
+
from rager.types import SparseEmbedding
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Embedder[E](Protocol):
|
|
25
|
+
"""Protocol for embedders."""
|
|
26
|
+
|
|
27
|
+
async def embed(self, chunk: str) -> E:
|
|
28
|
+
"""Convert a text chunk into a vector representation."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SentenceTransformerDenseEmbedder:
|
|
33
|
+
"""Dense embedding using SentenceTransformer."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, model_name: str = "all-MiniLM-L6-v2") -> None:
|
|
36
|
+
"""Initialize the dense embedder with a specific model."""
|
|
37
|
+
self.model_name = model_name
|
|
38
|
+
|
|
39
|
+
@cached_property
|
|
40
|
+
def model(self) -> SentenceTransformer:
|
|
41
|
+
"""Load the SentenceTransformer model."""
|
|
42
|
+
logger.info("Loading SentenceTransformer model %r", self.model_name)
|
|
43
|
+
return SentenceTransformer(self.model_name)
|
|
44
|
+
|
|
45
|
+
@cached_property
|
|
46
|
+
def _encode(self) -> Callable[[str], Awaitable[DenseEmbedding]]:
|
|
47
|
+
"""Coalesce concurrent calls into per-instance encoding batches."""
|
|
48
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._encode_batch)
|
|
49
|
+
|
|
50
|
+
async def _encode_batch(self, chunk: str) -> DenseEmbedding:
|
|
51
|
+
"""Convert a text chunk into a vector representation."""
|
|
52
|
+
chunks = await concresce.collect(chunk)
|
|
53
|
+
logger.debug(
|
|
54
|
+
"Encoding batch of %d chunks with %r", len(chunks), self.model_name
|
|
55
|
+
)
|
|
56
|
+
embeddings = self.model.encode(chunks, normalize_embeddings=True).tolist()
|
|
57
|
+
return concresce.scatter(embeddings)
|
|
58
|
+
|
|
59
|
+
@belljar.store(Path(".jar/embedders"))
|
|
60
|
+
async def embed(self, chunk: str) -> DenseEmbedding:
|
|
61
|
+
"""Convert a text chunk into a vector representation."""
|
|
62
|
+
belljar.include(self.model_name)
|
|
63
|
+
belljar.include(chunk)
|
|
64
|
+
belljar.check()
|
|
65
|
+
logger.debug("Cache miss; embedding chunk of %d characters", len(chunk))
|
|
66
|
+
return await self._encode(chunk)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class SpladeSparseEmbedder:
|
|
70
|
+
"""Sparse embedding using a SPLADE SparseEncoder."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, model_name: str = "prithivida/Splade_PP_en_v1") -> None:
|
|
73
|
+
"""Initialize the sparse embedder with a specific model."""
|
|
74
|
+
self.model_name = model_name
|
|
75
|
+
|
|
76
|
+
@cached_property
|
|
77
|
+
def model(self) -> SparseEncoder:
|
|
78
|
+
"""Load the SPLADE SparseEncoder model."""
|
|
79
|
+
logger.info("Loading SPLADE SparseEncoder model %r", self.model_name)
|
|
80
|
+
return SparseEncoder(self.model_name)
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _decode_entries(coalesced: Tensor) -> Iterator[tuple[int, int, float]]:
|
|
84
|
+
"""Yield (row, token_id, weight) triples from a coalesced sparse tensor."""
|
|
85
|
+
indices = coalesced.indices()
|
|
86
|
+
values = coalesced.values()
|
|
87
|
+
for row, token, weight in zip(indices[0], indices[1], values, strict=True):
|
|
88
|
+
yield int(row), int(token), float(weight)
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def _group_by_row(
|
|
92
|
+
entries: Iterable[tuple[int, int, float]], count: int
|
|
93
|
+
) -> list[SparseEmbedding]:
|
|
94
|
+
"""Bucket (row, token_id, weight) triples into one weight map per row."""
|
|
95
|
+
embeddings: list[SparseEmbedding] = [{} for _ in range(count)]
|
|
96
|
+
for row, token, weight in entries:
|
|
97
|
+
embeddings[row][token] = weight
|
|
98
|
+
return embeddings
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def _coalesced_to_embeddings(
|
|
102
|
+
cls, coalesced: Tensor, count: int
|
|
103
|
+
) -> list[SparseEmbedding]:
|
|
104
|
+
"""Split a coalesced sparse tensor into one weight map per input row."""
|
|
105
|
+
return cls._group_by_row(cls._decode_entries(coalesced), count)
|
|
106
|
+
|
|
107
|
+
@cached_property
|
|
108
|
+
def _encode(self) -> Callable[[str], Awaitable[SparseEmbedding]]:
|
|
109
|
+
"""Coalesce concurrent calls into per-instance encoding batches."""
|
|
110
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._encode_batch)
|
|
111
|
+
|
|
112
|
+
async def _encode_batch(self, chunk: str) -> SparseEmbedding:
|
|
113
|
+
"""Convert a text chunk into a sparse vector representation."""
|
|
114
|
+
chunks = await concresce.collect(chunk)
|
|
115
|
+
logger.debug(
|
|
116
|
+
"Encoding batch of %d chunks with %r", len(chunks), self.model_name
|
|
117
|
+
)
|
|
118
|
+
coalesced = self.model.encode(chunks).coalesce()
|
|
119
|
+
embeddings = self._coalesced_to_embeddings(coalesced, len(chunks))
|
|
120
|
+
return concresce.scatter(embeddings)
|
|
121
|
+
|
|
122
|
+
@belljar.store(Path(".jar/embedders"))
|
|
123
|
+
async def embed(self, chunk: str) -> SparseEmbedding:
|
|
124
|
+
"""Convert a text chunk into a sparse vector representation."""
|
|
125
|
+
belljar.include(self.model_name)
|
|
126
|
+
belljar.include(chunk)
|
|
127
|
+
belljar.check()
|
|
128
|
+
logger.debug("Cache miss; embedding chunk of %d characters", len(chunk))
|
|
129
|
+
return await self._encode(chunk)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Fusers for combining ranked lists of values."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import TYPE_CHECKING, Protocol
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from collections.abc import Hashable
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Fuser[V](Protocol):
|
|
13
|
+
"""Protocol for fusing values into ranked lists."""
|
|
14
|
+
|
|
15
|
+
def fuse(self, *values: list[V]) -> list[V]:
|
|
16
|
+
"""Fuse multiple values into one ranked list."""
|
|
17
|
+
...
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ReciprocalRankFuser[V: Hashable]:
|
|
21
|
+
"""Fuser that combines ranked lists by reciprocal rank fusion."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, k: int = 60) -> None:
|
|
24
|
+
"""Initialize the fuser with the reciprocal rank smoothing constant."""
|
|
25
|
+
self.k = k
|
|
26
|
+
|
|
27
|
+
def fuse(self, *values: list[V]) -> list[V]:
|
|
28
|
+
"""Fuse multiple ranked lists into one list ranked by reciprocal rank."""
|
|
29
|
+
logger.debug(
|
|
30
|
+
"Fusing %d rankings by reciprocal rank (k=%d)", len(values), self.k
|
|
31
|
+
)
|
|
32
|
+
scores: dict[V, float] = {}
|
|
33
|
+
for ranking in values:
|
|
34
|
+
for rank, value in enumerate(ranking, start=1):
|
|
35
|
+
scores[value] = scores.get(value, 0.0) + 1 / (self.k + rank)
|
|
36
|
+
fused = sorted(scores, key=lambda value: scores[value], reverse=True)
|
|
37
|
+
logger.debug("Fused rankings into %d distinct values", len(fused))
|
|
38
|
+
return fused
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BordaCountFuser[V: Hashable]:
|
|
42
|
+
"""Fuser that combines ranked lists by Borda count."""
|
|
43
|
+
|
|
44
|
+
def fuse(self, *values: list[V]) -> list[V]:
|
|
45
|
+
"""Fuse multiple ranked lists into one list ranked by Borda count."""
|
|
46
|
+
logger.debug("Fusing %d rankings by Borda count", len(values))
|
|
47
|
+
scores: dict[V, int] = {}
|
|
48
|
+
for ranking in values:
|
|
49
|
+
for rank, value in enumerate(ranking):
|
|
50
|
+
scores[value] = scores.get(value, 0) + len(ranking) - rank
|
|
51
|
+
fused = sorted(scores, key=lambda value: scores[value], reverse=True)
|
|
52
|
+
logger.debug("Fused rankings into %d distinct values", len(fused))
|
|
53
|
+
return fused
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Generators for producing answers to prompts."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Protocol
|
|
8
|
+
|
|
9
|
+
import belljar
|
|
10
|
+
import concresce
|
|
11
|
+
from transformers import pipeline
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Awaitable, Callable
|
|
15
|
+
|
|
16
|
+
from transformers import TextGenerationPipeline
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Generator(Protocol):
|
|
22
|
+
"""Protocol for prompting content generators."""
|
|
23
|
+
|
|
24
|
+
async def prompt(self, query: str) -> str:
|
|
25
|
+
"""Generate content based on the query."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TransformersGenerator:
|
|
30
|
+
"""Generator that prompts a local transformers text-generation model."""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
model_name: str = "HuggingFaceTB/SmolLM2-135M-Instruct",
|
|
35
|
+
max_new_tokens: int = 512,
|
|
36
|
+
) -> None:
|
|
37
|
+
"""Initialize the generator with a specific model."""
|
|
38
|
+
self.model_name = model_name
|
|
39
|
+
self.max_new_tokens = max_new_tokens
|
|
40
|
+
|
|
41
|
+
@cached_property
|
|
42
|
+
def model(self) -> TextGenerationPipeline:
|
|
43
|
+
"""Load the text-generation pipeline."""
|
|
44
|
+
logger.info("Loading text-generation pipeline for model %r", self.model_name)
|
|
45
|
+
return pipeline("text-generation", model=self.model_name)
|
|
46
|
+
|
|
47
|
+
@cached_property
|
|
48
|
+
def _generate(self) -> Callable[[str], Awaitable[str]]:
|
|
49
|
+
"""Coalesce concurrent calls into per-instance generation batches."""
|
|
50
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._generate_batch)
|
|
51
|
+
|
|
52
|
+
async def _generate_batch(self, query: str) -> str:
|
|
53
|
+
"""Generate an answer for each query in the collected batch."""
|
|
54
|
+
queries = await concresce.collect(query)
|
|
55
|
+
logger.debug(
|
|
56
|
+
"Generating answers for a batch of %d queries with %r (max_new_tokens=%d)",
|
|
57
|
+
len(queries),
|
|
58
|
+
self.model_name,
|
|
59
|
+
self.max_new_tokens,
|
|
60
|
+
)
|
|
61
|
+
chats = [[{"role": "user", "content": query}] for query in queries]
|
|
62
|
+
outputs = self.model(
|
|
63
|
+
chats,
|
|
64
|
+
max_new_tokens=self.max_new_tokens,
|
|
65
|
+
do_sample=False,
|
|
66
|
+
)
|
|
67
|
+
answers = [output[0]["generated_text"][-1]["content"] for output in outputs]
|
|
68
|
+
return concresce.scatter(answers)
|
|
69
|
+
|
|
70
|
+
@belljar.store(Path(".jar/generators"))
|
|
71
|
+
async def prompt(self, query: str) -> str:
|
|
72
|
+
"""Generate content based on the query."""
|
|
73
|
+
belljar.include(self.model_name)
|
|
74
|
+
belljar.include(self.max_new_tokens)
|
|
75
|
+
belljar.include(query)
|
|
76
|
+
belljar.check()
|
|
77
|
+
logger.debug(
|
|
78
|
+
"Cache miss; generating answer for query of %d characters", len(query)
|
|
79
|
+
)
|
|
80
|
+
return await self._generate(query)
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Embedding Index protocol definitions."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from typing import TYPE_CHECKING, Protocol
|
|
7
|
+
|
|
8
|
+
import blake3
|
|
9
|
+
import concresce
|
|
10
|
+
import faiss
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Awaitable, Callable
|
|
15
|
+
|
|
16
|
+
from rager import DenseEmbedding, SparseEmbedding
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Index[E, K](Protocol):
|
|
22
|
+
"""Protocol for an embedding index.
|
|
23
|
+
|
|
24
|
+
Similarity is measured by inner product, which equals cosine similarity
|
|
25
|
+
only when the embeddings are L2-normalized. Normalize your embeddings
|
|
26
|
+
before adding them if you want cosine ranking.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
async def add(self, embedding: E) -> K:
|
|
30
|
+
"""Add an embedding to the index and return its key."""
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
async def remove(self, key: K) -> None:
|
|
34
|
+
"""Remove an embedding from the index by its key."""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
async def similar(self, embedding: E, results: int = 100) -> list[K]:
|
|
38
|
+
"""Retrieve the keys of the ``results`` most similar embeddings."""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class DenseIndex:
|
|
43
|
+
"""Dense embedding index backed by a flat FAISS inner-product index.
|
|
44
|
+
|
|
45
|
+
Ranking uses inner product, so it matches cosine similarity only for
|
|
46
|
+
L2-normalized embeddings (as produced by the bundled dense embedder).
|
|
47
|
+
|
|
48
|
+
The embedding dimension is inferred from the first embedding added. Pass
|
|
49
|
+
``dimensions`` to validate that every embedding matches an expected width.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, dimensions: int | None = None) -> None:
|
|
53
|
+
"""Initialize the index, optionally fixing the embedding dimension."""
|
|
54
|
+
self.dimensions = dimensions
|
|
55
|
+
self._index: faiss.IndexIDMap2 | None = None
|
|
56
|
+
|
|
57
|
+
@cached_property
|
|
58
|
+
def add(self) -> Callable[[DenseEmbedding], Awaitable[int]]:
|
|
59
|
+
"""Add an embedding to the index and return its key."""
|
|
60
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._add)
|
|
61
|
+
|
|
62
|
+
@cached_property
|
|
63
|
+
def remove(self) -> Callable[[int], Awaitable[None]]:
|
|
64
|
+
"""Remove an embedding from the index by its key."""
|
|
65
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._remove)
|
|
66
|
+
|
|
67
|
+
async def similar(self, embedding: DenseEmbedding, results: int = 100) -> list[int]:
|
|
68
|
+
"""Retrieve the keys of the ``results`` most similar embeddings."""
|
|
69
|
+
return await self._similar(embedding, results)
|
|
70
|
+
|
|
71
|
+
@cached_property
|
|
72
|
+
def _similar(self) -> Callable[[DenseEmbedding, int], Awaitable[list[int]]]:
|
|
73
|
+
"""Coalesce concurrent queries into one batched FAISS search."""
|
|
74
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._similar_batch)
|
|
75
|
+
|
|
76
|
+
def _ensure_index(self, dimensions: int) -> faiss.IndexIDMap2:
|
|
77
|
+
"""Return the index, building it to match the first embedding's width."""
|
|
78
|
+
if self.dimensions is None:
|
|
79
|
+
logger.debug("Inferred embedding dimension %d from first batch", dimensions)
|
|
80
|
+
self.dimensions = dimensions
|
|
81
|
+
if dimensions != self.dimensions:
|
|
82
|
+
message = (
|
|
83
|
+
f"Embedding has {dimensions} dimensions, "
|
|
84
|
+
f"but the index expects {self.dimensions}."
|
|
85
|
+
)
|
|
86
|
+
logger.error(message)
|
|
87
|
+
raise ValueError(message)
|
|
88
|
+
if self._index is None:
|
|
89
|
+
logger.info("Created dense FAISS index with %d dimensions", self.dimensions)
|
|
90
|
+
self._index = faiss.IndexIDMap2(faiss.IndexFlatIP(self.dimensions))
|
|
91
|
+
return self._index
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def _to_rows(embeddings: list[DenseEmbedding]) -> np.ndarray:
|
|
95
|
+
"""Convert embeddings into a float32 matrix for FAISS."""
|
|
96
|
+
return np.asarray(embeddings, dtype=np.float32)
|
|
97
|
+
|
|
98
|
+
@staticmethod
|
|
99
|
+
def _key(row: np.ndarray) -> int:
|
|
100
|
+
"""Derive a deterministic int64 key from the embedding's content."""
|
|
101
|
+
digest = blake3.blake3(row.tobytes()).digest()
|
|
102
|
+
return int.from_bytes(digest[:8], "little", signed=True)
|
|
103
|
+
|
|
104
|
+
async def _add(self, embedding: DenseEmbedding) -> int:
|
|
105
|
+
"""Add an embedding to the index and return its key."""
|
|
106
|
+
embeddings = await concresce.collect(embedding)
|
|
107
|
+
rows = self._to_rows(embeddings)
|
|
108
|
+
index = self._ensure_index(rows.shape[1])
|
|
109
|
+
keys = [self._key(row) for row in rows]
|
|
110
|
+
unique = dict(zip(keys, rows, strict=True))
|
|
111
|
+
ids = np.asarray(list(unique), dtype=np.int64)
|
|
112
|
+
index.remove_ids(faiss.IDSelectorBatch(ids))
|
|
113
|
+
index.add_with_ids(self._to_rows(list(unique.values())), ids)
|
|
114
|
+
logger.debug(
|
|
115
|
+
"Added %d embeddings (%d unique) to the dense index; total is now %d",
|
|
116
|
+
len(keys),
|
|
117
|
+
len(unique),
|
|
118
|
+
index.ntotal,
|
|
119
|
+
)
|
|
120
|
+
return concresce.scatter(keys)
|
|
121
|
+
|
|
122
|
+
async def _remove(self, key: int) -> None:
|
|
123
|
+
"""Remove an embedding from the index by its key."""
|
|
124
|
+
keys = await concresce.collect(key)
|
|
125
|
+
if self._index is None:
|
|
126
|
+
logger.warning(
|
|
127
|
+
"Ignoring removal of %d keys from an empty dense index", len(keys)
|
|
128
|
+
)
|
|
129
|
+
else:
|
|
130
|
+
ids = np.asarray(keys, dtype=np.int64)
|
|
131
|
+
removed = self._index.remove_ids(faiss.IDSelectorBatch(ids))
|
|
132
|
+
logger.debug(
|
|
133
|
+
"Removed %d of %d keys from the dense index; total is now %d",
|
|
134
|
+
removed,
|
|
135
|
+
len(keys),
|
|
136
|
+
self._index.ntotal,
|
|
137
|
+
)
|
|
138
|
+
return concresce.scatter([None] * len(keys))
|
|
139
|
+
|
|
140
|
+
async def _similar_batch(
|
|
141
|
+
self, embedding: DenseEmbedding, results: int
|
|
142
|
+
) -> list[int]:
|
|
143
|
+
"""Retrieve the most similar embedding keys to the given embedding."""
|
|
144
|
+
collected = await concresce.collect((embedding, results))
|
|
145
|
+
embeddings = [query for query, _ in collected]
|
|
146
|
+
counts = [count for _, count in collected]
|
|
147
|
+
if self._index is None:
|
|
148
|
+
logger.warning(
|
|
149
|
+
"Similarity search of %d queries on an empty dense index",
|
|
150
|
+
len(collected),
|
|
151
|
+
)
|
|
152
|
+
return concresce.scatter([[] for _ in collected])
|
|
153
|
+
logger.debug(
|
|
154
|
+
"Searching the dense index of %d embeddings with %d queries",
|
|
155
|
+
self._index.ntotal,
|
|
156
|
+
len(collected),
|
|
157
|
+
)
|
|
158
|
+
_, ids = self._index.search(self._to_rows(embeddings), max(counts))
|
|
159
|
+
rankings = [
|
|
160
|
+
[int(i) for i in row[:count] if i != -1]
|
|
161
|
+
for row, count in zip(ids, counts, strict=True)
|
|
162
|
+
]
|
|
163
|
+
return concresce.scatter(rankings)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class SparseIndex:
|
|
167
|
+
"""Sparse embedding index using inner-product similarity over weight maps."""
|
|
168
|
+
|
|
169
|
+
def __init__(self) -> None:
|
|
170
|
+
"""Initialize the sparse index."""
|
|
171
|
+
self._embeddings: dict[int, SparseEmbedding] = {}
|
|
172
|
+
|
|
173
|
+
@cached_property
|
|
174
|
+
def add(self) -> Callable[[SparseEmbedding], Awaitable[int]]:
|
|
175
|
+
"""Add an embedding to the index and return its key."""
|
|
176
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._add)
|
|
177
|
+
|
|
178
|
+
@cached_property
|
|
179
|
+
def remove(self) -> Callable[[int], Awaitable[None]]:
|
|
180
|
+
"""Remove an embedding from the index by its key."""
|
|
181
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._remove)
|
|
182
|
+
|
|
183
|
+
async def similar(
|
|
184
|
+
self, embedding: SparseEmbedding, results: int = 100
|
|
185
|
+
) -> list[int]:
|
|
186
|
+
"""Retrieve the keys of the ``results`` most similar embeddings."""
|
|
187
|
+
return await self._similar(embedding, results)
|
|
188
|
+
|
|
189
|
+
@cached_property
|
|
190
|
+
def _similar(self) -> Callable[[SparseEmbedding, int], Awaitable[list[int]]]:
|
|
191
|
+
"""Coalesce concurrent queries into one batched ranking pass."""
|
|
192
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._similar_batch)
|
|
193
|
+
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _key(embedding: SparseEmbedding) -> int:
|
|
196
|
+
"""Derive a deterministic int64 key from the embedding's content."""
|
|
197
|
+
tokens = sorted(embedding)
|
|
198
|
+
weights = [embedding[token] for token in tokens]
|
|
199
|
+
data = np.asarray(tokens, dtype=np.int64).tobytes()
|
|
200
|
+
data += np.asarray(weights, dtype=np.float32).tobytes()
|
|
201
|
+
digest = blake3.blake3(data).digest()
|
|
202
|
+
return int.from_bytes(digest[:8], "little", signed=True)
|
|
203
|
+
|
|
204
|
+
@staticmethod
|
|
205
|
+
def _score(query: SparseEmbedding, stored: SparseEmbedding) -> float:
|
|
206
|
+
"""Compute the inner product between two weight maps."""
|
|
207
|
+
if len(stored) < len(query):
|
|
208
|
+
query, stored = stored, query
|
|
209
|
+
return sum(weight * stored.get(token, 0.0) for token, weight in query.items())
|
|
210
|
+
|
|
211
|
+
def _top_keys(self, query: SparseEmbedding, results: int) -> list[int]:
|
|
212
|
+
"""Rank stored keys by inner product with the query, dropping misses."""
|
|
213
|
+
scores = {
|
|
214
|
+
key: self._score(query, stored) for key, stored in self._embeddings.items()
|
|
215
|
+
}
|
|
216
|
+
ranked = sorted(scores, key=lambda key: scores[key], reverse=True)
|
|
217
|
+
return [key for key in ranked[:results] if scores[key] > 0]
|
|
218
|
+
|
|
219
|
+
async def _add(self, embedding: SparseEmbedding) -> int:
|
|
220
|
+
"""Add an embedding to the index and return its key."""
|
|
221
|
+
embeddings = await concresce.collect(embedding)
|
|
222
|
+
keys = [self._key(e) for e in embeddings]
|
|
223
|
+
self._embeddings.update(zip(keys, embeddings, strict=True))
|
|
224
|
+
logger.debug(
|
|
225
|
+
"Added %d embeddings to the sparse index; total is now %d",
|
|
226
|
+
len(keys),
|
|
227
|
+
len(self._embeddings),
|
|
228
|
+
)
|
|
229
|
+
return concresce.scatter(keys)
|
|
230
|
+
|
|
231
|
+
async def _remove(self, key: int) -> None:
|
|
232
|
+
"""Remove an embedding from the index by its key."""
|
|
233
|
+
keys = await concresce.collect(key)
|
|
234
|
+
removed = 0
|
|
235
|
+
for k in keys:
|
|
236
|
+
removed += self._embeddings.pop(k, None) is not None
|
|
237
|
+
logger.debug(
|
|
238
|
+
"Removed %d of %d keys from the sparse index; total is now %d",
|
|
239
|
+
removed,
|
|
240
|
+
len(keys),
|
|
241
|
+
len(self._embeddings),
|
|
242
|
+
)
|
|
243
|
+
return concresce.scatter([None] * len(keys))
|
|
244
|
+
|
|
245
|
+
async def _similar_batch(
|
|
246
|
+
self, embedding: SparseEmbedding, results: int
|
|
247
|
+
) -> list[int]:
|
|
248
|
+
"""Retrieve the most similar embedding keys to the given embedding."""
|
|
249
|
+
collected = await concresce.collect((embedding, results))
|
|
250
|
+
if not self._embeddings:
|
|
251
|
+
logger.warning(
|
|
252
|
+
"Similarity search of %d queries on an empty sparse index",
|
|
253
|
+
len(collected),
|
|
254
|
+
)
|
|
255
|
+
else:
|
|
256
|
+
logger.debug(
|
|
257
|
+
"Searching the sparse index of %d embeddings with %d queries",
|
|
258
|
+
len(self._embeddings),
|
|
259
|
+
len(collected),
|
|
260
|
+
)
|
|
261
|
+
rankings = [self._top_keys(query, count) for query, count in collected]
|
|
262
|
+
return concresce.scatter(rankings)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Parsers for extracting units from files."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import TYPE_CHECKING, Protocol
|
|
6
|
+
|
|
7
|
+
import belljar
|
|
8
|
+
import blake3
|
|
9
|
+
from unstructured.partition.auto import partition
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from rager.types import Hash
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Parser[F](Protocol):
|
|
18
|
+
"""Protocol for parsers."""
|
|
19
|
+
|
|
20
|
+
def units(self, file: F) -> list[str]:
|
|
21
|
+
"""Return the extracted text units."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
def id(self, file: F) -> Hash:
|
|
25
|
+
"""Return the file ID."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class UnstructuredFileParser:
|
|
30
|
+
"""Parser for unstructured files."""
|
|
31
|
+
|
|
32
|
+
@belljar.store(Path(".jar/parsers"))
|
|
33
|
+
def units(self, file: Path) -> list[str]:
|
|
34
|
+
"""Extract text units from the unstructured file."""
|
|
35
|
+
file_id = self.id(file)
|
|
36
|
+
belljar.include(file_id.digest())
|
|
37
|
+
belljar.check()
|
|
38
|
+
logger.info("Cache miss; parsing file %s", file)
|
|
39
|
+
elements = partition(filename=str(file))
|
|
40
|
+
units = [element.text for element in elements]
|
|
41
|
+
logger.debug("Extracted %d units from %s", len(units), file)
|
|
42
|
+
return units
|
|
43
|
+
|
|
44
|
+
def id(self, file: Path) -> Hash:
|
|
45
|
+
"""Return the content ID for the unstructured file."""
|
|
46
|
+
data = file.read_bytes()
|
|
47
|
+
logger.debug("Hashing %d bytes from %s", len(data), file)
|
|
48
|
+
return blake3.blake3(data)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
PdfFileParser = UnstructuredFileParser
|
|
52
|
+
MarkdownFileParser = UnstructuredFileParser
|
|
53
|
+
CsvFileParser = UnstructuredFileParser
|
|
File without changes
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Rerankers for scoring chunks based on relevance."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Protocol
|
|
8
|
+
|
|
9
|
+
import belljar
|
|
10
|
+
import concresce
|
|
11
|
+
from sentence_transformers import CrossEncoder
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Awaitable, Callable
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Scorer(Protocol):
|
|
20
|
+
"""Protocol for chunk scorers."""
|
|
21
|
+
|
|
22
|
+
async def score(self, query: str, chunk: str) -> float:
|
|
23
|
+
"""Score a chunk based on its semantic similarity to the query."""
|
|
24
|
+
...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CrossEncoderScorer:
|
|
28
|
+
"""Scorer that reranks chunks with a sentence-transformers cross-encoder."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, model_name: str = "cross-encoder/ms-marco-MiniLM-L6-v2") -> None:
|
|
31
|
+
"""Initialize the scorer with a specific model."""
|
|
32
|
+
self.model_name = model_name
|
|
33
|
+
|
|
34
|
+
@cached_property
|
|
35
|
+
def model(self) -> CrossEncoder:
|
|
36
|
+
"""Load the CrossEncoder model."""
|
|
37
|
+
logger.info("Loading CrossEncoder model %r", self.model_name)
|
|
38
|
+
return CrossEncoder(self.model_name)
|
|
39
|
+
|
|
40
|
+
@cached_property
|
|
41
|
+
def _predict(self) -> Callable[[str, str], Awaitable[float]]:
|
|
42
|
+
"""Coalesce concurrent calls into per-instance prediction batches."""
|
|
43
|
+
return concresce.batch(window=timedelta(milliseconds=1))(self._predict_batch)
|
|
44
|
+
|
|
45
|
+
async def _predict_batch(self, query: str, chunk: str) -> float:
|
|
46
|
+
"""Score a query-chunk pair with the cross-encoder."""
|
|
47
|
+
pairs = await concresce.collect((query, chunk))
|
|
48
|
+
logger.debug(
|
|
49
|
+
"Scoring batch of %d query-chunk pairs with %r",
|
|
50
|
+
len(pairs),
|
|
51
|
+
self.model_name,
|
|
52
|
+
)
|
|
53
|
+
scores = self.model.predict(pairs).tolist()
|
|
54
|
+
return concresce.scatter(scores)
|
|
55
|
+
|
|
56
|
+
@belljar.store(Path(".jar/scorers"))
|
|
57
|
+
async def score(self, query: str, chunk: str) -> float:
|
|
58
|
+
"""Score a chunk based on its semantic similarity to the query."""
|
|
59
|
+
belljar.include(self.model_name)
|
|
60
|
+
belljar.include(query)
|
|
61
|
+
belljar.include(chunk)
|
|
62
|
+
belljar.check()
|
|
63
|
+
logger.debug("Cache miss; scoring chunk of %d characters", len(chunk))
|
|
64
|
+
return await self._predict(query, chunk)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Key-value store protocol definitions."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Protocol
|
|
5
|
+
|
|
6
|
+
from rager.types import DenseEmbedding, Metadata, SparseEmbedding
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Store[V, K](Protocol):
|
|
12
|
+
"""Protocol for a key-value store mapping keys of type K to values of type V."""
|
|
13
|
+
|
|
14
|
+
def add(self, key: K, value: V) -> None:
|
|
15
|
+
"""Store a value with the given key."""
|
|
16
|
+
...
|
|
17
|
+
|
|
18
|
+
def get(self, key: K) -> V | None:
|
|
19
|
+
"""Retrieve a value by its key."""
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
def remove(self, key: K) -> None:
|
|
23
|
+
"""Remove a value by its key."""
|
|
24
|
+
...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class EmbeddingStore[E]:
|
|
28
|
+
"""In-memory store mapping index keys to embeddings."""
|
|
29
|
+
|
|
30
|
+
def __init__(self) -> None:
|
|
31
|
+
"""Initialize the store with no embeddings."""
|
|
32
|
+
self._embeddings: dict[int, E] = {}
|
|
33
|
+
|
|
34
|
+
def add(self, key: int, value: E) -> None:
|
|
35
|
+
"""Store an embedding with the given key."""
|
|
36
|
+
logger.debug("Storing embedding for key %d", key)
|
|
37
|
+
self._embeddings[key] = value
|
|
38
|
+
|
|
39
|
+
def get(self, key: int) -> E | None:
|
|
40
|
+
"""Retrieve an embedding by its key."""
|
|
41
|
+
embedding = self._embeddings.get(key)
|
|
42
|
+
if embedding is None:
|
|
43
|
+
logger.debug("No embedding stored for key %d", key)
|
|
44
|
+
return embedding
|
|
45
|
+
|
|
46
|
+
def remove(self, key: int) -> None:
|
|
47
|
+
"""Remove an embedding by its key."""
|
|
48
|
+
logger.debug("Removing embedding for key %d", key)
|
|
49
|
+
self._embeddings.pop(key, None)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
DenseEmbeddingStore = EmbeddingStore[DenseEmbedding]
|
|
53
|
+
SparseEmbeddingStore = EmbeddingStore[SparseEmbedding]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ChunkStore:
|
|
57
|
+
"""In-memory store mapping chunk indexes to chunk text."""
|
|
58
|
+
|
|
59
|
+
def __init__(self) -> None:
|
|
60
|
+
"""Initialize the store with no chunks."""
|
|
61
|
+
self._chunks: dict[int, str] = {}
|
|
62
|
+
|
|
63
|
+
def add(self, key: int, value: str) -> None:
|
|
64
|
+
"""Store chunk text with the given key."""
|
|
65
|
+
logger.debug("Storing chunk of %d characters for key %d", len(value), key)
|
|
66
|
+
self._chunks[key] = value
|
|
67
|
+
|
|
68
|
+
def get(self, key: int) -> str | None:
|
|
69
|
+
"""Retrieve chunk text by its key."""
|
|
70
|
+
chunk = self._chunks.get(key)
|
|
71
|
+
if chunk is None:
|
|
72
|
+
logger.debug("No chunk stored for key %d", key)
|
|
73
|
+
return chunk
|
|
74
|
+
|
|
75
|
+
def remove(self, key: int) -> None:
|
|
76
|
+
"""Remove chunk text by its key."""
|
|
77
|
+
logger.debug("Removing chunk for key %d", key)
|
|
78
|
+
self._chunks.pop(key, None)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class MetadataStore[M: Metadata]:
|
|
82
|
+
"""In-memory store mapping embedding keys to chunk metadata."""
|
|
83
|
+
|
|
84
|
+
def __init__(self) -> None:
|
|
85
|
+
"""Initialize the store with no metadata."""
|
|
86
|
+
self._metadata: dict[int, M] = {}
|
|
87
|
+
|
|
88
|
+
def add(self, key: int, value: M) -> None:
|
|
89
|
+
"""Store metadata with the given key."""
|
|
90
|
+
logger.debug("Storing metadata for key %d", key)
|
|
91
|
+
self._metadata[key] = value
|
|
92
|
+
|
|
93
|
+
def get(self, key: int) -> M | None:
|
|
94
|
+
"""Retrieve metadata by its key."""
|
|
95
|
+
metadata = self._metadata.get(key)
|
|
96
|
+
if metadata is None:
|
|
97
|
+
logger.debug("No metadata stored for key %d", key)
|
|
98
|
+
return metadata
|
|
99
|
+
|
|
100
|
+
def remove(self, key: int) -> None:
|
|
101
|
+
"""Remove metadata by its key."""
|
|
102
|
+
logger.debug("Removing metadata for key %d", key)
|
|
103
|
+
self._metadata.pop(key, None)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Type definitions for rager."""
|
|
2
|
+
|
|
3
|
+
from typing import Protocol
|
|
4
|
+
|
|
5
|
+
from blake3 import blake3
|
|
6
|
+
|
|
7
|
+
Hash = blake3
|
|
8
|
+
DenseEmbedding = list[float]
|
|
9
|
+
SparseEmbedding = dict[int, float]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Metadata(Protocol):
|
|
13
|
+
"""Protocol for the fields every chunk metadata class must provide."""
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def chunk(self) -> str:
|
|
17
|
+
"""The chunk text this metadata describes."""
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def file_id(self) -> Hash:
|
|
22
|
+
"""The content ID of the file the chunk was extracted from."""
|
|
23
|
+
...
|