aid-runtime-python 0.1.133__tar.gz → 0.1.135__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.
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/PKG-INFO +1 -1
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/pyproject.toml +1 -1
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/__init__.py +1 -1
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/__init__.py +6 -0
- aid_runtime_python-0.1.135/src/aid_runtime/retrieval/chunking.py +530 -0
- aid_runtime_python-0.1.135/src/aid_runtime/retrieval/connectors.py +528 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/retriever.py +27 -9
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/types.py +3 -2
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
- aid_runtime_python-0.1.135/tests/test_retrieval_chunking.py +409 -0
- aid_runtime_python-0.1.135/tests/test_retrieval_connectors.py +434 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_gate.py +66 -0
- aid_runtime_python-0.1.133/src/aid_runtime/retrieval/chunking.py +0 -222
- aid_runtime_python-0.1.133/src/aid_runtime/retrieval/connectors.py +0 -131
- aid_runtime_python-0.1.133/tests/test_retrieval_chunking.py +0 -257
- aid_runtime_python-0.1.133/tests/test_retrieval_connectors.py +0 -156
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/README.md +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/setup.cfg +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/__init__.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/chat_model.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/deep_agents.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/engine.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/guardrails.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/ir.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/loop.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/managed.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/memory.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/policy.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/agents/state.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/cache.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/concurrency.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/control.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/cost.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/decisions.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/errors.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/evals/__init__.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/evals/dataset.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/evals/gate.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/evals/metrics.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/evals/predicate.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/evals/runner.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/gateway.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/local_trace.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/pipeline.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/prompts.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/__init__.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/anthropic.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/base.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/bedrock.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/fake.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/gemini.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/gemini_wire.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/http.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/providers/vertex.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/py.typed +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/citations.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/embedding.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/filters.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/gate.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/hybrid.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/knowledge_base.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/metrics.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/pgvector.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/rerank.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/stores.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/steps.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/structured.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/tools.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/tracing.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/types.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime_python.egg-info/SOURCES.txt +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime_python.egg-info/requires.txt +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_agents_budget.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_agents_deep_agents.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_agents_hitl.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_agents_loop.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_agents_memory.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_anthropic_provider.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_bedrock_provider.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_cache.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_concurrency.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_control.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_cost.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_dataset.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_decisions.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_evals.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_evals_assert_gate.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_evals_decision.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_evals_gate.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_evals_predicate.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_gateway.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_gemini_provider.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_guardrails.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_guardrails_managed.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_guardrails_model_armor.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_http_provider.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_local_trace.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_package.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_pipeline.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_prompts.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_citations.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_embedding.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_filters.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_hybrid.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_knowledge_base.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_metrics.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_rerank.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_stores.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_retrieval_types.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_steps.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_streaming.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_structured.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_tool_permissions.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_tools.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_tracing.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_types.py +0 -0
- {aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/tests/test_vertex_provider.py +0 -0
|
@@ -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
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "aid-runtime-python"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.135"
|
|
8
8
|
description = "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."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
{aid_runtime_python-0.1.133 → aid_runtime_python-0.1.135}/src/aid_runtime/retrieval/__init__.py
RENAMED
|
@@ -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",
|
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
"""Turning documents into deterministic, size-bounded chunks.
|
|
2
|
+
|
|
3
|
+
The IR declares a strategy, a size and an overlap; it does not declare the split
|
|
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**:
|
|
6
|
+
|
|
7
|
+
``fixed``
|
|
8
|
+
Anywhere. The window always fills to ``size``, cutting mid-word when that is
|
|
9
|
+
where the budget ends. This is the honest baseline other strategies improve on.
|
|
10
|
+
``recursive``
|
|
11
|
+
Prefer the last paragraph break, then the last line break, then the last
|
|
12
|
+
sentence end, then the last word break inside the window.
|
|
13
|
+
``code``
|
|
14
|
+
Prefer the last blank line, then the last line break, then the last statement
|
|
15
|
+
end. Code is line-structured, so a blank line is the closest thing it has to a
|
|
16
|
+
paragraph, and cutting mid-statement is the failure worth avoiding.
|
|
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.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import abc
|
|
44
|
+
from collections.abc import Sequence
|
|
45
|
+
from math import sqrt
|
|
46
|
+
from typing import Protocol, runtime_checkable
|
|
47
|
+
|
|
48
|
+
from aid_runtime.errors import ConfigurationError, FeatureDeferredError
|
|
49
|
+
from aid_runtime.retrieval.connectors import SourceDocument
|
|
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
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"Chunker",
|
|
62
|
+
"CodeChunker",
|
|
63
|
+
"FixedChunker",
|
|
64
|
+
"RecursiveChunker",
|
|
65
|
+
"SemanticChunker",
|
|
66
|
+
"chunk_document",
|
|
67
|
+
"chunker_for",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
#: A boundary found in the first half of a window is ignored and the window is
|
|
71
|
+
#: filled to ``size`` instead. Without this, one early paragraph break near the end
|
|
72
|
+
#: of a split would produce a stream of very short chunks, and a chunker that emits
|
|
73
|
+
#: 5-character chunks is worse than one that cuts a sentence in half.
|
|
74
|
+
_MIN_FILL_NUMERATOR = 1
|
|
75
|
+
_MIN_FILL_DENOMINATOR = 2
|
|
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
|
+
|
|
115
|
+
|
|
116
|
+
@runtime_checkable
|
|
117
|
+
class Chunker(Protocol):
|
|
118
|
+
"""Splits a document into chunks, deterministically."""
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def strategy(self) -> ChunkingStrategy: ...
|
|
122
|
+
|
|
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, ...]: ...
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class _SizeChunker(abc.ABC):
|
|
132
|
+
"""Shared windowing. Subclasses only choose where a boundary may fall."""
|
|
133
|
+
|
|
134
|
+
def __init__(self, *, size: int, overlap: int, keep_metadata: Sequence[str] = ()) -> None:
|
|
135
|
+
_check_window(size, overlap)
|
|
136
|
+
self._size = size
|
|
137
|
+
self._overlap = overlap
|
|
138
|
+
self._keep = tuple(keep_metadata)
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
@abc.abstractmethod
|
|
142
|
+
def strategy(self) -> ChunkingStrategy: ...
|
|
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
|
+
|
|
150
|
+
@abc.abstractmethod
|
|
151
|
+
def _cut(self, text: str, start: int, limit: int) -> int:
|
|
152
|
+
"""Where to end the window that starts at ``start`` and may reach ``limit``."""
|
|
153
|
+
|
|
154
|
+
async def chunk(self, document: SourceDocument) -> tuple[Chunk, ...]:
|
|
155
|
+
text = document.text
|
|
156
|
+
chunks: list[Chunk] = []
|
|
157
|
+
start = 0
|
|
158
|
+
while start < len(text):
|
|
159
|
+
limit = min(start + self._size, len(text))
|
|
160
|
+
end = limit if limit >= len(text) else self._cut(text, start, limit)
|
|
161
|
+
# A boundary at or before `start` would stall the loop, so progress is
|
|
162
|
+
# guaranteed here rather than trusted from the strategy hook.
|
|
163
|
+
end = max(end, start + 1)
|
|
164
|
+
window = text[start:end]
|
|
165
|
+
if window.strip():
|
|
166
|
+
chunks.append(self._build(document, len(chunks), start, end, window))
|
|
167
|
+
if end >= len(text):
|
|
168
|
+
break
|
|
169
|
+
start = max(end - self._overlap, start + 1)
|
|
170
|
+
return tuple(chunks)
|
|
171
|
+
|
|
172
|
+
def _build(
|
|
173
|
+
self, document: SourceDocument, index: int, start: int, end: int, text: str
|
|
174
|
+
) -> Chunk:
|
|
175
|
+
return _build_chunk(document, index, start, end, text, self._keep)
|
|
176
|
+
|
|
177
|
+
def _boundary(self, text: str, start: int, limit: int, markers: Sequence[str]) -> int | None:
|
|
178
|
+
"""The end offset of the last ``marker`` in ``text[start:limit]``, if usable.
|
|
179
|
+
|
|
180
|
+
``None`` means "no boundary worth taking", and the caller falls back to
|
|
181
|
+
``limit``. The minimum-fill rule is applied here rather than by each
|
|
182
|
+
strategy so no strategy can forget it.
|
|
183
|
+
"""
|
|
184
|
+
floor = start + (self._size * _MIN_FILL_NUMERATOR) // _MIN_FILL_DENOMINATOR
|
|
185
|
+
window = text[start:limit]
|
|
186
|
+
found: int | None = None
|
|
187
|
+
for marker in markers:
|
|
188
|
+
position = window.rfind(marker)
|
|
189
|
+
if position != -1:
|
|
190
|
+
end = start + position + len(marker)
|
|
191
|
+
if end >= max(floor, start + 1):
|
|
192
|
+
found = end
|
|
193
|
+
break
|
|
194
|
+
return found
|
|
195
|
+
|
|
196
|
+
def _fill(
|
|
197
|
+
self, text: str, start: int, limit: int, marker_groups: Sequence[Sequence[str]]
|
|
198
|
+
) -> int:
|
|
199
|
+
"""The first usable boundary from ``marker_groups``, in preference order."""
|
|
200
|
+
for markers in marker_groups:
|
|
201
|
+
found = self._boundary(text, start, limit, markers)
|
|
202
|
+
if found is not None:
|
|
203
|
+
return found
|
|
204
|
+
return limit
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class FixedChunker(_SizeChunker):
|
|
208
|
+
"""Cuts on size alone."""
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def strategy(self) -> ChunkingStrategy:
|
|
212
|
+
return ChunkingStrategy.FIXED
|
|
213
|
+
|
|
214
|
+
def _cut(self, text: str, start: int, limit: int) -> int:
|
|
215
|
+
return limit
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class RecursiveChunker(_SizeChunker):
|
|
219
|
+
"""Prefers prose boundaries: paragraph, then line, then sentence, then word."""
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def strategy(self) -> ChunkingStrategy:
|
|
223
|
+
return ChunkingStrategy.RECURSIVE
|
|
224
|
+
|
|
225
|
+
def _cut(self, text: str, start: int, limit: int) -> int:
|
|
226
|
+
return self._fill(
|
|
227
|
+
text,
|
|
228
|
+
start,
|
|
229
|
+
limit,
|
|
230
|
+
(("\n\n",), ("\n",), (". ", "! ", "? "), (" ",)),
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class CodeChunker(_SizeChunker):
|
|
235
|
+
"""Prefers code boundaries: blank line, then line, then statement, then token."""
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def strategy(self) -> ChunkingStrategy:
|
|
239
|
+
return ChunkingStrategy.CODE
|
|
240
|
+
|
|
241
|
+
def _cut(self, text: str, start: int, limit: int) -> int:
|
|
242
|
+
return self._fill(
|
|
243
|
+
text,
|
|
244
|
+
start,
|
|
245
|
+
limit,
|
|
246
|
+
(("\n\n",), ("\n",), (";\n", ";\r\n", "; "), (" ",)),
|
|
247
|
+
)
|
|
248
|
+
|
|
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
|
+
|
|
478
|
+
_STRATEGIES: dict[ChunkingStrategy, type[_SizeChunker]] = {
|
|
479
|
+
ChunkingStrategy.FIXED: FixedChunker,
|
|
480
|
+
ChunkingStrategy.RECURSIVE: RecursiveChunker,
|
|
481
|
+
ChunkingStrategy.CODE: CodeChunker,
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def chunker_for(
|
|
486
|
+
spec: ChunkingSpec,
|
|
487
|
+
*,
|
|
488
|
+
embedder: Embedder | None = None,
|
|
489
|
+
model: PinnedEmbedding | None = None,
|
|
490
|
+
) -> Chunker:
|
|
491
|
+
"""Resolve a chunking block to an implementation.
|
|
492
|
+
|
|
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.
|
|
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
|
+
)
|
|
512
|
+
implementation = _STRATEGIES.get(spec.strategy)
|
|
513
|
+
if implementation is None:
|
|
514
|
+
raise FeatureDeferredError(
|
|
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"
|
|
517
|
+
)
|
|
518
|
+
return implementation(size=spec.size, overlap=spec.overlap, keep_metadata=spec.keep_metadata)
|
|
519
|
+
|
|
520
|
+
|
|
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, ...]:
|
|
528
|
+
"""Chunk one document with the strategy the spec names."""
|
|
529
|
+
chunker = chunker_for(spec, embedder=embedder, model=model)
|
|
530
|
+
return await chunker.chunk(document)
|