aid-runtime-python 0.1.94__tar.gz → 0.1.96__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.
Files changed (105) hide show
  1. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/PKG-INFO +1 -1
  2. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/pyproject.toml +1 -1
  3. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/__init__.py +7 -1
  4. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/control.py +90 -2
  5. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/decisions.py +38 -2
  6. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/tracing.py +26 -6
  7. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
  8. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_control.py +127 -1
  9. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_decisions.py +82 -1
  10. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/README.md +0 -0
  11. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/setup.cfg +0 -0
  12. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/__init__.py +0 -0
  13. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/chat_model.py +0 -0
  14. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/deep_agents.py +0 -0
  15. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/engine.py +0 -0
  16. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/guardrails.py +0 -0
  17. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/ir.py +0 -0
  18. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/loop.py +0 -0
  19. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/memory.py +0 -0
  20. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/policy.py +0 -0
  21. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/agents/state.py +0 -0
  22. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/cache.py +0 -0
  23. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/concurrency.py +0 -0
  24. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/cost.py +0 -0
  25. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/errors.py +0 -0
  26. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/evals/__init__.py +0 -0
  27. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/evals/dataset.py +0 -0
  28. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/evals/gate.py +0 -0
  29. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/evals/metrics.py +0 -0
  30. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/evals/predicate.py +0 -0
  31. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/evals/runner.py +0 -0
  32. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/gateway.py +0 -0
  33. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/local_trace.py +0 -0
  34. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/pipeline.py +0 -0
  35. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/prompts.py +0 -0
  36. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/providers/__init__.py +0 -0
  37. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/providers/anthropic.py +0 -0
  38. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/providers/base.py +0 -0
  39. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/providers/bedrock.py +0 -0
  40. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/providers/fake.py +0 -0
  41. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/providers/http.py +0 -0
  42. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/providers/vertex.py +0 -0
  43. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/py.typed +0 -0
  44. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/__init__.py +0 -0
  45. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/chunking.py +0 -0
  46. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/citations.py +0 -0
  47. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/connectors.py +0 -0
  48. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/embedding.py +0 -0
  49. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/gate.py +0 -0
  50. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/hybrid.py +0 -0
  51. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/metrics.py +0 -0
  52. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/pgvector.py +0 -0
  53. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/rerank.py +0 -0
  54. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/retriever.py +0 -0
  55. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/stores.py +0 -0
  56. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/retrieval/types.py +0 -0
  57. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/steps.py +0 -0
  58. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/structured.py +0 -0
  59. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/tools.py +0 -0
  60. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime/types.py +0 -0
  61. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime_python.egg-info/SOURCES.txt +0 -0
  62. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
  63. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime_python.egg-info/requires.txt +0 -0
  64. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
  65. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_agents_budget.py +0 -0
  66. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_agents_deep_agents.py +0 -0
  67. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_agents_hitl.py +0 -0
  68. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_agents_loop.py +0 -0
  69. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_agents_memory.py +0 -0
  70. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_anthropic_provider.py +0 -0
  71. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_bedrock_provider.py +0 -0
  72. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_cache.py +0 -0
  73. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_concurrency.py +0 -0
  74. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_cost.py +0 -0
  75. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_dataset.py +0 -0
  76. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_evals.py +0 -0
  77. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_evals_assert_gate.py +0 -0
  78. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_evals_decision.py +0 -0
  79. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_evals_gate.py +0 -0
  80. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_evals_predicate.py +0 -0
  81. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_gateway.py +0 -0
  82. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_guardrails.py +0 -0
  83. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_http_provider.py +0 -0
  84. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_local_trace.py +0 -0
  85. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_package.py +0 -0
  86. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_pipeline.py +0 -0
  87. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_prompts.py +0 -0
  88. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_chunking.py +0 -0
  89. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_citations.py +0 -0
  90. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_connectors.py +0 -0
  91. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_embedding.py +0 -0
  92. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_gate.py +0 -0
  93. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_hybrid.py +0 -0
  94. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_metrics.py +0 -0
  95. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_rerank.py +0 -0
  96. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_stores.py +0 -0
  97. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_retrieval_types.py +0 -0
  98. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_steps.py +0 -0
  99. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_streaming.py +0 -0
  100. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_structured.py +0 -0
  101. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_tool_permissions.py +0 -0
  102. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_tools.py +0 -0
  103. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_tracing.py +0 -0
  104. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/tests/test_types.py +0 -0
  105. {aid_runtime_python-0.1.94 → aid_runtime_python-0.1.96}/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.94
