aid-runtime-python 0.1.133__py3-none-any.whl → 0.1.135__py3-none-any.whl
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.
- aid_runtime/__init__.py +1 -1
- aid_runtime/retrieval/__init__.py +6 -0
- aid_runtime/retrieval/chunking.py +351 -43
- aid_runtime/retrieval/connectors.py +414 -17
- aid_runtime/retrieval/retriever.py +27 -9
- aid_runtime/retrieval/types.py +3 -2
- {aid_runtime_python-0.1.133.dist-info → aid_runtime_python-0.1.135.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.133.dist-info → aid_runtime_python-0.1.135.dist-info}/RECORD +10 -10
- {aid_runtime_python-0.1.133.dist-info → aid_runtime_python-0.1.135.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.133.dist-info → aid_runtime_python-0.1.135.dist-info}/top_level.txt +0 -0
aid_runtime/__init__.py
CHANGED
|
@@ -28,6 +28,7 @@ from aid_runtime.retrieval.chunking import (
|
|
|
28
28
|
CodeChunker,
|
|
29
29
|
FixedChunker,
|
|
30
30
|
RecursiveChunker,
|
|
31
|
+
SemanticChunker,
|
|
31
32
|
chunk_document,
|
|
32
33
|
chunker_for,
|
|
33
34
|
)
|
|
@@ -41,6 +42,8 @@ from aid_runtime.retrieval.citations import (
|
|
|
41
42
|
from aid_runtime.retrieval.connectors import (
|
|
42
43
|
Connector,
|
|
43
44
|
FileConnector,
|
|
45
|
+
HttpConnector,
|
|
46
|
+
S3Connector,
|
|
44
47
|
SourceDocument,
|
|
45
48
|
open_connector,
|
|
46
49
|
)
|
|
@@ -161,6 +164,7 @@ __all__ = [
|
|
|
161
164
|
"FixedChunker",
|
|
162
165
|
"FixtureKnowledgeBaseClient",
|
|
163
166
|
"GeminiEmbedder",
|
|
167
|
+
"HttpConnector",
|
|
164
168
|
"InMemoryVectorStore",
|
|
165
169
|
"IndexSpec",
|
|
166
170
|
"IngestReport",
|
|
@@ -196,8 +200,10 @@ __all__ = [
|
|
|
196
200
|
"Retriever",
|
|
197
201
|
"RetrieverBinding",
|
|
198
202
|
"RetrieverSpec",
|
|
203
|
+
"S3Connector",
|
|
199
204
|
"ScoredChunk",
|
|
200
205
|
"SearchHit",
|
|
206
|
+
"SemanticChunker",
|
|
201
207
|
"SourceDocument",
|
|
202
208
|
"SourceKind",
|
|
203
209
|
"SourceSpec",
|
|
@@ -1,13 +1,8 @@
|
|
|
1
1
|
"""Turning documents into deterministic, size-bounded chunks.
|
|
2
2
|
|
|
3
3
|
The IR declares a strategy, a size and an overlap; it does not declare the split
|
|
4
|
-
algorithm. This module pins one
|
|
5
|
-
|
|
6
|
-
is refused because it needs an embedding pass over the whole source at ingest --
|
|
7
|
-
a different shape of job, not a different boundary rule.
|
|
8
|
-
|
|
9
|
-
So all three implemented strategies are size-bounded splitters and the only thing
|
|
10
|
-
that distinguishes them is **where a boundary is allowed to fall**:
|
|
4
|
+
algorithm. This module pins one per strategy. Three of them are size-bounded
|
|
5
|
+
splitters and differ only in **where a boundary is allowed to fall**:
|
|
11
6
|
|
|
12
7
|
``fixed``
|
|
13
8
|
Anywhere. The window always fills to ``size``, cutting mid-word when that is
|
|
@@ -19,27 +14,55 @@ that distinguishes them is **where a boundary is allowed to fall**:
|
|
|
19
14
|
Prefer the last blank line, then the last line break, then the last statement
|
|
20
15
|
end. Code is line-structured, so a blank line is the closest thing it has to a
|
|
21
16
|
paragraph, and cutting mid-statement is the failure worth avoiding.
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
17
|
+
``semantic``
|
|
18
|
+
Cut where the text changes topic, measured as a valley in the cosine similarity
|
|
19
|
+
between adjacent *atomic units*. The units come from the same recursive
|
|
20
|
+
hierarchy, so the strategy never invents a boundary inside a paragraph it did
|
|
21
|
+
not have to split; it only chooses which of the existing boundaries to take.
|
|
22
|
+
|
|
23
|
+
``semantic`` is the one strategy that needs the embedder, so it pays for a boundary
|
|
24
|
+
pass: it embeds every atomic unit before it can decide where to cut, and the retriever
|
|
25
|
+
embeds the finished chunks afterwards. That is two embedding passes over one source,
|
|
26
|
+
not one. The chunker accumulates the boundary pass's :class:`~aid_runtime.types.TokenUsage`
|
|
27
|
+
and exposes it as :attr:`Chunker.usage`; :meth:`Retriever.ingest` adds it to the report's
|
|
28
|
+
``tokens`` and ``cost_usd`` and charges the same ledger entry the chunk pass uses, so an
|
|
29
|
+
ingest report never undercounts the work it caused. The size strategies report a zero
|
|
30
|
+
usage because they make no embed calls.
|
|
31
|
+
|
|
32
|
+
Chunks are pure functions of the text and the embeddings, so the same input always
|
|
33
|
+
produces the same chunks with the same ids in the same order -- which is what makes
|
|
34
|
+
re-ingesting a corpus a no-op instead of a duplicate.
|
|
35
|
+
|
|
36
|
+
The seam is ``async`` because a semantic boundary pass embeds, and the embedder is
|
|
37
|
+
async. The size strategies have no awaits; making them async changes nothing about
|
|
38
|
+
their boundaries, and their existing byte-level tests are the proof.
|
|
26
39
|
"""
|
|
27
40
|
|
|
28
41
|
from __future__ import annotations
|
|
29
42
|
|
|
30
43
|
import abc
|
|
31
44
|
from collections.abc import Sequence
|
|
45
|
+
from math import sqrt
|
|
32
46
|
from typing import Protocol, runtime_checkable
|
|
33
47
|
|
|
34
48
|
from aid_runtime.errors import ConfigurationError, FeatureDeferredError
|
|
35
49
|
from aid_runtime.retrieval.connectors import SourceDocument
|
|
36
|
-
from aid_runtime.retrieval.
|
|
50
|
+
from aid_runtime.retrieval.embedding import Embedder
|
|
51
|
+
from aid_runtime.retrieval.types import (
|
|
52
|
+
Chunk,
|
|
53
|
+
ChunkingSpec,
|
|
54
|
+
ChunkingStrategy,
|
|
55
|
+
PinnedEmbedding,
|
|
56
|
+
chunk_id_for,
|
|
57
|
+
)
|
|
58
|
+
from aid_runtime.types import TokenUsage
|
|
37
59
|
|
|
38
60
|
__all__ = [
|
|
39
61
|
"Chunker",
|
|
40
62
|
"CodeChunker",
|
|
41
63
|
"FixedChunker",
|
|
42
64
|
"RecursiveChunker",
|
|
65
|
+
"SemanticChunker",
|
|
43
66
|
"chunk_document",
|
|
44
67
|
"chunker_for",
|
|
45
68
|
]
|
|
@@ -51,6 +74,44 @@ __all__ = [
|
|
|
51
74
|
_MIN_FILL_NUMERATOR = 1
|
|
52
75
|
_MIN_FILL_DENOMINATOR = 2
|
|
53
76
|
|
|
77
|
+
#: Where the semantic strategy cuts: an adjacent-unit cosine similarity below this
|
|
78
|
+
#: value, at a local valley, is read as a topic change. 0.72 is a deliberately
|
|
79
|
+
#: conservative start. Adjacent sentences in the same paragraph sit well above it
|
|
80
|
+
#: (the pinned text-embedding-3-small model puts them around 0.85-0.95), a sentence
|
|
81
|
+
#: that starts a new subject sits well below it, and 0.72 leaves room for the drift
|
|
82
|
+
#: that a paraphrase introduces. It is one module constant rather than a spec field
|
|
83
|
+
#: because the IR does not carry it: a caller that could tune it could silently
|
|
84
|
+
#: change every chunk id, and the threshold is a property of the algorithm, not of
|
|
85
|
+
#: the application.
|
|
86
|
+
SEMANTIC_SIMILARITY_THRESHOLD = 0.72
|
|
87
|
+
|
|
88
|
+
#: A chunk shorter than ``size`` divided by this is a runt. It is only a *floor*: the
|
|
89
|
+
#: chunker merges such a chunk forward when it still can, because a 30-character chunk
|
|
90
|
+
#: ranks badly and cites worse. It never splits a unit to reach the floor.
|
|
91
|
+
SEMANTIC_MIN_CHUNK_DIVISOR = 4
|
|
92
|
+
|
|
93
|
+
#: The recursive hierarchy, most semantic first. A unit is split on the first level
|
|
94
|
+
#: that yields more than one piece, then each piece is offered the next level, so a
|
|
95
|
+
#: paragraph under ``size`` is never split at all.
|
|
96
|
+
_SEMANTIC_SEPARATORS: tuple[tuple[str, ...], ...] = (
|
|
97
|
+
("\n\n",),
|
|
98
|
+
("\n",),
|
|
99
|
+
(". ", "! ", "? "),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _check_window(size: int, overlap: int) -> None:
|
|
104
|
+
"""Reject a window that cannot advance. Shared so both families agree."""
|
|
105
|
+
if size <= 0:
|
|
106
|
+
raise ConfigurationError("chunking size must be positive")
|
|
107
|
+
if overlap < 0:
|
|
108
|
+
raise ConfigurationError("chunking overlap must not be negative")
|
|
109
|
+
if overlap >= size:
|
|
110
|
+
raise ConfigurationError(
|
|
111
|
+
f"chunking overlap {overlap} must be smaller than size {size}; otherwise a "
|
|
112
|
+
"window would not advance and chunking would never terminate"
|
|
113
|
+
)
|
|
114
|
+
|
|
54
115
|
|
|
55
116
|
@runtime_checkable
|
|
56
117
|
class Chunker(Protocol):
|
|
@@ -59,22 +120,19 @@ class Chunker(Protocol):
|
|
|
59
120
|
@property
|
|
60
121
|
def strategy(self) -> ChunkingStrategy: ...
|
|
61
122
|
|
|
62
|
-
|
|
123
|
+
@property
|
|
124
|
+
def usage(self) -> TokenUsage:
|
|
125
|
+
"""Tokens the chunker itself spent. Non-zero only for a semantic boundary pass."""
|
|
126
|
+
...
|
|
127
|
+
|
|
128
|
+
async def chunk(self, document: SourceDocument) -> tuple[Chunk, ...]: ...
|
|
63
129
|
|
|
64
130
|
|
|
65
131
|
class _SizeChunker(abc.ABC):
|
|
66
132
|
"""Shared windowing. Subclasses only choose where a boundary may fall."""
|
|
67
133
|
|
|
68
134
|
def __init__(self, *, size: int, overlap: int, keep_metadata: Sequence[str] = ()) -> None:
|
|
69
|
-
|
|
70
|
-
raise ConfigurationError("chunking size must be positive")
|
|
71
|
-
if overlap < 0:
|
|
72
|
-
raise ConfigurationError("chunking overlap must not be negative")
|
|
73
|
-
if overlap >= size:
|
|
74
|
-
raise ConfigurationError(
|
|
75
|
-
f"chunking overlap {overlap} must be smaller than size {size}; otherwise a "
|
|
76
|
-
"window would not advance and chunking would never terminate"
|
|
77
|
-
)
|
|
135
|
+
_check_window(size, overlap)
|
|
78
136
|
self._size = size
|
|
79
137
|
self._overlap = overlap
|
|
80
138
|
self._keep = tuple(keep_metadata)
|
|
@@ -83,11 +141,17 @@ class _SizeChunker(abc.ABC):
|
|
|
83
141
|
@abc.abstractmethod
|
|
84
142
|
def strategy(self) -> ChunkingStrategy: ...
|
|
85
143
|
|
|
144
|
+
@property
|
|
145
|
+
def usage(self) -> TokenUsage:
|
|
146
|
+
# A size strategy never calls the embedder, so it has nothing to report. It is
|
|
147
|
+
# a real property rather than an absent one so `chunker.usage` is total.
|
|
148
|
+
return TokenUsage(input_tokens=0, output_tokens=0)
|
|
149
|
+
|
|
86
150
|
@abc.abstractmethod
|
|
87
151
|
def _cut(self, text: str, start: int, limit: int) -> int:
|
|
88
152
|
"""Where to end the window that starts at ``start`` and may reach ``limit``."""
|
|
89
153
|
|
|
90
|
-
def chunk(self, document: SourceDocument) -> tuple[Chunk, ...]:
|
|
154
|
+
async def chunk(self, document: SourceDocument) -> tuple[Chunk, ...]:
|
|
91
155
|
text = document.text
|
|
92
156
|
chunks: list[Chunk] = []
|
|
93
157
|
start = 0
|
|
@@ -108,18 +172,7 @@ class _SizeChunker(abc.ABC):
|
|
|
108
172
|
def _build(
|
|
109
173
|
self, document: SourceDocument, index: int, start: int, end: int, text: str
|
|
110
174
|
) -> Chunk:
|
|
111
|
-
return
|
|
112
|
-
chunk_id=chunk_id_for(document.doc_id, index, text),
|
|
113
|
-
doc_id=document.doc_id,
|
|
114
|
-
uri=document.uri,
|
|
115
|
-
index=index,
|
|
116
|
-
start=start,
|
|
117
|
-
end=end,
|
|
118
|
-
text=text,
|
|
119
|
-
metadata={
|
|
120
|
-
key: document.metadata[key] for key in self._keep if key in document.metadata
|
|
121
|
-
},
|
|
122
|
-
)
|
|
175
|
+
return _build_chunk(document, index, start, end, text, self._keep)
|
|
123
176
|
|
|
124
177
|
def _boundary(self, text: str, start: int, limit: int, markers: Sequence[str]) -> int | None:
|
|
125
178
|
"""The end offset of the last ``marker`` in ``text[start:limit]``, if usable.
|
|
@@ -194,6 +247,234 @@ class CodeChunker(_SizeChunker):
|
|
|
194
247
|
)
|
|
195
248
|
|
|
196
249
|
|
|
250
|
+
def _build_chunk(
|
|
251
|
+
document: SourceDocument,
|
|
252
|
+
index: int,
|
|
253
|
+
start: int,
|
|
254
|
+
end: int,
|
|
255
|
+
text: str,
|
|
256
|
+
keep: Sequence[str],
|
|
257
|
+
) -> Chunk:
|
|
258
|
+
return Chunk(
|
|
259
|
+
chunk_id=chunk_id_for(document.doc_id, index, text),
|
|
260
|
+
doc_id=document.doc_id,
|
|
261
|
+
uri=document.uri,
|
|
262
|
+
index=index,
|
|
263
|
+
start=start,
|
|
264
|
+
end=end,
|
|
265
|
+
text=text,
|
|
266
|
+
metadata={key: document.metadata[key] for key in keep if key in document.metadata},
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _split_span(
|
|
271
|
+
text: str, start: int, end: int, separators: Sequence[str]
|
|
272
|
+
) -> list[tuple[int, int]]:
|
|
273
|
+
"""Split ``text[start:end]`` on every ``separators`` hit, keeping the separator.
|
|
274
|
+
|
|
275
|
+
The separator stays with the piece it ends, so a unit is always a raw slice of the
|
|
276
|
+
document and joining the pieces back together reproduces the span exactly.
|
|
277
|
+
"""
|
|
278
|
+
pieces: list[tuple[int, int]] = []
|
|
279
|
+
cursor = start
|
|
280
|
+
position = start
|
|
281
|
+
while position < end:
|
|
282
|
+
matched = next((item for item in separators if text.startswith(item, position)), None)
|
|
283
|
+
if matched is None:
|
|
284
|
+
position += 1
|
|
285
|
+
continue
|
|
286
|
+
cut = position + len(matched)
|
|
287
|
+
pieces.append((cursor, cut))
|
|
288
|
+
cursor = cut
|
|
289
|
+
position = cut
|
|
290
|
+
if cursor < end:
|
|
291
|
+
pieces.append((cursor, end))
|
|
292
|
+
return pieces
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _split_units(text: str, size: int) -> list[tuple[int, int]]:
|
|
296
|
+
"""Atomic units: the recursive hierarchy, hard-cut only when nothing else fits."""
|
|
297
|
+
units: list[tuple[int, int]] = []
|
|
298
|
+
|
|
299
|
+
def visit(start: int, end: int, depth: int) -> None:
|
|
300
|
+
if end <= start:
|
|
301
|
+
return
|
|
302
|
+
if end - start <= size:
|
|
303
|
+
if text[start:end].strip():
|
|
304
|
+
units.append((start, end))
|
|
305
|
+
return
|
|
306
|
+
if depth < len(_SEMANTIC_SEPARATORS):
|
|
307
|
+
pieces = _split_span(text, start, end, _SEMANTIC_SEPARATORS[depth])
|
|
308
|
+
if len(pieces) > 1:
|
|
309
|
+
for piece_start, piece_end in pieces:
|
|
310
|
+
visit(piece_start, piece_end, depth + 1)
|
|
311
|
+
return
|
|
312
|
+
# Nothing at this level separated the span, so try the next level with the
|
|
313
|
+
# same span rather than jumping straight to a hard cut. Falling through
|
|
314
|
+
# here would cut prose with no blank lines mid-word even though it has
|
|
315
|
+
# plenty of line breaks.
|
|
316
|
+
visit(start, end, depth + 1)
|
|
317
|
+
return
|
|
318
|
+
# The bottom of the hierarchy: one word or one very long line, where a hard
|
|
319
|
+
# cut is the only boundary left and `size` bounds it.
|
|
320
|
+
for cut in range(start, end, size):
|
|
321
|
+
visit(cut, min(cut + size, end), len(_SEMANTIC_SEPARATORS))
|
|
322
|
+
|
|
323
|
+
visit(0, len(text), 0)
|
|
324
|
+
return units
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _cosine(left: Sequence[float], right: Sequence[float]) -> float:
|
|
328
|
+
# Both operands are embeddings from the same pinned model, so a length
|
|
329
|
+
# disagreement is a real fault rather than something to truncate away.
|
|
330
|
+
dot = sum(a * b for a, b in zip(left, right, strict=True))
|
|
331
|
+
left_norm = sqrt(sum(a * a for a in left))
|
|
332
|
+
right_norm = sqrt(sum(b * b for b in right))
|
|
333
|
+
if left_norm == 0.0 or right_norm == 0.0:
|
|
334
|
+
return 0.0
|
|
335
|
+
return dot / (left_norm * right_norm)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _is_valley(similarities: Sequence[float], index: int) -> bool:
|
|
339
|
+
"""True when the similarity at ``index`` is a local low below the threshold."""
|
|
340
|
+
score = similarities[index]
|
|
341
|
+
return (
|
|
342
|
+
score < SEMANTIC_SIMILARITY_THRESHOLD
|
|
343
|
+
and (index == 0 or similarities[index - 1] >= score)
|
|
344
|
+
and (index + 1 == len(similarities) or similarities[index + 1] >= score)
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class SemanticChunker:
|
|
349
|
+
"""Cuts where adjacent-unit similarity dips, rather than at a fixed size.
|
|
350
|
+
|
|
351
|
+
The boundary pass and the chunk pass are separate: this class embeds the atomic
|
|
352
|
+
units to find the boundaries, and :class:`~aid_runtime.retrieval.retriever.Retriever`
|
|
353
|
+
embeds the finished chunks to index them. :attr:`usage` reports the boundary pass
|
|
354
|
+
so the ingest report can account for it.
|
|
355
|
+
"""
|
|
356
|
+
|
|
357
|
+
def __init__(
|
|
358
|
+
self,
|
|
359
|
+
*,
|
|
360
|
+
size: int,
|
|
361
|
+
overlap: int,
|
|
362
|
+
keep_metadata: Sequence[str] = (),
|
|
363
|
+
embedder: Embedder,
|
|
364
|
+
model: PinnedEmbedding,
|
|
365
|
+
) -> None:
|
|
366
|
+
_check_window(size, overlap)
|
|
367
|
+
self._size = size
|
|
368
|
+
self._overlap = overlap
|
|
369
|
+
self._keep = tuple(keep_metadata)
|
|
370
|
+
self._embedder = embedder
|
|
371
|
+
self._model = model
|
|
372
|
+
self._usage = TokenUsage(input_tokens=0, output_tokens=0)
|
|
373
|
+
|
|
374
|
+
@property
|
|
375
|
+
def strategy(self) -> ChunkingStrategy:
|
|
376
|
+
return ChunkingStrategy.SEMANTIC
|
|
377
|
+
|
|
378
|
+
@property
|
|
379
|
+
def usage(self) -> TokenUsage:
|
|
380
|
+
return self._usage
|
|
381
|
+
|
|
382
|
+
async def chunk(self, document: SourceDocument) -> tuple[Chunk, ...]:
|
|
383
|
+
text = document.text
|
|
384
|
+
self._usage = TokenUsage(input_tokens=0, output_tokens=0)
|
|
385
|
+
if not text.strip():
|
|
386
|
+
return ()
|
|
387
|
+
units = _split_units(text, self._size)
|
|
388
|
+
if not units:
|
|
389
|
+
return ()
|
|
390
|
+
if len(units) == 1:
|
|
391
|
+
# One unit needs no boundary decision, so the boundary pass is skipped
|
|
392
|
+
# entirely: zero embed calls, and `usage` stays zero.
|
|
393
|
+
start, end = units[0]
|
|
394
|
+
return (_build_chunk(document, 0, start, end, text[start:end], self._keep),)
|
|
395
|
+
|
|
396
|
+
batch = await self._embedder.embed(
|
|
397
|
+
[text[start:end] for start, end in units], model=self._model
|
|
398
|
+
)
|
|
399
|
+
self._usage = batch.usage
|
|
400
|
+
vectors = batch.vectors
|
|
401
|
+
similarities = [
|
|
402
|
+
_cosine(vectors[index], vectors[index + 1]) for index in range(len(units) - 1)
|
|
403
|
+
]
|
|
404
|
+
floor = max(1, self._size // SEMANTIC_MIN_CHUNK_DIVISOR)
|
|
405
|
+
|
|
406
|
+
spans: list[tuple[int, int]] = []
|
|
407
|
+
first_unit = 0
|
|
408
|
+
cursor_start = units[0][0]
|
|
409
|
+
for index in range(len(units) - 1):
|
|
410
|
+
next_start, next_end = units[index + 1]
|
|
411
|
+
length = units[index][1] - cursor_start
|
|
412
|
+
overflows = length + (next_end - next_start) > self._size
|
|
413
|
+
dips = length >= floor and _is_valley(similarities, index)
|
|
414
|
+
if not (overflows or dips):
|
|
415
|
+
continue
|
|
416
|
+
spans.append((cursor_start, units[index][1]))
|
|
417
|
+
carried = self._carry(units, first_unit, index, index + 1)
|
|
418
|
+
first_unit = carried[0] if carried else index + 1
|
|
419
|
+
cursor_start = units[first_unit][0]
|
|
420
|
+
spans.append((cursor_start, units[-1][1]))
|
|
421
|
+
spans = _merge_runts(spans, floor, self._size)
|
|
422
|
+
|
|
423
|
+
chunks: list[Chunk] = []
|
|
424
|
+
for start, end in spans:
|
|
425
|
+
window = text[start:end]
|
|
426
|
+
if window.strip():
|
|
427
|
+
chunks.append(_build_chunk(document, len(chunks), start, end, window, self._keep))
|
|
428
|
+
return tuple(chunks)
|
|
429
|
+
|
|
430
|
+
def _carry(
|
|
431
|
+
self, units: Sequence[tuple[int, int]], first: int, last: int, next_unit: int
|
|
432
|
+
) -> list[int]:
|
|
433
|
+
"""Trailing units of the chunk just emitted that fit inside ``overlap``."""
|
|
434
|
+
carried: list[int] = []
|
|
435
|
+
carried_length = 0
|
|
436
|
+
next_length = units[next_unit][1] - units[next_unit][0]
|
|
437
|
+
index = last
|
|
438
|
+
while index >= first:
|
|
439
|
+
unit_length = units[index][1] - units[index][0]
|
|
440
|
+
if carried_length + unit_length > self._overlap:
|
|
441
|
+
break
|
|
442
|
+
if carried_length + unit_length + next_length > self._size:
|
|
443
|
+
break
|
|
444
|
+
carried.insert(0, index)
|
|
445
|
+
carried_length += unit_length
|
|
446
|
+
index -= 1
|
|
447
|
+
return carried
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _merge_runts(spans: list[tuple[int, int]], floor: int, size: int) -> list[tuple[int, int]]:
|
|
451
|
+
"""Fold any chunk shorter than ``floor`` into a neighbour where the result fits.
|
|
452
|
+
|
|
453
|
+
A size overflow can leave a short chunk in the middle of a document, not only at
|
|
454
|
+
the end, so this repairs any runt: backward when the previous chunk has room, then
|
|
455
|
+
forward when the next one does. A runt with no room on either side stays as it is,
|
|
456
|
+
because growing it would break the ``size`` cap.
|
|
457
|
+
"""
|
|
458
|
+
merged = list(spans)
|
|
459
|
+
index = 0
|
|
460
|
+
while index < len(merged) and len(merged) > 1:
|
|
461
|
+
start, end = merged[index]
|
|
462
|
+
if end - start >= floor:
|
|
463
|
+
index += 1
|
|
464
|
+
continue
|
|
465
|
+
if index > 0 and end - merged[index - 1][0] <= size:
|
|
466
|
+
merged[index - 1] = (merged[index - 1][0], end)
|
|
467
|
+
del merged[index]
|
|
468
|
+
index = max(index - 1, 0)
|
|
469
|
+
continue
|
|
470
|
+
if index + 1 < len(merged) and merged[index + 1][1] - start <= size:
|
|
471
|
+
merged[index] = (start, merged[index + 1][1])
|
|
472
|
+
del merged[index + 1]
|
|
473
|
+
continue
|
|
474
|
+
index += 1
|
|
475
|
+
return merged
|
|
476
|
+
|
|
477
|
+
|
|
197
478
|
_STRATEGIES: dict[ChunkingStrategy, type[_SizeChunker]] = {
|
|
198
479
|
ChunkingStrategy.FIXED: FixedChunker,
|
|
199
480
|
ChunkingStrategy.RECURSIVE: RecursiveChunker,
|
|
@@ -201,22 +482,49 @@ _STRATEGIES: dict[ChunkingStrategy, type[_SizeChunker]] = {
|
|
|
201
482
|
}
|
|
202
483
|
|
|
203
484
|
|
|
204
|
-
def chunker_for(
|
|
485
|
+
def chunker_for(
|
|
486
|
+
spec: ChunkingSpec,
|
|
487
|
+
*,
|
|
488
|
+
embedder: Embedder | None = None,
|
|
489
|
+
model: PinnedEmbedding | None = None,
|
|
490
|
+
) -> Chunker:
|
|
205
491
|
"""Resolve a chunking block to an implementation.
|
|
206
492
|
|
|
207
|
-
``semantic``
|
|
208
|
-
|
|
493
|
+
``semantic`` needs the retriever's own embedder and pinned model, because it
|
|
494
|
+
embeds the units to choose a boundary. Nothing here resolves an alias or picks a
|
|
495
|
+
model: the caller passes the pin the index already uses. An unknown strategy is
|
|
496
|
+
still refused, because the runtime is reachable from generated code the validator
|
|
497
|
+
never saw.
|
|
209
498
|
"""
|
|
499
|
+
if spec.strategy is ChunkingStrategy.SEMANTIC:
|
|
500
|
+
if embedder is None or model is None:
|
|
501
|
+
raise ConfigurationError(
|
|
502
|
+
"semantic chunking needs the retriever's embedder and pinned model; pass both "
|
|
503
|
+
"to chunker_for rather than letting the runtime choose one"
|
|
504
|
+
)
|
|
505
|
+
return SemanticChunker(
|
|
506
|
+
size=spec.size,
|
|
507
|
+
overlap=spec.overlap,
|
|
508
|
+
keep_metadata=spec.keep_metadata,
|
|
509
|
+
embedder=embedder,
|
|
510
|
+
model=model,
|
|
511
|
+
)
|
|
210
512
|
implementation = _STRATEGIES.get(spec.strategy)
|
|
211
513
|
if implementation is None:
|
|
212
514
|
raise FeatureDeferredError(
|
|
213
|
-
f"chunking strategy {spec.strategy.value!r} is declared but not implemented:
|
|
214
|
-
"
|
|
215
|
-
"embedding pass over the whole source at ingest"
|
|
515
|
+
f"chunking strategy {spec.strategy.value!r} is declared but not implemented: fixed, "
|
|
516
|
+
"recursive, code and semantic are the strategies this runtime chunks with"
|
|
216
517
|
)
|
|
217
518
|
return implementation(size=spec.size, overlap=spec.overlap, keep_metadata=spec.keep_metadata)
|
|
218
519
|
|
|
219
520
|
|
|
220
|
-
def chunk_document(
|
|
521
|
+
async def chunk_document(
|
|
522
|
+
document: SourceDocument,
|
|
523
|
+
spec: ChunkingSpec,
|
|
524
|
+
*,
|
|
525
|
+
embedder: Embedder | None = None,
|
|
526
|
+
model: PinnedEmbedding | None = None,
|
|
527
|
+
) -> tuple[Chunk, ...]:
|
|
221
528
|
"""Chunk one document with the strategy the spec names."""
|
|
222
|
-
|
|
529
|
+
chunker = chunker_for(spec, embedder=embedder, model=model)
|
|
530
|
+
return await chunker.chunk(document)
|
|
@@ -1,43 +1,76 @@
|
|
|
1
|
-
"""Reading a ``file`` source.
|
|
1
|
+
"""Reading a ``file``, ``s3`` or ``http`` source.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
:class:`~aid_runtime.errors.FeatureDeferredError` here rather than indexing an
|
|
7
|
-
|
|
3
|
+
``file`` indexes a local directory and is implemented at every spec version. ``s3``
|
|
4
|
+
loads an object-store corpus and ``http`` loads exactly one document; both shipped in
|
|
5
|
+
spec 0.21. ``db`` and ``mcp`` are still reserved by the design, so they raise
|
|
6
|
+
:class:`~aid_runtime.errors.FeatureDeferredError` here rather than indexing an empty
|
|
7
|
+
corpus and looking healthy.
|
|
8
8
|
|
|
9
9
|
**Document identity is the POSIX path relative to the source root.** That is the
|
|
10
10
|
vocabulary the IR's retrieval metric already uses -- its ``expectDocs`` hold
|
|
11
11
|
``getting-started.md``, not ``./docs/getting-started.md`` -- and it is
|
|
12
12
|
machine-independent, so the same corpus indexed on Windows and on Linux yields the
|
|
13
13
|
same ids and the same eval outcome. Absolute paths would make a baseline
|
|
14
|
-
non-portable.
|
|
14
|
+
non-portable. The remote connectors keep the same rule: an ``s3`` object's ``doc_id``
|
|
15
|
+
is its key with the source prefix stripped, and an ``http`` document's is the last
|
|
16
|
+
non-empty segment of its path.
|
|
15
17
|
|
|
16
|
-
The protocol is ``async``
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
The protocol is ``async`` because the remote kinds are genuinely concurrent. The file
|
|
19
|
+
connector reads synchronously behind that seam so its behaviour is unchanged.
|
|
20
|
+
|
|
21
|
+
**The s3 signer is the Bedrock adapter's.** ``sigv4_headers`` already computes the
|
|
22
|
+
canonical request, scope and signing key for every other AWS call this runtime makes;
|
|
23
|
+
signing a ``GET`` with it -- ``service="s3"``, ``method="GET"`` and the canonical query
|
|
24
|
+
string -- avoids a second implementation that could disagree about encoding. There is
|
|
25
|
+
deliberately no boto3 dependency: ListObjectsV2 is one signed ``GET`` parsed with the
|
|
26
|
+
standard library's XML reader, and GetObject is another.
|
|
20
27
|
"""
|
|
21
28
|
|
|
22
29
|
from __future__ import annotations
|
|
23
30
|
|
|
31
|
+
import asyncio
|
|
32
|
+
import os
|
|
33
|
+
from collections.abc import Callable
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from datetime import UTC, datetime
|
|
24
36
|
from pathlib import Path
|
|
25
37
|
from typing import Protocol, runtime_checkable
|
|
38
|
+
from urllib.parse import quote, urlparse
|
|
39
|
+
from xml.etree import ElementTree
|
|
26
40
|
|
|
41
|
+
import httpx
|
|
27
42
|
from pydantic import BaseModel, ConfigDict, Field
|
|
28
43
|
|
|
29
44
|
from aid_runtime.errors import ConfigurationError, FeatureDeferredError
|
|
45
|
+
from aid_runtime.providers.bedrock import rfc3986, sigv4_headers
|
|
30
46
|
from aid_runtime.retrieval.types import SourceKind, SourceSpec
|
|
31
47
|
|
|
32
48
|
__all__ = [
|
|
33
49
|
"Connector",
|
|
34
50
|
"FileConnector",
|
|
51
|
+
"HttpConnector",
|
|
52
|
+
"S3Connector",
|
|
35
53
|
"SourceDocument",
|
|
36
54
|
"open_connector",
|
|
37
55
|
]
|
|
38
56
|
|
|
39
57
|
_RECORD = ConfigDict(frozen=True, extra="forbid")
|
|
40
58
|
|
|
59
|
+
#: The largest body either remote connector will read into one document.
|
|
60
|
+
_MAX_DOCUMENT_BYTES = 10 * 1024 * 1024
|
|
61
|
+
|
|
62
|
+
#: How many GetObject requests an s3 source keeps in flight.
|
|
63
|
+
_S3_CONCURRENCY = 8
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class _ListedObject:
|
|
68
|
+
"""One ``ListObjectsV2`` entry, before its body is fetched."""
|
|
69
|
+
|
|
70
|
+
key: str
|
|
71
|
+
etag: str
|
|
72
|
+
last_modified: str
|
|
73
|
+
|
|
41
74
|
|
|
42
75
|
class SourceDocument(BaseModel):
|
|
43
76
|
"""One document read from a source, before chunking."""
|
|
@@ -112,18 +145,382 @@ class FileConnector:
|
|
|
112
145
|
)
|
|
113
146
|
|
|
114
147
|
|
|
148
|
+
def _tokenize_glob(pattern: str) -> tuple[tuple[str, str], ...]:
|
|
149
|
+
"""Split a glob into the same tokens the TypeScript runtime's `compileGlob` uses."""
|
|
150
|
+
tokens: list[tuple[str, str]] = []
|
|
151
|
+
index = 0
|
|
152
|
+
while index < len(pattern):
|
|
153
|
+
char = pattern[index]
|
|
154
|
+
if char == "*":
|
|
155
|
+
if pattern[index + 1 : index + 2] == "*":
|
|
156
|
+
index += 1
|
|
157
|
+
if pattern[index + 1 : index + 2] == "/":
|
|
158
|
+
index += 1
|
|
159
|
+
tokens.append(("globstar_segment", ""))
|
|
160
|
+
else:
|
|
161
|
+
tokens.append(("globstar", ""))
|
|
162
|
+
else:
|
|
163
|
+
tokens.append(("star", ""))
|
|
164
|
+
elif char == "?":
|
|
165
|
+
tokens.append(("any_one", ""))
|
|
166
|
+
else:
|
|
167
|
+
tokens.append(("literal", char))
|
|
168
|
+
index += 1
|
|
169
|
+
return tuple(tokens)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _glob_matcher(pattern: str | None) -> Callable[[str], bool]:
|
|
173
|
+
"""Compile a ``*``/``**``/``?`` glob into a matcher over POSIX relative keys.
|
|
174
|
+
|
|
175
|
+
Deliberately the same token walk as the file connector's documented grammar and the
|
|
176
|
+
TypeScript runtime's ``compileGlob``: ``*`` and ``?`` stop at ``/``, ``**`` crosses
|
|
177
|
+
them, and anything else matches literally. Walking tokens is linear in the key
|
|
178
|
+
length whatever the pattern; a translated regular expression would let a pattern
|
|
179
|
+
with repeated double-stars cost a pathological number of steps to fail.
|
|
180
|
+
"""
|
|
181
|
+
if pattern is None:
|
|
182
|
+
return lambda _key: True
|
|
183
|
+
tokens = _tokenize_glob(pattern)
|
|
184
|
+
|
|
185
|
+
def matches(key: str) -> bool:
|
|
186
|
+
reachable = [False] * (len(key) + 1)
|
|
187
|
+
reachable[0] = True
|
|
188
|
+
for kind, char in tokens:
|
|
189
|
+
nxt = [False] * (len(key) + 1)
|
|
190
|
+
if kind == "literal":
|
|
191
|
+
for end in range(1, len(key) + 1):
|
|
192
|
+
nxt[end] = reachable[end - 1] and key[end - 1] == char
|
|
193
|
+
elif kind == "any_one":
|
|
194
|
+
for end in range(1, len(key) + 1):
|
|
195
|
+
nxt[end] = reachable[end - 1] and key[end - 1] != "/"
|
|
196
|
+
elif kind == "star":
|
|
197
|
+
for end in range(len(key) + 1):
|
|
198
|
+
extends = end > 0 and nxt[end - 1] and key[end - 1] != "/"
|
|
199
|
+
nxt[end] = reachable[end] or extends
|
|
200
|
+
elif kind == "globstar":
|
|
201
|
+
for end in range(len(key) + 1):
|
|
202
|
+
extends = end > 0 and nxt[end - 1]
|
|
203
|
+
nxt[end] = reachable[end] or extends
|
|
204
|
+
else: # globstar_segment
|
|
205
|
+
any_before = False
|
|
206
|
+
for end in range(len(key) + 1):
|
|
207
|
+
lands = any_before and end > 0 and key[end - 1] == "/"
|
|
208
|
+
nxt[end] = reachable[end] or lands
|
|
209
|
+
if reachable[end]:
|
|
210
|
+
any_before = True
|
|
211
|
+
reachable = nxt
|
|
212
|
+
return reachable[len(key)]
|
|
213
|
+
|
|
214
|
+
return matches
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _suffix(doc_id: str) -> str:
|
|
218
|
+
"""The extension of a document's final path segment, or ``''``."""
|
|
219
|
+
name = doc_id.rsplit("/", 1)[-1]
|
|
220
|
+
dot = name.rfind(".")
|
|
221
|
+
return "" if dot <= 0 else name[dot:]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _local_name(tag: str) -> str:
|
|
225
|
+
"""An element's tag without its XML namespace, so parsing ignores the prefix."""
|
|
226
|
+
return tag.rsplit("}", 1)[-1]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _s3_environment() -> tuple[dict[str, str], str, str | None]:
|
|
230
|
+
"""The credentials, region and optional endpoint an ``s3`` source reads."""
|
|
231
|
+
access_key = os.environ.get("AWS_ACCESS_KEY_ID", "")
|
|
232
|
+
secret_key = os.environ.get("AWS_SECRET_ACCESS_KEY", "")
|
|
233
|
+
if not access_key or not secret_key:
|
|
234
|
+
raise ConfigurationError(
|
|
235
|
+
"an s3 source needs AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the environment"
|
|
236
|
+
)
|
|
237
|
+
region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")
|
|
238
|
+
if not region:
|
|
239
|
+
raise ConfigurationError(
|
|
240
|
+
"an s3 source needs a region: set AWS_REGION or AWS_DEFAULT_REGION"
|
|
241
|
+
)
|
|
242
|
+
credentials = {"access_key_id": access_key, "secret_access_key": secret_key}
|
|
243
|
+
token = os.environ.get("AWS_SESSION_TOKEN")
|
|
244
|
+
if token:
|
|
245
|
+
credentials["session_token"] = token
|
|
246
|
+
endpoint = os.environ.get("AWS_ENDPOINT_URL_S3") or os.environ.get("AWS_ENDPOINT_URL")
|
|
247
|
+
return credentials, region, endpoint.rstrip("/") if endpoint else None
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _parse_listing(body: bytes) -> tuple[list[_ListedObject], str | None]:
|
|
251
|
+
"""Read one ListObjectsV2 page: its objects and the next continuation token."""
|
|
252
|
+
try:
|
|
253
|
+
# The body is the response to a signed request this process made to its own
|
|
254
|
+
# configured endpoint, not a document supplied by a third party.
|
|
255
|
+
root = ElementTree.fromstring(body) # noqa: S314
|
|
256
|
+
except ElementTree.ParseError as error:
|
|
257
|
+
raise ConfigurationError(
|
|
258
|
+
f"the s3 ListObjectsV2 response is not valid XML: {error}"
|
|
259
|
+
) from error
|
|
260
|
+
listed: list[_ListedObject] = []
|
|
261
|
+
is_truncated = False
|
|
262
|
+
next_token: str | None = None
|
|
263
|
+
for element in root.iter():
|
|
264
|
+
name = _local_name(element.tag)
|
|
265
|
+
if name == "Contents":
|
|
266
|
+
key = etag = last_modified = ""
|
|
267
|
+
for child in element:
|
|
268
|
+
child_name = _local_name(child.tag)
|
|
269
|
+
if child_name == "Key":
|
|
270
|
+
key = child.text or ""
|
|
271
|
+
elif child_name == "ETag":
|
|
272
|
+
etag = (child.text or "").strip('"')
|
|
273
|
+
elif child_name == "LastModified":
|
|
274
|
+
last_modified = child.text or ""
|
|
275
|
+
if key:
|
|
276
|
+
listed.append(_ListedObject(key=key, etag=etag, last_modified=last_modified))
|
|
277
|
+
elif name == "IsTruncated":
|
|
278
|
+
is_truncated = (element.text or "").strip().lower() == "true"
|
|
279
|
+
elif name == "NextContinuationToken":
|
|
280
|
+
text = (element.text or "").strip()
|
|
281
|
+
next_token = text or None
|
|
282
|
+
return listed, next_token if is_truncated else None
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
async def _get_bytes(
|
|
286
|
+
client: httpx.AsyncClient,
|
|
287
|
+
url: str,
|
|
288
|
+
headers: dict[str, str],
|
|
289
|
+
*,
|
|
290
|
+
label: str,
|
|
291
|
+
) -> bytes:
|
|
292
|
+
"""One ``GET``, requiring a 2xx and refusing a body over the document limit."""
|
|
293
|
+
async with client.stream("GET", url, headers=headers) as response:
|
|
294
|
+
if not 200 <= response.status_code < 300:
|
|
295
|
+
detail = (await response.aread())[:200].decode("utf-8", "replace").strip()
|
|
296
|
+
suffix = f": {detail}" if detail else ""
|
|
297
|
+
raise ConfigurationError(f"{label} returned HTTP {response.status_code}{suffix}")
|
|
298
|
+
declared = response.headers.get("content-length")
|
|
299
|
+
if declared is not None and declared.isdigit() and int(declared) > _MAX_DOCUMENT_BYTES:
|
|
300
|
+
raise ConfigurationError(
|
|
301
|
+
f"{label} is {declared} bytes, over the {_MAX_DOCUMENT_BYTES}-byte limit"
|
|
302
|
+
)
|
|
303
|
+
chunks: list[bytes] = []
|
|
304
|
+
total = 0
|
|
305
|
+
async for chunk in response.aiter_bytes():
|
|
306
|
+
total += len(chunk)
|
|
307
|
+
if total > _MAX_DOCUMENT_BYTES:
|
|
308
|
+
raise ConfigurationError(
|
|
309
|
+
f"{label} exceeds the {_MAX_DOCUMENT_BYTES}-byte document limit"
|
|
310
|
+
)
|
|
311
|
+
chunks.append(chunk)
|
|
312
|
+
return b"".join(chunks)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
class S3Connector:
|
|
316
|
+
"""Reads an ``s3://bucket[/prefix]`` corpus, one document per object.
|
|
317
|
+
|
|
318
|
+
An object's ``doc_id`` is its key with the source prefix stripped, so the same
|
|
319
|
+
corpus indexed out of a bucket and out of a directory yields the same ids. Objects
|
|
320
|
+
are fetched concurrently -- bounded, so a bucket with a thousand keys does not open
|
|
321
|
+
a thousand sockets -- and emitted in sorted ``doc_id`` order regardless.
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
def __init__(
|
|
325
|
+
self,
|
|
326
|
+
uri: str,
|
|
327
|
+
*,
|
|
328
|
+
glob: str | None = None,
|
|
329
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
330
|
+
timeout: float = 30.0,
|
|
331
|
+
now: Callable[[], datetime] | None = None,
|
|
332
|
+
) -> None:
|
|
333
|
+
parsed = urlparse(uri)
|
|
334
|
+
if parsed.scheme != "s3" or not parsed.netloc:
|
|
335
|
+
raise ConfigurationError(
|
|
336
|
+
f"s3 source uri {uri!r} must be an absolute 's3://<bucket>[/<prefix>]' uri"
|
|
337
|
+
)
|
|
338
|
+
self._bucket = parsed.netloc
|
|
339
|
+
raw_prefix = parsed.path.lstrip("/")
|
|
340
|
+
# A prefix names a directory: without the trailing slash, ``docs`` would also
|
|
341
|
+
# list ``docs-archive/`` objects that are not under the source at all.
|
|
342
|
+
self._prefix = (
|
|
343
|
+
f"{raw_prefix}/" if raw_prefix and not raw_prefix.endswith("/") else raw_prefix
|
|
344
|
+
)
|
|
345
|
+
self._glob = glob
|
|
346
|
+
self._credentials, self._region, self._endpoint = _s3_environment()
|
|
347
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
348
|
+
self._client = httpx.AsyncClient(transport=transport, timeout=timeout)
|
|
349
|
+
|
|
350
|
+
@property
|
|
351
|
+
def kind(self) -> SourceKind:
|
|
352
|
+
return SourceKind.S3
|
|
353
|
+
|
|
354
|
+
async def documents(self) -> tuple[SourceDocument, ...]:
|
|
355
|
+
matcher = _glob_matcher(self._glob)
|
|
356
|
+
candidates = [
|
|
357
|
+
(item, self._relative_key(item.key))
|
|
358
|
+
for item in await self._list_objects()
|
|
359
|
+
if not item.key.endswith("/")
|
|
360
|
+
]
|
|
361
|
+
selected = [(item, doc_id) for item, doc_id in candidates if matcher(doc_id)]
|
|
362
|
+
semaphore = asyncio.Semaphore(_S3_CONCURRENCY)
|
|
363
|
+
documents = await asyncio.gather(
|
|
364
|
+
*(self._fetch_object(item, doc_id, semaphore) for item, doc_id in selected)
|
|
365
|
+
)
|
|
366
|
+
return tuple(sorted(documents, key=lambda document: document.doc_id))
|
|
367
|
+
|
|
368
|
+
async def aclose(self) -> None:
|
|
369
|
+
await self._client.aclose()
|
|
370
|
+
|
|
371
|
+
def _relative_key(self, key: str) -> str:
|
|
372
|
+
if self._prefix and key.startswith(self._prefix):
|
|
373
|
+
return key[len(self._prefix) :].lstrip("/")
|
|
374
|
+
return key.lstrip("/")
|
|
375
|
+
|
|
376
|
+
def _list_request(self, token: str | None) -> tuple[str, str]:
|
|
377
|
+
params = {"list-type": "2"}
|
|
378
|
+
if self._prefix:
|
|
379
|
+
params["prefix"] = self._prefix
|
|
380
|
+
if token is not None:
|
|
381
|
+
params["continuation-token"] = token
|
|
382
|
+
query = "&".join(
|
|
383
|
+
f"{quote(name, safe='-_.~')}={quote(value, safe='-_.~')}"
|
|
384
|
+
for name, value in sorted(params.items())
|
|
385
|
+
)
|
|
386
|
+
if self._endpoint is not None:
|
|
387
|
+
return f"{self._endpoint}/{self._bucket}?{query}", query
|
|
388
|
+
return f"https://{self._bucket}.s3.{self._region}.amazonaws.com/?{query}", query
|
|
389
|
+
|
|
390
|
+
def _object_url(self, key: str) -> str:
|
|
391
|
+
encoded = "/".join(rfc3986(segment) for segment in key.split("/"))
|
|
392
|
+
if self._endpoint is not None:
|
|
393
|
+
return f"{self._endpoint}/{self._bucket}/{encoded}"
|
|
394
|
+
return f"https://{self._bucket}.s3.{self._region}.amazonaws.com/{encoded}"
|
|
395
|
+
|
|
396
|
+
async def _list_objects(self) -> list[_ListedObject]:
|
|
397
|
+
listed: list[_ListedObject] = []
|
|
398
|
+
token: str | None = None
|
|
399
|
+
while True:
|
|
400
|
+
url, query = self._list_request(token)
|
|
401
|
+
headers = sigv4_headers(
|
|
402
|
+
url=url,
|
|
403
|
+
body="",
|
|
404
|
+
region=self._region,
|
|
405
|
+
credentials=self._credentials,
|
|
406
|
+
moment=self._now(),
|
|
407
|
+
service="s3",
|
|
408
|
+
method="GET",
|
|
409
|
+
query=query,
|
|
410
|
+
)
|
|
411
|
+
body = await _get_bytes(self._client, url, headers, label="the s3 listing")
|
|
412
|
+
page, token = _parse_listing(body)
|
|
413
|
+
listed.extend(page)
|
|
414
|
+
if token is None:
|
|
415
|
+
return listed
|
|
416
|
+
|
|
417
|
+
async def _fetch_object(
|
|
418
|
+
self,
|
|
419
|
+
item: _ListedObject,
|
|
420
|
+
doc_id: str,
|
|
421
|
+
semaphore: asyncio.Semaphore,
|
|
422
|
+
) -> SourceDocument:
|
|
423
|
+
url = self._object_url(item.key)
|
|
424
|
+
async with semaphore:
|
|
425
|
+
headers = sigv4_headers(
|
|
426
|
+
url=url,
|
|
427
|
+
body="",
|
|
428
|
+
region=self._region,
|
|
429
|
+
credentials=self._credentials,
|
|
430
|
+
moment=self._now(),
|
|
431
|
+
service="s3",
|
|
432
|
+
method="GET",
|
|
433
|
+
)
|
|
434
|
+
body = await _get_bytes(self._client, url, headers, label=f"the s3 object {item.key!r}")
|
|
435
|
+
try:
|
|
436
|
+
text = body.decode("utf-8")
|
|
437
|
+
except UnicodeDecodeError as error:
|
|
438
|
+
raise ConfigurationError(
|
|
439
|
+
f"the s3 object {item.key!r} is not valid UTF-8: {error}"
|
|
440
|
+
) from error
|
|
441
|
+
return SourceDocument(
|
|
442
|
+
doc_id=doc_id,
|
|
443
|
+
uri=f"s3://{self._bucket}/{item.key}",
|
|
444
|
+
text=text,
|
|
445
|
+
metadata={
|
|
446
|
+
"path": doc_id,
|
|
447
|
+
"suffix": _suffix(doc_id),
|
|
448
|
+
"etag": item.etag,
|
|
449
|
+
"lastModified": item.last_modified,
|
|
450
|
+
},
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
class HttpConnector:
|
|
455
|
+
"""Reads exactly one document from an absolute ``http://`` or ``https://`` url.
|
|
456
|
+
|
|
457
|
+
An http source names a document, not a set, which is why it takes no ``glob``: a
|
|
458
|
+
pattern there would describe documents the connector deliberately does not fetch.
|
|
459
|
+
"""
|
|
460
|
+
|
|
461
|
+
def __init__(
|
|
462
|
+
self,
|
|
463
|
+
uri: str,
|
|
464
|
+
*,
|
|
465
|
+
glob: str | None = None,
|
|
466
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
467
|
+
timeout: float = 30.0,
|
|
468
|
+
) -> None:
|
|
469
|
+
if glob is not None:
|
|
470
|
+
raise ConfigurationError(
|
|
471
|
+
f"http source {uri!r} takes no 'glob': an http source is exactly one "
|
|
472
|
+
"document, and a pattern describes a set"
|
|
473
|
+
)
|
|
474
|
+
parsed = urlparse(uri)
|
|
475
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
476
|
+
raise ConfigurationError(
|
|
477
|
+
f"http source uri {uri!r} must be an absolute 'http://' or 'https://' url"
|
|
478
|
+
)
|
|
479
|
+
self._uri = uri
|
|
480
|
+
self._segments = [segment for segment in parsed.path.split("/") if segment]
|
|
481
|
+
self._client = httpx.AsyncClient(transport=transport, timeout=timeout)
|
|
482
|
+
|
|
483
|
+
@property
|
|
484
|
+
def kind(self) -> SourceKind:
|
|
485
|
+
return SourceKind.HTTP
|
|
486
|
+
|
|
487
|
+
async def documents(self) -> tuple[SourceDocument, ...]:
|
|
488
|
+
body = await _get_bytes(self._client, self._uri, {}, label=f"the http source {self._uri!r}")
|
|
489
|
+
try:
|
|
490
|
+
text = body.decode("utf-8")
|
|
491
|
+
except UnicodeDecodeError as error:
|
|
492
|
+
raise ConfigurationError(
|
|
493
|
+
f"the http source {self._uri!r} is not valid UTF-8: {error}"
|
|
494
|
+
) from error
|
|
495
|
+
doc_id = self._segments[-1] if self._segments else "index"
|
|
496
|
+
return (
|
|
497
|
+
SourceDocument(
|
|
498
|
+
doc_id=doc_id,
|
|
499
|
+
uri=self._uri,
|
|
500
|
+
text=text,
|
|
501
|
+
metadata={"path": doc_id, "suffix": _suffix(doc_id)},
|
|
502
|
+
),
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
async def aclose(self) -> None:
|
|
506
|
+
await self._client.aclose()
|
|
507
|
+
|
|
508
|
+
|
|
115
509
|
def open_connector(spec: SourceSpec, *, base_dir: str | Path | None = None) -> Connector:
|
|
116
510
|
"""Open the connector for a source entry.
|
|
117
511
|
|
|
118
|
-
``base_dir`` resolves a relative source ``uri``; it is explicit because the
|
|
119
|
-
runtime has no opinion about a working directory, and a corpus must not depend
|
|
120
|
-
|
|
512
|
+
``base_dir`` resolves a relative ``file`` source ``uri``; it is explicit because the
|
|
513
|
+
runtime has no opinion about a working directory, and a corpus must not depend on
|
|
514
|
+
where a process happened to be started.
|
|
121
515
|
"""
|
|
516
|
+
if spec.kind is SourceKind.S3:
|
|
517
|
+
return S3Connector(spec.uri, glob=spec.glob)
|
|
518
|
+
if spec.kind is SourceKind.HTTP:
|
|
519
|
+
return HttpConnector(spec.uri, glob=spec.glob)
|
|
122
520
|
if spec.kind is not SourceKind.FILE:
|
|
123
521
|
raise FeatureDeferredError(
|
|
124
|
-
f"source kind {spec.kind.value!r} is
|
|
125
|
-
"
|
|
126
|
-
"belong to the phase that ships them"
|
|
522
|
+
f"source kind {spec.kind.value!r} is still reserved: the s3 and http loaders "
|
|
523
|
+
"shipped in spec 0.21, and db and mcp remain part of the design but unimplemented"
|
|
127
524
|
)
|
|
128
525
|
root = Path(spec.uri)
|
|
129
526
|
if not root.is_absolute() and base_dir is not None:
|
|
@@ -85,6 +85,10 @@ class IngestReport(BaseModel):
|
|
|
85
85
|
``chunks``. ``removed`` counts chunks deleted because their document no longer
|
|
86
86
|
yields them. All three are zero-or-more, and all but ``written`` are zero for a
|
|
87
87
|
``full`` refresh, which never reads the index and never deletes from it.
|
|
88
|
+
|
|
89
|
+
``tokens`` and ``cost_usd`` include the semantic chunker's boundary pass. That pass
|
|
90
|
+
embeds every unit before a chunk exists, so reporting only the chunk embeddings
|
|
91
|
+
would undercount what the ingest actually spent.
|
|
88
92
|
"""
|
|
89
93
|
|
|
90
94
|
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
@@ -216,8 +220,18 @@ class Retriever:
|
|
|
216
220
|
local = self._local
|
|
217
221
|
incremental = local.refresh_mode is RefreshMode.INCREMENTAL
|
|
218
222
|
source_documents = tuple(documents) if documents is not None else await self._read_source()
|
|
219
|
-
chunker = chunker_for(local.chunking)
|
|
220
|
-
chunks = [
|
|
223
|
+
chunker = chunker_for(local.chunking, embedder=self._embedder, model=local.embedding)
|
|
224
|
+
chunks: list[Chunk] = []
|
|
225
|
+
# A chunker reports one document's boundary work, so a corpus has to be summed
|
|
226
|
+
# here: reading `chunker.usage` after the loop would report only the last
|
|
227
|
+
# document.
|
|
228
|
+
boundary_input = 0
|
|
229
|
+
boundary_output = 0
|
|
230
|
+
for document in source_documents:
|
|
231
|
+
document_chunks = await chunker.chunk(document)
|
|
232
|
+
boundary_input += chunker.usage.input_tokens
|
|
233
|
+
boundary_output += chunker.usage.output_tokens
|
|
234
|
+
chunks.extend(document_chunks)
|
|
221
235
|
|
|
222
236
|
to_embed = chunks
|
|
223
237
|
removed = 0
|
|
@@ -229,8 +243,11 @@ class Retriever:
|
|
|
229
243
|
to_embed = [chunk for chunk in chunks if chunk.chunk_id not in stored]
|
|
230
244
|
|
|
231
245
|
records: list[StoreRecord] = []
|
|
232
|
-
|
|
233
|
-
|
|
246
|
+
# A semantic chunker embeds every unit before it can cut, so its boundary pass
|
|
247
|
+
# is work this ingest caused and must report. The size chunkers report zero.
|
|
248
|
+
boundary_usage = TokenUsage(input_tokens=boundary_input, output_tokens=boundary_output)
|
|
249
|
+
tokens = boundary_usage.input_tokens
|
|
250
|
+
cost = self._charge_embedding(boundary_usage) if boundary_usage.total_tokens else 0.0
|
|
234
251
|
for start in range(0, len(to_embed), _BATCH_SIZE):
|
|
235
252
|
batch = to_embed[start : start + _BATCH_SIZE]
|
|
236
253
|
embedded, batch_cost = await self._embed(tuple(chunk.text for chunk in batch))
|
|
@@ -429,10 +446,11 @@ class Retriever:
|
|
|
429
446
|
raise AssertionError("_embed called without an embedder")
|
|
430
447
|
local = self._local
|
|
431
448
|
embedded = await embedder.embed(texts, model=local.embedding)
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
449
|
+
return embedded, self._charge_embedding(embedded.usage)
|
|
450
|
+
|
|
451
|
+
def _charge_embedding(self, usage: TokenUsage) -> float:
|
|
452
|
+
"""Price one embedding pass through the pinned profile and charge the ledger."""
|
|
453
|
+
local = self._local
|
|
436
454
|
# Priced through CostProfile rather than a ModelSpec: a ModelSpec requires a
|
|
437
455
|
# context window and an output ceiling, and fabricating those to reuse a
|
|
438
456
|
# pricing helper would put invented numbers in a generated artifact.
|
|
@@ -448,7 +466,7 @@ class Retriever:
|
|
|
448
466
|
cost_usd=cost,
|
|
449
467
|
),
|
|
450
468
|
)
|
|
451
|
-
return
|
|
469
|
+
return cost
|
|
452
470
|
|
|
453
471
|
async def _search_vector(
|
|
454
472
|
self,
|
aid_runtime/retrieval/types.py
CHANGED
|
@@ -88,8 +88,9 @@ class DistanceMetric(StrEnum):
|
|
|
88
88
|
class SourceKind(StrEnum):
|
|
89
89
|
"""``retriever.source.kind``.
|
|
90
90
|
|
|
91
|
-
``FILE``
|
|
92
|
-
of the IR contract and fail loudly rather than
|
|
91
|
+
``FILE``, ``S3`` and ``HTTP`` are implemented; ``S3`` and ``HTTP`` shipped in spec
|
|
92
|
+
0.21. ``DB`` and ``MCP`` are part of the IR contract and fail loudly rather than
|
|
93
|
+
silently indexing nothing.
|
|
93
94
|
"""
|
|
94
95
|
|
|
95
96
|
FILE = "file"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: aid-runtime-python
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.135
|
|
4
4
|
Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
|
|
5
5
|
Author: The AID Framework authors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
aid_runtime/__init__.py,sha256=
|
|
1
|
+
aid_runtime/__init__.py,sha256=ipwHMqB9ql4GoVYeJ2vMfkA0Tj2bp_7Fg9IPwdmcAU4,13238
|
|
2
2
|
aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
|
|
3
3
|
aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
|
|
4
4
|
aid_runtime/control.py,sha256=y6wPn0fqYJv0nVSsjzpzfiaq1Y7zBoMxCpdrEuqkfvg,17529
|
|
@@ -41,10 +41,10 @@ aid_runtime/providers/gemini.py,sha256=gM4Kvgz6lnFbHgYYhyVCBTFTcGAKfiNuj7lS1XSld
|
|
|
41
41
|
aid_runtime/providers/gemini_wire.py,sha256=ZwIiYuAVihszE0c90-uAbSn6_hdMa2Md4asySIYeQTw,13032
|
|
42
42
|
aid_runtime/providers/http.py,sha256=c5DLmX1FqtAUO01MqDf0m82x8zHD480LyL-QtTrxnn4,13168
|
|
43
43
|
aid_runtime/providers/vertex.py,sha256=XdwPuPw2Ce5CGuoEyzY5jVpqtKeTXWOvY_9WegxheEk,9341
|
|
44
|
-
aid_runtime/retrieval/__init__.py,sha256=
|
|
45
|
-
aid_runtime/retrieval/chunking.py,sha256=
|
|
44
|
+
aid_runtime/retrieval/__init__.py,sha256=xlOnQyWfAMH9E4knJiUAfFbq2ypHauwgQDN_joWvDkY,6277
|
|
45
|
+
aid_runtime/retrieval/chunking.py,sha256=jn4tWXaWaQpSkfhqW_pkgd0J95z8PKCasbMgM7l7w-I,20495
|
|
46
46
|
aid_runtime/retrieval/citations.py,sha256=UL9fsxLTzzO0n8tEW3X2O5erJ0hrk08NYMkZ9Pk8Jdg,4287
|
|
47
|
-
aid_runtime/retrieval/connectors.py,sha256=
|
|
47
|
+
aid_runtime/retrieval/connectors.py,sha256=iKvnQVCKx3gYaDmwRAmLwExYbUuiWpF9tgdysx0sxCk,20582
|
|
48
48
|
aid_runtime/retrieval/embedding.py,sha256=Ea7zOZnnX2oGdnKi2AcecxYZkn9KirgJO_xOf7iDDI8,24775
|
|
49
49
|
aid_runtime/retrieval/filters.py,sha256=mEa2Ok20VG5Fxe5GWYAxvhl4HK4HV6FHZ5r0wnr-ZLI,6240
|
|
50
50
|
aid_runtime/retrieval/gate.py,sha256=3avH1Gwp7iv7mMOskmNbk70Yq85tXwJrKVrQAKKI4Js,4840
|
|
@@ -53,10 +53,10 @@ aid_runtime/retrieval/knowledge_base.py,sha256=xNFTdIdIMvS7Ij9y4niXGrgxAhtsmWe2k
|
|
|
53
53
|
aid_runtime/retrieval/metrics.py,sha256=LN36BIXzpbhkG9grzE0q5wncgXt_Y85-b5jGJ038-3Y,7904
|
|
54
54
|
aid_runtime/retrieval/pgvector.py,sha256=tahRZQr8xQp7tZ5spgTzlEEMv2HpSx3OLPKjdq_vz0c,11015
|
|
55
55
|
aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJMc,5114
|
|
56
|
-
aid_runtime/retrieval/retriever.py,sha256=
|
|
56
|
+
aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
|
|
57
57
|
aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
|
|
58
|
-
aid_runtime/retrieval/types.py,sha256=
|
|
59
|
-
aid_runtime_python-0.1.
|
|
60
|
-
aid_runtime_python-0.1.
|
|
61
|
-
aid_runtime_python-0.1.
|
|
62
|
-
aid_runtime_python-0.1.
|
|
58
|
+
aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
|
|
59
|
+
aid_runtime_python-0.1.135.dist-info/METADATA,sha256=ECWGkiJven1N3KfSpDolgiTcMssYxGbOqA_UJtpdr7o,16983
|
|
60
|
+
aid_runtime_python-0.1.135.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
61
|
+
aid_runtime_python-0.1.135.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
|
|
62
|
+
aid_runtime_python-0.1.135.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|