aid-runtime-python 0.1.150__py3-none-any.whl → 0.1.152__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
@@ -146,6 +146,13 @@ from aid_runtime.evals import (
146
146
  )
147
147
  from aid_runtime.gateway import ModelGateway, estimate_usage
148
148
  from aid_runtime.local_trace import TRACE_DIR_ENV, local_trace_enabled
149
+ from aid_runtime.metrics import (
150
+ AGENT_LABEL,
151
+ EVAL_LABEL,
152
+ METRIC_NAMES,
153
+ record_agent_run,
154
+ record_eval_case,
155
+ )
149
156
  from aid_runtime.pipeline import (
150
157
  STEPS_KEY,
151
158
  Pipeline,
@@ -287,6 +294,7 @@ from aid_runtime.telemetry import (
287
294
  ExportReason,
288
295
  ExportStatus,
289
296
  configure_export,
297
+ configure_metrics,
290
298
  )
291
299
  from aid_runtime.tools import Tool, ToolExecutor
292
300
  from aid_runtime.tracing import (
@@ -323,9 +331,10 @@ from aid_runtime.types import (
323
331
  )
324
332
 
325
333
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
326
- __version__ = "0.1.150"
334
+ __version__ = "0.1.152"
327
335
 
328
336
  __all__ = [
337
+ "AGENT_LABEL",
329
338
  "ANTHROPIC_VERSION",
330
339
  "ATTRIBUTES",
331
340
  "BEDROCK_SERVICE",
@@ -339,6 +348,7 @@ __all__ = [
339
348
  "DEFAULT_VERTEX_LOCATION",
340
349
  "DEPTH_KEY",
341
350
  "EMITTED_KEY",
351
+ "EVAL_LABEL",
342
352
  "EXPORT_KINDS",
343
353
  "GEMINI_API_KEY_ENV",
344
354
  "GEN_AI_OPERATION_CHAT",
@@ -349,6 +359,7 @@ __all__ = [
349
359
  "LIMITER_KEY",
350
360
  "MAX_STEP_DEPTH",
351
361
  "METADATA_TOKEN_URL",
362
+ "METRIC_NAMES",
352
363
  "OTLP_EXTRA",
353
364
  "PRINCIPAL_KEY",
354
365
  "REDUCED_KEY",
@@ -549,6 +560,7 @@ __all__ = [
549
560
  "chunker_for",
550
561
  "cite",
551
562
  "configure_export",
563
+ "configure_metrics",
552
564
  "create_store",
553
565
  "decision_cost_usd",
554
566
  "decision_key",
@@ -581,8 +593,10 @@ __all__ = [
581
593
  "parallel",
582
594
  "parse_structured",
583
595
  "pinned_embedding",
596
+ "record_agent_run",
584
597
  "record_attributes",
585
598
  "record_cost",
599
+ "record_eval_case",
586
600
  "record_exception",
587
601
  "record_hitl",
588
602
  "record_usage",
@@ -89,6 +89,7 @@ from aid_runtime.errors import (
89
89
  ToolPermissionError,
90
90
  )
91
91
  from aid_runtime.gateway import ModelGateway
92
+ from aid_runtime.metrics import record_agent_run
92
93
  from aid_runtime.providers.base import Provider
93
94
  from aid_runtime.tools import Tool, ToolExecutor
94
95
  from aid_runtime.tracing import agent_span, record_attributes, record_guardrail, record_hitl
@@ -274,11 +275,17 @@ class AgentRuntime:
274
275
  )
275
276
  start_cost = self._gateway.ledger.cost_usd
276
277
  start_tokens = self._gateway.ledger.total_tokens
277
- outcome = await self._drive(
278
- frame,
279
- principal=principal if principal is not None else Principal(),
280
- memory_key=key,
281
- )
278
+ try:
279
+ outcome = await self._drive(
280
+ frame,
281
+ principal=principal if principal is not None else Principal(),
282
+ memory_key=key,
283
+ )
284
+ except BaseException:
285
+ # A run stopped by a guardrail or an exhausted ceiling was already billed.
286
+ # The refusal is re-raised unchanged: publishing the spend is not a recovery.
287
+ self._publish_spend(agent.id, start_cost, start_tokens)
288
+ raise
282
289
  return self._wrap(outcome, start_cost, start_tokens)
283
290
 
284
291
  async def resume(
@@ -293,11 +300,16 @@ class AgentRuntime:
293
300
  self._restore_ledger(checkpoint)
294
301
  start_cost = self._gateway.ledger.cost_usd
295
302
  start_tokens = self._gateway.ledger.total_tokens
296
- outcome = await self._resume(
297
- checkpoint,
298
- resolved,
299
- principal if principal is not None else Principal(),
300
- )
303
+ try:
304
+ outcome = await self._resume(
305
+ checkpoint,
306
+ resolved,
307
+ principal if principal is not None else Principal(),
308
+ )
309
+ except BaseException:
310
+ # Same rule as `run`: a resumed run that fails has been billed too.
311
+ self._publish_spend(checkpoint.agent_id, start_cost, start_tokens)
312
+ raise
301
313
  return self._wrap(outcome, start_cost, start_tokens)
302
314
 
303
315
  async def _resume(
@@ -1238,19 +1250,36 @@ class AgentRuntime:
1238
1250
  )
1239
1251
 
1240
1252
  def _wrap(self, outcome: _Outcome, start_cost: float, start_tokens: int) -> RunResult:
1241
- ledger = self._gateway.ledger
1253
+ cost_usd, total_tokens = self._publish_spend(outcome.agent_id, start_cost, start_tokens)
1242
1254
  return RunResult(
1243
1255
  status=outcome.status,
1244
1256
  agent_id=outcome.agent_id,
1245
1257
  answer=outcome.answer,
1246
1258
  steps=tuple(outcome.steps),
1247
1259
  path=outcome.path,
1248
- cost_usd=round(max(ledger.cost_usd - start_cost, 0.0), 6),
1249
- total_tokens=max(ledger.total_tokens - start_tokens, 0),
1260
+ cost_usd=cost_usd,
1261
+ total_tokens=total_tokens,
1250
1262
  checkpoint=outcome.checkpoint,
1251
1263
  guardrails=outcome.guardrails,
1252
1264
  )
1253
1265
 
1266
+ def _publish_spend(
1267
+ self, agent_id: str, start_cost: float, start_tokens: int
1268
+ ) -> tuple[float, int]:
1269
+ """Record what a run spent since ``start_*`` and return the same figures.
1270
+
1271
+ Every run is assembled here, on both engines, so this is the one place a run's
1272
+ spend is published without counting a turn twice. It is called from the exception
1273
+ paths as well: a run stopped by a guardrail or an exhausted budget has already
1274
+ been billed, and a budget alarm that only saw successful runs would under-report
1275
+ exactly when guardrails are firing.
1276
+ """
1277
+ ledger = self._gateway.ledger
1278
+ cost_usd = round(max(ledger.cost_usd - start_cost, 0.0), 6)
1279
+ total_tokens = max(ledger.total_tokens - start_tokens, 0)
1280
+ record_agent_run(agent_id=agent_id, cost_usd=cost_usd, tokens=total_tokens)
1281
+ return cost_usd, total_tokens
1282
+
1254
1283
 
1255
1284
  def _budget_of(thread: ThreadMemory) -> int:
1256
1285
  return thread.token_budget if thread.token_budget is not None else 0
@@ -9,6 +9,7 @@ from __future__ import annotations
9
9
 
10
10
  import statistics
11
11
  from collections.abc import Awaitable, Callable, Sequence
12
+ from time import perf_counter
12
13
 
13
14
  from pydantic import BaseModel, ConfigDict, Field
14
15
 
@@ -17,6 +18,7 @@ from aid_runtime.evals.dataset import Dataset, EvalCase
17
18
  from aid_runtime.evals.gate import EvalRun, MetricRun
18
19
  from aid_runtime.evals.metrics import Metric, MetricResult
19
20
  from aid_runtime.gateway import ModelGateway
21
+ from aid_runtime.metrics import record_eval_case
20
22
  from aid_runtime.types import CompletionRequest, Message
21
23
 
22
24
  __all__ = [
@@ -174,32 +176,81 @@ async def gateway_judge(
174
176
  return call
175
177
 
176
178
 
177
- async def evaluate_once(dataset: Dataset, runner: Runner, metrics: Sequence[Metric]) -> DatasetRun:
178
- """One pass over ``dataset``, scoring every prediction with every metric."""
179
+ async def evaluate_once(
180
+ dataset: Dataset,
181
+ runner: Runner,
182
+ metrics: Sequence[Metric],
183
+ *,
184
+ eval_id: str | None = None,
185
+ ) -> DatasetRun:
186
+ """One pass over ``dataset``, scoring every prediction with every metric.
187
+
188
+ Every case publishes its spend and duration as it completes, which is what makes
189
+ ``eval.cost`` and ``eval.latency.p95`` a series an alarm can watch. ``eval_id`` is the
190
+ *declared* eval this dataset belongs to -- the id an alarm's ``source`` names -- and
191
+ falls back to the dataset's own name for a caller that runs a dataset directly.
192
+ """
179
193
  if not metrics:
180
194
  raise ValueError("at least one metric is required")
195
+ label = dataset.name if eval_id is None else eval_id
181
196
  outcomes: list[CaseOutcome] = []
182
197
  for case in dataset.cases:
198
+ cost_before = _runner_cost(runner)
199
+ started = perf_counter()
183
200
  prediction = await runner(case)
201
+ # The runner call, not the scoring, is what a latency budget constrains: scoring
202
+ # is the harness measuring the answer, and charging its time to the pipeline would
203
+ # report a slower product because a judge was added to its eval.
204
+ latency_ms = (perf_counter() - started) * 1000.0
184
205
  scores = tuple([await metric.score(case, prediction) for metric in metrics])
185
206
  outcomes.append(CaseOutcome(case_id=case.id, prediction=prediction, scores=scores))
207
+ # Cost is read after scoring, because a model-backed metric spends money too and a
208
+ # cost budget that ignored the judge would be measuring half the run.
209
+ record_eval_case(
210
+ eval_id=label,
211
+ cost_usd=_spent_since(runner, cost_before),
212
+ latency_ms=latency_ms,
213
+ )
186
214
  return DatasetRun(
187
215
  dataset=dataset.name, dataset_version=dataset.version, outcomes=tuple(outcomes)
188
216
  )
189
217
 
190
218
 
219
+ def _runner_cost(runner: Runner) -> float | None:
220
+ """A runner's cumulative model spend, when it meters one.
221
+
222
+ A :data:`Runner` is any callable, so most say nothing here; one built by
223
+ :class:`EvalRunner` reads its gateway ledger. An unmetered runner reports a real
224
+ ``0.0`` rather than a guess, which is why "does not meter" and "spent nothing" are the
225
+ same answer for a series that only ever sums.
226
+ """
227
+ spent = getattr(runner, "cost_usd", None)
228
+ return float(spent) if isinstance(spent, int | float) else None
229
+
230
+
231
+ def _spent_since(runner: Runner, before: float | None) -> float:
232
+ after = _runner_cost(runner)
233
+ if before is None or after is None:
234
+ return 0.0
235
+ return max(after - before, 0.0)
236
+
237
+
191
238
  async def run_evaluation(
192
239
  dataset: Dataset,
193
240
  runner: Runner,
194
241
  metrics: Sequence[Metric],
195
242
  *,
196
243
  runs: int = 5,
244
+ eval_id: str | None = None,
197
245
  ) -> EvalRun:
198
246
  """Sample ``dataset`` ``runs`` times, recording one mean per metric per run.
199
247
 
200
248
  Every run makes fresh calls, which is the point: the spread across runs is the
201
249
  measurement of how much this system varies when nothing has changed. Without
202
250
  it there is nothing to compare a "regression" against.
251
+
252
+ ``eval_id`` is forwarded to :func:`evaluate_once` so every case's published series
253
+ carries the declared eval, which is the value an alarm scopes itself to.
203
254
  """
204
255
  if runs < 1:
205
256
  raise ValueError("runs must be at least 1")
@@ -208,7 +259,7 @@ async def run_evaluation(
208
259
 
209
260
  collected: dict[str, list[float]] = {metric.name: [] for metric in metrics}
210
261
  for _ in range(runs):
211
- pass_result = await evaluate_once(dataset, runner, metrics)
262
+ pass_result = await evaluate_once(dataset, runner, metrics, eval_id=eval_id)
212
263
  means = pass_result.means()
213
264
  for metric in metrics:
214
265
  collected[metric.name].append(means[metric.name])
aid_runtime/metrics.py ADDED
@@ -0,0 +1,133 @@
1
+ """Publishing the four series an ``observability.alerts`` entry can watch.
2
+
3
+ An alarm is only as real as the series under it. This module is the producer side of the
4
+ four metric names the deploy plan's alarm policies name -- ``agent.cost``,
5
+ ``agent.tokens``, ``eval.cost`` and ``eval.latency.p95`` -- recorded where the values are
6
+ already computed rather than recomputed from a second reading of the run: the agent loop
7
+ knows what a run cost when it assembles the result, and the eval harness knows how long a
8
+ case took when it scores it.
9
+
10
+ Recording is a no-op until :func:`aid_runtime.telemetry.configure_metrics` installs a meter
11
+ provider, for the same reason spans are dropped until a tracer provider is installed: a
12
+ library must not decide its host's export destination, and a service that never asked for a
13
+ collector should pay nothing for one. The instruments are created through the OpenTelemetry
14
+ *API*, so an instrument made before the provider exists still forwards once it does.
15
+
16
+ Names and units are not invented here. ``agent.cost`` and ``eval.cost`` are dollars,
17
+ ``agent.tokens`` is a token count and ``eval.latency.p95`` is milliseconds -- the same
18
+ pairing ``alertUnit`` derives in ``@aid-framework/ir``, which is why a threshold in a
19
+ document is never ambiguous about what its number means.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Final
25
+
26
+ from opentelemetry import metrics
27
+
28
+ __all__ = [
29
+ "AGENT_LABEL",
30
+ "EVAL_LABEL",
31
+ "METRIC_NAMES",
32
+ "record_agent_run",
33
+ "record_eval_case",
34
+ ]
35
+
36
+ #: Every series a document can name in ``observability.alerts[].metric``. Kept in the
37
+ #: generator's order so this module and the schema read the same four names.
38
+ METRIC_NAMES: Final[tuple[str, ...]] = (
39
+ "agent.cost",
40
+ "agent.tokens",
41
+ "eval.cost",
42
+ "eval.latency.p95",
43
+ )
44
+
45
+ #: The label that separates one agent's series from another's. It is the span attribute
46
+ #: ``aid.agent.id`` under the same name, so a trace and a metric name the same run the same
47
+ #: way -- and a value an operator can match against an alarm's ``source`` either way.
48
+ #:
49
+ #: The generated alarm narrows by the cloud's own spelling of that idea: ``alerts.ts``
50
+ #: writes ``dimensions = { Source = "<source>" }`` for CloudWatch and
51
+ #: ``metric.label.source`` for Cloud Monitoring, whose label keys are lowercased. Nothing
52
+ #: in this package renames attributes on the way out -- an OTLP collector maps
53
+ #: ``aid.agent.id`` to those keys once, in the exporter config, because the mapping is the
54
+ #: operator's account detail and the runtime's job is only to publish a labelled series.
55
+ AGENT_LABEL: Final = "aid.agent.id"
56
+
57
+ #: The eval counterpart of :data:`AGENT_LABEL`. The value is the *declared* eval id -- the
58
+ #: ``observability.alerts[].source`` an operator writes for an eval suite, and the id the
59
+ #: deploy plan derives an alarm for -- not a per-case identifier. A per-case label would
60
+ #: spread one suite's cost across as many series as it has cases, and an alarm scoped to
61
+ #: the suite would then watch a series nothing writes.
62
+ EVAL_LABEL: Final = "aid.eval.id"
63
+
64
+ #: The meter's scope name. Distinct from the tracer's only by convention; both are the
65
+ #: runtime's own wiring rather than the application's.
66
+ _METER_NAME: Final = "aid_runtime"
67
+
68
+ _instruments: dict[str, Any] | None = None
69
+
70
+
71
+ def _recorders() -> dict[str, Any]:
72
+ """Create the four instruments once.
73
+
74
+ Built lazily rather than at import so a process that imports this package for
75
+ something else does not register instruments it will never record. Safe to create
76
+ before a provider exists: the API returns forwarding instruments that bind to the
77
+ provider when one is installed.
78
+ """
79
+ global _instruments
80
+ if _instruments is None:
81
+ meter = metrics.get_meter(_METER_NAME)
82
+ _instruments = {
83
+ "agent.cost": meter.create_counter(
84
+ name="agent.cost",
85
+ unit="usd",
86
+ description="Model spend of one agent run, in US dollars.",
87
+ ),
88
+ "agent.tokens": meter.create_counter(
89
+ name="agent.tokens",
90
+ unit="tokens",
91
+ description="Total tokens one agent run consumed, input and output.",
92
+ ),
93
+ "eval.cost": meter.create_counter(
94
+ name="eval.cost",
95
+ unit="usd",
96
+ description="Model spend of one eval case, in US dollars.",
97
+ ),
98
+ "eval.latency.p95": meter.create_histogram(
99
+ name="eval.latency.p95",
100
+ unit="ms",
101
+ description="Wall-clock duration of one eval case, in milliseconds.",
102
+ ),
103
+ }
104
+ return _instruments
105
+
106
+
107
+ def record_agent_run(*, agent_id: str, cost_usd: float, tokens: int) -> None:
108
+ """Publish one completed agent run's spend and token count.
109
+
110
+ Both series carry ``aid.agent.id``, so an alarm scoped to an agent watches that
111
+ agent's runs and an alarm with no ``source`` watches the whole environment. A run that
112
+ fails still spent money, so the caller records every run it assembles rather than only
113
+ the successful ones -- a budget alarm that ignored failures would under-report exactly
114
+ the runs most likely to overspend.
115
+ """
116
+ recorders = _recorders()
117
+ labels = {AGENT_LABEL: agent_id}
118
+ recorders["agent.cost"].add(cost_usd, labels)
119
+ recorders["agent.tokens"].add(tokens, labels)
120
+
121
+
122
+ def record_eval_case(*, eval_id: str, cost_usd: float, latency_ms: float) -> None:
123
+ """Publish one eval case's spend and duration.
124
+
125
+ ``eval_id`` is the declared eval's id, so every case in one suite lands on the same
126
+ series and an alarm scoped to that suite sees the suite's total. ``eval.latency.p95`` is
127
+ a histogram rather than a gauge: a percentile is computed from a distribution, and a
128
+ backend that cannot reduce a histogram cannot answer a p95.
129
+ """
130
+ recorders = _recorders()
131
+ labels = {EVAL_LABEL: eval_id}
132
+ recorders["eval.cost"].add(cost_usd, labels)
133
+ recorders["eval.latency.p95"].record(latency_ms, labels)
@@ -33,6 +33,7 @@ mean comparison.
33
33
  from __future__ import annotations
34
34
 
35
35
  from collections.abc import Sequence
36
+ from time import perf_counter
36
37
  from typing import cast
37
38
 
38
39
  from aid_runtime.errors import EvalError
@@ -45,6 +46,7 @@ from aid_runtime.evals.gate import (
45
46
  Threshold,
46
47
  )
47
48
  from aid_runtime.evals.metrics import Metric
49
+ from aid_runtime.metrics import record_eval_case
48
50
  from aid_runtime.retrieval.metrics import RetrievalCase, RetrievalMetric
49
51
  from aid_runtime.retrieval.retriever import Retriever
50
52
 
@@ -84,8 +86,16 @@ class RetrievalGate:
84
86
  runs: int,
85
87
  dataset: str,
86
88
  dataset_version: str,
89
+ eval_id: str | None = None,
87
90
  ) -> EvalRun:
88
- """Run every case ``runs`` times, producing one mean per metric per run."""
91
+ """Run every case ``runs`` times, producing one mean per metric per run.
92
+
93
+ Each case also publishes its duration, which is what makes ``eval.latency.p95`` a
94
+ series an alarm can watch for a retrieval eval just as for a model-backed one. The
95
+ spend is a real ``0.0``: retrieval costs embedding and vector queries rather than
96
+ model calls, and a counter that stayed silent would leave a cost alarm reporting
97
+ no data instead of reporting that there was nothing to spend.
98
+ """
89
99
  if not cases:
90
100
  raise EvalError("a retrieval run needs at least one case")
91
101
  if runs < 1:
@@ -93,16 +103,20 @@ class RetrievalGate:
93
103
  if not self._metrics:
94
104
  raise EvalError("a retrieval run needs at least one metric")
95
105
 
106
+ label = dataset if eval_id is None else eval_id
96
107
  samples: dict[str, list[float]] = {metric.name: [] for metric in self._metrics}
97
108
  for _ in range(runs):
98
109
  totals: dict[str, float] = {metric.name: 0.0 for metric in self._metrics}
99
110
  for case in cases:
100
111
  # k comes from the case, because a case is what says how many
101
112
  # passages count as an answer; a retriever's own topK is a default.
113
+ started = perf_counter()
102
114
  retrieved = await retriever.retrieve(case.query, top_k=case.k)
115
+ latency_ms = (perf_counter() - started) * 1000.0
103
116
  for metric in self._metrics:
104
117
  result = await metric.score(case, retrieved)
105
118
  totals[metric.name] += result.score
119
+ record_eval_case(eval_id=label, cost_usd=0.0, latency_ms=latency_ms)
106
120
  for name, total in totals.items():
107
121
  samples[name].append(total / len(cases))
108
122
 
aid_runtime/telemetry.py CHANGED
@@ -1,20 +1,30 @@
1
- """Installing the span exporter a document declared.
1
+ """Installing the exporters a document declared.
2
2
 
3
- ``observability.export`` states where spans should go, and ``observability.endpointEnv``
3
+ ``observability.export`` states where telemetry should go, and ``observability.endpointEnv``
4
4
  names -- never holds -- the variable carrying the collector address. Those two facts were
5
5
  declarable from spec 0.27 and unenforced until this module: :mod:`aid_runtime.tracing`
6
6
  writes every span through the OpenTelemetry *API*, so with no provider installed the spans
7
7
  were recorded and dropped.
8
8
 
9
+ Two exporters are installed from that one switch, because a document that asked for a
10
+ collector asked for the telemetry stream, not for one of its halves:
11
+
12
+ - :func:`configure_export` installs the span exporter behind ``observability.trace``.
13
+ - :func:`configure_metrics` installs the metric exporter that publishes the four series
14
+ ``observability.alerts`` watches (:mod:`aid_runtime.metrics`), which is what makes a
15
+ declared alarm watch a series something actually writes.
16
+
17
+ One variable feeds both, so the value is read as a collector address and completed with the
18
+ signal's own path -- a document never has to name two variables to get two signals.
19
+
9
20
  This is the one place the runtime installs a provider, and it is deliberately a function
10
21
  the application calls rather than an import side effect. A library that configured global
11
22
  telemetry on import would decide its host's export destination, and the entrypoint that
12
23
  runs it belongs to the application, not to this package.
13
24
 
14
- Nothing here raises. A missing endpoint or a missing exporter is reported as an
15
- :class:`ExportStatus` the caller can log, because telemetry that cannot start must not stop
16
- a service from serving -- the honest alternative to a silent drop is a status that names
17
- what was missing.
25
+ Nothing here raises. A missing endpoint or a missing exporter is reported as a status the
26
+ caller can log, because telemetry that cannot start must not stop a service from serving --
27
+ the honest alternative to a silent drop is a status that names what was missing.
18
28
  """
19
29
 
20
30
  from __future__ import annotations
@@ -30,6 +40,7 @@ __all__ = [
30
40
  "ExportReason",
31
41
  "ExportStatus",
32
42
  "configure_export",
43
+ "configure_metrics",
33
44
  ]
34
45
 
35
46
  #: The variable an OTLP/HTTP collector address conventionally lives in, and the value a
@@ -45,6 +56,14 @@ EXPORT_KINDS: Final[tuple[str, ...]] = ("otlp",)
45
56
  #: mistake this message exists to stop.
46
57
  OTLP_EXTRA: Final = "aid-runtime-python[otlp]"
47
58
 
59
+ #: The two signals this module can send. Named once so the status details and the
60
+ #: endpoint paths cannot drift from the exporter each one installs.
61
+ Signal = Literal["traces", "metrics"]
62
+
63
+ #: The OTLP/HTTP path each signal is posted to, in the order a collector address is
64
+ #: stripped of one before another is appended.
65
+ SIGNAL_PATHS: Final[tuple[str, ...]] = ("/v1/traces", "/v1/metrics")
66
+
48
67
  ExportReason = Literal[
49
68
  "configured",
50
69
  "already-configured",
@@ -56,11 +75,12 @@ ExportReason = Literal[
56
75
 
57
76
  @dataclass(frozen=True, slots=True)
58
77
  class ExportStatus:
59
- """What :func:`configure_export` did, in terms a caller can log or assert on.
78
+ """What :func:`configure_export` or :func:`configure_metrics` did, in terms a caller
79
+ can log or assert on.
60
80
 
61
- ``configured`` is the answer to "will spans leave this process", and it is never
81
+ ``configured`` is the answer to "will this signal leave this process", and it is never
62
82
  inferred from the document alone: an endpoint variable that is unset means the same
63
- dropped spans as no declaration, so it reports ``False`` with a reason rather than
83
+ dropped telemetry as no declaration, so it reports ``False`` with a reason rather than
64
84
  echoing the declaration back as if it had been honoured.
65
85
  """
66
86
 
@@ -94,6 +114,69 @@ def _status(
94
114
  )
95
115
 
96
116
 
117
+ def _preamble(
118
+ *,
119
+ declared: Literal["otlp", "none"],
120
+ endpoint_env: str,
121
+ inactive: str,
122
+ ) -> tuple[ExportStatus | None, str]:
123
+ """The two gates both signals share, and the endpoint when they pass.
124
+
125
+ ``inactive`` finishes the sentence "…so nothing is exported and <inactive>", which is
126
+ the only part that differs between spans and series: the gates themselves are the same
127
+ two facts -- what the document asked for, and whether the environment supplied it.
128
+ """
129
+ if declared != "otlp":
130
+ return (
131
+ _status(
132
+ configured=False,
133
+ reason="not-declared",
134
+ endpoint_env=endpoint_env,
135
+ detail=(
136
+ f"observability.export is not otlp, so no exporter is installed and {inactive}"
137
+ ),
138
+ ),
139
+ "",
140
+ )
141
+
142
+ endpoint = os.environ.get(endpoint_env, "").strip()
143
+ if not endpoint:
144
+ return (
145
+ _status(
146
+ configured=False,
147
+ reason="endpoint-env-unset",
148
+ endpoint_env=endpoint_env,
149
+ detail=(
150
+ f"{endpoint_env} is unset or empty, so the OTLP exporter has no "
151
+ f"collector to send to and {inactive}"
152
+ ),
153
+ ),
154
+ "",
155
+ )
156
+ return None, endpoint
157
+
158
+
159
+ def _signal_endpoint(endpoint: str, signal: Signal) -> str:
160
+ """The URL a request carrying ``signal`` is posted to.
161
+
162
+ One document declares one ``endpointEnv``, and that variable now feeds two signals. The
163
+ OTLP spec answers this with a base address per signal, so the value is read as a
164
+ collector address: this signal's own path is used when the value already ends with it,
165
+ the other signal's path is replaced, and a bare address gets the path appended.
166
+
167
+ Without this, the values in use today would all break -- a variable holding
168
+ ``http://collector:4318/v1/traces`` would post metric protobuf to the trace endpoint, a
169
+ collector would reject it, and the alarms watching those series would report no data
170
+ while every startup status claimed the exporter was running.
171
+ """
172
+ trimmed = endpoint.rstrip("/")
173
+ for path in SIGNAL_PATHS:
174
+ if trimmed.endswith(path):
175
+ trimmed = trimmed[: -len(path)]
176
+ break
177
+ return f"{trimmed}/v1/{signal}"
178
+
179
+
97
180
  def configure_export(
98
181
  *,
99
182
  service_name: str,
@@ -115,34 +198,18 @@ def configure_export(
115
198
  ``declared`` is the document's ``observability.export`` as generated, so a document
116
199
  that never asked for export reports ``not-declared`` instead of guessing from the
117
200
  environment. ``endpoint_env`` is the *name* of the variable to read at call time,
118
- which is what lets one image run in several environments.
201
+ which is what lets one image run in several environments. Its value may be the
202
+ collector's base address or this signal's own URL; see :func:`_signal_endpoint`.
119
203
 
120
204
  Re-calling after a successful install returns ``already-configured`` and installs
121
205
  nothing: the OpenTelemetry API forbids replacing a global provider, and quietly trying
122
206
  would produce the warning every second call currently produces.
123
207
  """
124
- if declared != "otlp":
125
- return _status(
126
- configured=False,
127
- reason="not-declared",
128
- endpoint_env=endpoint_env,
129
- detail=(
130
- "observability.export is not otlp, so no exporter is installed and spans "
131
- "stay in-process"
132
- ),
133
- )
134
-
135
- endpoint = os.environ.get(endpoint_env, "").strip()
136
- if not endpoint:
137
- return _status(
138
- configured=False,
139
- reason="endpoint-env-unset",
140
- endpoint_env=endpoint_env,
141
- detail=(
142
- f"{endpoint_env} is unset or empty, so the OTLP exporter has no collector "
143
- "to send to and spans stay in-process"
144
- ),
145
- )
208
+ refused, endpoint = _preamble(
209
+ declared=declared, endpoint_env=endpoint_env, inactive="spans stay in-process"
210
+ )
211
+ if refused is not None:
212
+ return refused
146
213
 
147
214
  try:
148
215
  from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
@@ -174,11 +241,98 @@ def configure_export(
174
241
  )
175
242
 
176
243
  provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
177
- provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint)))
244
+ target = _signal_endpoint(endpoint, "traces")
245
+ provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=target)))
178
246
  trace.set_tracer_provider(provider)
179
247
  return _status(
180
248
  configured=True,
181
249
  reason="configured",
182
250
  endpoint_env=endpoint_env,
183
- detail=f"spans export to {endpoint} over OTLP/HTTP as service {service_name}",
251
+ detail=f"spans export to {target} over OTLP/HTTP as service {service_name}",
252
+ )
253
+
254
+
255
+ def configure_metrics(
256
+ *,
257
+ service_name: str,
258
+ declared: Literal["otlp", "none"] = "otlp",
259
+ endpoint_env: str = DEFAULT_ENDPOINT_ENV,
260
+ interval_ms: int = 60000,
261
+ ) -> ExportStatus:
262
+ """Install the OTLP metric exporter that carries the series alarms watch.
263
+
264
+ This is the other half of the same switch. A document may declare four alarms over
265
+ ``agent.cost``, ``agent.tokens``, ``eval.cost`` and ``eval.latency.p95``; the recording
266
+ points live in :mod:`aid_runtime.metrics` and write nothing anywhere until a meter
267
+ provider exists. An alarm over a series nobody publishes does not fail -- it reports no
268
+ data, forever, which is the failure mode that looks like health.
269
+
270
+ The gates are :func:`configure_export`'s gates, because they are the same questions: did
271
+ the document ask for a collector, and did the environment name one. ``interval_ms`` is
272
+ the export period; the default matches the periodic reader's own, so a caller passes it
273
+ only to shorten the window in a test.
274
+
275
+ Call it beside :func:`configure_export`, at startup:
276
+
277
+ .. code-block:: python
278
+
279
+ from aid_runtime.telemetry import configure_export, configure_metrics
280
+
281
+ configure_export(service_name="support-copilot")
282
+ configure_metrics(service_name="support-copilot")
283
+ """
284
+ refused, endpoint = _preamble(
285
+ declared=declared,
286
+ endpoint_env=endpoint_env,
287
+ inactive="the alert series are never published",
288
+ )
289
+ if refused is not None:
290
+ return refused
291
+
292
+ try:
293
+ from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
294
+ OTLPMetricExporter,
295
+ )
296
+ from opentelemetry.sdk.metrics import MeterProvider
297
+ from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
298
+ from opentelemetry.sdk.resources import Resource
299
+ except ImportError:
300
+ return _status(
301
+ configured=False,
302
+ reason="exporter-not-installed",
303
+ endpoint_env=endpoint_env,
304
+ detail=(
305
+ "the OpenTelemetry SDK and OTLP exporter are not installed; install "
306
+ f"{OTLP_EXTRA} to publish the series observability.alerts watches"
307
+ ),
308
+ )
309
+
310
+ from opentelemetry import metrics
311
+
312
+ existing = metrics.get_meter_provider()
313
+ if isinstance(existing, MeterProvider):
314
+ return _status(
315
+ configured=True,
316
+ reason="already-configured",
317
+ endpoint_env=endpoint_env,
318
+ detail="a meter provider is already installed; this call installed nothing",
319
+ )
320
+
321
+ target = _signal_endpoint(endpoint, "metrics")
322
+ reader = PeriodicExportingMetricReader(
323
+ OTLPMetricExporter(endpoint=target), export_interval_millis=interval_ms
324
+ )
325
+ provider = MeterProvider(
326
+ resource=Resource.create({"service.name": service_name}),
327
+ metric_readers=[reader],
328
+ )
329
+ metrics.set_meter_provider(provider)
330
+ return _status(
331
+ configured=True,
332
+ reason="configured",
333
+ endpoint_env=endpoint_env,
334
+ detail=(
335
+ f"metrics export to {target} over OTLP/HTTP as service {service_name} "
336
+ f"every {interval_ms}ms"
337
+ ),
184
338
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.150
3
+ Version: 0.1.152
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0
@@ -1,4 +1,4 @@
1
- aid_runtime/__init__.py,sha256=86bjw0qQXGb_g6Tmv6hM5AFXfM45cwtMZjwrBXqM-RA,13766
1
+ aid_runtime/__init__.py,sha256=QiMu_qQLmxEIdjp8oWyHH85LH91zaBlV-EwaGvwXv-E,14050
2
2
  aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
3
3
  aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
4
4
  aid_runtime/control.py,sha256=y6wPn0fqYJv0nVSsjzpzfiaq1Y7zBoMxCpdrEuqkfvg,17529
@@ -7,12 +7,13 @@ aid_runtime/decisions.py,sha256=1V0d9EttfwTuh8jgtC5X3wQDTZrl20ZREcs6VqIdcHY,1566
7
7
  aid_runtime/errors.py,sha256=TKkZyZZcFTl5yxNKlA8jUF4ORpYHLGFEvc6r9FK4X70,12572
8
8
  aid_runtime/gateway.py,sha256=p0qsaQUAYrwSzlWwpUi1wY6pdOeU98QjsWLzq8045Fo,18267
9
9
  aid_runtime/local_trace.py,sha256=eg5LDsg1VfNmJNqs8KjtdzTjSqg7SWTXunLwg-b3IcM,7870
10
+ aid_runtime/metrics.py,sha256=w55qPlFRQXUfASxpskgYiSeFcFxkL_mwbDp2IhevAbg,6050
10
11
  aid_runtime/pipeline.py,sha256=Y2jiiYISLLxgBKGBj5J2rseEDzE8RXP8v5pJ_edjHfM,6334
11
12
  aid_runtime/prompts.py,sha256=eN3p_Yc-J6pyKaL2w4I-EmwvcPKErnXBvvI_Syq13ZM,7083
12
13
  aid_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
14
  aid_runtime/steps.py,sha256=44v8-ebN77VGZePmfhBYi0KORFBrH2GWFSzlfczaJhs,12047
14
15
  aid_runtime/structured.py,sha256=Uga-VoGJN56lUtr-M3nmUjAKGF32cAAk-p7WceUgPzg,5061
15
- aid_runtime/telemetry.py,sha256=KFcOILI2QFdcmNbcRaXTCL6Im0E9r0St3uFGzszvGNM,6602
16
+ aid_runtime/telemetry.py,sha256=ykAXCL3XFi0yok3xr-fjD3oGvVycdfyrqJ8nGKC_ZHc,12872
16
17
  aid_runtime/tools.py,sha256=7LeaPI5aJioNe3vexUv94tvIRpOwxj1Ujt723qvO3UI,9906
17
18
  aid_runtime/tracing.py,sha256=jZMl5btxcUSQQDeWGMT0lQB-YSdRW7cxl5QsJVeWE7Q,9795
18
19
  aid_runtime/types.py,sha256=cVYgmacDIhStQT5dX_X67-q57sPBBaWC5nybtGVqVsw,10389
@@ -22,7 +23,7 @@ aid_runtime/agents/deep_agents.py,sha256=Eg_BLm2cg7T_tXSxR7ag8SEvTMCFBLHoIvln3Bo
22
23
  aid_runtime/agents/engine.py,sha256=3cXCYY806URDblYD500cfw7873IoVCy8BH1d4h2YAsc,5789
23
24
  aid_runtime/agents/guardrails.py,sha256=0HhbToZBxPZHEDRLyD9BGS_jmV-TkKPGEhRynYxLXx8,32813
24
25
  aid_runtime/agents/ir.py,sha256=MgqX5gEkq7vimXojtSNb5MuVeTIZaWkZCFitxAqSAe0,32855
25
- aid_runtime/agents/loop.py,sha256=iQ_kk-Miu7oZUKeRtCpMGzAQUwV2IaVM9BdXhThZ77I,52728
26
+ aid_runtime/agents/loop.py,sha256=4NA3RokG_KogiXgOYJk3agEaci-s5Cv_bb5az3lOllQ,54237
26
27
  aid_runtime/agents/managed.py,sha256=SFyx6Rca2aoiMzA9q6B4Nfes6ZCjn_5_zN0SxzemIII,23247
27
28
  aid_runtime/agents/memory.py,sha256=6_D6k2bzAiR2euNvzr6HB28wsUUq-R-WTQc12gkB8ao,9156
28
29
  aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
@@ -32,7 +33,7 @@ aid_runtime/evals/dataset.py,sha256=waG4tYSJsgsZ9DLxkhUvF_X-aQB8w2OexYxc7Wwdiyg,
32
33
  aid_runtime/evals/gate.py,sha256=_nLWXvcuHwq8nE3HpiONg_wBkrzZyGrGT49ZNeKMyTY,15524
33
34
  aid_runtime/evals/metrics.py,sha256=il9lzJa-hir59pw9Muyg9MhDuozUqAQaO1Tb75CxBKc,14185
34
35
  aid_runtime/evals/predicate.py,sha256=JaeN1LJFpliI4JHYdFPtXfjH5_Aad-2-U3ZC6_hManE,8726
35
- aid_runtime/evals/runner.py,sha256=Lkl-kAVxegPO40pCBUcprRBKvfL6bjYzVf__xe6Z-Mc,7951
36
+ aid_runtime/evals/runner.py,sha256=mF7YpGm8LOi2ansEmbre13Kz30NmOTpBgHZoJqrG1bo,10154
36
37
  aid_runtime/providers/__init__.py,sha256=MQ-vU_QeeUgfqMlwLi0layJBhmvbZat9gIkDFcFl7Pg,1827
37
38
  aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
38
39
  aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
@@ -48,7 +49,7 @@ aid_runtime/retrieval/citations.py,sha256=UL9fsxLTzzO0n8tEW3X2O5erJ0hrk08NYMkZ9P
48
49
  aid_runtime/retrieval/connectors.py,sha256=iKvnQVCKx3gYaDmwRAmLwExYbUuiWpF9tgdysx0sxCk,20582
49
50
  aid_runtime/retrieval/embedding.py,sha256=Ea7zOZnnX2oGdnKi2AcecxYZkn9KirgJO_xOf7iDDI8,24775
50
51
  aid_runtime/retrieval/filters.py,sha256=mEa2Ok20VG5Fxe5GWYAxvhl4HK4HV6FHZ5r0wnr-ZLI,6240
51
- aid_runtime/retrieval/gate.py,sha256=3avH1Gwp7iv7mMOskmNbk70Yq85tXwJrKVrQAKKI4Js,4840
52
+ aid_runtime/retrieval/gate.py,sha256=MpQQYVd4rJlk4iZ2egJIP1kC9WL-W_HtjKXo20Vx_Ng,5642
52
53
  aid_runtime/retrieval/hybrid.py,sha256=-GIBeI3njT5uaEvSeq2t151Zlv2yOPHOPje4TJLNVyU,5804
53
54
  aid_runtime/retrieval/knowledge_base.py,sha256=zCYuPFQwfU1a_G4FOv1nRL7MQqxmMkpN5yIdlS3bY4I,42241
54
55
  aid_runtime/retrieval/metrics.py,sha256=LN36BIXzpbhkG9grzE0q5wncgXt_Y85-b5jGJ038-3Y,7904
@@ -57,7 +58,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
57
58
  aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
58
59
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
59
60
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
60
- aid_runtime_python-0.1.150.dist-info/METADATA,sha256=V_PyFw8MH7dvLHXPe6DGqt6HC43fcotGLuksuY-wd80,17163
61
- aid_runtime_python-0.1.150.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
62
- aid_runtime_python-0.1.150.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
63
- aid_runtime_python-0.1.150.dist-info/RECORD,,
61
+ aid_runtime_python-0.1.152.dist-info/METADATA,sha256=r_WcpearshoGkgMXH0HFFBGRHA_0vRHGczIsveD-QB4,17163
62
+ aid_runtime_python-0.1.152.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
63
+ aid_runtime_python-0.1.152.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
64
+ aid_runtime_python-0.1.152.dist-info/RECORD,,