aid-runtime-python 0.1.39__py3-none-any.whl → 0.1.48__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
@@ -268,7 +268,7 @@ from aid_runtime.types import (
268
268
  )
269
269
 
270
270
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
271
- __version__ = "0.1.39"
271
+ __version__ = "0.1.48"
272
272
 
273
273
  __all__ = [
274
274
  "ATTRIBUTES",
@@ -65,7 +65,7 @@ class RetrievalGate:
65
65
  # from these, which is the part of the protocol a retrieval metric shares.
66
66
  self._gate = BaselineGate(
67
67
  thresholds,
68
- metrics=cast("Sequence[Metric]", self._metrics),
68
+ metrics=cast(Sequence[Metric], self._metrics),
69
69
  )
70
70
 
71
71
  @property
@@ -0,0 +1,276 @@
1
+ Metadata-Version: 2.4
2
+ Name: aid-runtime-python
3
+ Version: 0.1.48
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
+ Author: The AID Framework authors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/aid-framework/aid-framework
8
+ Project-URL: Documentation, https://github.com/aid-framework/aid-framework/blob/main/docs/design.md
9
+ Project-URL: Issues, https://github.com/aid-framework/aid-framework/issues
10
+ Keywords: ai,codegen,llm,evals,opentelemetry,pydantic
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ Requires-Dist: httpx<1,>=0.27
21
+ Requires-Dist: opentelemetry-api<2,>=1.24
22
+ Requires-Dist: pydantic<3,>=2.7
23
+ Requires-Dist: pydantic-ai-slim<3,>=2
24
+ Provides-Extra: pgvector
25
+ Requires-Dist: psycopg[binary]<4,>=3.1; extra == "pgvector"
26
+ Provides-Extra: deepagents
27
+ Requires-Dist: deepagents==0.7.32; extra == "deepagents"
28
+ Provides-Extra: dev
29
+ Requires-Dist: mypy<3,>=1.11; extra == "dev"
30
+ Requires-Dist: opentelemetry-sdk<2,>=1.24; extra == "dev"
31
+ Requires-Dist: pytest<10,>=8; extra == "dev"
32
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == "dev"
33
+ Requires-Dist: ruff<1,>=0.6; extra == "dev"
34
+
35
+ # `aid-runtime-python`
36
+
37
+ The Python runtime for [AID Framework](https://github.com/aid-framework/aid-framework): the behavior layer that
38
+ apps generated by the [`py-fastapi`](https://github.com/aid-framework/aid-framework/tree/main/packages/generators/py-fastapi)
39
+ target import. Generated code is thin glue; this is where the behavior lives.
40
+
41
+ Distribution name **`aid-runtime-python`**, import package **`aid_runtime`**. The two differ deliberately: a
42
+ distribution name is conventionally hyphenated, and a Python import package cannot be. That asymmetry is asserted
43
+ by the test suite so it cannot drift.
44
+
45
+ ## Install
46
+
47
+ ```sh
48
+ pip install aid-runtime-python
49
+ ```
50
+
51
+ Requires Python 3.11 or newer. Dependencies are `httpx`, `pydantic`, `pydantic-ai-slim` and
52
+ `opentelemetry-api`.
53
+
54
+ Two optional extras:
55
+
56
+ ```sh
57
+ pip install "aid-runtime-python[pgvector]" # the pgvector store adapter
58
+ pip install "aid-runtime-python[deepagents]" # the deepagents agent engine, pinned
59
+ ```
60
+
61
+ ## Quick start
62
+
63
+ ```python
64
+ from aid_runtime import (
65
+ Budget,
66
+ CompletionRequest,
67
+ CostProfile,
68
+ ModelGateway,
69
+ ModelSpec,
70
+ OpenAICompatibleProvider,
71
+ PinnedModel,
72
+ )
73
+
74
+ spec = ModelSpec(
75
+ name="gpt-4o-2024-08-06",
76
+ provider="openai-compatible",
77
+ cost=CostProfile(input_per_1k_usd=0.0025, output_per_1k_usd=0.01),
78
+ context_window=128_000,
79
+ max_output_tokens=4_096,
80
+ )
81
+
82
+ gateway = ModelGateway(
83
+ providers={"openai-compatible": OpenAICompatibleProvider(api_key=...)},
84
+ aliases={"small": PinnedModel(alias="small", spec=spec)},
85
+ budget=Budget(max_usd=5.0, scope="nightly"),
86
+ )
87
+
88
+ result = await gateway.generate("small", CompletionRequest.prompt("hello"))
89
+
90
+ result.text, result.usage, result.cost_usd, result.alias, result.attempts, result.fell_back
91
+ ```
92
+
93
+ ## What it provides
94
+
95
+ | Module | Provides |
96
+ | --- | --- |
97
+ | `gateway.py` | `ModelGateway` — alias resolution, capability negotiation, ordered fallback, cost accounting, GenAI spans |
98
+ | `providers/` | The `Provider` protocol, one HTTP adapter (`OpenAICompatibleProvider`), one deterministic fake (`FakeProvider`) |
99
+ | `prompts.py` | `PromptTemplate` / `PromptRegistry` — versioned prompts, typed rendering, few-shot assembly |
100
+ | `structured.py` | `build_agent` — structured output via Pydantic AI only |
101
+ | `tools.py` | `Tool` / `ToolExecutor` — declared definitions, argument validation, structured results |
102
+ | `pipeline.py` | `Pipeline` / `PipelineContext` — plain-async named steps over a frozen context |
103
+ | `agents/` | `AgentRuntime` — the loop, transfer vs. delegate, step/token/cost budgets with bounded degrade, memory, checkpointed human-in-the-loop |
104
+ | `retrieval/` | Connectors, chunkers, the `Embedder` / `Reranker` / `VectorStore` protocols, hybrid fusion, citations, retrieval metrics |
105
+ | `evals/` | Datasets, metrics, and the statistical baseline gate |
106
+ | `tracing.py` | OTel GenAI spans: `llm_span`, `agent_span`, `record_usage`, `record_cost`, `record_attributes`, `record_hitl`, `record_exception` |
107
+ | `cost.py` | `Budget`, `CostLedger`, `estimate_cost_usd`, `estimate_tokens` |
108
+ | `types.py` | The request/response/usage/spec models everything else is typed against |
109
+
110
+ 194 names are exported. The layering is acyclic and one-directional: `errors` and `types` import nothing else in
111
+ the package, `gateway` is imported only by the package `__init__` and the eval runner, and no core module imports
112
+ a higher layer back.
113
+
114
+ ## Model pinning
115
+
116
+ An **alias resolves to an exact provider model id**, including a pinned version. That is not cosmetic: a baseline
117
+ recorded against `gpt-4o` means nothing if the alias floats to `gpt-4o-2026-…` on the next run, so an **unknown
118
+ alias is an error** (`UnknownModelAliasError`) rather than a silent fall-through to a provider default.
119
+
120
+ - `resolve(alias)` returns the `PinnedModel` (alias + `spec`); `provider_for(alias)` its provider.
121
+ - `require(alias, capabilities)` asserts the capabilities *and* returns the pinned model, checking **both** sides —
122
+ a model that supports tool calling behind an adapter that does not serialise tool definitions cannot tool-call —
123
+ and raises `CapabilityMismatchError` naming what is missing.
124
+ - `generate(alias, request, *, fallbacks=(), budget=None)` tries the alias then each fallback **in the order
125
+ given**, and reports the aliases actually attempted. Fallbacks are ordered, not conditional.
126
+ - Every charged call opens a span and updates the ledger. `CostLedger` tracks per-call `LedgerEntry` records and
127
+ yields a `SpendSummary`; `Budget` (`max_usd`, `max_total_tokens`, `scope`) is enforced *before* the call, and
128
+ `estimate_usage` / `estimate_cost_usd` price a request from a model's `CostProfile` when a caller wants to check
129
+ before spending.
130
+
131
+ ## The eval gate measures statistics, not equality
132
+
133
+ A model is **expected** to vary between runs, so a metric that compares two runs for equality is either always
134
+ red or measuring nothing. Non-determinism is not a bug to be fixed here; it is the property the gate is built to
135
+ be robust against.
136
+
137
+ - `Dataset` — versioned cases with inputs, expectations, tags and metadata; `from_records` / `from_json` /
138
+ `from_path`, `to_json`, and lookups by id (`case`) and by tag (`by_tag`).
139
+ - Metrics — `ExactMatch`, `NormalizedContains`, `JsonSchemaValid`, and `LlmJudge`. `metric_names` and
140
+ `default_metrics` cover the common set.
141
+ - `run_evaluation(dataset, runner, metrics, runs=5)` samples the runner **N times** and produces an `EvalRun` of
142
+ per-run metric means, so a single unlucky run does not decide the verdict. `evaluate_once` is the single-pass
143
+ primitive; a `DatasetRun` gives per-case outcomes and a rendered `summary()`.
144
+ - `EvalBaseline.from_run(run, model=..., note=...)` stores a baseline as JSON: per metric the sample count, mean
145
+ and spread. A committed example ships at `runtimes/python/tests/fixtures/capitals-baseline.json`.
146
+ - `BaselineGate(thresholds).evaluate(run, baseline)` compares the current sample against the baseline using a
147
+ one-sided normal test. Each `Threshold` carries a `metric`, an optional absolute `min_mean`, a
148
+ `max_regression` allowance, and an `alpha` significance level. A metric passes by clearing `min_mean`, by being
149
+ within `max_regression` of the baseline, or by regressing only within sampling noise.
150
+
151
+ Two deliberate limits:
152
+
153
+ - **`LlmJudge` is implemented and never CI-required.** A judge is itself a model call, and a gate that depends on
154
+ one non-deterministic call inside the gate you are trying to trust is the problem this design avoids.
155
+ `gateway_judge(gateway, alias)` builds the judge call when a caller wants it.
156
+ - **`GateConfigurationError` refuses a threshold on a model-derived metric**, because an N-run sample of a
157
+ probabilistic judge cannot carry a fixed threshold honestly.
158
+
159
+ `cost` is the enforced budget. A latency p95 budget belongs with dashboards, not here.
160
+
161
+ ## Retrieval
162
+
163
+ `retrieval/` is an IR-driven layer: `binding_from_spec(retriever, embedding=..., store=...)` folds the IR's
164
+ `retrievers`, `embeddings` and `stores` entries into one `RetrieverBinding`, which a `Retriever` then ingests and
165
+ searches through. The runtime consumes the names the IR emits, field for field.
166
+
167
+ - Three protocols, in the same style as `providers.Provider`: `Embedder`, `Reranker`, `VectorStore`.
168
+ - `FakeDeterministicEmbedder` maps text to a stable unit vector with a hash — keyless and offline, which is what
169
+ lets a retrieval gate run in CI. `OpenAICompatibleEmbedder` is the one hosted adapter: a single POST to
170
+ `/embeddings` over `httpx`, with the retry, timeout and error-chaining behavior of the HTTP provider.
171
+ - `LexicalReranker` is the only reranker. It is deterministic and lexical; there is no hosted rerank adapter.
172
+ - Chunk ids are **content hashes**, so re-ingesting the same input produces the same ids and a no-op diff. Ingest
173
+ is held to idempotence rather than to the byte-identical codegen guarantee.
174
+ - **Pinning.** `embed_model` names an IR `embeddings` entry and resolves at codegen time to an exact `model_id`
175
+ plus its recorded width; the resolved id, width and store `kind` travel into the generated code. An alias is
176
+ never resolved at runtime, because a baseline recorded against a floating model means nothing.
177
+ - **Cost.** Embedding calls charge the existing `CostLedger` through the existing `Budget`, using the catalog's
178
+ `CostProfile` for the pinned model. There is no retrieval-specific budgeting machinery.
179
+
180
+ `RetrievalMetric` (`RecallAtK`, `MeanReciprocalRank`, `CitationGrounding`) is deliberately a **separate protocol**
181
+ from the shipped `Metric`, which scores a single string prediction. Retrieval scores a *retrieved set*:
182
+ recall@k and MRR need the ranked ids, and citation grounding needs the passages behind the citations. Retrieval is
183
+ therefore sampled through `RetrievalGate.sample(...)`, producing a standard `EvalRun`, and then judged by the
184
+ **unchanged** `BaselineGate`. Retrieval metrics are deterministic, so they pass the gate's own eligibility check.
185
+
186
+ ### pgvector
187
+
188
+ `PgVectorStore` is a thin adapter over `psycopg` and the `vector` extension.
189
+
190
+ - It is **locally provisioned and not covered by CI.** No CI job starts a database; the in-memory adapter carries
191
+ the store tests, and both adapters share the same `VectorStore` protocol and `similarity` semantics.
192
+ `compose.pgvector.yml` in the repository brings up a database for local use.
193
+ - The `[pgvector]` extra is **import-safe when absent**: importing `aid_runtime` or `aid_runtime.retrieval` never
194
+ imports the driver, and loading the adapter raises a `ConfigurationError` naming the extra.
195
+
196
+ ## Control flow is plain async
197
+
198
+ `Pipeline` is a list of named async (or plain) steps over a `PipelineContext` that is **frozen**, so a step cannot
199
+ mutate what an earlier step observed — it returns a new context, which keeps a failed run's state inspectable. A
200
+ step may return a context, a mapping, or `None`. Each step runs in its own span, a step raising anything aborts
201
+ the run with the original exception chained (`PipelineError.__cause__`), and `StopPipeline` is the supported early
202
+ exit.
203
+
204
+ **Pydantic AI is used for structured output and nothing else** (`structured.build_agent`). The orchestration
205
+ library stays out of the control-flow path deliberately, so it remains swappable, and **no graph or orchestration
206
+ dependency is taken at all**: the agent loop in `agents/` is this package's own.
207
+
208
+ Tracing follows the OTel GenAI semantic conventions: `gen_ai.*` attributes for the operation, model, provider,
209
+ request parameters and usage, with AID-specific values namespaced `aid.*` so the two never collide. A failing call
210
+ records its exception exactly once.
211
+
212
+ ## The agent runtime
213
+
214
+ `AgentRuntime.from_ir(document, providers=..., ...)` reads the emitted IR and runs an agent to a stop condition:
215
+ model call, tool calls, observations, until a terminal answer, `max_steps`, or a budget breach. Model calls go
216
+ through `ModelGateway`, so fallback, cost accounting and tracing apply without a second implementation.
217
+
218
+ **Transfer and delegation are different, and the API says which.** `_transfer` (`handoffs`) hands the conversation
219
+ to the target and never resumes the caller, so `RunResult.agent_id` is the target and `path` grows. `_delegate`
220
+ (`delegates`) runs the target in an isolated `[system, user]` context and returns its answer as a single tool
221
+ observation, so `RunResult.agent_id` is the caller and `path` is unchanged. Both refuse to re-enter an agent
222
+ already on the path.
223
+
224
+ **A budget breach fails hard.** `BudgetExceededError` stops the run; the gateway preflight and the ledger both
225
+ enforce the ceiling. An agent declaring `on_budget_exhausted: "degrade"` (spec v0.2) instead steps exactly one rung
226
+ down its declared alias ladder — no retry loop, and the build-time gate rejects the declaration when no strictly
227
+ cheaper alias exists. Each degraded step is recorded in `StepRecord.degraded_from`, and a checkpoint carries its
228
+ current alias so a resumed run re-routes from where it stopped.
229
+
230
+ **Memory** is in-process plus one store-backed adapter. `thread` scope is the checkpointer unit: trimmed to its
231
+ `token_budget`, never written to a store. `user` and `global` scopes read and write the store and render as one
232
+ extra system message, so injection is visible in the request rather than hidden.
233
+
234
+ **Human-in-the-loop** pauses by returning a checkpoint (completed steps, pending call, current alias), and
235
+ `resume(checkpoint, decision)` continues it. The pause is recorded as an `aid.hitl` span event, not an attribute,
236
+ because a run can pause more than once.
237
+
238
+ ## Limits, stated plainly
239
+
240
+ These are refused explicitly rather than approximated — each raises `FeatureDeferredError` or a
241
+ `ConfigurationError` naming the reason:
242
+
243
+ - `ModelGateway.stream` — the transport is request/response only, and no provider advertises
244
+ `Capability.STREAMING`.
245
+ - Retrieval: non-file sources, `semantic` chunking, `incremental` refresh, retriever `filters`, a hosted
246
+ reranker, and the `qdrant` / `pinecone` / `weaviate` / `custom` store kinds.
247
+ - Escalation routing and third-party orchestration frameworks.
248
+
249
+ ## Development
250
+
251
+ From a checkout of the repository:
252
+
253
+ ```sh
254
+ pip install -e ".[dev]"
255
+ pytest
256
+ ruff check .
257
+ ruff format --check .
258
+ mypy
259
+ ```
260
+
261
+ `mypy` runs strict over `src` **and** `tests`, so the tests are type-checked too.
262
+
263
+ **Non-responsibility:** no app-specific prompts, tools, or rubrics. Those belong to the generated app's
264
+ `business/` tier — the seam this runtime is called from.
265
+
266
+ ## See also
267
+
268
+ - [`@aid-framework/runtime`](https://www.npmjs.com/package/@aid-framework/runtime) — the same runtime in
269
+ TypeScript, module for module
270
+ - [`@aid-framework/generator-py-fastapi`](https://www.npmjs.com/package/@aid-framework/generator-py-fastapi) — the
271
+ generator that emits apps against this runtime
272
+
273
+ ## License
274
+
275
+ [Apache-2.0](https://github.com/aid-framework/aid-framework/blob/main/LICENSE). Code generated by AID Framework is
276
+ not subject to this license.
@@ -1,4 +1,4 @@
1
- aid_runtime/__init__.py,sha256=E8pW04ODgOND66tyve5B8CYcSjCjZeMuX93Mey_o0I0,11009
1
+ aid_runtime/__init__.py,sha256=yA0v2rlJEFNknADLofgxAgVW1i78O5gAdkkUa6ZsoDc,11009
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=u4U97QFdYSSjOPY3D6f1-GZhkGhygEdR-apdgw_jJok,13797
@@ -38,7 +38,7 @@ aid_runtime/retrieval/chunking.py,sha256=GMJvY1GoIua-FkpCH1S5qNmUrWSaSbl6sBJPCrS
38
38
  aid_runtime/retrieval/citations.py,sha256=UL9fsxLTzzO0n8tEW3X2O5erJ0hrk08NYMkZ9Pk8Jdg,4287
39
39
  aid_runtime/retrieval/connectors.py,sha256=JNEwq6S8zKX1GdlWe4Gn2Rdon87DWXlG_WNQfZTlN34,4744
40
40
  aid_runtime/retrieval/embedding.py,sha256=ZPjALe_nEzYpa8N5COExPGrojjZFX8awTz6vzJYfx_4,12374
41
- aid_runtime/retrieval/gate.py,sha256=fxrI7Og9d3J-NKUcn3QI-2N4K3o4-LQehXxCK19qzCM,4842
41
+ aid_runtime/retrieval/gate.py,sha256=3avH1Gwp7iv7mMOskmNbk70Yq85tXwJrKVrQAKKI4Js,4840
42
42
  aid_runtime/retrieval/hybrid.py,sha256=-GIBeI3njT5uaEvSeq2t151Zlv2yOPHOPje4TJLNVyU,5804
43
43
  aid_runtime/retrieval/metrics.py,sha256=LN36BIXzpbhkG9grzE0q5wncgXt_Y85-b5jGJ038-3Y,7904
44
44
  aid_runtime/retrieval/pgvector.py,sha256=kdE6Gdk9JhR6-QxN353CmuNYMLyr5eBvnQl4krLzLew,10040
@@ -46,7 +46,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
46
46
  aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
47
47
  aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
48
48
  aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
49
- aid_runtime_python-0.1.39.dist-info/METADATA,sha256=NqIxXTImMqSvUWC2zPniEyZoopmh3ByGXVD2ICZVOGI,16364
50
- aid_runtime_python-0.1.39.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
51
- aid_runtime_python-0.1.39.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
52
- aid_runtime_python-0.1.39.dist-info/RECORD,,
49
+ aid_runtime_python-0.1.48.dist-info/METADATA,sha256=lu5Id8N5V5c5J9iJfPNGIIAmd5sVr6ZCk_0SiOgrJ9E,15559
50
+ aid_runtime_python-0.1.48.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
51
+ aid_runtime_python-0.1.48.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
52
+ aid_runtime_python-0.1.48.dist-info/RECORD,,
@@ -1,268 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: aid-runtime-python
3
- Version: 0.1.39
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
- Author: The AID Framework authors
6
- License-Expression: Apache-2.0
7
- Project-URL: Homepage, https://github.com/aid-framework/aid-framework
8
- Project-URL: Documentation, https://github.com/aid-framework/aid-framework/blob/main/docs/design.md
9
- Project-URL: Issues, https://github.com/aid-framework/aid-framework/issues
10
- Keywords: ai,codegen,llm,evals,opentelemetry,pydantic
11
- Classifier: Development Status :: 3 - Alpha
12
- Classifier: Intended Audience :: Developers
13
- Classifier: Programming Language :: Python :: 3
14
- Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: Programming Language :: Python :: 3.13
17
- Classifier: Typing :: Typed
18
- Requires-Python: >=3.11
19
- Description-Content-Type: text/markdown
20
- Requires-Dist: httpx<1,>=0.27
21
- Requires-Dist: opentelemetry-api<2,>=1.24
22
- Requires-Dist: pydantic<3,>=2.7
23
- Requires-Dist: pydantic-ai-slim<3,>=2
24
- Provides-Extra: pgvector
25
- Requires-Dist: psycopg[binary]<4,>=3.1; extra == "pgvector"
26
- Provides-Extra: deepagents
27
- Requires-Dist: deepagents==0.7.32; extra == "deepagents"
28
- Provides-Extra: dev
29
- Requires-Dist: mypy<3,>=1.11; extra == "dev"
30
- Requires-Dist: opentelemetry-sdk<2,>=1.24; extra == "dev"
31
- Requires-Dist: pytest<10,>=8; extra == "dev"
32
- Requires-Dist: pytest-asyncio<2,>=0.24; extra == "dev"
33
- Requires-Dist: ruff<1,>=0.6; extra == "dev"
34
-
35
- # AID runtime — Python
36
-
37
- The Python runtime library: the behavior layer imported by apps generated by the
38
- [`py-fastapi`](../../packages/generators/py-fastapi/) generator. Generated code is thin glue; this is where
39
- the behavior lives ([`docs/design.md` §4](../../docs/design.md), principle 1).
40
-
41
- Distribution name **`aid-runtime-python`**, import package **`aid_runtime`**. The two differ deliberately: a
42
- distribution name is conventionally hyphenated, and a Python import package cannot be. That asymmetry is
43
- asserted in `tests/test_package.py` so it cannot drift.
44
-
45
- Requires Python 3.11+.
46
-
47
- ```sh
48
- pip install -e ".[dev]" # the runtime plus its test/lint/type tooling
49
- pytest -q
50
- pip install -e ".[pgvector]" # only if you want the pgvector store adapter
51
- ```
52
-
53
- ## What it provides
54
-
55
- | Module | Provides |
56
- | --- | --- |
57
- | `gateway.py` | `ModelGateway` — alias resolution, capability negotiation, ordered fallback, cost accounting, GenAI spans |
58
- | `providers/` | The `Provider` protocol, one HTTP adapter (`OpenAICompatibleProvider`), and one deterministic fake (`FakeProvider`) |
59
- | `prompts.py` | `PromptTemplate` / `PromptRegistry` — versioned prompts, typed rendering, few-shot assembly |
60
- | `structured.py` | `build_agent` — structured output via Pydantic AI only |
61
- | `tools.py` | `Tool` / `ToolExecutor` — declared definitions, argument validation, structured results |
62
- | `pipeline.py` | `Pipeline` / `PipelineContext` — plain-async named steps over a frozen context |
63
- | `agents/` | The native agent runtime: `AgentRuntime` — the loop, transfer vs. delegate, step/token/cost budgets with bounded degrade, memory, and a checkpointed human-in-the-loop pause |
64
- | `retrieval/` | Retrieval: connectors, chunkers, the `Embedder` / `Reranker` / `VectorStore` protocols, hybrid fusion, citations, and retrieval metrics |
65
- | `evals/` | Datasets, metrics, and the statistical baseline gate |
66
- | `tracing.py` | OTel GenAI spans: `llm_span`, `agent_span`, `record_usage`, `record_cost`, `record_attributes`, `record_hitl`, `record_exception` |
67
- | `cost.py` | `Budget`, `CostLedger`, `estimate_cost_usd`, `estimate_tokens` |
68
- | `types.py` | The request/response/usage/spec models everything else is typed against |
69
-
70
- 194 names are exported from `aid_runtime`. The layering is acyclic and one-directional: `errors` and `types` import
71
- nothing else in the package, `gateway` is imported only by the package `__init__` and the eval runner, and no
72
- core module imports a higher layer back.
73
-
74
- ## Model pinning
75
-
76
- An **alias resolves to an exact provider model id**, including a pinned version. That is not cosmetic: a
77
- baseline recorded against `gpt-4o` means nothing if the alias floats to `gpt-4o-2026-…` on the next run, so an
78
- **unknown alias is an error** (`UnknownModelAliasError`) rather than a silent fall-through to a provider
79
- default.
80
-
81
- ```python
82
- from aid_runtime import (
83
- Budget,
84
- CompletionRequest,
85
- CostProfile,
86
- ModelGateway,
87
- ModelSpec,
88
- OpenAICompatibleProvider,
89
- PinnedModel,
90
- )
91
-
92
- spec = ModelSpec(
93
- name="gpt-4o-2024-08-06",
94
- provider="openai-compatible",
95
- cost=CostProfile(input_per_1k_usd=0.0025, output_per_1k_usd=0.01),
96
- context_window=128_000,
97
- max_output_tokens=4096,
98
- )
99
-
100
- gateway = ModelGateway(
101
- providers={"openai-compatible": OpenAICompatibleProvider(api_key=...)},
102
- aliases={"small": PinnedModel(alias="small", spec=spec)},
103
- budget=Budget(max_usd=5.0, scope="nightly"),
104
- )
105
-
106
- result = await gateway.generate("small", CompletionRequest.prompt("hello"))
107
- result.text, result.usage, result.cost_usd, result.alias, result.attempts, result.fell_back
108
- ```
109
-
110
- - `resolve(alias)` returns the `PinnedModel` (alias + `spec`); `provider_for(alias)` its provider. `require(alias,
111
- capabilities)` asserts the capabilities *and* returns the pinned model, checking **both** sides — a model that
112
- supports tool calling behind an adapter that does not serialise tool definitions cannot tool-call — and raises
113
- `CapabilityMismatchError` naming what is missing.
114
- - `generate(alias, request, *, fallbacks=(), budget=None)` tries the alias then each fallback **in the order
115
- given**, and reports the aliases actually attempted on the result. Fallbacks are ordered, not conditional.
116
- - Every charged call opens a span and updates the ledger. `CostLedger` tracks per-call `LedgerEntry` records
117
- and yields a `SpendSummary`; `Budget` (`max_usd`, `max_total_tokens`, `scope`) is enforced before the call,
118
- and `estimate_usage` / `estimate_cost_usd` price a request from a model's `CostProfile` when a caller wants
119
- to check before spending.
120
-
121
- ## The eval harness gates on statistics, not equality
122
-
123
- Phase 0 ratifies sampling-based gating: a model is **expected** to vary between runs, so a metric that
124
- compares two runs for equality is either always red or measuring nothing. Non-determinism here is not a bug to
125
- be fixed; it is the property the gate has to be robust against.
126
-
127
- - `Dataset` — versioned cases with inputs, expectations, tags and metadata; `from_records` / `from_json` /
128
- `from_path`, `to_json`, and lookups by id (`case`) and by tag (`by_tag`).
129
- - Metrics — `ExactMatch`, `NormalizedContains`, `JsonSchemaValid`, and `LlmJudge`. `metric_names` and
130
- `default_metrics` cover the common set.
131
- - `run_evaluation(dataset, runner, metrics, runs=5)` samples the runner **N times** and produces an `EvalRun`
132
- of per-run metric means, so a single unlucky run does not decide the verdict. `evaluate_once` is the
133
- single-pass primitive; a `DatasetRun` gives per-case outcomes and a rendered `summary()`.
134
- - `EvalBaseline.from_run(run, model=..., note=...)` stores a baseline as JSON: per metric the sample count,
135
- mean and spread. `runtimes/python/tests/fixtures/capitals-baseline.json` is a committed example.
136
- - `BaselineGate(thresholds).evaluate(run, baseline)` compares the current sample against the baseline using a
137
- one-sided normal test, with each `Threshold` carrying `metric`, an optional absolute `min_mean`, a
138
- `max_regression` allowance, and an `alpha` significance level. A metric passes by clearing `min_mean`, by
139
- being within `max_regression` of the baseline, or by regressing only within sampling noise.
140
-
141
- Two deliberate limits:
142
-
143
- - **`LlmJudge` is implemented and never CI-required.** A judge is itself a model call, and a gate that
144
- depends on one non-deterministic call inside the gate you are trying to trust is the problem this design
145
- avoids. `gateway_judge(gateway, alias)` builds the judge call when a caller wants it.
146
- - **`GateConfigurationError` refuses a threshold on a model-derived metric**, because an N-run sample of a
147
- probabilistic judge cannot carry a fixed threshold honestly.
148
-
149
- `cost` is the enforced budget; a latency p95 budget belongs with Phase 2 dashboards, not here.
150
-
151
- ## Retrieval
152
-
153
- `retrieval/` is an IR-driven layer: `binding_from_spec(retriever, embedding=..., store=...)` folds the IR's
154
- `retrievers`, `embeddings` and `stores` entries into one `RetrieverBinding`, which a `Retriever` then ingests
155
- and searches through. The runtime consumes the names the IR emits, field for field.
156
-
157
- - Three protocols, in the same style as `providers.Provider`: `Embedder`, `Reranker`, `VectorStore`. Phase 1
158
- ships the implementations listed below and no others.
159
- - `FakeDeterministicEmbedder` maps text to a stable unit vector with a hash — keyless and offline, which is
160
- what lets a retrieval gate run in CI. `OpenAICompatibleEmbedder` is the one hosted adapter: a single POST to
161
- `/embeddings` over `httpx`, with the retry, timeout and error-chaining behaviour of the HTTP provider.
162
- - `LexicalReranker` is the only reranker. It is deterministic and lexical; there is no hosted rerank adapter.
163
- - Chunk ids are **content hashes**, so re-ingesting the same input produces the same ids and a no-op diff.
164
- Ingest is therefore held to idempotence rather than to the byte-identical codegen guarantee.
165
- - **Pinning.** `embedModel` names an IR `embeddings` entry and resolves at codegen time to an exact `modelId`
166
- plus its recorded width; the resolved id, width and store `kind` travel into the generated code. An alias is
167
- never resolved at runtime, because a baseline recorded against a floating model means nothing.
168
- - **Cost.** Embedding calls charge the existing `CostLedger` through the existing `Budget`, using the catalog's
169
- `CostProfile` for the pinned model. There is no retrieval-specific budgeting machinery.
170
-
171
- `RetrievalMetric` (`RecallAtK`, `MeanReciprocalRank`, `CitationGrounding`) is deliberately a **separate
172
- protocol** from the shipped `Metric`, which scores a single string prediction. Retrieval scores a *retrieved
173
- set*: recall@k and MRR need the ranked ids, and citation-grounding needs the passages behind the citations.
174
- Widening `Metric` would have changed an interface the existing gate already threshold-checks, for every
175
- existing implementation — so retrieval is sampled through `RetrievalGate.sample(...)` instead, producing a
176
- standard `EvalRun`, and then judged by the **unchanged** `BaselineGate`. Retrieval metrics are deterministic,
177
- so they pass the gate's own eligibility check.
178
-
179
- ### pgvector
180
-
181
- `PgVectorStore` is a thin adapter over `psycopg` and the `vector` extension. Two consequences worth stating:
182
-
183
- - It is **locally provisioned and not covered by any gate.** No CI job starts a database, and no required
184
- check touches one; the in-memory adapter carries the store gates, and the two adapters share the same
185
- `VectorStore` protocol and the same `similarity` semantics. `compose.pgvector.yml` beside this README brings
186
- up a database for local use.
187
- - The `[pgvector]` extra is **import-safe when absent**: importing `aid_runtime` or `aid_runtime.retrieval`
188
- never imports the driver, and the adapter loading it raises a `ConfigurationError` naming the extra.
189
-
190
- ## Control flow is plain async
191
-
192
- `Pipeline` is a list of named async (or plain) steps over a `PipelineContext` that is **frozen**, so a step
193
- cannot mutate what an earlier step observed — it returns a new context, which keeps a failed run's state
194
- inspectable. A step may return a context, a mapping, or `None`. Each step runs in its own span, a step raising
195
- anything aborts the run with the original exception chained (`PipelineError.__cause__`), and `StopPipeline` is
196
- the supported early exit.
197
-
198
- **Pydantic AI is used for structured output and nothing else** (`structured.build_agent`). The orchestration
199
- library stays out of the control-flow path deliberately, so it remains swappable, and **no graph/orchestration
200
- dependency is taken at all**: the agent loop in `agents/` is this package's own, and escalation routing and
201
- third-party orchestration frameworks remain out of scope ([`docs/design.md` §14](../../docs/design.md)).
202
-
203
- Tracing follows the OTel GenAI semantic conventions: `gen_ai.*` attributes for the operation, model, provider,
204
- request parameters and usage, with AID-specific values namespaced `aid.*` so the two never collide. A failing
205
- call records its exception exactly once.
206
-
207
- ## The agent runtime
208
-
209
- `AgentRuntime.from_ir(document, providers=..., ...)` reads the emitted IR and runs an agent to a stop
210
- condition: model call, tool calls, observations, until a terminal answer, `maxSteps`, or a budget breach.
211
- Model calls go through `ModelGateway`, so fallback, cost accounting and tracing apply without a second
212
- implementation.
213
-
214
- **Transfer and delegation are different, and the API says which.** `_transfer` (`handoffs`) hands the
215
- conversation to the target and never resumes the caller, so `RunResult.agent_id` is the target and `path`
216
- grows. `_delegate` (`delegates`) runs the target in an isolated `[system, user]` context and returns its answer
217
- as a single tool observation, so `RunResult.agent_id` is the caller and `path` is unchanged. Both refuse to
218
- re-enter an agent already on the path.
219
-
220
- **A budget breach fails hard.** `BudgetExceededError` stops the run; the gateway preflight and the ledger both
221
- enforce the ceiling. An agent declaring `onBudgetExhausted: 'degrade'` (v0.2) instead steps exactly one rung
222
- down its declared alias ladder — no retry loop, and the build-time gate rejects the declaration when no
223
- strictly cheaper alias exists. Each degraded step is recorded in `StepRecord.degraded_from`, and a checkpoint
224
- carries its current alias so a resumed run re-routes from where it stopped.
225
-
226
- **Memory** is in-process plus one store-backed adapter. `thread` scope is the checkpointer unit: trimmed to its
227
- `tokenBudget`, never written to a store. `user` and `global` scopes read and write the store and render as one
228
- extra system message, so injection is visible in the request rather than hidden.
229
-
230
- **Human-in-the-loop** pauses by returning a checkpoint (completed steps, pending call, current alias), and
231
- `resume(checkpoint, decision)` continues it. The pause is recorded as an `aid.hitl` span event, not an
232
- attribute, because a run can pause more than once.
233
-
234
- ## Development
235
-
236
- Four gates, all run by the `python` job in [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) over
237
- real content:
238
-
239
- ```sh
240
- pytest
241
- ruff check .
242
- ruff format --check .
243
- mypy
244
- ```
245
-
246
- `mypy` runs strict over `src` **and** `tests`, so the tests are type-checked too. The `python` job is a real
247
- gate but is **advisory**: the `main` ruleset requires the `node`, `workflows` and `licenses` contexts only.
248
-
249
- `tests/fixtures/capitals-baseline.json` is regenerated from `FakeProvider(accuracy=0.6, seed=0)` over 10 runs
250
- — the fake is seeded and deterministic per call, so the committed baseline reproduces exactly while a fresh
251
- sample of it still varies, which is exactly the property the gate has to tolerate.
252
-
253
- **Non-responsibility:** no app-specific prompts, tools, or rubrics. Those belong to the generated app's
254
- `business/` tier ([`docs/design.md` §8.4](../../docs/design.md), the seam).
255
-
256
- **Status:** Phase 0 scope implemented, plus the Phase 1 retrieval runtime. One thing deferred and
257
- undeclared, on purpose: `ModelGateway.stream` raises `FeatureDeferredError`, and no provider advertises
258
- `Capability.STREAMING` or target declares the capability, because the transport is request/response-only.
259
- Retrieval likewise fails loudly rather than
260
- approximating: non-file sources, `semantic` chunking, `incremental` refresh, retriever `filters`, a hosted
261
- reranker, and the `qdrant` / `pinecone` / `weaviate` / `custom` store kinds all raise `FeatureDeferredError`.
262
- Also deferred (§14): escalation routing, memory, guardrails, prompt/semantic caching, rate limiting, token
263
- buckets, and adapters beyond the one HTTP provider and the fake.
264
-
265
- Emitting retrieval into a generated app and indexing it from the CLI are later layers, so this package adds no
266
- entry point for either.
267
-
268
- Reference: [`docs/design.md` §9, §12, §14, §17 #2](../../docs/design.md).