3
+ Version: 0.1.96
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.94"
7
+ version = "0.1.96"
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"
@@ -60,6 +60,7 @@ from aid_runtime.control import (
60
60
  map_step,
61
61
  parallel,
62
62
  reduce_step,
63
+ route,
63
64
  )
64
65
  from aid_runtime.cost import (
65
66
  Budget,
@@ -71,6 +72,7 @@ from aid_runtime.cost import (
71
72
  )
72
73
  from aid_runtime.decisions import (
73
74
  DEFAULT_TYPESAFE_BASE_URL,
75
+ JEV_INPUT_USD_PER_MTOK,
74
76
  JEV_MOVING_ALIASES,
75
77
  TYPESAFE_API_KEY_ENVS,
76
78
  TYPESAFE_BASE_URL_ENV,
@@ -78,6 +80,7 @@ from aid_runtime.decisions import (
78
80
  DecisionClient,
79
81
  DecisionQuestion,
80
82
  DecisionResponse,
83
+ decision_cost_usd,
81
84
  decision_key,
82
85
  is_reproducible_model,
83
86
  )
@@ -294,7 +297,7 @@ from aid_runtime.types import (
294
297
  )
295
298
 
296
299
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
297
- __version__ = "0.1.94"
300
+ __version__ = "0.1.96"
298
301
 
299
302
  __all__ = [
300
303
  "ANTHROPIC_VERSION",
@@ -310,6 +313,7 @@ __all__ = [
310
313
  "GEN_AI_OPERATION_CHAT",
311
314
  "INDEX_KEY",
312
315
  "ITEM_KEY",
316
+ "JEV_INPUT_USD_PER_MTOK",
313
317
  "JEV_MOVING_ALIASES",
314
318
  "LIMITER_KEY",
315
319
  "MAX_STEP_DEPTH",
@@ -498,6 +502,7 @@ __all__ = [
498
502
  "chunker_for",
499
503
  "cite",
500
504
  "create_store",
505
+ "decision_cost_usd",
501
506
  "decision_key",
502
507
  "default_bedrock_base_url",
503
508
  "default_metrics",
@@ -539,6 +544,7 @@ __all__ = [
539
544
  "resolve_uri",
540
545
  "retrieval_metrics",
541
546
  "retrieve_step",
547
+ "route",
542
548
  "rrf_score",
543
549
  "run_evaluation",
544
550
  "run_structured",
@@ -1,4 +1,4 @@
1
- """Composite pipeline steps: ``branch``, ``parallel``, ``map`` and ``reduce``.
1
+ """Composite pipeline steps: ``branch``, ``route``, ``parallel``, ``map`` and ``reduce``.
2
2
 
3
3
  :class:`~aid_runtime.pipeline.Pipeline` is a sequential reducer, and it stays one.
4
4
  Each factory here returns an ordinary :data:`~aid_runtime.pipeline.Step`, so a
@@ -27,13 +27,18 @@ from __future__ import annotations
27
27
 
28
28
  import asyncio
29
29
  from collections.abc import Awaitable, Callable, Mapping, Sequence
30
- from typing import Any, TypeVar
30
+ from typing import TYPE_CHECKING, Any, TypeVar
31
31
 
32
32
  from aid_runtime.agents.policy import Principal, evaluate_policy, policy_source
33
33
  from aid_runtime.concurrency import ConcurrencyLimiter, holds_slot
34
+ from aid_runtime.decisions import DecisionClient, DecisionQuestion
34
35
  from aid_runtime.errors import PipelineError
35
36
  from aid_runtime.pipeline import STEPS_KEY, Pipeline, PipelineContext
36
37
 
38
+ if TYPE_CHECKING:
39
+ from aid_runtime.agents.guardrails import DecisionAsker
40
+ from aid_runtime.agents.ir import DecisionDefinition
41
+
37
42
  __all__ = [
38
43
  "DEPTH_KEY",
39
44
  "INDEX_KEY",
@@ -47,6 +52,7 @@ __all__ = [
47
52
  "map_step",
48
53
  "parallel",
49
54
  "reduce_step",
55
+ "route",
50
56
  ]
51
57
 
52
58
  #: Deepest composite nesting a pipeline may declare.
@@ -208,6 +214,88 @@ def branch(
208
214
  return _named(_branch, name)
209
215
 
210
216
 
217
+ def route(
218
+ *,
219
+ decision: str,
220
+ state: str,
221
+ on: Mapping[str, Pipeline],
222
+ otherwise: Pipeline | None = None,
223
+ as_: str | None = None,
224
+ decisions: Mapping[str, DecisionDefinition] | None = None,
225
+ client_factory: Callable[[], DecisionAsker] | None = None,
226
+ max_depth: int = MAX_STEP_DEPTH,
227
+ name: str | None = None,
228
+ ) -> CompositeStep:
229
+ """Ask one ``choice`` decision which arm to run, then run that arm.
230
+
231
+ This is the one composite that asks a model a question, and it is the difference
232
+ between a ``branch`` and a ``route``: a branch's predicate is a policy over the
233
+ caller, so it can only answer who is asking. A route's question is asked about
234
+ ``state`` -- the rendered text of what the pipeline has produced so far -- so it
235
+ can answer what the request *means*.
236
+
237
+ Every way the question can fail fails the run rather than picking an arm:
238
+ a decision with no definition in this runtime, a client that raises, an answer
239
+ with no choice, and a label no arm maps. A default is deliberately not a fourth
240
+ outcome; it is the arm an *unexpected* label runs, and the spec gate refuses a
241
+ default that a mapped set already covers.
242
+
243
+ ``as_`` binds the label that was answered -- including one that fell through to
244
+ ``otherwise`` -- so a later step can name the arm that ran rather than re-deriving
245
+ it. The client is built on first use, not when the pipeline is assembled: an app
246
+ with no TypeSafe key still boots as long as no request reaches a route.
247
+ """
248
+ declared = dict(decisions or {})
249
+ factory = client_factory or DecisionClient
250
+ client: DecisionAsker | None = None
251
+
252
+ async def _route(context: PipelineContext) -> PipelineContext:
253
+ nonlocal client
254
+ nested = _enter(context, max_depth, f"route ({decision})")
255
+ definition = declared.get(decision)
256
+ if definition is None:
257
+ raise PipelineError(
258
+ f"route needs a definition for decision {decision!r}; the generated app "
259
+ f"carries one for every decision its routes name"
260
+ )
261
+ if client is None:
262
+ client = factory()
263
+ question = DecisionQuestion(
264
+ type="choice",
265
+ instructions=definition.instructions,
266
+ criteria=definition.criteria,
267
+ )
268
+ try:
269
+ response = await client.decide(
270
+ model=definition.model,
271
+ state=state,
272
+ questions={decision: question},
273
+ )
274
+ except Exception as error:
275
+ raise PipelineError(f"route decision {decision!r} could not answer: {error}") from error
276
+ answer = response.answers.get(decision)
277
+ label = None if answer is None else answer.choice
278
+ if label is None:
279
+ raise PipelineError(
280
+ f"route decision {decision!r} returned no choice, so no arm can be "
281
+ f"selected; a route does not guess which one was meant"
282
+ )
283
+ chosen = on.get(label)
284
+ if chosen is None:
285
+ if otherwise is None:
286
+ raise PipelineError(
287
+ f"route decision {decision!r} answered {label!r}, which no arm maps "
288
+ f"and no `default` catches"
289
+ )
290
+ chosen = otherwise
291
+ _, added = await _run_body(chosen, nested)
292
+ if as_ is not None:
293
+ added[as_] = label
294
+ return _escape(context.with_values(**added))
295
+
296
+ return _named(_route, name)
297
+
298
+
211
299
  def parallel(
212
300
  *,
213
301
  branches: Sequence[Pipeline],
@@ -38,9 +38,12 @@ from typing import Any, Literal
38
38
  import httpx
39
39
 
40
40
  from aid_runtime.errors import ConfigurationError, ProviderError, ProviderResponseError
41
+ from aid_runtime.tracing import llm_span, record_attributes, record_cost, record_usage
42
+ from aid_runtime.types import TokenUsage
41
43
 
42
44
  __all__ = [
43
45
  "DEFAULT_TYPESAFE_BASE_URL",
46
+ "JEV_INPUT_USD_PER_MTOK",
44
47
  "JEV_MOVING_ALIASES",
45
48
  "TYPESAFE_API_KEY_ENVS",
46
49
  "TYPESAFE_BASE_URL_ENV",
@@ -48,6 +51,7 @@ __all__ = [
48
51
  "DecisionClient",
49
52
  "DecisionQuestion",
50
53
  "DecisionResponse",
54
+ "decision_cost_usd",
51
55
  "decision_key",
52
56
  "is_reproducible_model",
53
57
  ]
@@ -64,6 +68,11 @@ TYPESAFE_BASE_URL_ENV = "TYPESAFE_BASE_URL"
64
68
  #: ``reproducible=True``.
65
69
  JEV_MOVING_ALIASES = frozenset({"jev-latest", "jev-preview"})
66
70
 
71
+ #: Jev bills input tokens at $42 per billion ($0.042 per million) and states that
72
+ #: output tokens are free. A call therefore needs an input row only, and a
73
+ #: decision run must never be reported as unpriceable.
74
+ JEV_INPUT_USD_PER_MTOK = 0.042
75
+
67
76
  QuestionType = Literal["choice", "score", "noul"]
68
77
 
69
78
  _QUESTION_TYPES: frozenset[str] = frozenset({"choice", "score", "noul"})
@@ -93,6 +102,19 @@ def is_reproducible_model(model: str) -> bool:
93
102
  return model not in JEV_MOVING_ALIASES
94
103
 
95
104
 
105
+ def decision_cost_usd(input_tokens: int | None) -> float:
106
+ """Price one decision call from its input tokens alone.
107
+
108
+ Output tokens are free by contract, so they are deliberately not part of the
109
+ arithmetic: a caller that passed a total would overcharge the run. ``None``
110
+ means the vendor reported no usage; :meth:`DecisionClient.decide` then records
111
+ no cost at all, so the call stays unknown rather than free.
112
+ """
113
+ if input_tokens is None:
114
+ return 0.0
115
+ return (input_tokens / 1_000_000) * JEV_INPUT_USD_PER_MTOK
116
+
117
+
96
118
  @dataclass(frozen=True, slots=True)
97
119
  class DecisionQuestion:
98
120
  """One typed question.
@@ -228,8 +250,22 @@ class DecisionClient:
228
250
  "state": state,
229
251
  "questions": {key: question.as_payload() for key, question in questions.items()},
230
252
  }
231
- body = await self._post(payload)
232
- return self._parse(body, questions)
253
+ # A decision is billed like any other model call, so it gets the same
254
+ # span: `aid cost` and the eval budget read `aid.cost.usd` off it.
255
+ with llm_span(model=model, provider=self._name, operation="decision") as span:
256
+ body = await self._post(payload)
257
+ response = self._parse(body, questions)
258
+ if response.input_tokens is not None:
259
+ usage = TokenUsage(
260
+ input_tokens=response.input_tokens,
261
+ output_tokens=response.output_tokens or 0,
262
+ )
263
+ record_usage(span, usage)
264
+ record_cost(span, decision_cost_usd(usage.input_tokens))
265
+ # The vendor echoes the version that actually answered, which is the
266
+ # only record of what a moving alias resolved to.
267
+ record_attributes(span, response_model=response.model)
268
+ return response
233
269
 
234
270
  async def close(self) -> None:
235
271
  if self._closed:
@@ -14,8 +14,8 @@ that must not decide a host application's telemetry setup for it.
14
14
  from __future__ import annotations
15
15
 
16
16
  import contextlib
17
- from collections.abc import Iterator
18
- from typing import TYPE_CHECKING, Any
17
+ from collections.abc import Iterator, Sequence
18
+ from typing import Any, Protocol
19
19
 
20
20
  from opentelemetry import trace
21
21
  from opentelemetry.trace import Span, SpanKind, Status, StatusCode
@@ -23,12 +23,10 @@ from opentelemetry.trace import Span, SpanKind, Status, StatusCode
23
23
  from aid_runtime.local_trace import finish_span, wrap_span
24
24
  from aid_runtime.types import TokenUsage
25
25
 
26
- if TYPE_CHECKING:
27
- from aid_runtime.agents.guardrails import GuardrailRecord
28
-
29
26
  __all__ = [
30
27
  "ATTRIBUTES",
31
28
  "GEN_AI_OPERATION_CHAT",
29
+ "GuardrailEvent",
32
30
  "agent_span",
33
31
  "aid_attributes",
34
32
  "get_tracer",
@@ -226,7 +224,29 @@ def record_hitl(
226
224
  span.add_event("aid.hitl", attributes)
227
225
 
228
226
 
229
- def record_guardrail(span: Span, record: GuardrailRecord) -> None:
227
+ class GuardrailEvent(Protocol):
228
+ """The fields :func:`record_guardrail` reads from a fired guardrail.
229
+
230
+ Structural on purpose. Importing ``GuardrailRecord`` would close a module cycle --
231
+ ``guardrails`` imports the decision client, which imports this module, which would
232
+ import ``guardrails`` again -- and a protocol keeps the annotation honest without
233
+ the import.
234
+ """
235
+
236
+ @property
237
+ def guardrail(self) -> str: ...
238
+
239
+ @property
240
+ def stage(self) -> str: ...
241
+
242
+ @property
243
+ def action(self) -> str: ...
244
+
245
+ @property
246
+ def policies(self) -> Sequence[str]: ...
247
+
248
+
249
+ def record_guardrail(span: Span, record: GuardrailEvent) -> None:
230
250
  """Record one guardrail hit as an ``aid.guardrail`` span event."""
231
251
  span.add_event(
232
252
  "aid.guardrail",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.94
3
+ Version: 0.1.96
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
- """The composite step family: branch, parallel, map and reduce.
1
+ """The composite step family: branch, parallel, map, reduce and route.
2
2
 
3
3
  Each test drives real pipelines rather than asserting that the factories were
4
4
  called, because every property this family promises -- the cap, the ordering, the
@@ -33,7 +33,10 @@ from aid_runtime import (
33
33
  map_step,
34
34
  parallel,
35
35
  reduce_step,
36
+ route,
36
37
  )
38
+ from aid_runtime.agents.ir import DecisionDefinition
39
+ from aid_runtime.decisions import DecisionAnswer, DecisionResponse
37
40
 
38
41
  IS_AUTHENTICATED: Mapping[str, Any] = {"kind": "call", "name": "isAuthenticated", "args": []}
39
42
  HAS_ROLE_ADMIN: Mapping[str, Any] = {
@@ -462,3 +465,126 @@ def test_the_sequence_guard_refuses_a_string_even_though_it_is_a_sequence() -> N
462
465
  _items(context(text="abc"), "text", "map")
463
466
  assert _items(context(text=["abc"]), "text", "map") == ["abc"]
464
467
  assert isinstance([], Sequence)
468
+
469
+
470
+ TOPIC = DecisionDefinition(
471
+ id="topic",
472
+ model="jev-1.14.0",
473
+ instructions="Which part of the product is this question about",
474
+ criteria=("product", "billing"),
475
+ )
476
+
477
+ DECISIONS = {"topic": TOPIC}
478
+
479
+
480
+ class ScriptedAsker:
481
+ """A ``DecisionAsker`` returning one scripted answer and recording every call."""
482
+
483
+ def __init__(self, choice: str | None = None, *, error: Exception | None = None) -> None:
484
+ self._choice = choice
485
+ self._error = error
486
+ self.calls: list[dict[str, Any]] = []
487
+
488
+ async def decide(
489
+ self,
490
+ *,
491
+ model: str,
492
+ state: Any,
493
+ questions: Any,
494
+ reproducible: bool = False,
495
+ ) -> DecisionResponse:
496
+ self.calls.append({"model": model, "state": state, "questions": dict(questions)})
497
+ if self._error is not None:
498
+ raise self._error
499
+ answer = DecisionAnswer(type="choice", choice=self._choice)
500
+ return DecisionResponse(model=model, answers={"topic": answer})
501
+
502
+
503
+ def topic_route(asker: ScriptedAsker, **kwargs: Any) -> Any:
504
+ """A route over two mapped labels, so an answer outside them has to find a default."""
505
+ options: dict[str, Any] = {
506
+ "decision": "topic",
507
+ "state": "How much does the pro plan cost",
508
+ "on": {
509
+ "product": Pipeline.of(step("product_ran")),
510
+ "billing": Pipeline.of(step("billing_ran")),
511
+ },
512
+ "decisions": DECISIONS,
513
+ "client_factory": lambda: asker,
514
+ }
515
+ options.update(kwargs)
516
+ return route(**options)
517
+
518
+
519
+ async def test_route_runs_the_arm_the_decision_names_and_binds_the_label() -> None:
520
+ asker = ScriptedAsker("product")
521
+ result = await Pipeline.of(topic_route(asker, as_="path")).run(context())
522
+
523
+ assert result.get("product_ran") == "product_ran"
524
+ assert "billing_ran" not in result.values
525
+ assert result.get("path") == "product"
526
+ assert asker.calls[0]["state"] == "How much does the pro plan cost"
527
+
528
+
529
+ async def test_route_asks_a_choice_question_from_the_carried_definition() -> None:
530
+ asker = ScriptedAsker("product")
531
+ await Pipeline.of(topic_route(asker)).run(context())
532
+
533
+ assert asker.calls[0]["model"] == TOPIC.model
534
+ question = asker.calls[0]["questions"]["topic"]
535
+ assert question.type == "choice"
536
+ assert question.instructions == TOPIC.instructions
537
+ assert question.criteria == TOPIC.criteria
538
+
539
+
540
+ async def test_route_runs_the_default_for_an_unmapped_label_and_binds_it() -> None:
541
+ asker = ScriptedAsker("off_topic")
542
+ result = await Pipeline.of(
543
+ topic_route(asker, otherwise=Pipeline.of(step("default_ran")), as_="path")
544
+ ).run(context())
545
+
546
+ assert result.get("default_ran") == "default_ran"
547
+ assert result.get("path") == "off_topic"
548
+
549
+
550
+ async def test_route_fails_closed_for_an_unmapped_label_with_no_default() -> None:
551
+ with pytest.raises(PipelineError, match="no arm maps"):
552
+ await Pipeline.of(topic_route(ScriptedAsker("off_topic"))).run(context())
553
+
554
+
555
+ async def test_route_fails_when_the_decision_has_no_definition() -> None:
556
+ asker = ScriptedAsker("product")
557
+ with pytest.raises(PipelineError, match="needs a definition"):
558
+ await Pipeline.of(topic_route(asker, decision="nowhere")).run(context())
559
+
560
+ assert asker.calls == []
561
+
562
+
563
+ async def test_route_fails_when_the_client_raises() -> None:
564
+ with pytest.raises(PipelineError, match="could not answer: vendor exploded"):
565
+ await Pipeline.of(
566
+ topic_route(ScriptedAsker("product", error=RuntimeError("vendor exploded")))
567
+ ).run(context())
568
+
569
+
570
+ async def test_route_fails_when_the_answer_carries_no_choice() -> None:
571
+ with pytest.raises(PipelineError, match="returned no choice"):
572
+ await Pipeline.of(topic_route(ScriptedAsker())).run(context())
573
+
574
+
575
+ async def test_route_builds_its_client_on_first_use_and_reuses_it() -> None:
576
+ asker = ScriptedAsker("product")
577
+ built: list[ScriptedAsker] = []
578
+
579
+ def factory() -> ScriptedAsker:
580
+ built.append(asker)
581
+ return asker
582
+
583
+ pipeline = Pipeline.of(topic_route(asker, client_factory=factory))
584
+ assert built == []
585
+
586
+ await pipeline.run(context())
587
+ await pipeline.run(context())
588
+
589
+ assert built == [asker]
590
+ assert len(asker.calls) == 2
@@ -8,16 +8,25 @@ gone over the wire.
8
8
  from __future__ import annotations
9
9
 
10
10
  import json
11
+ from pathlib import Path
11
12
  from typing import Any
12
13
 
13
14
  import httpx
14
15
  import pytest
15
16
 
16
- from aid_runtime import ConfigurationError, ProviderError, ProviderResponseError
17
+ from aid_runtime import (
18
+ ATTRIBUTES,
19
+ TRACE_DIR_ENV,
20
+ ConfigurationError,
21
+ ProviderError,
22
+ ProviderResponseError,
23
+ )
17
24
  from aid_runtime.decisions import (
18
25
  DEFAULT_TYPESAFE_BASE_URL,
26
+ JEV_INPUT_USD_PER_MTOK,
19
27
  DecisionClient,
20
28
  DecisionQuestion,
29
+ decision_cost_usd,
21
30
  decision_key,
22
31
  is_reproducible_model,
23
32
  )
@@ -281,3 +290,75 @@ def test_aliases_are_not_reproducible() -> None:
281
290
  assert is_reproducible_model("jev-1.14.0")
282
291
  assert not is_reproducible_model("jev-latest")
283
292
  assert not is_reproducible_model("jev-preview")
293
+
294
+
295
+ def test_jev_prices_input_tokens_only() -> None:
296
+ assert JEV_INPUT_USD_PER_MTOK == 0.042
297
+ # $42 per billion: a ~430-token classification is about $0.000018.
298
+ assert decision_cost_usd(430) == pytest.approx(0.00001806)
299
+ assert decision_cost_usd(1_000_000) == pytest.approx(JEV_INPUT_USD_PER_MTOK)
300
+ assert decision_cost_usd(0) == 0.0
301
+ # No reported usage is unknown; the caller records no cost at all rather than
302
+ # claiming the call was free.
303
+ assert decision_cost_usd(None) == 0.0
304
+
305
+
306
+ def _trace_lines(directory: Path) -> list[dict[str, Any]]:
307
+ (path,) = directory.glob("trace-*.jsonl")
308
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]
309
+
310
+
311
+ @pytest.mark.asyncio
312
+ async def test_a_decision_is_priced_on_its_span(
313
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
314
+ ) -> None:
315
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
316
+ client = _client(
317
+ Recorder(_reply({"triage": {"choice": "billing", "confidence": 0.91}})),
318
+ )
319
+
320
+ await client.decide(
321
+ model=MODEL,
322
+ state={"message": "I was charged twice"},
323
+ questions={
324
+ "triage": DecisionQuestion(
325
+ type="choice",
326
+ instructions="Which team should handle this",
327
+ criteria=("billing", "technical"),
328
+ )
329
+ },
330
+ )
331
+
332
+ (record,) = _trace_lines(tmp_path)
333
+ attributes = record["attributes"]
334
+ assert record["name"] == f"decision {MODEL}"
335
+ assert attributes[ATTRIBUTES["system"]] == "typesafe"
336
+ assert attributes[ATTRIBUTES["operation"]] == "decision"
337
+ assert attributes[ATTRIBUTES["input_tokens"]] == 430
338
+ assert attributes[ATTRIBUTES["output_tokens"]] == 0
339
+ assert attributes[ATTRIBUTES["cost_usd"]] == pytest.approx(0.00001806)
340
+ assert attributes[ATTRIBUTES["response_model"]] == MODEL
341
+
342
+
343
+ @pytest.mark.asyncio
344
+ async def test_a_reply_without_usage_records_no_cost(
345
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
346
+ ) -> None:
347
+ monkeypatch.setenv(TRACE_DIR_ENV, str(tmp_path))
348
+ body = {
349
+ "model": MODEL,
350
+ "answers": {"urgent": {"noul": 0.2}},
351
+ }
352
+ client = _client(Recorder(httpx.Response(200, json=body)))
353
+
354
+ await client.decide(
355
+ model=MODEL,
356
+ state="x",
357
+ questions={"urgent": DecisionQuestion(type="noul", instructions="Is it urgent")},
358
+ )
359
+
360
+ (record,) = _trace_lines(tmp_path)
361
+ assert ATTRIBUTES["cost_usd"] not in record["attributes"]
362
+ assert ATTRIBUTES["input_tokens"] not in record["attributes"]
363
+ # The serving model is recorded even when the vendor omits usage.
364
+ assert record["attributes"][ATTRIBUTES["response_model"]] == MODEL