aid-runtime-python 0.1.156__py3-none-any.whl → 0.1.158__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
@@ -114,6 +114,8 @@ from aid_runtime.errors import (
114
114
  UnknownModelAliasError,
115
115
  )
116
116
  from aid_runtime.evals import (
117
+ AgentEvalRunner,
118
+ ApprovalPolicy,
117
119
  BaselineGate,
118
120
  CaseOutcome,
119
121
  CostCeiling,
@@ -184,7 +186,12 @@ from aid_runtime.providers import (
184
186
  GeminiProvider,
185
187
  OpenAICompatibleProvider,
186
188
  Provider,
189
+ RecordedProvider,
190
+ RecordingProvider,
191
+ ReplayDivergenceError,
187
192
  ScriptedTurn,
193
+ Transcript,
194
+ TranscriptEntry,
188
195
  VertexProvider,
189
196
  default_bedrock_base_url,
190
197
  default_vertex_base_url,
@@ -337,7 +344,7 @@ from aid_runtime.types import (
337
344
  )
338
345
 
339
346
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
340
- __version__ = "0.1.156"
347
+ __version__ = "0.1.158"
341
348
 
342
349
  __all__ = [
343
350
  "AGENT_LABEL",
@@ -378,11 +385,13 @@ __all__ = [
378
385
  "AgentBudgetDegradedError",
379
386
  "AgentCheckpoint",
380
387
  "AgentDefinition",
388
+ "AgentEvalRunner",
381
389
  "AgentHandoffUnsupportedError",
382
390
  "AgentRuntime",
383
391
  "AgentTransferCycleError",
384
392
  "AidRuntimeError",
385
393
  "AnthropicProvider",
394
+ "ApprovalPolicy",
386
395
  "BaselineGate",
387
396
  "BedrockProvider",
388
397
  "Budget",
@@ -496,10 +505,13 @@ __all__ = [
496
505
  "ProviderResponseError",
497
506
  "RankedId",
498
507
  "RecallAtK",
508
+ "RecordedProvider",
509
+ "RecordingProvider",
499
510
  "RecursiveChunker",
500
511
  "RefreshMode",
501
512
  "RefreshSpec",
502
513
  "RenderedPrompt",
514
+ "ReplayDivergenceError",
503
515
  "RerankSpec",
504
516
  "Reranker",
505
517
  "RetrievalCase",
@@ -553,6 +565,8 @@ __all__ = [
553
565
  "ToolSpec",
554
566
  "ToolTrace",
555
567
  "Trajectory",
568
+ "Transcript",
569
+ "TranscriptEntry",
556
570
  "UnknownModelAliasError",
557
571
  "VectorStore",
558
572
  "VectorStoreSpec",
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from aid_runtime.evals.agent_runner import AgentEvalRunner, ApprovalPolicy
5
6
  from aid_runtime.evals.dataset import Dataset, EvalCase
6
7
  from aid_runtime.evals.gate import (
7
8
  BaselineGate,
@@ -45,6 +46,8 @@ from aid_runtime.evals.runner import (
45
46
  from aid_runtime.evals.trajectory import RunOutput, Trajectory
46
47
 
47
48
  __all__ = [
49
+ "AgentEvalRunner",
50
+ "ApprovalPolicy",
48
51
  "AssertMetric",
49
52
  "BaselineGate",
50
53
  "CaseOutcome",
@@ -0,0 +1,213 @@
1
+ """An agent as an eval subject: run it, and score what it did.
2
+
3
+ The runner is the seam between a dataset and the agent loop, and it exists so that the
4
+ loop does not have to know it is being evaluated. A case goes in, an answer plus the
5
+ trajectory comes out, and ``tool-trace`` can then ask whether the run looked the order up
6
+ before issuing the refund.
7
+
8
+ Two things this runner is careful about, because getting either wrong makes an agent eval
9
+ say something it cannot back:
10
+
11
+ **It reports the trajectory or it says nothing.** ``RunOutput.trajectory`` is read off the
12
+ steps the loop recorded, so a run that paused at an approval still reports the calls that
13
+ asked for it. A runner that returned a bare string would satisfy every text metric and
14
+ fail every ``tool-trace`` one, which is the correct outcome: refusing beats passing on
15
+ evidence that was never collected.
16
+
17
+ **It does not answer on the reviewer's behalf.** A run pauses because the spec said a
18
+ person must decide. The decisions come from the case (``EvalCase.approvals``), and a case
19
+ that pauses without supplying one is refused. The one exception is deliberate and opt-in:
20
+ ``ApprovalPolicy.APPROVE``/``REJECT`` exist for datasets that are testing something other
21
+ than the approval, and they are named so a reader of the eval sees the scripted answer.
22
+
23
+ What this measures is worth stating plainly, since the module is named after the eval and
24
+ not the model. When the provider is a recorded transcript or a scripted fake, the model's
25
+ choices are fixed input: the run verifies that the machinery around the model obeys the
26
+ spec -- the step ceiling stops the run, an interior tool stays interior, a rejected
27
+ approval blocks the call, the spend is attributed to the case. It does not measure whether
28
+ a model chooses those calls, because no model is consulted. Verifying model behaviour
29
+ needs a pinned provider and belongs with the baselines, not with a gate.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from collections.abc import Iterable, Iterator, Mapping
35
+ from enum import StrEnum
36
+
37
+ from aid_runtime.agents.loop import AgentRuntime
38
+ from aid_runtime.agents.memory import InProcessMemoryStore
39
+ from aid_runtime.agents.state import HumanDecision, RunResult, RunStatus
40
+ from aid_runtime.errors import ConfigurationError, EvalError
41
+ from aid_runtime.evals.dataset import EvalCase
42
+ from aid_runtime.evals.trajectory import RunOutput, Trajectory
43
+ from aid_runtime.providers.base import Provider
44
+ from aid_runtime.tools import Tool
45
+
46
+ __all__ = ["AgentEvalRunner", "ApprovalPolicy"]
47
+
48
+
49
+ class ApprovalPolicy(StrEnum):
50
+ """How the harness answers when a run pauses for a person.
51
+
52
+ ``FROM_CASE`` is the default and the only policy that claims to model approval: every
53
+ pause consumes the next decision the case declared. The other two exist for datasets
54
+ whose subject is something else, and they are explicit so a reader is not left
55
+ guessing whether a paused case was approved or merely allowed through.
56
+ """
57
+
58
+ #: Take each decision from ``EvalCase.approvals``; refuse when the case runs out.
59
+ FROM_CASE = "from-case"
60
+ #: Approve every pause. Only for a case that is not about approval.
61
+ APPROVE = "approve"
62
+ #: Reject every pause.
63
+ REJECT = "reject"
64
+
65
+
66
+ #: How many pauses one case may resume through before the runner calls it a loop. The
67
+ #: agent's own ``maxSteps`` bounds the run; this bounds the *harness*, so a case that
68
+ #: keeps supplying decisions to a run that keeps pausing cannot spin forever.
69
+ _DEFAULT_MAX_RESUMES = 8
70
+
71
+
72
+ class AgentEvalRunner:
73
+ """Turns an :class:`~aid_runtime.evals.dataset.EvalCase` into a :class:`RunOutput`.
74
+
75
+ Constructed once per eval and called once per case. The runtime is rebuilt per case
76
+ rather than reused, because the cost ledger, the step counter, and the memory store
77
+ are per-run state: a shared runtime would charge case two for case one's tokens and
78
+ let a later case see an earlier case's thread memory.
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ document: Mapping[str, object],
84
+ agent_id: str,
85
+ *,
86
+ providers: Mapping[str, Provider],
87
+ tools: Iterable[Tool] = (),
88
+ approval_policy: ApprovalPolicy | str = ApprovalPolicy.FROM_CASE,
89
+ max_resumes: int = _DEFAULT_MAX_RESUMES,
90
+ ) -> None:
91
+ if not providers:
92
+ raise ConfigurationError(
93
+ "an agent eval needs at least one provider: an agent run is model calls, and "
94
+ "a runner with no provider would report an empty trajectory as a real one"
95
+ )
96
+ if max_resumes < 0:
97
+ raise ConfigurationError("max_resumes cannot be negative")
98
+ declared = _declared_agents(document)
99
+ if agent_id not in declared:
100
+ raise ConfigurationError(
101
+ f"no agent {agent_id!r} in the eval's document; declared agents: {sorted(declared)}"
102
+ )
103
+ self._document = document
104
+ self._agent_id = agent_id
105
+ self._providers = dict(providers)
106
+ self._tools = tuple(tools)
107
+ self._policy = ApprovalPolicy(approval_policy)
108
+ self._max_resumes = max_resumes
109
+ #: Cumulative model spend, which is what ``evaluate_once`` differences to charge
110
+ #: each case. Read from the ledger of the most recent run.
111
+ self._cost_usd = 0.0
112
+ self._last: RunResult | None = None
113
+
114
+ @property
115
+ def agent_id(self) -> str:
116
+ return self._agent_id
117
+
118
+ @property
119
+ def approval_policy(self) -> ApprovalPolicy:
120
+ return self._policy
121
+
122
+ @property
123
+ def cost_usd(self) -> float:
124
+ """Total spend across every case so far, so a caller can difference it."""
125
+ return self._cost_usd
126
+
127
+ @property
128
+ def last_result(self) -> RunResult | None:
129
+ """The most recent run, for a caller that needs more than the trajectory.
130
+
131
+ ``evaluate_once`` only hands a metric the trajectory, so this exists for the
132
+ direct caller -- a walkthrough, a report, or a test -- that wants the status and
133
+ the steps. Metrics do not reach through it.
134
+ """
135
+ return self._last
136
+
137
+ async def __call__(self, case: EvalCase) -> RunOutput:
138
+ runtime = self._runtime()
139
+ before = runtime.gateway.ledger.cost_usd
140
+ try:
141
+ result = await runtime.run(self._agent_id, case.input)
142
+ result = await self._settle(runtime, case, result)
143
+ finally:
144
+ # Charged even when the run raised: a case stopped by a guardrail was billed,
145
+ # and a cost series that only saw completed cases would under-report exactly
146
+ # when the guardrails fire.
147
+ self._cost_usd += max(runtime.gateway.ledger.cost_usd - before, 0.0)
148
+ self._last = result
149
+ return RunOutput(text=result.answer, trajectory=Trajectory.from_run(result))
150
+
151
+ def _runtime(self) -> AgentRuntime:
152
+ # A fresh memory store per case, for the same reason as the fresh ledger: ``run``
153
+ # keys thread memory on the agent id when the caller passes no ``memory_key``, so a
154
+ # shared store would hand case two the first case's conversation.
155
+ return AgentRuntime.from_ir(
156
+ self._document,
157
+ providers=self._providers,
158
+ tools=self._tools,
159
+ memory_store=InProcessMemoryStore(),
160
+ )
161
+
162
+ async def _settle(self, runtime: AgentRuntime, case: EvalCase, result: RunResult) -> RunResult:
163
+ """Resume through every pause the case has decisions for."""
164
+ decisions = iter(case.approvals)
165
+ resumes = 0
166
+ while result.status is RunStatus.PAUSED:
167
+ checkpoint = result.checkpoint
168
+ if checkpoint is None:
169
+ raise EvalError(
170
+ f"case {case.id!r} is paused but its run carries no checkpoint, so it "
171
+ "cannot be resumed; the loop must record one before reporting a pause"
172
+ )
173
+ decision = self._decision(case, decisions)
174
+ resumes += 1
175
+ if resumes > self._max_resumes:
176
+ raise EvalError(
177
+ f"case {case.id!r} paused {self._max_resumes} times and is still asking; "
178
+ "the case is supplying decisions to a run that is not converging, and "
179
+ "resuming it again would only multiply the spend"
180
+ )
181
+ result = await runtime.resume(checkpoint, decision)
182
+ return result
183
+
184
+ def _decision(self, case: EvalCase, decisions: Iterator[str]) -> HumanDecision:
185
+ if self._policy is ApprovalPolicy.APPROVE:
186
+ return HumanDecision.APPROVE
187
+ if self._policy is ApprovalPolicy.REJECT:
188
+ return HumanDecision.REJECT
189
+ for decision in decisions:
190
+ return HumanDecision(decision)
191
+ raise EvalError(
192
+ f"case {case.id!r} paused for approval and declared no decision for it: add "
193
+ "`approvals` to the case (in order, one per pause) to say what the reviewer "
194
+ "answered, or construct the runner with ApprovalPolicy.APPROVE when this eval "
195
+ "is not about approval"
196
+ )
197
+
198
+
199
+ def _declared_agents(document: Mapping[str, object]) -> set[str]:
200
+ """The ids the document declares, read structurally so a typo fails before case one.
201
+
202
+ The full IR parser would answer this too, but it wants the tools registered, and a
203
+ caller that mistyped the agent id should hear about it at construction -- not after a
204
+ fifty-case dataset has charged the budget.
205
+ """
206
+ entries = document.get("agents")
207
+ if not isinstance(entries, list):
208
+ return set()
209
+ return {
210
+ entry["id"]
211
+ for entry in entries
212
+ if isinstance(entry, Mapping) and isinstance(entry.get("id"), str)
213
+ }
@@ -27,6 +27,28 @@ class EvalCase(BaseModel):
27
27
  expected: str | None = None
28
28
  tags: tuple[str, ...] = ()
29
29
  metadata: dict[str, str] = Field(default_factory=dict)
30
+ #: What a person answers, in order, each time the run pauses for approval. An
31
+ #: agent case that pauses and supplies no answer here is refused rather than
32
+ #: auto-approved: the harness must not stand in for the reviewer it is modelling.
33
+ approvals: tuple[str, ...] = ()
34
+
35
+ @field_validator("approvals", mode="before")
36
+ @classmethod
37
+ def _coerce_approvals(cls, value: object) -> object:
38
+ if isinstance(value, str):
39
+ return (value,)
40
+ return value
41
+
42
+ @field_validator("approvals")
43
+ @classmethod
44
+ def _check_approvals(cls, value: tuple[str, ...]) -> tuple[str, ...]:
45
+ allowed = {"approve", "reject"}
46
+ for decision in value:
47
+ if decision not in allowed:
48
+ raise ValueError(
49
+ f"a case's approvals may only be 'approve' or 'reject', not {decision!r}"
50
+ )
51
+ return value
30
52
 
31
53
 
32
54
  class Dataset(BaseModel):
@@ -73,5 +95,18 @@ class Dataset(BaseModel):
73
95
  return cls.from_json(Path(path).read_text(encoding="utf-8"))
74
96
 
75
97
  def to_json(self) -> str:
76
- """Canonical JSON: sorted keys, so a dataset diff is reviewable."""
77
- return json.dumps(self.model_dump(mode="json"), indent=2, sort_keys=True) + "\n"
98
+ """Canonical JSON: sorted keys, so a dataset diff is reviewable.
99
+
100
+ ``approvals`` is omitted when a case declared none, so adding approval-aware
101
+ trajectory evals did not rewrite every dataset already in a repository. A case
102
+ that does declare decisions writes them, because a reader has to be able to see
103
+ what the reviewer answered.
104
+ """
105
+ return json.dumps(self._dumped(), indent=2, sort_keys=True) + "\n"
106
+
107
+ def _dumped(self) -> dict[str, object]:
108
+ payload = self.model_dump(mode="json")
109
+ for case in payload.get("cases", ()):
110
+ if not case.get("approvals"):
111
+ case.pop("approvals", None)
112
+ return payload
@@ -6,7 +6,9 @@ Converse API, and Gemini's ``generateContent`` -- which the Vertex AI adapter
6
6
  serves over an OAuth2 bearer token and the Gemini API adapter serves with one API
7
7
  key. Bedrock is signed with SigV4 and Vertex is OAuth2-bearer, which is why
8
8
  neither can be an OpenAI-compatible base URL. A sixth, deterministic fake serves
9
- tests and the eval-gate fixture.
9
+ tests and builds the scripted side of an eval case. A seventh, ``recorded``,
10
+ replays a committed transcript so an agent eval can be gated without calling a
11
+ vendor; it has no fall-through to a live model, by design.
10
12
  """
11
13
 
12
14
  from __future__ import annotations
@@ -30,6 +32,13 @@ from aid_runtime.providers.gemini import (
30
32
  GeminiProvider,
31
33
  )
32
34
  from aid_runtime.providers.http import DEFAULT_BASE_URL, OpenAICompatibleProvider
35
+ from aid_runtime.providers.recorded import (
36
+ RecordedProvider,
37
+ RecordingProvider,
38
+ ReplayDivergenceError,
39
+ Transcript,
40
+ TranscriptEntry,
41
+ )
33
42
  from aid_runtime.providers.vertex import (
34
43
  DEFAULT_VERTEX_LOCATION,
35
44
  METADATA_TOKEN_URL,
@@ -54,7 +63,12 @@ __all__ = [
54
63
  "GeminiProvider",
55
64
  "OpenAICompatibleProvider",
56
65
  "Provider",
66
+ "RecordedProvider",
67
+ "RecordingProvider",
68
+ "ReplayDivergenceError",
57
69
  "ScriptedTurn",
70
+ "Transcript",
71
+ "TranscriptEntry",
58
72
  "VertexProvider",
59
73
  "default_bedrock_base_url",
60
74
  "default_vertex_base_url",
@@ -0,0 +1,342 @@
1
+ """A provider transcript, replayed instead of called.
2
+
3
+ An agent eval needs the model's *tool calls*, and a live model decides those itself. That
4
+ is the right thing to measure in production and the wrong thing to gate a build on: a CI
5
+ suite that spends money and answers differently on Tuesday cannot refuse a pull request.
6
+ So the model's turns are recorded once, committed beside the dataset, and replayed.
7
+
8
+ What that buys and what it costs are stated together on purpose. A replayed suite verifies
9
+ that the machinery around the model does what the spec says -- the step ceiling stops the
10
+ run, an unreachable tool stays unreachable, a rejected approval blocks the call, the cost
11
+ is attributed. It says nothing about whether the model would choose those calls, because
12
+ the model is not consulted. A green replayed suite is evidence about plumbing, never about
13
+ model quality; measuring a model needs a pinned provider and belongs with the baselines.
14
+
15
+ Replay is **positional and verified**, not a search for a matching question. Each recorded
16
+ entry carries a digest of the request it answered, and the provider checks the digest of
17
+ the request it is handed. A prompt edit, a changed tool result or a reordered step changes
18
+ that digest, and the run stops with the call index and the first differing message instead
19
+ of quietly serving an answer to a question nobody asked. The alternative -- matching on
20
+ content -- would turn a diverged run into a permissive one.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import json
27
+ from collections.abc import AsyncIterator, Sequence
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from pydantic import BaseModel, ConfigDict, Field
32
+
33
+ from aid_runtime.errors import EvalError
34
+ from aid_runtime.providers.base import Provider
35
+ from aid_runtime.types import (
36
+ Capability,
37
+ CompletionRequest,
38
+ CompletionResponse,
39
+ FinishReason,
40
+ Message,
41
+ ModelSpec,
42
+ StreamChunk,
43
+ TokenUsage,
44
+ )
45
+
46
+ __all__ = [
47
+ "RecordedProvider",
48
+ "RecordingProvider",
49
+ "ReplayDivergenceError",
50
+ "Transcript",
51
+ "TranscriptEntry",
52
+ ]
53
+
54
+
55
+ class ReplayDivergenceError(EvalError):
56
+ """A replayed run asked something the recording does not answer.
57
+
58
+ Deliberately *not* a :class:`~aid_runtime.errors.ProviderError`: the gateway treats a
59
+ provider error as a reason to try the next candidate model, and a divergence is not a
60
+ vendor outage -- every candidate would diverge identically. Inheriting the gateway's
61
+ retry path would hide the call index behind a "no candidate produced a response"
62
+ message and spend a fallback finding nothing.
63
+ """
64
+
65
+
66
+ def _digest(messages: Sequence[Message]) -> str:
67
+ """A stable digest of a request's transcript.
68
+
69
+ Every field that reaches the provider is folded in, including tool-call ids and
70
+ names, because a change to any of them is a change to what the model was asked. The
71
+ encoding is fixed rather than default, so the digest does not move with a Python
72
+ upgrade and a committed transcript keeps checking out.
73
+ """
74
+ payload = [
75
+ {
76
+ "role": message.role,
77
+ "content": message.content,
78
+ "tool_calls": [
79
+ {"id": call.id, "name": call.name, "arguments": call.arguments}
80
+ for call in message.tool_calls
81
+ ],
82
+ "tool_call_id": message.tool_call_id,
83
+ "name": message.name,
84
+ }
85
+ for message in messages
86
+ ]
87
+ encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
88
+ return hashlib.sha256(encoded.encode()).hexdigest()
89
+
90
+
91
+ class TranscriptEntry(BaseModel):
92
+ """One recorded exchange: what was asked, and what came back."""
93
+
94
+ model_config = ConfigDict(frozen=True, extra="forbid")
95
+
96
+ request_digest: str = Field(min_length=1)
97
+ response: CompletionResponse
98
+ #: The first user message of the request, kept for a human reading the file. It is
99
+ #: not used for matching -- the digest is -- so it may be trimmed without changing
100
+ #: what the transcript replays.
101
+ prompt_preview: str = ""
102
+
103
+
104
+ class Transcript(BaseModel):
105
+ """A recorded provider session, as a file a repository can commit."""
106
+
107
+ model_config = ConfigDict(frozen=True, extra="forbid")
108
+
109
+ provider: str
110
+ model: str
111
+ #: The spec version the recording was made under. A transcript is evidence about a
112
+ #: particular document, so a bump that changes what an eval runs should prompt a
113
+ #: re-record rather than silently reusing turns planned against the old shape.
114
+ spec_version: str = ""
115
+ entries: tuple[TranscriptEntry, ...] = ()
116
+
117
+ @classmethod
118
+ def from_path(cls, path: Path) -> Transcript:
119
+ if not path.is_file():
120
+ raise FileNotFoundError(
121
+ f"no recorded transcript at {path}; record one by wrapping a pinned provider in "
122
+ "RecordingProvider, then save its transcript() here and commit it beside the "
123
+ "dataset"
124
+ )
125
+ return cls.model_validate_json(path.read_text(encoding="utf-8"))
126
+
127
+ def save(self, path: Path) -> None:
128
+ path.parent.mkdir(parents=True, exist_ok=True)
129
+ # Trailing newline and a stable key order, so recording twice from the same
130
+ # session produces the same bytes and a diff means the run really changed.
131
+ path.write_text(
132
+ json.dumps(self.model_dump(mode="json"), indent=2, sort_keys=True) + "\n",
133
+ encoding="utf-8",
134
+ )
135
+
136
+ def __len__(self) -> int:
137
+ return len(self.entries)
138
+
139
+ def __bool__(self) -> bool:
140
+ return bool(self.entries)
141
+
142
+
143
+ class RecordedProvider:
144
+ """Replays a :class:`Transcript`, one entry per call.
145
+
146
+ Deliberately not a cache: a cache answers a question it has seen before and falls
147
+ through to a live call otherwise, which is exactly the behaviour that makes a gated
148
+ suite flaky. This provider has no fall-through. Once the transcript is exhausted the
149
+ run has taken more steps than were recorded, which is a finding rather than a reason
150
+ to call a vendor.
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ transcript: Transcript,
156
+ *,
157
+ name: str | None = None,
158
+ verify_requests: bool = True,
159
+ ) -> None:
160
+ self._transcript = transcript
161
+ self._name = transcript.provider if name is None else name
162
+ self._verify = verify_requests
163
+ self._served = 0
164
+
165
+ @classmethod
166
+ def from_path(cls, path: Path, **kwargs: Any) -> RecordedProvider:
167
+ return cls(Transcript.from_path(path), **kwargs)
168
+
169
+ @property
170
+ def name(self) -> str:
171
+ return self._name
172
+
173
+ @property
174
+ def capabilities(self) -> frozenset[Capability]:
175
+ # The recorded provider can answer whatever was recorded. Advertising the full
176
+ # set would let a model negotiate a capability no entry exercises, so it claims
177
+ # only what a transcript can carry.
178
+ return frozenset({Capability.TOOL_CALLING, Capability.STRUCTURED_OUTPUT})
179
+
180
+ @property
181
+ def served(self) -> int:
182
+ return self._served
183
+
184
+ @property
185
+ def remaining(self) -> int:
186
+ return max(len(self._transcript) - self._served, 0)
187
+
188
+ async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
189
+ entry = self._next(request)
190
+ return entry.response
191
+
192
+ async def stream(
193
+ self, request: CompletionRequest, *, model: ModelSpec
194
+ ) -> AsyncIterator[StreamChunk]:
195
+ """Stream a recorded answer as one terminal chunk.
196
+
197
+ Recordings do not carry token boundaries, so inventing them would make a
198
+ replayed run differ from the recorded one in the one place streaming is
199
+ observable. A single chunk carrying the whole answer and the usage is the
200
+ honest reconstruction.
201
+ """
202
+ response = await self.complete(request, model=model)
203
+ yield StreamChunk(
204
+ delta=response.text,
205
+ finish_reason=response.finish_reason,
206
+ usage=response.usage,
207
+ )
208
+
209
+ async def aclose(self) -> None:
210
+ return None
211
+
212
+ def _next(self, request: CompletionRequest) -> TranscriptEntry:
213
+ if self._served >= len(self._transcript):
214
+ raise ReplayDivergenceError(
215
+ f"the recording in this transcript ends after {len(self._transcript)} call(s) "
216
+ f"and the run asked for number {self._served + 1}: the app took a step the "
217
+ "recording does not cover. Record a longer one by wrapping the live provider "
218
+ "in RecordingProvider, or fix the step that now runs further than it did"
219
+ )
220
+ entry = self._transcript.entries[self._served]
221
+ if self._verify:
222
+ self._verify_digest(entry, request, self._served)
223
+ self._served += 1
224
+ return entry
225
+
226
+ def _verify_digest(
227
+ self, entry: TranscriptEntry, request: CompletionRequest, index: int
228
+ ) -> None:
229
+ actual = _digest(request.messages)
230
+ if actual == entry.request_digest:
231
+ return
232
+ raise ReplayDivergenceError(
233
+ f"replayed call {index + 1} does not match the recording: "
234
+ f"{self._first_difference(entry, request)}. A recorded transcript answers the "
235
+ "question that was asked when it was recorded; a changed prompt, tool result or "
236
+ "step order is a different question"
237
+ )
238
+
239
+ def _first_difference(self, entry: TranscriptEntry, request: CompletionRequest) -> str:
240
+ """Name the first message that moved, so the fix is locatable.
241
+
242
+ The recording keeps only a preview, so this can say *which* message differs and
243
+ what the run sent, not what was recorded in full. That is enough to find the
244
+ step, and promising more detail than the file holds would be a lie.
245
+ """
246
+ previews = entry.prompt_preview
247
+ for position, message in enumerate(request.messages):
248
+ if position == 0 and previews and message.content != previews:
249
+ return (
250
+ f"the opening user message is now {message.content[:80]!r} and the "
251
+ f"recording was made with {previews[:80]!r}"
252
+ )
253
+ return (
254
+ f"the request's message digest changed ({len(request.messages)} message(s) "
255
+ "sent); compare the prompt and the tool results at this step"
256
+ )
257
+
258
+
259
+ class RecordingProvider:
260
+ """Wraps a live provider and keeps every exchange, so a run can be replayed offline.
261
+
262
+ Recording is opt-in and explicit. Nothing here is enabled by an eval run that merely
263
+ happens to have a network connection: a suite that recorded itself would gate the
264
+ build on whatever the model did on the day it ran.
265
+ """
266
+
267
+ def __init__(self, inner: Provider, *, spec_version: str = "") -> None:
268
+ self._inner = inner
269
+ self._spec_version = spec_version
270
+ self._entries: list[TranscriptEntry] = []
271
+ self._model = ""
272
+
273
+ @property
274
+ def name(self) -> str:
275
+ return str(self._inner.name)
276
+
277
+ @property
278
+ def capabilities(self) -> frozenset[Capability]:
279
+ return frozenset(self._inner.capabilities)
280
+
281
+ @property
282
+ def entries(self) -> tuple[TranscriptEntry, ...]:
283
+ return tuple(self._entries)
284
+
285
+ def transcript(self) -> Transcript:
286
+ return Transcript(
287
+ provider=self.name,
288
+ model=self._model,
289
+ spec_version=self._spec_version,
290
+ entries=tuple(self._entries),
291
+ )
292
+
293
+ async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
294
+ response = await self._inner.complete(request, model=model)
295
+ self._model = model.name
296
+ user = next((message.content for message in request.messages if message.role == "user"), "")
297
+ self._entries.append(
298
+ TranscriptEntry(
299
+ request_digest=_digest(request.messages),
300
+ response=response,
301
+ prompt_preview=user[:200],
302
+ )
303
+ )
304
+ return response
305
+
306
+ async def stream(
307
+ self, request: CompletionRequest, *, model: ModelSpec
308
+ ) -> AsyncIterator[StreamChunk]:
309
+ # Streaming is recorded as the assembled answer rather than as chunks: a
310
+ # transcript is replayed for its *content*, and a chunk boundary is not
311
+ # something an eval asserts.
312
+ chunks: list[StreamChunk] = []
313
+ async for chunk in self._inner.stream(request, model=model):
314
+ chunks.append(chunk)
315
+ text = "".join(chunk.delta for chunk in chunks)
316
+ usage = next((chunk.usage for chunk in reversed(chunks) if chunk.usage is not None), None)
317
+ finish: FinishReason = next(
318
+ (chunk.finish_reason for chunk in reversed(chunks) if chunk.finish_reason is not None),
319
+ "stop",
320
+ )
321
+ self._model = model.name
322
+ user = next((message.content for message in request.messages if message.role == "user"), "")
323
+ self._entries.append(
324
+ TranscriptEntry(
325
+ request_digest=_digest(request.messages),
326
+ response=CompletionResponse(
327
+ text=text,
328
+ model=model.name,
329
+ provider=self.name,
330
+ usage=usage
331
+ if usage is not None
332
+ else TokenUsage(input_tokens=0, output_tokens=0),
333
+ finish_reason=finish,
334
+ ),
335
+ prompt_preview=user[:200],
336
+ )
337
+ )
338
+ for chunk in chunks:
339
+ yield chunk
340
+
341
+ async def aclose(self) -> None:
342
+ return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.156
3
+ Version: 0.1.158
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=rm3R-GDVRLpMV-Gdua9Svn09YVJ39CjMYMaXE79C_hM,14260
1
+ aid_runtime/__init__.py,sha256=FxxraMYMXS_QTNAWTg8S0IuvhLe-DCUc1bJvJCi1LHU,14574
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
@@ -28,14 +28,15 @@ 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=dx3pD1BDOZUtdN2OQpEf1G6qk6tWSaoDjoGfGyPN87o,1661
32
- aid_runtime/evals/dataset.py,sha256=waG4tYSJsgsZ9DLxkhUvF_X-aQB8w2OexYxc7Wwdiyg,2494
31
+ aid_runtime/evals/__init__.py,sha256=RiMCcDZWro0l0L4zQaYSvcJE7UiyhHD2MR_fyMS3Y84,1781
32
+ aid_runtime/evals/agent_runner.py,sha256=U1I52pH92bKqat9pieR38QLaCanF0X8frERq2mwQJck,9707
33
+ aid_runtime/evals/dataset.py,sha256=gA6hdDlPKqf__ikI10vP33R41Za9D7L9MVMWjNSLd8c,3930
33
34
  aid_runtime/evals/gate.py,sha256=_nLWXvcuHwq8nE3HpiONg_wBkrzZyGrGT49ZNeKMyTY,15524
34
35
  aid_runtime/evals/metrics.py,sha256=hmUy2vMKiGTD7xNFCRE3iRka53nn_NNDxLInSBzAQgY,22305
35
36
  aid_runtime/evals/predicate.py,sha256=JaeN1LJFpliI4JHYdFPtXfjH5_Aad-2-U3ZC6_hManE,8726
36
37
  aid_runtime/evals/runner.py,sha256=kj2fdDzbVMCRAlaliPU8ycYxHE9qr0s5WDo_kvl-PAo,11498
37
38
  aid_runtime/evals/trajectory.py,sha256=kwK7Cj1OSbgHj6m4Kar0fPNe7wFqzmC_OcpNqRYqRJs,2587
38
- aid_runtime/providers/__init__.py,sha256=MQ-vU_QeeUgfqMlwLi0layJBhmvbZat9gIkDFcFl7Pg,1827
39
+ aid_runtime/providers/__init__.py,sha256=5XMe1kPqckeyv2l_FrfYEiTPWOTGsPKpWtiiTdSn3ic,2284
39
40
  aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
40
41
  aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
41
42
  aid_runtime/providers/bedrock.py,sha256=mb-sF5u3Y3Dp_FBgrAublA7sKtExhWrWGOA5p9o0_HA,24515
@@ -43,6 +44,7 @@ aid_runtime/providers/fake.py,sha256=oAcpaDOUIp7lmKGEEWG5ktagstg2dvoHR-9xaUeCDLo
43
44
  aid_runtime/providers/gemini.py,sha256=gM4Kvgz6lnFbHgYYhyVCBTFTcGAKfiNuj7lS1XSldnU,3975
44
45
  aid_runtime/providers/gemini_wire.py,sha256=ZwIiYuAVihszE0c90-uAbSn6_hdMa2Md4asySIYeQTw,13032
45
46
  aid_runtime/providers/http.py,sha256=c5DLmX1FqtAUO01MqDf0m82x8zHD480LyL-QtTrxnn4,13168
47
+ aid_runtime/providers/recorded.py,sha256=2MgAHEkt0jFlr2Z4x_5edASQithiLqtpeDy1tBy5rbA,13566
46
48
  aid_runtime/providers/vertex.py,sha256=XdwPuPw2Ce5CGuoEyzY5jVpqtKeTXWOvY_9WegxheEk,9341
47
49
  aid_runtime/retrieval/__init__.py,sha256=DkFzyKzqT-NjRlOldstTK84y3paEWjWXri7V36xx_cY,6455
48
50
  aid_runtime/retrieval/chunking.py,sha256=jn4tWXaWaQpSkfhqW_pkgd0J95z8PKCasbMgM7l7w-I,20495
@@ -59,7 +61,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
59
61
  aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
60
62
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
61
63
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
62
- aid_runtime_python-0.1.156.dist-info/METADATA,sha256=r1P3pB9HZBSzSWAm1VBwlhY4fwAml3df4nQrP8Uatk8,17163
63
- aid_runtime_python-0.1.156.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
64
- aid_runtime_python-0.1.156.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
65
- aid_runtime_python-0.1.156.dist-info/RECORD,,
64
+ aid_runtime_python-0.1.158.dist-info/METADATA,sha256=udi0s6tWWUZERyDmGNft2IFckAT-HdiIcrizN1mktPk,17163
65
+ aid_runtime_python-0.1.158.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
66
+ aid_runtime_python-0.1.158.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
67
+ aid_runtime_python-0.1.158.dist-info/RECORD,,