aid-runtime-python 0.1.152__py3-none-any.whl → 0.1.154__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
@@ -116,6 +116,7 @@ from aid_runtime.errors import (
116
116
  from aid_runtime.evals import (
117
117
  BaselineGate,
118
118
  CaseOutcome,
119
+ CostCeiling,
119
120
  Dataset,
120
121
  DatasetRun,
121
122
  EvalBaseline,
@@ -126,6 +127,7 @@ from aid_runtime.evals import (
126
127
  GatewayRunner,
127
128
  JsonSchemaValid,
128
129
  JudgeVerdict,
130
+ LatencyCeiling,
129
131
  LlmJudge,
130
132
  Metric,
131
133
  MetricBaseline,
@@ -133,8 +135,12 @@ from aid_runtime.evals import (
133
135
  MetricResult,
134
136
  MetricRun,
135
137
  NormalizedContains,
138
+ RunContext,
136
139
  Runner,
140
+ RunOutput,
137
141
  Threshold,
142
+ ToolTrace,
143
+ Trajectory,
138
144
  default_metrics,
139
145
  evaluate_once,
140
146
  gate_from_config,
@@ -331,7 +337,7 @@ from aid_runtime.types import (
331
337
  )
332
338
 
333
339
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
334
- __version__ = "0.1.152"
340
+ __version__ = "0.1.154"
335
341
 
336
342
  __all__ = [
337
343
  "AGENT_LABEL",
@@ -397,6 +403,7 @@ __all__ = [
397
403
  "ConcurrencyLimiter",
398
404
  "ConfigurationError",
399
405
  "Connector",
406
+ "CostCeiling",
400
407
  "CostLedger",
401
408
  "CostProfile",
402
409
  "Dataset",
@@ -450,6 +457,7 @@ __all__ = [
450
457
  "KnowledgeDataSourceKind",
451
458
  "KnowledgeDataSourceSpec",
452
459
  "KnowledgeVectorStoreSpec",
460
+ "LatencyCeiling",
453
461
  "LedgerEntry",
454
462
  "LexicalReranker",
455
463
  "LlmJudge",
@@ -505,6 +513,8 @@ __all__ = [
505
513
  "RetrieverSeam",
506
514
  "RetrieverSpec",
507
515
  "Role",
516
+ "RunContext",
517
+ "RunOutput",
508
518
  "RunResult",
509
519
  "RunStatus",
510
520
  "Runner",
@@ -541,6 +551,8 @@ __all__ = [
541
551
  "ToolPermissionError",
542
552
  "ToolResult",
543
553
  "ToolSpec",
554
+ "ToolTrace",
555
+ "Trajectory",
544
556
  "UnknownModelAliasError",
545
557
  "VectorStore",
546
558
  "VectorStoreSpec",
@@ -17,14 +17,18 @@ from aid_runtime.evals.gate import (
17
17
  )
18
18
  from aid_runtime.evals.metrics import (
19
19
  AssertMetric,
20
+ CostCeiling,
20
21
  DecisionScore,
21
22
  ExactMatch,
22
23
  JsonSchemaValid,
23
24
  JudgeVerdict,
25
+ LatencyCeiling,
24
26
  LlmJudge,
25
27
  Metric,
26
28
  MetricResult,
27
29
  NormalizedContains,
30
+ RunContext,
31
+ ToolTrace,
28
32
  default_metrics,
29
33
  metric_names,
30
34
  normalize,
@@ -38,11 +42,13 @@ from aid_runtime.evals.runner import (
38
42
  gateway_judge,
39
43
  run_evaluation,
40
44
  )
45
+ from aid_runtime.evals.trajectory import RunOutput, Trajectory
41
46
 
42
47
  __all__ = [
43
48
  "AssertMetric",
44
49
  "BaselineGate",
45
50
  "CaseOutcome",
51
+ "CostCeiling",
46
52
  "Dataset",
47
53
  "DatasetRun",
48
54
  "DecisionScore",
@@ -54,6 +60,7 @@ __all__ = [
54
60
  "GatewayRunner",
55
61
  "JsonSchemaValid",
56
62
  "JudgeVerdict",
63
+ "LatencyCeiling",
57
64
  "LlmJudge",
58
65
  "Metric",
59
66
  "MetricBaseline",
@@ -61,8 +68,12 @@ __all__ = [
61
68
  "MetricResult",
62
69
  "MetricRun",
63
70
  "NormalizedContains",
71
+ "RunContext",
72
+ "RunOutput",
64
73
  "Runner",
65
74
  "Threshold",
75
+ "ToolTrace",
76
+ "Trajectory",
66
77
  "default_metrics",
67
78
  "evaluate_once",
68
79
  "gate_from_config",
@@ -21,18 +21,23 @@ from aid_runtime.decisions import DecisionClient, DecisionQuestion, DecisionResp
21
21
  from aid_runtime.errors import ConfigurationError, EvalError
22
22
  from aid_runtime.evals.dataset import EvalCase
23
23
  from aid_runtime.evals.predicate import evaluate_predicate
24
+ from aid_runtime.evals.trajectory import Trajectory
24
25
  from aid_runtime.structured import run_structured
25
26
 
26
27
  __all__ = [
27
28
  "AssertMetric",
29
+ "CostCeiling",
28
30
  "DecisionScore",
29
31
  "ExactMatch",
30
32
  "JsonSchemaValid",
31
33
  "JudgeVerdict",
34
+ "LatencyCeiling",
32
35
  "LlmJudge",
33
36
  "Metric",
34
37
  "MetricResult",
35
38
  "NormalizedContains",
39
+ "RunContext",
40
+ "ToolTrace",
36
41
  "default_metrics",
37
42
  "metric_names",
38
43
  "normalize",
@@ -52,6 +57,33 @@ class MetricResult(BaseModel):
52
57
  detail: str = ""
53
58
 
54
59
 
60
+ class RunContext(BaseModel):
61
+ """What the harness measured about the run a prediction came from.
62
+
63
+ A prediction on its own cannot answer "what did this case cost" or "how long did
64
+ it take", and those are numbers the harness already has. They travel beside the
65
+ prediction so a ceiling metric can read them without the runner having to smuggle
66
+ them through the answer text. A metric that only inspects text ignores this and
67
+ behaves exactly as it did before.
68
+
69
+ ``metered`` is deliberately separate from ``cost_usd``. An unmetered runner reports
70
+ a real ``0.0`` -- "does not meter" and "spent nothing" are the same number -- so a
71
+ cost ceiling has to be told which one it is looking at, or it would pass forever
72
+ over a run nobody measured.
73
+
74
+ ``trajectory`` is ``None`` when the runner said nothing about tool calls, and that is
75
+ distinguishable from a run that called no tools: the second is an empty trajectory,
76
+ the first is a runner that only ever returned its answer text.
77
+ """
78
+
79
+ model_config = ConfigDict(frozen=True, extra="forbid")
80
+
81
+ cost_usd: float = Field(default=0.0, ge=0.0)
82
+ latency_ms: float = Field(default=0.0, ge=0.0)
83
+ metered: bool = False
84
+ trajectory: Trajectory | None = None
85
+
86
+
55
87
  @runtime_checkable
56
88
  class Metric(Protocol):
57
89
  """Scores a single prediction."""
@@ -71,7 +103,9 @@ class Metric(Protocol):
71
103
  """
72
104
  ...
73
105
 
74
- async def score(self, case: EvalCase, prediction: str) -> MetricResult: ...
106
+ async def score(
107
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
108
+ ) -> MetricResult: ...
75
109
 
76
110
 
77
111
  def normalize(text: str) -> str:
@@ -94,7 +128,9 @@ class ExactMatch:
94
128
  def deterministic(self) -> bool:
95
129
  return True
96
130
 
97
- async def score(self, case: EvalCase, prediction: str) -> MetricResult:
131
+ async def score(
132
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
133
+ ) -> MetricResult:
98
134
  if case.expected is None:
99
135
  raise EvalError(f"case {case.id!r} has no expected value for {self.name}")
100
136
  ok = normalize(prediction) == normalize(case.expected)
@@ -120,7 +156,9 @@ class NormalizedContains:
120
156
  def deterministic(self) -> bool:
121
157
  return True
122
158
 
123
- async def score(self, case: EvalCase, prediction: str) -> MetricResult:
159
+ async def score(
160
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
161
+ ) -> MetricResult:
124
162
  if case.expected is None:
125
163
  raise EvalError(f"case {case.id!r} has no expected value for {self.name}")
126
164
  ok = normalize(case.expected) in normalize(prediction)
@@ -150,7 +188,9 @@ class JsonSchemaValid:
150
188
  def deterministic(self) -> bool:
151
189
  return True
152
190
 
153
- async def score(self, case: EvalCase, prediction: str) -> MetricResult:
191
+ async def score(
192
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
193
+ ) -> MetricResult:
154
194
  schema = case.metadata.get("json_schema")
155
195
  try:
156
196
  parsed = json.loads(prediction)
@@ -198,7 +238,9 @@ class AssertMetric:
198
238
  def deterministic(self) -> bool:
199
239
  return True
200
240
 
201
- async def score(self, case: EvalCase, prediction: str) -> MetricResult:
241
+ async def score(
242
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
243
+ ) -> MetricResult:
202
244
  ok = evaluate_predicate(self._expr, case=case, prediction=prediction)
203
245
  return MetricResult(
204
246
  metric=self.name,
@@ -251,7 +293,9 @@ class LlmJudge:
251
293
  def deterministic(self) -> bool:
252
294
  return False
253
295
 
254
- async def score(self, case: EvalCase, prediction: str) -> MetricResult:
296
+ async def score(
297
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
298
+ ) -> MetricResult:
255
299
  prompt = self._build_prompt(case, prediction)
256
300
  try:
257
301
  verdict = await run_structured(self._call, JudgeVerdict, prompt, retries=self._retries)
@@ -324,7 +368,9 @@ class DecisionScore:
324
368
  def deterministic(self) -> bool:
325
369
  return False
326
370
 
327
- async def score(self, case: EvalCase, prediction: str) -> MetricResult:
371
+ async def score(
372
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
373
+ ) -> MetricResult:
328
374
  response = await self._ask(prediction)
329
375
  answer = response.answers.get(self._decision.id)
330
376
  if answer is None or answer.score is None:
@@ -362,6 +408,186 @@ class DecisionScore:
362
408
  )
363
409
 
364
410
 
411
+ class _Ceiling:
412
+ """Shared shape for the two metrics that read a number off the run context.
413
+
414
+ Both refuse rather than pass when the number they are asked to bound was never
415
+ measured: a ceiling that passes over an unmeasured run is a gate that cannot fail,
416
+ which is worse than no gate at all because it looks like coverage.
417
+ """
418
+
419
+ _quantity = "value"
420
+
421
+ def __init__(self, *, name: str) -> None:
422
+ self._name = name
423
+
424
+ @property
425
+ def name(self) -> str:
426
+ return self._name
427
+
428
+ @property
429
+ def deterministic(self) -> bool:
430
+ return True
431
+
432
+ def _measure(self, case: EvalCase, context: RunContext | None) -> float:
433
+ raise NotImplementedError
434
+
435
+ async def score(
436
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
437
+ ) -> MetricResult:
438
+ ceiling = self._limit()
439
+ measured = self._measure(case, context)
440
+ ok = measured <= ceiling
441
+ return MetricResult(
442
+ metric=self.name,
443
+ score=1.0 if ok else 0.0,
444
+ passed=ok,
445
+ detail=f"{self._quantity} {self._format(measured)}, ceiling {self._format(ceiling)}",
446
+ )
447
+
448
+ def _limit(self) -> float:
449
+ raise NotImplementedError
450
+
451
+ def _format(self, value: float) -> str:
452
+ return f"{value:.4f}"
453
+
454
+
455
+ class CostCeiling(_Ceiling):
456
+ """Whether one case stayed inside a declared per-case spend.
457
+
458
+ Costs money to find out, so it is opt-in: an eval declares it and the generator
459
+ maps it. The harness reads spend from the gateway ledger, which only exists for a
460
+ runner that meters, so an unmetered runner is refused, not scored.
461
+ """
462
+
463
+ _quantity = "spent"
464
+
465
+ def __init__(self, *, max_usd: float, name: str = "cost") -> None:
466
+ if max_usd <= 0:
467
+ raise ConfigurationError(f"a cost ceiling must be above zero, got {max_usd:g}")
468
+ super().__init__(name=name)
469
+ self._max = max_usd
470
+
471
+ def _limit(self) -> float:
472
+ return self._max
473
+
474
+ def _measure(self, case: EvalCase, context: RunContext | None) -> float:
475
+ if context is None or not context.metered:
476
+ raise EvalError(
477
+ f"case {case.id!r} carries a cost ceiling, but its runner does not meter "
478
+ "spend, so the ceiling would pass over a run nobody measured"
479
+ )
480
+ return context.cost_usd
481
+
482
+ def _format(self, value: float) -> str:
483
+ return f"${value:.4f}"
484
+
485
+
486
+ class LatencyCeiling(_Ceiling):
487
+ """Whether one case finished inside a declared wall-clock budget.
488
+
489
+ Measured by the harness around the runner call, so it is available for every
490
+ runner rather than only the metering ones.
491
+ """
492
+
493
+ _quantity = "took"
494
+
495
+ def __init__(self, *, max_ms: float, name: str = "latency") -> None:
496
+ if max_ms <= 0:
497
+ raise ConfigurationError(f"a latency ceiling must be above zero, got {max_ms:g}")
498
+ super().__init__(name=name)
499
+ self._max = max_ms
500
+
501
+ def _limit(self) -> float:
502
+ return self._max
503
+
504
+ def _measure(self, case: EvalCase, context: RunContext | None) -> float:
505
+ if context is None:
506
+ raise EvalError(
507
+ f"case {case.id!r} carries a latency ceiling, but it was scored outside a "
508
+ "measured run, so there is no elapsed time to compare against it"
509
+ )
510
+ return context.latency_ms
511
+
512
+ def _format(self, value: float) -> str:
513
+ return f"{value:.0f}ms"
514
+
515
+
516
+ class ToolTrace:
517
+ """Whether a run called the tools it was expected to, in the order it was told.
518
+
519
+ ``ordered`` is the whole semantics, and it is the reason this metric needs a
520
+ decision rather than a default: ``True`` means ``expect`` has to appear as a
521
+ *subsequence* of the calls made, ``False`` means every expected tool has to appear
522
+ at least once, in any order. Extra calls are tolerated either way -- a run that
523
+ looked one more thing up on the way did more than the minimum, and failing it would
524
+ benchmark one exact transcript rather than a capability. A run that calls an
525
+ expected tool twice passes too; the metric asks whether the tool was called, not how
526
+ often, because "how often" is a budget question and ``cost`` answers it.
527
+
528
+ Refuses rather than passes when the runner reported no trajectory: a trace assertion
529
+ over an answer-only runner would pass on every case by having nothing to compare,
530
+ which is coverage that does not exist.
531
+ """
532
+
533
+ def __init__(
534
+ self,
535
+ *,
536
+ expect: Sequence[str],
537
+ ordered: bool = False,
538
+ name: str = "tool-trace",
539
+ ) -> None:
540
+ if not expect:
541
+ raise ConfigurationError("a tool-trace metric must expect at least one tool")
542
+ self._name = name
543
+ self._expect = tuple(expect)
544
+ self._ordered = ordered
545
+
546
+ @property
547
+ def name(self) -> str:
548
+ return self._name
549
+
550
+ @property
551
+ def deterministic(self) -> bool:
552
+ return True
553
+
554
+ async def score(
555
+ self, case: EvalCase, prediction: str, *, context: RunContext | None = None
556
+ ) -> MetricResult:
557
+ if context is None or context.trajectory is None:
558
+ raise EvalError(
559
+ f"case {case.id!r} carries a tool-trace metric, but its runner reported no "
560
+ "tool calls, so there is nothing to compare the expectation against"
561
+ )
562
+ calls = context.trajectory.calls
563
+ ok = self._satisfied_by(calls)
564
+ return MetricResult(
565
+ metric=self.name,
566
+ score=1.0 if ok else 0.0,
567
+ passed=ok,
568
+ detail=(
569
+ f"called {_tool_list(calls)}"
570
+ if ok
571
+ else (
572
+ f"expected {_tool_list(self._expect)}"
573
+ f"{' in order' if self._ordered else ''}, called {_tool_list(calls)}"
574
+ )
575
+ ),
576
+ )
577
+
578
+ def _satisfied_by(self, calls: Sequence[str]) -> bool:
579
+ if not self._ordered:
580
+ return set(self._expect) <= set(calls)
581
+ # Walking the calls once with a cursor is the subsequence test: `in` on an
582
+ # iterator advances it, so each expected tool has to be found after the last one.
583
+ remaining = iter(calls)
584
+ return all(tool in remaining for tool in self._expect)
585
+
586
+
587
+ def _tool_list(names: Sequence[str]) -> str:
588
+ return ", ".join(names) if names else "no tools"
589
+
590
+
365
591
  def default_metrics() -> tuple[Metric, ...]:
366
592
  """The deterministic gate metrics: everything that needs no model call."""
367
593
  return (ExactMatch(), NormalizedContains(), JsonSchemaValid())
@@ -16,7 +16,8 @@ from pydantic import BaseModel, ConfigDict, Field
16
16
  from aid_runtime.errors import EvalError
17
17
  from aid_runtime.evals.dataset import Dataset, EvalCase
18
18
  from aid_runtime.evals.gate import EvalRun, MetricRun
19
- from aid_runtime.evals.metrics import Metric, MetricResult
19
+ from aid_runtime.evals.metrics import Metric, MetricResult, RunContext
20
+ from aid_runtime.evals.trajectory import RunOutput, Trajectory
20
21
  from aid_runtime.gateway import ModelGateway
21
22
  from aid_runtime.metrics import record_eval_case
22
23
  from aid_runtime.types import CompletionRequest, Message
@@ -31,18 +32,25 @@ __all__ = [
31
32
  "run_evaluation",
32
33
  ]
33
34
 
34
- #: Anything that turns a case into a prediction.
35
- Runner = Callable[[EvalCase], Awaitable[str]]
35
+ #: Anything that turns a case into a prediction. A runner that can also say how it got
36
+ #: there returns a :class:`RunOutput`; one that only has an answer returns a ``str``,
37
+ #: which is what every text metric needs and all a ``tool-trace`` metric refuses.
38
+ Runner = Callable[[EvalCase], Awaitable[str | RunOutput]]
36
39
 
37
40
 
38
41
  class CaseOutcome(BaseModel):
39
- """One case's prediction and its per-metric scores, for inspection."""
42
+ """One case's prediction and its per-metric scores, for inspection.
43
+
44
+ ``trajectory`` is ``None`` for a runner that reported no tool calls, so "the runner
45
+ said nothing" and "the run called no tools" stay different answers.
46
+ """
40
47
 
41
48
  model_config = ConfigDict(frozen=True, extra="forbid")
42
49
 
43
50
  case_id: str
44
51
  prediction: str
45
52
  scores: tuple[MetricResult, ...] = ()
53
+ trajectory: Trajectory | None = None
46
54
 
47
55
  @property
48
56
  def passed(self) -> bool:
@@ -197,15 +205,33 @@ async def evaluate_once(
197
205
  for case in dataset.cases:
198
206
  cost_before = _runner_cost(runner)
199
207
  started = perf_counter()
200
- prediction = await runner(case)
208
+ raw = await runner(case)
209
+ prediction, trajectory = _split(raw)
201
210
  # The runner call, not the scoring, is what a latency budget constrains: scoring
202
211
  # is the harness measuring the answer, and charging its time to the pipeline would
203
212
  # report a slower product because a judge was added to its eval.
204
213
  latency_ms = (perf_counter() - started) * 1000.0
205
- scores = tuple([await metric.score(case, prediction) for metric in metrics])
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.
214
+ # Metrics see the pipeline's own spend, measured before scoring, because "what did
215
+ # this task cost" is a property of the product and not of the harness auditing it.
216
+ context = RunContext(
217
+ cost_usd=_spent_since(runner, cost_before),
218
+ latency_ms=latency_ms,
219
+ metered=cost_before is not None,
220
+ trajectory=trajectory,
221
+ )
222
+ scores = tuple(
223
+ [await metric.score(case, prediction, context=context) for metric in metrics]
224
+ )
225
+ outcomes.append(
226
+ CaseOutcome(
227
+ case_id=case.id,
228
+ prediction=prediction,
229
+ scores=scores,
230
+ trajectory=trajectory,
231
+ )
232
+ )
233
+ # The published series is read after scoring, because a model-backed metric spends
234
+ # money too and a cost series that ignored the judge would report half the run.
209
235
  record_eval_case(
210
236
  eval_id=label,
211
237
  cost_usd=_spent_since(runner, cost_before),
@@ -216,6 +242,13 @@ async def evaluate_once(
216
242
  )
217
243
 
218
244
 
245
+ def _split(raw: str | RunOutput) -> tuple[str, Trajectory | None]:
246
+ """The prediction, and the trajectory when the runner reported one."""
247
+ if isinstance(raw, RunOutput):
248
+ return raw.text, raw.trajectory
249
+ return raw, None
250
+
251
+
219
252
  def _runner_cost(runner: Runner) -> float | None:
220
253
  """A runner's cumulative model spend, when it meters one.
221
254
 
@@ -0,0 +1,69 @@
1
+ """The tool calls a run made, in the order it made them.
2
+
3
+ A prediction is what a pipeline *said*; a trajectory is how an agent got there. Scoring
4
+ "did it look the order up before issuing the refund" needs the second, and the agent loop
5
+ already records it: every :class:`~aid_runtime.agents.state.StepRecord` carries the tool
6
+ names that step called, so the sequence is a flatten, not a new instrumentation point.
7
+
8
+ :class:`RunOutput` is how a runner hands both back. A runner that returns a plain ``str``
9
+ still works and still scores every text metric; what it cannot do is satisfy a
10
+ ``tool-trace`` metric, which refuses rather than passing over a run it was never told the
11
+ tool calls of.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Sequence
17
+ from typing import TYPE_CHECKING
18
+
19
+ from pydantic import BaseModel, ConfigDict
20
+
21
+ if TYPE_CHECKING:
22
+ # Type-only: this module reaches into a record's shape, never its definitions, so
23
+ # importing the agent package at runtime would only buy an import cycle.
24
+ from aid_runtime.agents.state import RunResult, StepRecord
25
+
26
+ __all__ = ["RunOutput", "Trajectory"]
27
+
28
+
29
+ class Trajectory(BaseModel):
30
+ """Every tool call a run made, flattened into the order they happened.
31
+
32
+ Deliberately just the names, not arguments or results: an expectation is written
33
+ against *what* a run did, and pinning the arguments of a model-authored call would
34
+ make the assertion fail on a paraphrase that was equally correct.
35
+ """
36
+
37
+ model_config = ConfigDict(frozen=True, extra="forbid")
38
+
39
+ calls: tuple[str, ...] = ()
40
+
41
+ @classmethod
42
+ def from_steps(cls, steps: Sequence[StepRecord]) -> Trajectory:
43
+ return cls(calls=tuple(name for step in steps for name in step.tool_names))
44
+
45
+ @classmethod
46
+ def from_run(cls, result: RunResult) -> Trajectory:
47
+ """The trajectory of an agent run, read off the steps it recorded.
48
+
49
+ A paused or blocked run still has one: the loop records a step before it decides
50
+ what to do with it, so a run that stopped at an approval records the calls that
51
+ asked for it.
52
+ """
53
+ return cls.from_steps(result.steps)
54
+
55
+ def __bool__(self) -> bool:
56
+ return bool(self.calls)
57
+
58
+
59
+ class RunOutput(BaseModel):
60
+ """An answer, plus how the run arrived at it.
61
+
62
+ Returning this instead of a bare string is the whole opt-in for trajectory evals: a
63
+ runner that has nothing to say about tool calls keeps returning ``str``.
64
+ """
65
+
66
+ model_config = ConfigDict(frozen=True, extra="forbid")
67
+
68
+ text: str
69
+ trajectory: Trajectory = Trajectory()
aid_runtime/gateway.py CHANGED
@@ -32,7 +32,14 @@ from aid_runtime.errors import (
32
32
  UnknownModelAliasError,
33
33
  )
34
34
  from aid_runtime.providers.base import Provider
35
- from aid_runtime.tracing import ATTRIBUTES, get_tracer, llm_span, record_cost, record_usage
35
+ from aid_runtime.tracing import (
36
+ ATTRIBUTES,
37
+ get_tracer,
38
+ llm_span,
39
+ record_content,
40
+ record_cost,
41
+ record_usage,
42
+ )
36
43
  from aid_runtime.types import (
37
44
  Capability,
38
45
  CompletionRequest,
@@ -55,6 +62,15 @@ _CACHE_CHUNK = 16
55
62
  CallHook = Callable[[LedgerEntry], None]
56
63
 
57
64
 
65
+ def _prompt_text(request: CompletionRequest) -> str:
66
+ """The prompt as one string, for a span that was asked to record payloads.
67
+
68
+ Role-prefixed rather than concatenated, so a captured prompt still shows which
69
+ turn a line came from once it is a row of JSONL rather than a live message list.
70
+ """
71
+ return "\n\n".join(f"{message.role}: {message.content}" for message in request.messages)
72
+
73
+
58
74
  def _sse(payload: dict[str, Any]) -> bytes:
59
75
  """Encode one Server-Sent Event ``data`` frame as UTF-8 bytes."""
60
76
  return f"data: {json.dumps(payload, separators=(',', ':'))}\n\n".encode()
@@ -270,6 +286,7 @@ class ModelGateway:
270
286
  cost = spec.cost.cost_usd(usage)
271
287
  record_usage(span, usage)
272
288
  record_cost(span, cost, alias=pinned.alias)
289
+ record_content(span, input_text=_prompt_text(request), output_text=text)
273
290
 
274
291
  entry = LedgerEntry(
275
292
  alias=pinned.alias,
@@ -341,6 +358,7 @@ class ModelGateway:
341
358
  cost = spec.cost.cost_usd(response.usage)
342
359
  record_usage(span, response.usage)
343
360
  record_cost(span, cost, alias=pinned.alias)
361
+ record_content(span, input_text=_prompt_text(request), output_text=response.text)
344
362
  if len(attempted) > 1:
345
363
  span.set_attribute(ATTRIBUTES["attempts"], list(attempted))
346
364
 
aid_runtime/tracing.py CHANGED
@@ -16,6 +16,7 @@ spans written here leave the process.
16
16
  from __future__ import annotations
17
17
 
18
18
  import contextlib
19
+ import os
19
20
  from collections.abc import Iterator, Sequence
20
21
  from typing import Any, Protocol
21
22
 
@@ -27,13 +28,17 @@ from aid_runtime.types import TokenUsage
27
28
 
28
29
  __all__ = [
29
30
  "ATTRIBUTES",
31
+ "CONTENT_ENV",
30
32
  "GEN_AI_OPERATION_CHAT",
33
+ "MAX_CONTENT_CHARS",
31
34
  "GuardrailEvent",
32
35
  "agent_span",
33
36
  "aid_attributes",
37
+ "content_capture_enabled",
34
38
  "get_tracer",
35
39
  "llm_span",
36
40
  "record_attributes",
41
+ "record_content",
37
42
  "record_cost",
38
43
  "record_exception",
39
44
  "record_guardrail",
@@ -87,8 +92,20 @@ ATTRIBUTES: dict[str, str] = {
87
92
  "guardrail_stage": "aid.guardrail.stage",
88
93
  "guardrail_action": "aid.guardrail.action",
89
94
  "guardrail_policies": "aid.guardrail.policies",
95
+ # Payload text. Written only when ``AID_TRACE_CONTENT`` asks for it; see
96
+ # :func:`record_content` for why the default is off.
97
+ "input_text": "aid.input.text",
98
+ "output_text": "aid.output.text",
90
99
  }
91
100
 
101
+ #: The environment variable that opts in to recording prompt and completion text.
102
+ CONTENT_ENV = "AID_TRACE_CONTENT"
103
+
104
+ #: Longest payload fragment a span records. A dataset needs enough of the input to
105
+ #: name the case, not a full transcript, and an unbounded attribute would put a
106
+ #: megabyte into one JSONL line.
107
+ MAX_CONTENT_CHARS = 4000
108
+
92
109
  _TRACER_NAME = "aid_runtime"
93
110
 
94
111
 
@@ -162,6 +179,41 @@ def record_attributes(span: Span, **values: Any) -> None:
162
179
  span.set_attribute(key, value)
163
180
 
164
181
 
182
+ def content_capture_enabled() -> bool:
183
+ """Whether ``AID_TRACE_CONTENT`` asks for prompt and completion text on spans."""
184
+ return os.environ.get(CONTENT_ENV, "").strip().lower() in {"1", "true", "yes", "on"}
185
+
186
+
187
+ def record_content(span: Span, *, input_text: str | None, output_text: str | None) -> None:
188
+ """Attach the prompt and the completion to a span **only** when asked to.
189
+
190
+ Everything else this runtime records is a fact about a call -- a model, a token
191
+ count, a price. Payloads are what a user said and what a model answered, so they
192
+ stay out of the trace unless the operator names :data:`CONTENT_ENV`. Three
193
+ reasons the default matters:
194
+
195
+ - The sink writes to a local directory that a repository may commit and a CI log
196
+ may echo, so text that is off by default cannot leak by accident.
197
+ - Nothing here redacts. A captured prompt is captured as it was sent, and the
198
+ operator who set the variable owns that decision; the spec's ``pii.redact``
199
+ governs the deployed feedback path, not this local switch.
200
+ - ``aid trace export --dataset`` is the one reader that wants the text, and it
201
+ can only build a case from a run that recorded one.
202
+
203
+ Empty and whitespace-only text is skipped, so a span that carried nothing does
204
+ not look like a decided empty answer.
205
+ """
206
+ if not content_capture_enabled():
207
+ return
208
+ for key, value in (
209
+ ("input_text", input_text),
210
+ ("output_text", output_text),
211
+ ):
212
+ if value is None or value.strip() == "":
213
+ continue
214
+ span.set_attribute(ATTRIBUTES[key], value[:MAX_CONTENT_CHARS])
215
+
216
+
165
217
  @contextlib.contextmanager
166
218
  def agent_span(
167
219
  *,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.152
3
+ Version: 0.1.154
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,11 +1,11 @@
1
- aid_runtime/__init__.py,sha256=QiMu_qQLmxEIdjp8oWyHH85LH91zaBlV-EwaGvwXv-E,14050
1
+ aid_runtime/__init__.py,sha256=GvcSITYjTsYcSr_ixvyI3YvXdK100ykdOLLLE1yE5wI,14260
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
5
5
  aid_runtime/cost.py,sha256=Hc7X6mtkeanL9eJ1lEZZCQ9LxZurhL1it0gm3s9LpQE,5465
6
6
  aid_runtime/decisions.py,sha256=1V0d9EttfwTuh8jgtC5X3wQDTZrl20ZREcs6VqIdcHY,15662
7
7
  aid_runtime/errors.py,sha256=TKkZyZZcFTl5yxNKlA8jUF4ORpYHLGFEvc6r9FK4X70,12572
8
- aid_runtime/gateway.py,sha256=p0qsaQUAYrwSzlWwpUi1wY6pdOeU98QjsWLzq8045Fo,18267
8
+ aid_runtime/gateway.py,sha256=MEEjWucsAiDzjoVfWiLxjlS0bjkYYCj5lQYY0N2CsdI,18903
9
9
  aid_runtime/local_trace.py,sha256=eg5LDsg1VfNmJNqs8KjtdzTjSqg7SWTXunLwg-b3IcM,7870
10
10
  aid_runtime/metrics.py,sha256=w55qPlFRQXUfASxpskgYiSeFcFxkL_mwbDp2IhevAbg,6050
11
11
  aid_runtime/pipeline.py,sha256=Y2jiiYISLLxgBKGBj5J2rseEDzE8RXP8v5pJ_edjHfM,6334
@@ -15,7 +15,7 @@ aid_runtime/steps.py,sha256=44v8-ebN77VGZePmfhBYi0KORFBrH2GWFSzlfczaJhs,12047
15
15
  aid_runtime/structured.py,sha256=Uga-VoGJN56lUtr-M3nmUjAKGF32cAAk-p7WceUgPzg,5061
16
16
  aid_runtime/telemetry.py,sha256=ykAXCL3XFi0yok3xr-fjD3oGvVycdfyrqJ8nGKC_ZHc,12872
17
17
  aid_runtime/tools.py,sha256=7LeaPI5aJioNe3vexUv94tvIRpOwxj1Ujt723qvO3UI,9906
18
- aid_runtime/tracing.py,sha256=jZMl5btxcUSQQDeWGMT0lQB-YSdRW7cxl5QsJVeWE7Q,9795
18
+ aid_runtime/tracing.py,sha256=wcu-gKToGcWn6O_kKz_0kcWkyaQLoRCWLkWRDgBqDRE,12080
19
19
  aid_runtime/types.py,sha256=cVYgmacDIhStQT5dX_X67-q57sPBBaWC5nybtGVqVsw,10389
20
20
  aid_runtime/agents/__init__.py,sha256=H_WKu9u0fvF56W7ccTByEv1RdayzwUfRzEKsXXDRr2A,3113
21
21
  aid_runtime/agents/chat_model.py,sha256=fZdCmSpoECuBVGZE1s8NmT2erT33RhDuLh3yJM6kAJE,14808
@@ -28,12 +28,13 @@ aid_runtime/agents/managed.py,sha256=SFyx6Rca2aoiMzA9q6B4Nfes6ZCjn_5_zN0SxzemIII
28
28
  aid_runtime/agents/memory.py,sha256=6_D6k2bzAiR2euNvzr6HB28wsUUq-R-WTQc12gkB8ao,9156
29
29
  aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
30
30
  aid_runtime/agents/state.py,sha256=4itT7BWv2JKSeWpRrDyxLguOOVnz9gGH_qgRdCbWCaw,6086
31
- aid_runtime/evals/__init__.py,sha256=Xxoz6OImHs9-BfaRQo7O4tu9J8zAIDXiotqIM-xnj1Q,1419
31
+ aid_runtime/evals/__init__.py,sha256=dx3pD1BDOZUtdN2OQpEf1G6qk6tWSaoDjoGfGyPN87o,1661
32
32
  aid_runtime/evals/dataset.py,sha256=waG4tYSJsgsZ9DLxkhUvF_X-aQB8w2OexYxc7Wwdiyg,2494
33
33
  aid_runtime/evals/gate.py,sha256=_nLWXvcuHwq8nE3HpiONg_wBkrzZyGrGT49ZNeKMyTY,15524
34
- aid_runtime/evals/metrics.py,sha256=il9lzJa-hir59pw9Muyg9MhDuozUqAQaO1Tb75CxBKc,14185
34
+ aid_runtime/evals/metrics.py,sha256=hmUy2vMKiGTD7xNFCRE3iRka53nn_NNDxLInSBzAQgY,22305
35
35
  aid_runtime/evals/predicate.py,sha256=JaeN1LJFpliI4JHYdFPtXfjH5_Aad-2-U3ZC6_hManE,8726
36
- aid_runtime/evals/runner.py,sha256=mF7YpGm8LOi2ansEmbre13Kz30NmOTpBgHZoJqrG1bo,10154
36
+ aid_runtime/evals/runner.py,sha256=kj2fdDzbVMCRAlaliPU8ycYxHE9qr0s5WDo_kvl-PAo,11498
37
+ aid_runtime/evals/trajectory.py,sha256=kwK7Cj1OSbgHj6m4Kar0fPNe7wFqzmC_OcpNqRYqRJs,2587
37
38
  aid_runtime/providers/__init__.py,sha256=MQ-vU_QeeUgfqMlwLi0layJBhmvbZat9gIkDFcFl7Pg,1827
38
39
  aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
39
40
  aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
@@ -58,7 +59,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
58
59
  aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
59
60
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
60
61
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
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,,
62
+ aid_runtime_python-0.1.154.dist-info/METADATA,sha256=quePdCie5bBK87s2ER18gEEvNHF9YkPZxjh8BO9oPR0,17163
63
+ aid_runtime_python-0.1.154.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
64
+ aid_runtime_python-0.1.154.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
65
+ aid_runtime_python-0.1.154.dist-info/RECORD,,