aid-runtime-python 0.1.134__py3-none-any.whl → 0.1.136__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 CHANGED
@@ -310,7 +310,7 @@ from aid_runtime.types import (
310
310
  )
311
311
 
312
312
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
313
- __version__ = "0.1.134"
313
+ __version__ = "0.1.136"
314
314
 
315
315
  __all__ = [
316
316
  "ANTHROPIC_VERSION",
@@ -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
  )
@@ -202,6 +203,7 @@ __all__ = [
202
203
  "S3Connector",
203
204
  "ScoredChunk",
204
205
  "SearchHit",
206
+ "SemanticChunker",
205
207
  "SourceDocument",
206
208
  "SourceKind",
207
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, and the pin is the spec validator's own reading
5
- of the intent: *"spec v0.1 chunks by size (fixed, recursive, code)"*. ``semantic``
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
- Chunks are pure functions of the text, so the same input always produces the same
24
- chunks with the same ids in the same order -- which is what makes re-ingesting a
25
- corpus a no-op instead of a duplicate.
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.types import Chunk, ChunkingSpec, ChunkingStrategy, chunk_id_for
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
- def chunk(self, document: SourceDocument) -> tuple[Chunk, ...]: ...
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
- if size <= 0:
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 Chunk(
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(spec: ChunkingSpec) -> Chunker:
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`` is refused here as well as in the spec validator, because the
208
- runtime is reachable from generated code the validator never saw.
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: spec "
214
- "v0.1 chunks by size (fixed, recursive, code), and semantic chunking needs an "
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(document: SourceDocument, spec: ChunkingSpec) -> tuple[Chunk, ...]:
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
- return chunker_for(spec).chunk(document)
529
+ chunker = chunker_for(spec, embedder=embedder, model=model)
530
+ return await chunker.chunk(document)
@@ -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 = [chunk for document in source_documents for chunk in chunker.chunk(document)]
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
- tokens = 0
233
- cost = 0.0
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
- usage = TokenUsage(
433
- input_tokens=embedded.usage.input_tokens,
434
- output_tokens=embedded.usage.output_tokens,
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 embedded, cost
469
+ return cost
452
470
 
453
471
  async def _search_vector(
454
472
  self,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.134
3
+ Version: 0.1.136
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=Y0CAy42x2-aQyG4Zs4EkHfQPvxHNv8nQIV5EKeL4sFw,13238
1
+ aid_runtime/__init__.py,sha256=HrBWlzj8b0iPBa9imiFPU6I1pRpgpuXpyyCsf1EOiqY,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,8 +41,8 @@ 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=uzEILO7_CNMcW2o0dGQzTpIwj44DJpTVa9gqsf3gWVI,6233
45
- aid_runtime/retrieval/chunking.py,sha256=GMJvY1GoIua-FkpCH1S5qNmUrWSaSbl6sBJPCrSDAg4,8296
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
47
  aid_runtime/retrieval/connectors.py,sha256=iKvnQVCKx3gYaDmwRAmLwExYbUuiWpF9tgdysx0sxCk,20582
48
48
  aid_runtime/retrieval/embedding.py,sha256=Ea7zOZnnX2oGdnKi2AcecxYZkn9KirgJO_xOf7iDDI8,24775
@@ -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=5pO4muNPm-rn5jQZNJwkk8dwNkQKoaywuCX-tArEj3o,23241
56
+ aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
57
57
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
58
58
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
59
- aid_runtime_python-0.1.134.dist-info/METADATA,sha256=EZQhJnjhN3aVtnAgN8D4dZsbPUuGAcpWLfjEklo8fwI,16983
60
- aid_runtime_python-0.1.134.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
61
- aid_runtime_python-0.1.134.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
62
- aid_runtime_python-0.1.134.dist-info/RECORD,,
59
+ aid_runtime_python-0.1.136.dist-info/METADATA,sha256=uObCqKokS7qq6CZCVIgiuZApc27OaARvLyzmf6pOlsM,16983
60
+ aid_runtime_python-0.1.136.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
61
+ aid_runtime_python-0.1.136.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
62
+ aid_runtime_python-0.1.136.dist-info/RECORD,,