aid-runtime-python 0.1.150__tar.gz → 0.1.152__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 (120) hide show
  1. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/PKG-INFO +1 -1
  2. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/pyproject.toml +1 -1
  3. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/__init__.py +15 -1
  4. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/loop.py +42 -13
  5. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/evals/runner.py +54 -3
  6. aid_runtime_python-0.1.152/src/aid_runtime/metrics.py +133 -0
  7. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/gate.py +15 -1
  8. aid_runtime_python-0.1.152/src/aid_runtime/telemetry.py +338 -0
  9. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
  10. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime_python.egg-info/SOURCES.txt +2 -0
  11. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_agents_budget.py +58 -0
  12. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_evals.py +29 -0
  13. aid_runtime_python-0.1.152/tests/test_metrics.py +127 -0
  14. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_gate.py +52 -0
  15. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_telemetry.py +189 -1
  16. aid_runtime_python-0.1.150/src/aid_runtime/telemetry.py +0 -184
  17. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/README.md +0 -0
  18. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/setup.cfg +0 -0
  19. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/__init__.py +0 -0
  20. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/chat_model.py +0 -0
  21. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/deep_agents.py +0 -0
  22. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/engine.py +0 -0
  23. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/guardrails.py +0 -0
  24. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/ir.py +0 -0
  25. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/managed.py +0 -0
  26. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/memory.py +0 -0
  27. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/policy.py +0 -0
  28. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/agents/state.py +0 -0
  29. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/cache.py +0 -0
  30. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/concurrency.py +0 -0
  31. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/control.py +0 -0
  32. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/cost.py +0 -0
  33. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/decisions.py +0 -0
  34. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/errors.py +0 -0
  35. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/evals/__init__.py +0 -0
  36. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/evals/dataset.py +0 -0
  37. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/evals/gate.py +0 -0
  38. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/evals/metrics.py +0 -0
  39. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/evals/predicate.py +0 -0
  40. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/gateway.py +0 -0
  41. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/local_trace.py +0 -0
  42. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/pipeline.py +0 -0
  43. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/prompts.py +0 -0
  44. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/__init__.py +0 -0
  45. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/anthropic.py +0 -0
  46. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/base.py +0 -0
  47. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/bedrock.py +0 -0
  48. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/fake.py +0 -0
  49. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/gemini.py +0 -0
  50. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/gemini_wire.py +0 -0
  51. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/http.py +0 -0
  52. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/providers/vertex.py +0 -0
  53. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/py.typed +0 -0
  54. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/__init__.py +0 -0
  55. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/chunking.py +0 -0
  56. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/citations.py +0 -0
  57. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/connectors.py +0 -0
  58. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/embedding.py +0 -0
  59. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/filters.py +0 -0
  60. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/hybrid.py +0 -0
  61. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/knowledge_base.py +0 -0
  62. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/metrics.py +0 -0
  63. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/pgvector.py +0 -0
  64. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/rerank.py +0 -0
  65. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/retriever.py +0 -0
  66. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/stores.py +0 -0
  67. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/retrieval/types.py +0 -0
  68. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/steps.py +0 -0
  69. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/structured.py +0 -0
  70. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/tools.py +0 -0
  71. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/tracing.py +0 -0
  72. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime/types.py +0 -0
  73. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
  74. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime_python.egg-info/requires.txt +0 -0
  75. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
  76. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_agents_deep_agents.py +0 -0
  77. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_agents_hitl.py +0 -0
  78. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_agents_loop.py +0 -0
  79. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_agents_memory.py +0 -0
  80. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_anthropic_provider.py +0 -0
  81. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_bedrock_provider.py +0 -0
  82. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_cache.py +0 -0
  83. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_concurrency.py +0 -0
  84. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_control.py +0 -0
  85. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_cost.py +0 -0
  86. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_dataset.py +0 -0
  87. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_decisions.py +0 -0
  88. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_evals_assert_gate.py +0 -0
  89. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_evals_decision.py +0 -0
  90. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_evals_gate.py +0 -0
  91. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_evals_predicate.py +0 -0
  92. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_gateway.py +0 -0
  93. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_gemini_provider.py +0 -0
  94. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_guardrails.py +0 -0
  95. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_guardrails_managed.py +0 -0
  96. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_guardrails_model_armor.py +0 -0
  97. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_http_provider.py +0 -0
  98. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_local_trace.py +0 -0
  99. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_package.py +0 -0
  100. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_pipeline.py +0 -0
  101. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_prompts.py +0 -0
  102. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_chunking.py +0 -0
  103. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_citations.py +0 -0
  104. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_connectors.py +0 -0
  105. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_embedding.py +0 -0
  106. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_filters.py +0 -0
  107. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_hybrid.py +0 -0
  108. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_knowledge_base.py +0 -0
  109. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_metrics.py +0 -0
  110. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_rerank.py +0 -0
  111. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_stores.py +0 -0
  112. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_retrieval_types.py +0 -0
  113. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_steps.py +0 -0
  114. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_streaming.py +0 -0
  115. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_structured.py +0 -0
  116. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_tool_permissions.py +0 -0
  117. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_tools.py +0 -0
  118. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_tracing.py +0 -0
  119. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/tests/test_types.py +0 -0
  120. {aid_runtime_python-0.1.150 → aid_runtime_python-0.1.152}/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.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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "aid-runtime-python"
7
- version = "0.1.150"
7
+ version = "0.1.152"
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"
@@ -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])
@@ -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