chunkbuster 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.
- chunkbuster-0.1.0/.gitignore +11 -0
- chunkbuster-0.1.0/ARCHITECTURE.md +315 -0
- chunkbuster-0.1.0/LICENSE +21 -0
- chunkbuster-0.1.0/PKG-INFO +276 -0
- chunkbuster-0.1.0/README.md +266 -0
- chunkbuster-0.1.0/pyproject.toml +48 -0
- chunkbuster-0.1.0/src/chunkbuster/__init__.py +36 -0
- chunkbuster-0.1.0/src/chunkbuster/core/__init__.py +8 -0
- chunkbuster-0.1.0/src/chunkbuster/core/_async.py +11 -0
- chunkbuster-0.1.0/src/chunkbuster/core/config.py +51 -0
- chunkbuster-0.1.0/src/chunkbuster/core/contracts.py +24 -0
- chunkbuster-0.1.0/src/chunkbuster/core/dag.py +62 -0
- chunkbuster-0.1.0/src/chunkbuster/core/models.py +35 -0
- chunkbuster-0.1.0/src/chunkbuster/core/ranking.py +137 -0
- chunkbuster-0.1.0/src/chunkbuster/errors.py +34 -0
- chunkbuster-0.1.0/src/chunkbuster/py.typed +1 -0
- chunkbuster-0.1.0/src/chunkbuster/retrieval/__init__.py +11 -0
- chunkbuster-0.1.0/src/chunkbuster/retrieval/config.py +43 -0
- chunkbuster-0.1.0/src/chunkbuster/retrieval/models.py +43 -0
- chunkbuster-0.1.0/src/chunkbuster/retrieval/pipeline.py +209 -0
- chunkbuster-0.1.0/src/chunkbuster/tree_classification/__init__.py +22 -0
- chunkbuster-0.1.0/src/chunkbuster/tree_classification/config.py +72 -0
- chunkbuster-0.1.0/src/chunkbuster/tree_classification/decisions.py +30 -0
- chunkbuster-0.1.0/src/chunkbuster/tree_classification/models.py +111 -0
- chunkbuster-0.1.0/src/chunkbuster/tree_classification/pipeline.py +174 -0
- chunkbuster-0.1.0/src/chunkbuster/tree_classification/scoring.py +69 -0
- chunkbuster-0.1.0/src/chunkbuster/tree_classification/taxonomy.py +91 -0
- chunkbuster-0.1.0/tests/core/test_ranking.py +54 -0
- chunkbuster-0.1.0/tests/retrieval/test_retrieval_pipeline.py +181 -0
- chunkbuster-0.1.0/tests/tree_classification/test_pipeline.py +263 -0
- chunkbuster-0.1.0/tests/tree_classification/test_taxonomy.py +62 -0
- chunkbuster-0.1.0/uv.lock +775 -0
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
# Arquitectura
|
|
2
|
+
|
|
3
|
+
Este documento describe el paquete bajo `src/chunkbuster`; el repositorio ya no
|
|
4
|
+
conserva la implementación del prototipo anterior.
|
|
5
|
+
|
|
6
|
+
## Estado de esta entrega
|
|
7
|
+
|
|
8
|
+
La primera entrega implementa dos recorridos completos, deliberadamente
|
|
9
|
+
estrechos:
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
Tree:
|
|
13
|
+
query -> embedding -> dense node scores -> mean path ranking -> decider -> output
|
|
14
|
+
|
|
15
|
+
Retrieval:
|
|
16
|
+
query -> preprocessor -> source/candidate retrievers -> optional RRF -> output
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
| Área | Disponible |
|
|
20
|
+
|---|---|
|
|
21
|
+
| Tree taxonomy | Bosque estricto, múltiples raíces y paths raíz-hoja exactos |
|
|
22
|
+
| Tree scoring | Un preprocessor embedding, un scorer dense y un path scorer mean |
|
|
23
|
+
| Tree decisions | `top_one`, `top_k`, `threshold` y outputs nombrados |
|
|
24
|
+
| Retrieval | Retrievers fuente y restringidos, DAG de rankings, RRF y outputs nombrados |
|
|
25
|
+
| Configuración | YAML, JSON, mapping o modelo Pydantic |
|
|
26
|
+
| Adapters | Objetos Python explícitos, síncronos o asíncronos |
|
|
27
|
+
|
|
28
|
+
No están implementados todavía BM25, fusiones de nodos/paths en Tree,
|
|
29
|
+
rerankers, LLMs, scheduling concurrente ni aislamiento de fallos por output.
|
|
30
|
+
Los diseños futuros no deben documentarse como capacidades actuales.
|
|
31
|
+
|
|
32
|
+
## Estructura real
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
src/chunkbuster/
|
|
36
|
+
├── __init__.py
|
|
37
|
+
├── errors.py
|
|
38
|
+
├── py.typed
|
|
39
|
+
├── core/
|
|
40
|
+
│ ├── _async.py
|
|
41
|
+
│ ├── config.py
|
|
42
|
+
│ ├── contracts.py
|
|
43
|
+
│ ├── dag.py
|
|
44
|
+
│ ├── models.py
|
|
45
|
+
│ └── ranking.py
|
|
46
|
+
├── tree_classification/
|
|
47
|
+
│ ├── config.py
|
|
48
|
+
│ ├── decisions.py
|
|
49
|
+
│ ├── models.py
|
|
50
|
+
│ ├── pipeline.py
|
|
51
|
+
│ ├── scoring.py
|
|
52
|
+
│ └── taxonomy.py
|
|
53
|
+
└── retrieval/
|
|
54
|
+
├── config.py
|
|
55
|
+
├── models.py
|
|
56
|
+
└── pipeline.py
|
|
57
|
+
|
|
58
|
+
tests/
|
|
59
|
+
├── core/
|
|
60
|
+
├── tree_classification/
|
|
61
|
+
└── retrieval/
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`core` contiene solo contratos realmente usados por ambos productos.
|
|
65
|
+
`tree_classification` y `retrieval` dependen de `core`, pero no se importan
|
|
66
|
+
entre sí. El paquete no importa SDKs de proveedores.
|
|
67
|
+
|
|
68
|
+
No hay todavía `integrations/`, Registry, sistema de plugins ni runtime
|
|
69
|
+
genérico. Se crearán solo cuando exista un segundo consumidor real para la
|
|
70
|
+
abstracción correspondiente.
|
|
71
|
+
|
|
72
|
+
## Invariantes compartidos
|
|
73
|
+
|
|
74
|
+
1. La configuración es estricta, validada e inmutable.
|
|
75
|
+
2. Código, clientes, modelos y secretos se inyectan; nunca se deserializan.
|
|
76
|
+
3. Los datos estables se resuelven durante `build()` y cada query usa estado
|
|
77
|
+
privado.
|
|
78
|
+
4. Los objetos de dominio son dataclasses frozen; metadata y resultados
|
|
79
|
+
públicos exponen mappings de solo lectura.
|
|
80
|
+
5. Un `Ranking` tiene IDs únicos y orden determinista.
|
|
81
|
+
6. Una etapa restringida no puede inventar identidades fuera de su input.
|
|
82
|
+
7. La configuración se valida antes de ejecutar queries siempre que la
|
|
83
|
+
propiedad pueda conocerse durante `build()`.
|
|
84
|
+
8. Se usa stdlib antes de incorporar una dependencia o framework.
|
|
85
|
+
|
|
86
|
+
## Core
|
|
87
|
+
|
|
88
|
+
### Query y configuración
|
|
89
|
+
|
|
90
|
+
`Query` contiene texto, ID opcional y metadata. Tanto `classify()` como
|
|
91
|
+
`retrieve()` aceptan también un `str`, que se normaliza a `Query`.
|
|
92
|
+
|
|
93
|
+
`load_config()` carga:
|
|
94
|
+
|
|
95
|
+
- un `Mapping`/`dict`;
|
|
96
|
+
- una ruta `.yaml`, `.yml` o `.json`;
|
|
97
|
+
- un modelo Pydantic ya validado.
|
|
98
|
+
|
|
99
|
+
Cada producto tiene su propio modelo Pydantic estricto. `extra="forbid"`
|
|
100
|
+
evita errores silenciosos y los modelos son frozen. No hay una configuración
|
|
101
|
+
universal ni deep-merge de overrides por request.
|
|
102
|
+
|
|
103
|
+
### Bindings
|
|
104
|
+
|
|
105
|
+
`ComponentBindings` contiene mappings de objetos concretos:
|
|
106
|
+
|
|
107
|
+
```text
|
|
108
|
+
preprocessors
|
|
109
|
+
retrievers
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
La clave del mapping coincide con `binding` en la configuración. El objeto no
|
|
113
|
+
repite su nombre y no debe heredar de una clase base: basta con implementar el
|
|
114
|
+
método esperado. `_async.resolve()` permite implementaciones sync o async sin
|
|
115
|
+
duplicar la API pública.
|
|
116
|
+
|
|
117
|
+
### Ranking
|
|
118
|
+
|
|
119
|
+
`RankedItem[T]` conserva:
|
|
120
|
+
|
|
121
|
+
- `id` canónico;
|
|
122
|
+
- item original;
|
|
123
|
+
- score finito;
|
|
124
|
+
- rank normalizado;
|
|
125
|
+
- provenance y metadata.
|
|
126
|
+
|
|
127
|
+
`Ranking[T]` es una tupla ordenada e inmutable. Al construirla se rechazan IDs
|
|
128
|
+
duplicados y se reasignan ranks desde uno. `require_subset()` canonicaliza el
|
|
129
|
+
item contra el input y rechaza IDs inventados.
|
|
130
|
+
|
|
131
|
+
La primera estrategia compartida es RRF:
|
|
132
|
+
|
|
133
|
+
```text
|
|
134
|
+
score(id) = sum(1 / (k + rank_en_cada_input))
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Opera por identidad, no compara escalas originales y resuelve empates por el
|
|
138
|
+
primer orden observado. Requiere al menos dos rankings y aplica su propio
|
|
139
|
+
`top_k`.
|
|
140
|
+
|
|
141
|
+
### DAG
|
|
142
|
+
|
|
143
|
+
`compile_dag()` recibe `nombre -> dependencias` y outputs terminales. Usa
|
|
144
|
+
`graphlib.TopologicalSorter` para:
|
|
145
|
+
|
|
146
|
+
- resolver referencias;
|
|
147
|
+
- rechazar inputs repetidos;
|
|
148
|
+
- detectar ciclos;
|
|
149
|
+
- calcular alcanzabilidad desde outputs;
|
|
150
|
+
- rechazar nodos declarados pero no utilizados.
|
|
151
|
+
|
|
152
|
+
No ejecuta negocio ni interpreta tipos. Hoy lo usa Retrieval, donde todos los
|
|
153
|
+
nodos producen `Ranking[Chunk]`. Tree valida directamente su único recorrido;
|
|
154
|
+
generalizar antes de tener fusiones reales añadiría complejidad sin uso.
|
|
155
|
+
|
|
156
|
+
## TreeClassificationPipeline
|
|
157
|
+
|
|
158
|
+
### Dominio e identidad
|
|
159
|
+
|
|
160
|
+
`Taxonomy` contiene nodos y aristas planos. Un `TaxonomyNode` tiene `id`,
|
|
161
|
+
`label`, `text`, `embedding`, `tokens` y metadata. En esta entrega solo se usa
|
|
162
|
+
`embedding`; `tokens` queda como dato de dominio para el siguiente vertical.
|
|
163
|
+
|
|
164
|
+
La estructura es un bosque estricto:
|
|
165
|
+
|
|
166
|
+
- una o más raíces;
|
|
167
|
+
- cada nodo no raíz tiene exactamente un padre;
|
|
168
|
+
- sin self-loops, ciclos ni endpoints desconocidos;
|
|
169
|
+
- una raíz sin hijos es un subárbol válido;
|
|
170
|
+
- todos los nodos son alcanzables desde alguna raíz.
|
|
171
|
+
|
|
172
|
+
`taxonomy.py` usa mapas parent/children y DFS de stdlib. Enumera una vez cada
|
|
173
|
+
path raíz-hoja en orden de entrada. La identidad de `TaxonomyPath` es la
|
|
174
|
+
secuencia completa de IDs serializada de forma estable, aunque una hoja sea
|
|
175
|
+
unívoca en el bosque actual. Esto preserva explicabilidad y no implementa aún
|
|
176
|
+
una taxonomía DAG.
|
|
177
|
+
|
|
178
|
+
### Build
|
|
179
|
+
|
|
180
|
+
El vertical actual exige exactamente:
|
|
181
|
+
|
|
182
|
+
- un preprocessor de embeddings;
|
|
183
|
+
- un node scorer dense;
|
|
184
|
+
- un path scorer `mean`;
|
|
185
|
+
- uno o más deciders alcanzables desde `outputs`.
|
|
186
|
+
|
|
187
|
+
Si todos los nodos traen embeddings, se validan dimensión y finitud. Si ninguno
|
|
188
|
+
los trae, `build()` llama una vez a
|
|
189
|
+
`preprocessor.prepare_documents(tuple[text, ...])` y guarda los vectores en un
|
|
190
|
+
snapshot nuevo. Una cobertura parcial falla para evitar mezclar modelos o
|
|
191
|
+
versiones. El `Taxonomy` entregado por el caller nunca se muta.
|
|
192
|
+
|
|
193
|
+
El preprocessor siempre debe implementar `prepare_query(text)`. El usuario es
|
|
194
|
+
responsable de inyectar el mismo modelo, versión, dimensión y normalización que
|
|
195
|
+
produjo los embeddings de los nodos; la librería solo puede comprobar sus
|
|
196
|
+
propiedades numéricas.
|
|
197
|
+
|
|
198
|
+
### Classify
|
|
199
|
+
|
|
200
|
+
Para cada query:
|
|
201
|
+
|
|
202
|
+
1. se genera un embedding;
|
|
203
|
+
2. se puntúa cada nodo con cosine, dot product o euclidean negativo;
|
|
204
|
+
3. cada path recibe la media aritmética de sus node scores;
|
|
205
|
+
4. el ranking se ordena determinísticamente y se recorta;
|
|
206
|
+
5. cada output solicitado ejecuta su decider.
|
|
207
|
+
|
|
208
|
+
`top_one` selecciona como máximo uno. `top_k` selecciona hasta `count`.
|
|
209
|
+
`threshold` selecciona todos los candidatos con `score >= min_score`, con un
|
|
210
|
+
`count` opcional. Una selección vacía produce `status="abstained"`.
|
|
211
|
+
|
|
212
|
+
`classify(query, outputs=...)` puede materializar solo un subconjunto de outputs
|
|
213
|
+
públicos, pero no cambia configuración ni scoring.
|
|
214
|
+
|
|
215
|
+
## RetrievalPipeline
|
|
216
|
+
|
|
217
|
+
### Grafo de rankings
|
|
218
|
+
|
|
219
|
+
La configuración declara preprocessors, retrievers, fusiones y outputs. Los
|
|
220
|
+
nombres de retrievers y fusiones comparten namespace. Cada retriever referencia
|
|
221
|
+
un preprocessor y un binding explícitos.
|
|
222
|
+
|
|
223
|
+
Un retriever sin `input` es fuente:
|
|
224
|
+
|
|
225
|
+
```text
|
|
226
|
+
retrieve(query_representation, *, top_k) -> Ranking[Chunk]
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Un retriever con `input` es restringido:
|
|
230
|
+
|
|
231
|
+
```text
|
|
232
|
+
retrieve_candidates(query_representation, candidates, *, top_k)
|
|
233
|
+
-> Ranking[Chunk]
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
El segundo solo puede devolver IDs presentes en `candidates`. El pipeline
|
|
237
|
+
reemplaza cualquier copia del chunk por el objeto canónico de entrada y aplica
|
|
238
|
+
`top_k`.
|
|
239
|
+
|
|
240
|
+
Una fusion `type: rrf` consume al menos dos rankings nombrados. “Hybrid” no es
|
|
241
|
+
un tipo especial: es simplemente una RRF entre señales diferentes. “Cascade”
|
|
242
|
+
es un retriever cuyo `input` referencia otro ranking.
|
|
243
|
+
|
|
244
|
+
### Build y retrieve
|
|
245
|
+
|
|
246
|
+
`build()` valida nombres, preprocessors usados, bindings, métodos requeridos,
|
|
247
|
+
referencias, outputs, nodos muertos y ciclos. No consulta stores ni ejecuta
|
|
248
|
+
retrievers.
|
|
249
|
+
|
|
250
|
+
En `retrieve()` los nodos se recorren secuencialmente en orden topológico. Cada
|
|
251
|
+
preprocessor se memoiza por nombre y se ejecuta como máximo una vez por query,
|
|
252
|
+
aunque lo compartan varios retrievers. Los rankings intermedios viven solo en
|
|
253
|
+
esa llamada.
|
|
254
|
+
|
|
255
|
+
Cada output publica `terminal_node`, `ranking` y un status derivado
|
|
256
|
+
`completed|empty`. `retrieve(query, outputs=...)` puede seleccionar un subset
|
|
257
|
+
de grupos públicos.
|
|
258
|
+
|
|
259
|
+
Esta ejecución es deliberadamente secuencial. Todavía no hay scheduler de
|
|
260
|
+
nodos listos, semáforos ni resultados `failed`: cualquier error aborta la
|
|
261
|
+
llamada completa.
|
|
262
|
+
|
|
263
|
+
## Fronteras externas
|
|
264
|
+
|
|
265
|
+
Adapters y retrievers son trust boundaries. El pipeline valida forma,
|
|
266
|
+
dimensiones, finitud, tipo `Ranking`, unicidad y subconjuntos cuando corresponde.
|
|
267
|
+
Las implementaciones del usuario son responsables de timeouts, retries,
|
|
268
|
+
credenciales, rate limits y seguridad del cliente externo.
|
|
269
|
+
|
|
270
|
+
La jerarquía pública de errores se mantiene corta:
|
|
271
|
+
|
|
272
|
+
```text
|
|
273
|
+
ChunkbusterError
|
|
274
|
+
├── ConfigurationError
|
|
275
|
+
├── BuildError
|
|
276
|
+
│ └── InvalidTaxonomyError
|
|
277
|
+
└── ExecutionError
|
|
278
|
+
├── PreprocessingError
|
|
279
|
+
├── RetrievalError
|
|
280
|
+
└── InvalidModelOutputError
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
No se crean excepciones por cada clase interna.
|
|
284
|
+
|
|
285
|
+
## Tests y política de cambios
|
|
286
|
+
|
|
287
|
+
Los tests nuevos cubren contratos, no detalles accidentales:
|
|
288
|
+
|
|
289
|
+
- unicidad y scores finitos de rankings;
|
|
290
|
+
- RRF determinista;
|
|
291
|
+
- bosque, múltiples raíces, ciclos y múltiples padres;
|
|
292
|
+
- embeddings provistos o generados una sola vez;
|
|
293
|
+
- carga equivalente desde dict, YAML y JSON;
|
|
294
|
+
- source/candidate retrieval, preprocessing compartido y RRF;
|
|
295
|
+
- rechazo de IDs inventados y ciclos del DAG.
|
|
296
|
+
|
|
297
|
+
Una nueva capacidad debe añadir primero el test mínimo que demuestra el
|
|
298
|
+
vertical completo. Las abstracciones compartidas se extraen cuando ambos
|
|
299
|
+
productos ya exhiben el mismo contrato, no por anticipación.
|
|
300
|
+
|
|
301
|
+
## Próximos verticales
|
|
302
|
+
|
|
303
|
+
Orden orientativo, sin promesa de compatibilidad hasta estabilizar la API:
|
|
304
|
+
|
|
305
|
+
1. Tree lexical: tokenización/BM25, node fusions y ranking fusions.
|
|
306
|
+
2. Transformaciones externas: rerankers y canonicalización común.
|
|
307
|
+
3. LLM estructurado: decider 0..N para Tree y selector de rankings para
|
|
308
|
+
Retrieval.
|
|
309
|
+
4. Runtime: nodos independientes concurrentes, límites y aislamiento de fallos
|
|
310
|
+
por output.
|
|
311
|
+
5. Integraciones concretas con embeddings y vectorstores, una por vez.
|
|
312
|
+
|
|
313
|
+
Siguen fuera de alcance hasta que exista un caso medido: plugin discovery,
|
|
314
|
+
workflow engine genérico, taxonomía DAG, persistencia propia, CLI, servidor
|
|
315
|
+
HTTP, cache distribuido y compatibilidad con la API del prototipo.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cristian Gofiar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: chunkbuster
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Composable tree classification and retrieval pipelines
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
8
|
+
Requires-Dist: pyyaml<7,>=6
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# chunkbuster
|
|
12
|
+
|
|
13
|
+
`chunkbuster` es una librería Python experimental para construir pipelines de
|
|
14
|
+
clasificación jerárquica y retrieval mediante configuración estricta y
|
|
15
|
+
componentes Python inyectados explícitamente.
|
|
16
|
+
|
|
17
|
+
La API todavía puede cambiar. Esta primera entrega implementa dos verticales
|
|
18
|
+
pequeños de extremo a extremo:
|
|
19
|
+
|
|
20
|
+
| Producto | Implementado ahora |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `TreeClassificationPipeline` | Bosque estricto, embeddings densos, score medio por path y deciders `top_one`, `top_k` y `threshold` |
|
|
23
|
+
| `RetrievalPipeline` | Retrievers fuente, retrievers restringidos por candidatos, fusión RRF y múltiples outputs |
|
|
24
|
+
|
|
25
|
+
No se incluyen SDKs, modelos, vectorstores ni credenciales. Esos objetos se
|
|
26
|
+
inyectan mediante `ComponentBindings`; la configuración solo describe cómo se
|
|
27
|
+
conectan.
|
|
28
|
+
|
|
29
|
+
## Instalación local
|
|
30
|
+
|
|
31
|
+
Requiere Python 3.12 o superior.
|
|
32
|
+
|
|
33
|
+
Con uv:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
uv sync --dev
|
|
37
|
+
uv run pytest
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Con pip:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
python -m venv .venv
|
|
44
|
+
source .venv/bin/activate
|
|
45
|
+
python -m pip install -e .
|
|
46
|
+
pytest
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
El paquete distribuible vive bajo `src/chunkbuster`.
|
|
50
|
+
|
|
51
|
+
## Tree classification
|
|
52
|
+
|
|
53
|
+
Una taxonomía es un bosque: puede tener varias raíces, pero cada nodo no raíz
|
|
54
|
+
tiene exactamente un padre. Cada hoja define una clase identificada por su path
|
|
55
|
+
completo desde la raíz.
|
|
56
|
+
|
|
57
|
+
Este ejemplo deja que `build()` genere los embeddings ausentes una sola vez:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import asyncio
|
|
61
|
+
|
|
62
|
+
from chunkbuster import (
|
|
63
|
+
ComponentBindings,
|
|
64
|
+
Taxonomy,
|
|
65
|
+
TaxonomyEdge,
|
|
66
|
+
TaxonomyNode,
|
|
67
|
+
TreeClassificationPipeline,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class FakeEmbeddings:
|
|
72
|
+
vectors = {
|
|
73
|
+
"Productos": (1.0, 0.0),
|
|
74
|
+
"Reembolsos": (1.0, 0.0),
|
|
75
|
+
"Acceso": (0.0, 1.0),
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async def prepare_documents(self, texts):
|
|
79
|
+
return tuple(self.vectors[text] for text in texts)
|
|
80
|
+
|
|
81
|
+
async def prepare_query(self, text):
|
|
82
|
+
return (1.0, 0.0)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
taxonomy = Taxonomy(
|
|
86
|
+
id="support",
|
|
87
|
+
nodes=(
|
|
88
|
+
TaxonomyNode("products", "Productos"),
|
|
89
|
+
TaxonomyNode("refunds", "Reembolsos"),
|
|
90
|
+
TaxonomyNode("access", "Acceso"),
|
|
91
|
+
),
|
|
92
|
+
edges=(
|
|
93
|
+
TaxonomyEdge("products", "refunds"),
|
|
94
|
+
TaxonomyEdge("products", "access"),
|
|
95
|
+
),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
config = {
|
|
99
|
+
"version": 1,
|
|
100
|
+
"name": "support_classifier",
|
|
101
|
+
"kind": "tree_classification",
|
|
102
|
+
"preprocessors": [
|
|
103
|
+
{
|
|
104
|
+
"name": "semantic",
|
|
105
|
+
"type": "embedding",
|
|
106
|
+
"binding": "fake_embeddings",
|
|
107
|
+
"dimensions": 2,
|
|
108
|
+
}
|
|
109
|
+
],
|
|
110
|
+
"node_scorers": [
|
|
111
|
+
{
|
|
112
|
+
"name": "dense_nodes",
|
|
113
|
+
"type": "dense",
|
|
114
|
+
"preprocessor": "semantic",
|
|
115
|
+
"similarity": "cosine",
|
|
116
|
+
}
|
|
117
|
+
],
|
|
118
|
+
"path_scorers": [
|
|
119
|
+
{"name": "mean_paths", "type": "mean", "input": "dense_nodes", "top_k": 10}
|
|
120
|
+
],
|
|
121
|
+
"deciders": [
|
|
122
|
+
{"name": "best", "type": "top_one", "input": "mean_paths"}
|
|
123
|
+
],
|
|
124
|
+
"outputs": {"primary": "best"},
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def main():
|
|
129
|
+
pipeline = await TreeClassificationPipeline.build(
|
|
130
|
+
taxonomy=taxonomy,
|
|
131
|
+
config=config,
|
|
132
|
+
bindings=ComponentBindings(
|
|
133
|
+
preprocessors={"fake_embeddings": FakeEmbeddings()}
|
|
134
|
+
),
|
|
135
|
+
)
|
|
136
|
+
result = await pipeline.classify("¿Dónde está mi devolución?")
|
|
137
|
+
print(result.outputs["primary"].selected[0].item.node_ids)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
asyncio.run(main()) # ('products', 'refunds')
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Si cada nodo ya trae `embedding`, `prepare_documents()` no se invoca. La
|
|
144
|
+
cobertura debe ser completa: mezclar nodos con y sin embedding falla durante
|
|
145
|
+
`build()`.
|
|
146
|
+
|
|
147
|
+
## Retrieval
|
|
148
|
+
|
|
149
|
+
Un retriever fuente introduce chunks. Un retriever con `input` solo puede
|
|
150
|
+
filtrar o reordenar los candidatos recibidos. Las fusiones RRF combinan dos o
|
|
151
|
+
más rankings por identidad.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
import asyncio
|
|
155
|
+
|
|
156
|
+
from chunkbuster import ComponentBindings, RankedItem, Ranking
|
|
157
|
+
from chunkbuster.retrieval import Chunk, RetrievalPipeline
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def ranking(*ids):
|
|
161
|
+
return Ranking(
|
|
162
|
+
tuple(
|
|
163
|
+
RankedItem(item_id, Chunk(item_id, f"chunk {item_id}"), 1.0 / rank)
|
|
164
|
+
for rank, item_id in enumerate(ids, 1)
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class FakeQueryPreprocessor:
|
|
170
|
+
async def prepare_query(self, text):
|
|
171
|
+
return text.casefold()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class FakeSource:
|
|
175
|
+
def __init__(self, result):
|
|
176
|
+
self.result = result
|
|
177
|
+
|
|
178
|
+
async def retrieve(self, query, *, top_k):
|
|
179
|
+
return self.result.top(top_k)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class FakeCandidateFilter:
|
|
183
|
+
async def retrieve_candidates(self, query, candidates, *, top_k):
|
|
184
|
+
return Ranking(tuple(item for item in candidates if item.id == "b"))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
config = {
|
|
188
|
+
"version": 1,
|
|
189
|
+
"name": "products",
|
|
190
|
+
"kind": "retrieve",
|
|
191
|
+
"preprocessors": [{"name": "shared", "binding": "query_text"}],
|
|
192
|
+
"retrievers": [
|
|
193
|
+
{
|
|
194
|
+
"name": "catalog_a",
|
|
195
|
+
"binding": "source_a",
|
|
196
|
+
"preprocessor": "shared",
|
|
197
|
+
"top_k": 10,
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
"name": "catalog_b",
|
|
201
|
+
"binding": "source_b",
|
|
202
|
+
"preprocessor": "shared",
|
|
203
|
+
"top_k": 10,
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
"name": "filtered_a",
|
|
207
|
+
"binding": "candidate_filter",
|
|
208
|
+
"preprocessor": "shared",
|
|
209
|
+
"input": "catalog_a",
|
|
210
|
+
"top_k": 5,
|
|
211
|
+
},
|
|
212
|
+
],
|
|
213
|
+
"fusions": [
|
|
214
|
+
{
|
|
215
|
+
"name": "combined",
|
|
216
|
+
"type": "rrf",
|
|
217
|
+
"inputs": ["filtered_a", "catalog_b"],
|
|
218
|
+
"k": 60,
|
|
219
|
+
"top_k": 3,
|
|
220
|
+
}
|
|
221
|
+
],
|
|
222
|
+
"outputs": {"primary": "combined"},
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
async def main():
|
|
227
|
+
pipeline = await RetrievalPipeline.build(
|
|
228
|
+
config=config,
|
|
229
|
+
bindings=ComponentBindings(
|
|
230
|
+
preprocessors={"query_text": FakeQueryPreprocessor()},
|
|
231
|
+
retrievers={
|
|
232
|
+
"source_a": FakeSource(ranking("a", "b")),
|
|
233
|
+
"source_b": FakeSource(ranking("b", "c")),
|
|
234
|
+
"candidate_filter": FakeCandidateFilter(),
|
|
235
|
+
},
|
|
236
|
+
),
|
|
237
|
+
)
|
|
238
|
+
result = await pipeline.retrieve("productos")
|
|
239
|
+
print(result.outputs["primary"].ranking.ids)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
asyncio.run(main()) # ('b', 'c')
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## Configuración y bindings
|
|
246
|
+
|
|
247
|
+
`build(config=...)` acepta el mismo esquema como:
|
|
248
|
+
|
|
249
|
+
- `dict` o cualquier `Mapping` de Python;
|
|
250
|
+
- ruta `.yaml` o `.yml`;
|
|
251
|
+
- ruta `.json`;
|
|
252
|
+
- modelo Pydantic de configuración ya validado.
|
|
253
|
+
|
|
254
|
+
Las claves desconocidas fallan. Un archivo describe un pipeline y sus
|
|
255
|
+
referencias; no contiene código, clientes ni secretos. El campo `binding`
|
|
256
|
+
resuelve el objeto concreto dentro de `ComponentBindings`.
|
|
257
|
+
|
|
258
|
+
Los adapters pueden ser síncronos o asíncronos. Deben devolver los objetos
|
|
259
|
+
tipados de la librería. Un retriever restringido no puede inventar IDs fuera de
|
|
260
|
+
su input.
|
|
261
|
+
|
|
262
|
+
## Limitaciones actuales
|
|
263
|
+
|
|
264
|
+
Esta entrega es deliberadamente pequeña. Todavía no implementa:
|
|
265
|
+
|
|
266
|
+
- BM25 ni tokenización;
|
|
267
|
+
- node fusions o ranking fusions en Tree;
|
|
268
|
+
- rerankers;
|
|
269
|
+
- deciders/selectors LLM;
|
|
270
|
+
- ejecución concurrente o límites de concurrencia;
|
|
271
|
+
- aislamiento de fallos por output;
|
|
272
|
+
- integraciones con proveedores o vectorstores;
|
|
273
|
+
- persistencia, índices incrementales, CLI o servidor HTTP.
|
|
274
|
+
|
|
275
|
+
Consulte [ARCHITECTURE.md](ARCHITECTURE.md) para contratos internos, estado del
|
|
276
|
+
diseño y próximos verticales.
|