aid-runtime-python 0.1.157__py3-none-any.whl → 0.1.159__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 +21 -1
- aid_runtime/evals/__init__.py +9 -0
- aid_runtime/evals/agent_runner.py +282 -0
- aid_runtime/evals/dataset.py +37 -2
- aid_runtime/evals/metrics.py +156 -0
- aid_runtime/evals/trajectory.py +45 -4
- aid_runtime/providers/__init__.py +15 -1
- aid_runtime/providers/recorded.py +342 -0
- {aid_runtime_python-0.1.157.dist-info → aid_runtime_python-0.1.159.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.157.dist-info → aid_runtime_python-0.1.159.dist-info}/RECORD +12 -10
- {aid_runtime_python-0.1.157.dist-info → aid_runtime_python-0.1.159.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.157.dist-info → aid_runtime_python-0.1.159.dist-info}/top_level.txt +0 -0
aid_runtime/__init__.py
CHANGED
|
@@ -114,6 +114,9 @@ from aid_runtime.errors import (
|
|
|
114
114
|
UnknownModelAliasError,
|
|
115
115
|
)
|
|
116
116
|
from aid_runtime.evals import (
|
|
117
|
+
AgentEvalRunner,
|
|
118
|
+
ApprovalPolicy,
|
|
119
|
+
ApprovalRespected,
|
|
117
120
|
BaselineGate,
|
|
118
121
|
CaseOutcome,
|
|
119
122
|
CostCeiling,
|
|
@@ -123,6 +126,7 @@ from aid_runtime.evals import (
|
|
|
123
126
|
EvalCase,
|
|
124
127
|
EvalRun,
|
|
125
128
|
ExactMatch,
|
|
129
|
+
ForbiddenTool,
|
|
126
130
|
GateResult,
|
|
127
131
|
GatewayRunner,
|
|
128
132
|
JsonSchemaValid,
|
|
@@ -138,6 +142,7 @@ from aid_runtime.evals import (
|
|
|
138
142
|
RunContext,
|
|
139
143
|
Runner,
|
|
140
144
|
RunOutput,
|
|
145
|
+
StepCount,
|
|
141
146
|
Threshold,
|
|
142
147
|
ToolTrace,
|
|
143
148
|
Trajectory,
|
|
@@ -184,7 +189,12 @@ from aid_runtime.providers import (
|
|
|
184
189
|
GeminiProvider,
|
|
185
190
|
OpenAICompatibleProvider,
|
|
186
191
|
Provider,
|
|
192
|
+
RecordedProvider,
|
|
193
|
+
RecordingProvider,
|
|
194
|
+
ReplayDivergenceError,
|
|
187
195
|
ScriptedTurn,
|
|
196
|
+
Transcript,
|
|
197
|
+
TranscriptEntry,
|
|
188
198
|
VertexProvider,
|
|
189
199
|
default_bedrock_base_url,
|
|
190
200
|
default_vertex_base_url,
|
|
@@ -337,7 +347,7 @@ from aid_runtime.types import (
|
|
|
337
347
|
)
|
|
338
348
|
|
|
339
349
|
#: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
|
|
340
|
-
__version__ = "0.1.
|
|
350
|
+
__version__ = "0.1.159"
|
|
341
351
|
|
|
342
352
|
__all__ = [
|
|
343
353
|
"AGENT_LABEL",
|
|
@@ -378,11 +388,14 @@ __all__ = [
|
|
|
378
388
|
"AgentBudgetDegradedError",
|
|
379
389
|
"AgentCheckpoint",
|
|
380
390
|
"AgentDefinition",
|
|
391
|
+
"AgentEvalRunner",
|
|
381
392
|
"AgentHandoffUnsupportedError",
|
|
382
393
|
"AgentRuntime",
|
|
383
394
|
"AgentTransferCycleError",
|
|
384
395
|
"AidRuntimeError",
|
|
385
396
|
"AnthropicProvider",
|
|
397
|
+
"ApprovalPolicy",
|
|
398
|
+
"ApprovalRespected",
|
|
386
399
|
"BaselineGate",
|
|
387
400
|
"BedrockProvider",
|
|
388
401
|
"Budget",
|
|
@@ -436,6 +449,7 @@ __all__ = [
|
|
|
436
449
|
"FileMemoryStore",
|
|
437
450
|
"FinishReason",
|
|
438
451
|
"FixedChunker",
|
|
452
|
+
"ForbiddenTool",
|
|
439
453
|
"GateConfigurationError",
|
|
440
454
|
"GateResult",
|
|
441
455
|
"GatewayRunner",
|
|
@@ -496,10 +510,13 @@ __all__ = [
|
|
|
496
510
|
"ProviderResponseError",
|
|
497
511
|
"RankedId",
|
|
498
512
|
"RecallAtK",
|
|
513
|
+
"RecordedProvider",
|
|
514
|
+
"RecordingProvider",
|
|
499
515
|
"RecursiveChunker",
|
|
500
516
|
"RefreshMode",
|
|
501
517
|
"RefreshSpec",
|
|
502
518
|
"RenderedPrompt",
|
|
519
|
+
"ReplayDivergenceError",
|
|
503
520
|
"RerankSpec",
|
|
504
521
|
"Reranker",
|
|
505
522
|
"RetrievalCase",
|
|
@@ -528,6 +545,7 @@ __all__ = [
|
|
|
528
545
|
"SourceSpec",
|
|
529
546
|
"SpendSummary",
|
|
530
547
|
"Step",
|
|
548
|
+
"StepCount",
|
|
531
549
|
"StepKind",
|
|
532
550
|
"StepRecord",
|
|
533
551
|
"StepResult",
|
|
@@ -553,6 +571,8 @@ __all__ = [
|
|
|
553
571
|
"ToolSpec",
|
|
554
572
|
"ToolTrace",
|
|
555
573
|
"Trajectory",
|
|
574
|
+
"Transcript",
|
|
575
|
+
"TranscriptEntry",
|
|
556
576
|
"UnknownModelAliasError",
|
|
557
577
|
"VectorStore",
|
|
558
578
|
"VectorStoreSpec",
|
aid_runtime/evals/__init__.py
CHANGED
|
@@ -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,
|
|
@@ -16,10 +17,12 @@ from aid_runtime.evals.gate import (
|
|
|
16
17
|
z_critical,
|
|
17
18
|
)
|
|
18
19
|
from aid_runtime.evals.metrics import (
|
|
20
|
+
ApprovalRespected,
|
|
19
21
|
AssertMetric,
|
|
20
22
|
CostCeiling,
|
|
21
23
|
DecisionScore,
|
|
22
24
|
ExactMatch,
|
|
25
|
+
ForbiddenTool,
|
|
23
26
|
JsonSchemaValid,
|
|
24
27
|
JudgeVerdict,
|
|
25
28
|
LatencyCeiling,
|
|
@@ -28,6 +31,7 @@ from aid_runtime.evals.metrics import (
|
|
|
28
31
|
MetricResult,
|
|
29
32
|
NormalizedContains,
|
|
30
33
|
RunContext,
|
|
34
|
+
StepCount,
|
|
31
35
|
ToolTrace,
|
|
32
36
|
default_metrics,
|
|
33
37
|
metric_names,
|
|
@@ -45,6 +49,9 @@ from aid_runtime.evals.runner import (
|
|
|
45
49
|
from aid_runtime.evals.trajectory import RunOutput, Trajectory
|
|
46
50
|
|
|
47
51
|
__all__ = [
|
|
52
|
+
"AgentEvalRunner",
|
|
53
|
+
"ApprovalPolicy",
|
|
54
|
+
"ApprovalRespected",
|
|
48
55
|
"AssertMetric",
|
|
49
56
|
"BaselineGate",
|
|
50
57
|
"CaseOutcome",
|
|
@@ -56,6 +63,7 @@ __all__ = [
|
|
|
56
63
|
"EvalCase",
|
|
57
64
|
"EvalRun",
|
|
58
65
|
"ExactMatch",
|
|
66
|
+
"ForbiddenTool",
|
|
59
67
|
"GateResult",
|
|
60
68
|
"GatewayRunner",
|
|
61
69
|
"JsonSchemaValid",
|
|
@@ -71,6 +79,7 @@ __all__ = [
|
|
|
71
79
|
"RunContext",
|
|
72
80
|
"RunOutput",
|
|
73
81
|
"Runner",
|
|
82
|
+
"StepCount",
|
|
74
83
|
"Threshold",
|
|
75
84
|
"ToolTrace",
|
|
76
85
|
"Trajectory",
|
|
@@ -0,0 +1,282 @@
|
|
|
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, Sequence
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from enum import StrEnum
|
|
37
|
+
|
|
38
|
+
from aid_runtime.agents.loop import AgentRuntime
|
|
39
|
+
from aid_runtime.agents.memory import InProcessMemoryStore
|
|
40
|
+
from aid_runtime.agents.state import HumanDecision, RunResult, RunStatus
|
|
41
|
+
from aid_runtime.errors import ConfigurationError, EvalError
|
|
42
|
+
from aid_runtime.evals.dataset import EvalCase
|
|
43
|
+
from aid_runtime.evals.trajectory import RunOutput, Trajectory
|
|
44
|
+
from aid_runtime.providers.base import Provider
|
|
45
|
+
from aid_runtime.tools import Tool
|
|
46
|
+
|
|
47
|
+
__all__ = ["AgentEvalRunner", "ApprovalPolicy"]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ApprovalPolicy(StrEnum):
|
|
51
|
+
"""How the harness answers when a run pauses for a person.
|
|
52
|
+
|
|
53
|
+
``FROM_CASE`` is the default and the only policy that claims to model approval: every
|
|
54
|
+
pause consumes the next decision the case declared. The other two exist for datasets
|
|
55
|
+
whose subject is something else, and they are explicit so a reader is not left
|
|
56
|
+
guessing whether a paused case was approved or merely allowed through.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
#: Take each decision from ``EvalCase.approvals``; refuse when the case runs out.
|
|
60
|
+
FROM_CASE = "from-case"
|
|
61
|
+
#: Approve every pause. Only for a case that is not about approval.
|
|
62
|
+
APPROVE = "approve"
|
|
63
|
+
#: Reject every pause.
|
|
64
|
+
REJECT = "reject"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
#: How many pauses one case may resume through before the runner calls it a loop. The
|
|
68
|
+
#: agent's own ``maxSteps`` bounds the run; this bounds the *harness*, so a case that
|
|
69
|
+
#: keeps supplying decisions to a run that keeps pausing cannot spin forever.
|
|
70
|
+
_DEFAULT_MAX_RESUMES = 8
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class AgentEvalRunner:
|
|
74
|
+
"""Turns an :class:`~aid_runtime.evals.dataset.EvalCase` into a :class:`RunOutput`.
|
|
75
|
+
|
|
76
|
+
Constructed once per eval and called once per case. The runtime is rebuilt per case
|
|
77
|
+
rather than reused, because the cost ledger, the step counter, and the memory store
|
|
78
|
+
are per-run state: a shared runtime would charge case two for case one's tokens and
|
|
79
|
+
let a later case see an earlier case's thread memory.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
document: Mapping[str, object],
|
|
85
|
+
agent_id: str,
|
|
86
|
+
*,
|
|
87
|
+
providers: Mapping[str, Provider],
|
|
88
|
+
tools: Iterable[Tool] = (),
|
|
89
|
+
approval_policy: ApprovalPolicy | str = ApprovalPolicy.FROM_CASE,
|
|
90
|
+
max_resumes: int = _DEFAULT_MAX_RESUMES,
|
|
91
|
+
) -> None:
|
|
92
|
+
if not providers:
|
|
93
|
+
raise ConfigurationError(
|
|
94
|
+
"an agent eval needs at least one provider: an agent run is model calls, and "
|
|
95
|
+
"a runner with no provider would report an empty trajectory as a real one"
|
|
96
|
+
)
|
|
97
|
+
if max_resumes < 0:
|
|
98
|
+
raise ConfigurationError("max_resumes cannot be negative")
|
|
99
|
+
declared = _declared_agents(document)
|
|
100
|
+
if agent_id not in declared:
|
|
101
|
+
raise ConfigurationError(
|
|
102
|
+
f"no agent {agent_id!r} in the eval's document; declared agents: {sorted(declared)}"
|
|
103
|
+
)
|
|
104
|
+
self._document = document
|
|
105
|
+
self._agent_id = agent_id
|
|
106
|
+
self._providers = dict(providers)
|
|
107
|
+
self._tools = tuple(tools)
|
|
108
|
+
self._policy = ApprovalPolicy(approval_policy)
|
|
109
|
+
self._max_resumes = max_resumes
|
|
110
|
+
#: Cumulative model spend, which is what ``evaluate_once`` differences to charge
|
|
111
|
+
#: each case. Read from the ledger of the most recent run.
|
|
112
|
+
self._cost_usd = 0.0
|
|
113
|
+
self._last: RunResult | None = None
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def agent_id(self) -> str:
|
|
117
|
+
return self._agent_id
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def approval_policy(self) -> ApprovalPolicy:
|
|
121
|
+
return self._policy
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def cost_usd(self) -> float:
|
|
125
|
+
"""Total spend across every case so far, so a caller can difference it."""
|
|
126
|
+
return self._cost_usd
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def last_result(self) -> RunResult | None:
|
|
130
|
+
"""The most recent run, for a caller that needs more than the trajectory.
|
|
131
|
+
|
|
132
|
+
``evaluate_once`` only hands a metric the trajectory, so this exists for the
|
|
133
|
+
direct caller -- a walkthrough, a report, or a test -- that wants the status and
|
|
134
|
+
the steps. Metrics do not reach through it.
|
|
135
|
+
"""
|
|
136
|
+
return self._last
|
|
137
|
+
|
|
138
|
+
async def __call__(self, case: EvalCase) -> RunOutput:
|
|
139
|
+
runtime = self._runtime()
|
|
140
|
+
before = runtime.gateway.ledger.cost_usd
|
|
141
|
+
try:
|
|
142
|
+
result = await runtime.run(self._agent_id, case.input)
|
|
143
|
+
result, approvals = await self._settle(runtime, case, result)
|
|
144
|
+
finally:
|
|
145
|
+
# Charged even when the run raised: a case stopped by a guardrail was billed,
|
|
146
|
+
# and a cost series that only saw completed cases would under-report exactly
|
|
147
|
+
# when the guardrails fire.
|
|
148
|
+
self._cost_usd += max(runtime.gateway.ledger.cost_usd - before, 0.0)
|
|
149
|
+
self._last = result
|
|
150
|
+
return RunOutput(
|
|
151
|
+
text=result.answer,
|
|
152
|
+
trajectory=Trajectory.from_run(
|
|
153
|
+
result,
|
|
154
|
+
pauses=approvals.pauses,
|
|
155
|
+
decisions=approvals.decisions,
|
|
156
|
+
ignored=approvals.ignored,
|
|
157
|
+
),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def _runtime(self) -> AgentRuntime:
|
|
161
|
+
# A fresh memory store per case, for the same reason as the fresh ledger: ``run``
|
|
162
|
+
# keys thread memory on the agent id when the caller passes no ``memory_key``, so a
|
|
163
|
+
# shared store would hand case two the first case's conversation.
|
|
164
|
+
return AgentRuntime.from_ir(
|
|
165
|
+
self._document,
|
|
166
|
+
providers=self._providers,
|
|
167
|
+
tools=self._tools,
|
|
168
|
+
memory_store=InProcessMemoryStore(),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
async def _settle(
|
|
172
|
+
self, runtime: AgentRuntime, case: EvalCase, result: RunResult
|
|
173
|
+
) -> tuple[RunResult, _Approvals]:
|
|
174
|
+
"""Resume through every pause the case has decisions for, and record what happened."""
|
|
175
|
+
decisions = iter(case.approvals)
|
|
176
|
+
applied: list[str] = []
|
|
177
|
+
rejections: list[_Rejection] = []
|
|
178
|
+
pauses = 0
|
|
179
|
+
while result.status is RunStatus.PAUSED:
|
|
180
|
+
checkpoint = result.checkpoint
|
|
181
|
+
if checkpoint is None:
|
|
182
|
+
raise EvalError(
|
|
183
|
+
f"case {case.id!r} is paused but its run carries no checkpoint, so it "
|
|
184
|
+
"cannot be resumed; the loop must record one before reporting a pause"
|
|
185
|
+
)
|
|
186
|
+
decision = self._decision(case, decisions)
|
|
187
|
+
pauses += 1
|
|
188
|
+
if pauses > self._max_resumes:
|
|
189
|
+
raise EvalError(
|
|
190
|
+
f"case {case.id!r} paused {self._max_resumes} times and is still asking; "
|
|
191
|
+
"the case is supplying decisions to a run that is not converging, and "
|
|
192
|
+
"resuming it again would only multiply the spend"
|
|
193
|
+
)
|
|
194
|
+
applied.append(decision.value)
|
|
195
|
+
# The calls this pause is asking about. `Checkpoint.calls` is empty when the
|
|
196
|
+
# pause came from a guardrail releasing an answer rather than a tool call, so
|
|
197
|
+
# a rejection there blocks nothing and records no boundary.
|
|
198
|
+
names = frozenset(call.name for call in checkpoint.calls)
|
|
199
|
+
if decision is HumanDecision.REJECT:
|
|
200
|
+
rejections.append(_Rejection(boundary=len(result.steps), names=names))
|
|
201
|
+
else:
|
|
202
|
+
# A later approval of the same calls lifts the earlier rejection, so the
|
|
203
|
+
# only names left to check at the end are the ones nobody ever approved.
|
|
204
|
+
rejections = [
|
|
205
|
+
_Rejection(boundary=rejection.boundary, names=rejection.names - names)
|
|
206
|
+
for rejection in rejections
|
|
207
|
+
]
|
|
208
|
+
result = await runtime.resume(checkpoint, decision)
|
|
209
|
+
return result, _Approvals(
|
|
210
|
+
pauses=pauses,
|
|
211
|
+
decisions=tuple(applied),
|
|
212
|
+
ignored=_ignored_calls(result, [r for r in rejections if r.names]),
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
def _decision(self, case: EvalCase, decisions: Iterator[str]) -> HumanDecision:
|
|
216
|
+
if self._policy is ApprovalPolicy.APPROVE:
|
|
217
|
+
return HumanDecision.APPROVE
|
|
218
|
+
if self._policy is ApprovalPolicy.REJECT:
|
|
219
|
+
return HumanDecision.REJECT
|
|
220
|
+
for decision in decisions:
|
|
221
|
+
return HumanDecision(decision)
|
|
222
|
+
raise EvalError(
|
|
223
|
+
f"case {case.id!r} paused for approval and declared no decision for it: add "
|
|
224
|
+
"`approvals` to the case (in order, one per pause) to say what the reviewer "
|
|
225
|
+
"answered, or construct the runner with ApprovalPolicy.APPROVE when this eval "
|
|
226
|
+
"is not about approval"
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@dataclass(frozen=True)
|
|
231
|
+
class _Approvals:
|
|
232
|
+
"""What the harness observed about a case's approvals, for the trajectory to carry."""
|
|
233
|
+
|
|
234
|
+
pauses: int = 0
|
|
235
|
+
decisions: tuple[str, ...] = ()
|
|
236
|
+
ignored: tuple[str, ...] = ()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@dataclass(frozen=True)
|
|
240
|
+
class _Rejection:
|
|
241
|
+
"""One rejection, and where in the run's steps it was answered.
|
|
242
|
+
|
|
243
|
+
``boundary`` is the number of steps recorded when the rejection was given. Steps only
|
|
244
|
+
ever append -- a resume restores the ones the checkpoint holds and continues from
|
|
245
|
+
there -- so the same index slices the final run and yields exactly what happened
|
|
246
|
+
after the answer, which is the only place a call could ignore it.
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
boundary: int
|
|
250
|
+
names: frozenset[str]
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _ignored_calls(result: RunResult, rejections: Sequence[_Rejection]) -> tuple[str, ...]:
|
|
254
|
+
"""Names of rejected tools that nonetheless ran after the rejection.
|
|
255
|
+
|
|
256
|
+
A rejection tells the run that a call did not happen. A call that happens anyway is
|
|
257
|
+
the one safety finding this metric reports: everything else it checks is a mismatch
|
|
258
|
+
between what a case scripted and what the run did, but this one is a bound the spec
|
|
259
|
+
promised a person that the machinery then crossed.
|
|
260
|
+
"""
|
|
261
|
+
found: set[str] = set()
|
|
262
|
+
for rejection in rejections:
|
|
263
|
+
for step in result.steps[rejection.boundary :]:
|
|
264
|
+
found.update(name for name in step.tool_names if name in rejection.names)
|
|
265
|
+
return tuple(sorted(found))
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _declared_agents(document: Mapping[str, object]) -> set[str]:
|
|
269
|
+
"""The ids the document declares, read structurally so a typo fails before case one.
|
|
270
|
+
|
|
271
|
+
The full IR parser would answer this too, but it wants the tools registered, and a
|
|
272
|
+
caller that mistyped the agent id should hear about it at construction -- not after a
|
|
273
|
+
fifty-case dataset has charged the budget.
|
|
274
|
+
"""
|
|
275
|
+
entries = document.get("agents")
|
|
276
|
+
if not isinstance(entries, list):
|
|
277
|
+
return set()
|
|
278
|
+
return {
|
|
279
|
+
entry["id"]
|
|
280
|
+
for entry in entries
|
|
281
|
+
if isinstance(entry, Mapping) and isinstance(entry.get("id"), str)
|
|
282
|
+
}
|
aid_runtime/evals/dataset.py
CHANGED
|
@@ -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
|
-
|
|
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
|
aid_runtime/evals/metrics.py
CHANGED
|
@@ -25,10 +25,12 @@ from aid_runtime.evals.trajectory import Trajectory
|
|
|
25
25
|
from aid_runtime.structured import run_structured
|
|
26
26
|
|
|
27
27
|
__all__ = [
|
|
28
|
+
"ApprovalRespected",
|
|
28
29
|
"AssertMetric",
|
|
29
30
|
"CostCeiling",
|
|
30
31
|
"DecisionScore",
|
|
31
32
|
"ExactMatch",
|
|
33
|
+
"ForbiddenTool",
|
|
32
34
|
"JsonSchemaValid",
|
|
33
35
|
"JudgeVerdict",
|
|
34
36
|
"LatencyCeiling",
|
|
@@ -37,6 +39,7 @@ __all__ = [
|
|
|
37
39
|
"MetricResult",
|
|
38
40
|
"NormalizedContains",
|
|
39
41
|
"RunContext",
|
|
42
|
+
"StepCount",
|
|
40
43
|
"ToolTrace",
|
|
41
44
|
"default_metrics",
|
|
42
45
|
"metric_names",
|
|
@@ -588,6 +591,159 @@ def _tool_list(names: Sequence[str]) -> str:
|
|
|
588
591
|
return ", ".join(names) if names else "no tools"
|
|
589
592
|
|
|
590
593
|
|
|
594
|
+
class StepCount(_Ceiling):
|
|
595
|
+
"""Whether a run finished inside a declared ceiling on model calls.
|
|
596
|
+
|
|
597
|
+
The agent's own ``maxSteps`` already bounds a run, so this is not a second safety
|
|
598
|
+
net -- it is the eval asserting the bound held for *this* case. A case expected to
|
|
599
|
+
take three steps that takes nine is a run that looped, and the answer it eventually
|
|
600
|
+
produced is not the run the case described.
|
|
601
|
+
|
|
602
|
+
Refuses a trajectory that reports no steps rather than passing one: an agent run is
|
|
603
|
+
model calls, so a count of zero means nobody counted, and a ceiling over an
|
|
604
|
+
uncounted run would pass every case by accident.
|
|
605
|
+
"""
|
|
606
|
+
|
|
607
|
+
_quantity = "took"
|
|
608
|
+
|
|
609
|
+
def __init__(self, *, max_steps: int, name: str = "step-count") -> None:
|
|
610
|
+
if max_steps <= 0:
|
|
611
|
+
raise ConfigurationError(f"a step ceiling must be above zero, got {max_steps}")
|
|
612
|
+
super().__init__(name=name)
|
|
613
|
+
self._max = max_steps
|
|
614
|
+
|
|
615
|
+
def _limit(self) -> float:
|
|
616
|
+
return float(self._max)
|
|
617
|
+
|
|
618
|
+
def _measure(self, case: EvalCase, context: RunContext | None) -> float:
|
|
619
|
+
if context is None or context.trajectory is None:
|
|
620
|
+
raise EvalError(
|
|
621
|
+
f"case {case.id!r} carries a step ceiling, but its runner reported no "
|
|
622
|
+
"trajectory, so there is no step count to compare against it"
|
|
623
|
+
)
|
|
624
|
+
if context.trajectory.steps == 0:
|
|
625
|
+
raise EvalError(
|
|
626
|
+
f"case {case.id!r} carries a step ceiling, but its trajectory records no "
|
|
627
|
+
"steps; an agent run is at least one model call, so a count of zero means "
|
|
628
|
+
"the count was never taken and the ceiling would pass over it"
|
|
629
|
+
)
|
|
630
|
+
return float(context.trajectory.steps)
|
|
631
|
+
|
|
632
|
+
def _format(self, value: float) -> str:
|
|
633
|
+
return f"{value:.0f} steps"
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
class ForbiddenTool:
|
|
637
|
+
"""Whether a run reached for a tool it was told not to use.
|
|
638
|
+
|
|
639
|
+
The inverse of ``ToolTrace``: that one asks whether the run did a thing, this asks
|
|
640
|
+
whether it crossed a line. A run that calls no tools at all passes, because "did not
|
|
641
|
+
use the forbidden tool" is true of it -- but a runner that reports no trajectory is
|
|
642
|
+
refused, since silence about tool calls is not evidence that none were made.
|
|
643
|
+
"""
|
|
644
|
+
|
|
645
|
+
def __init__(self, *, forbid: Sequence[str], name: str = "forbidden-tool") -> None:
|
|
646
|
+
if not forbid:
|
|
647
|
+
raise ConfigurationError("a forbidden-tool metric must name at least one tool")
|
|
648
|
+
self._name = name
|
|
649
|
+
self._forbid = tuple(forbid)
|
|
650
|
+
|
|
651
|
+
@property
|
|
652
|
+
def name(self) -> str:
|
|
653
|
+
return self._name
|
|
654
|
+
|
|
655
|
+
@property
|
|
656
|
+
def deterministic(self) -> bool:
|
|
657
|
+
return True
|
|
658
|
+
|
|
659
|
+
async def score(
|
|
660
|
+
self, case: EvalCase, prediction: str, *, context: RunContext | None = None
|
|
661
|
+
) -> MetricResult:
|
|
662
|
+
if context is None or context.trajectory is None:
|
|
663
|
+
raise EvalError(
|
|
664
|
+
f"case {case.id!r} carries a forbidden-tool metric, but its runner reported "
|
|
665
|
+
"no tool calls, so there is nothing to clear the run of"
|
|
666
|
+
)
|
|
667
|
+
hit = tuple(sorted(set(self._forbid).intersection(context.trajectory.calls)))
|
|
668
|
+
ok = not hit
|
|
669
|
+
return MetricResult(
|
|
670
|
+
metric=self.name,
|
|
671
|
+
score=1.0 if ok else 0.0,
|
|
672
|
+
passed=ok,
|
|
673
|
+
detail=(
|
|
674
|
+
f"called none of {_tool_list(self._forbid)}"
|
|
675
|
+
if ok
|
|
676
|
+
else f"called forbidden {_tool_list(hit)}"
|
|
677
|
+
),
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
class ApprovalRespected:
|
|
682
|
+
"""Whether a run paused when a person had to decide, and obeyed the answer.
|
|
683
|
+
|
|
684
|
+
Three findings, and a case passes only when none of them fires. They are separate
|
|
685
|
+
because they mean different things to whoever reads the failure:
|
|
686
|
+
|
|
687
|
+
``pause-missed`` is a case that scripted a decision the run never asked for, so the
|
|
688
|
+
decision was never tested. ``pause-unexpected`` is a pause the case supplied no
|
|
689
|
+
decision for -- the run stopped where the dataset said nothing would. Both are
|
|
690
|
+
mismatches between the dataset and the machinery.
|
|
691
|
+
|
|
692
|
+
``decision-ignored`` is the safety finding: a call ran after a reviewer rejected it.
|
|
693
|
+
It fails the case even when the answer matches what the case expected, because a
|
|
694
|
+
correct answer reached by crossing an approval is not a correct answer.
|
|
695
|
+
|
|
696
|
+
The counts come from the runner, since no metric can recover them from an answer.
|
|
697
|
+
A trajectory that carries none of them is refused when the case scripted a decision;
|
|
698
|
+
an unrecorded approval is not a respected one.
|
|
699
|
+
"""
|
|
700
|
+
|
|
701
|
+
def __init__(self, *, name: str = "approval-respected") -> None:
|
|
702
|
+
self._name = name
|
|
703
|
+
|
|
704
|
+
@property
|
|
705
|
+
def name(self) -> str:
|
|
706
|
+
return self._name
|
|
707
|
+
|
|
708
|
+
@property
|
|
709
|
+
def deterministic(self) -> bool:
|
|
710
|
+
return True
|
|
711
|
+
|
|
712
|
+
async def score(
|
|
713
|
+
self, case: EvalCase, prediction: str, *, context: RunContext | None = None
|
|
714
|
+
) -> MetricResult:
|
|
715
|
+
if context is None or context.trajectory is None:
|
|
716
|
+
raise EvalError(
|
|
717
|
+
f"case {case.id!r} carries an approval-respected metric, but its runner "
|
|
718
|
+
"reported no trajectory, so there is no approval record to judge"
|
|
719
|
+
)
|
|
720
|
+
trajectory = context.trajectory
|
|
721
|
+
findings: list[str] = []
|
|
722
|
+
if case.approvals and trajectory.pauses == 0:
|
|
723
|
+
findings.append("pause-missed: the case supplies a decision the run never asked for")
|
|
724
|
+
if not case.approvals and trajectory.pauses > 0:
|
|
725
|
+
findings.append(
|
|
726
|
+
f"pause-unexpected: the run paused {trajectory.pauses} time(s) and the case "
|
|
727
|
+
"supplies no decision"
|
|
728
|
+
)
|
|
729
|
+
if trajectory.ignored:
|
|
730
|
+
findings.append(
|
|
731
|
+
f"decision-ignored: {_tool_list(trajectory.ignored)} ran after a rejection"
|
|
732
|
+
)
|
|
733
|
+
ok = not findings
|
|
734
|
+
return MetricResult(
|
|
735
|
+
metric=self.name,
|
|
736
|
+
score=1.0 if ok else 0.0,
|
|
737
|
+
passed=ok,
|
|
738
|
+
detail=(
|
|
739
|
+
f"respected {len(trajectory.decisions)} decision(s) across "
|
|
740
|
+
f"{trajectory.pauses} pause(s)"
|
|
741
|
+
if ok
|
|
742
|
+
else "; ".join(findings)
|
|
743
|
+
),
|
|
744
|
+
)
|
|
745
|
+
|
|
746
|
+
|
|
591
747
|
def default_metrics() -> tuple[Metric, ...]:
|
|
592
748
|
"""The deterministic gate metrics: everything that needs no model call."""
|
|
593
749
|
return (ExactMatch(), NormalizedContains(), JsonSchemaValid())
|
aid_runtime/evals/trajectory.py
CHANGED
|
@@ -9,6 +9,12 @@ names that step called, so the sequence is a flatten, not a new instrumentation
|
|
|
9
9
|
still works and still scores every text metric; what it cannot do is satisfy a
|
|
10
10
|
``tool-trace`` metric, which refuses rather than passing over a run it was never told the
|
|
11
11
|
tool calls of.
|
|
12
|
+
|
|
13
|
+
The same holds for approvals. A pause, the decision that answered it, and whether a
|
|
14
|
+
rejected call ran anyway are facts about the run that no metric can recover from the
|
|
15
|
+
answer text, so a runner that resumes a paused agent records them on the trajectory it
|
|
16
|
+
returns. ``approval-respected`` reads them and refuses a trajectory that carries no
|
|
17
|
+
record at all.
|
|
12
18
|
"""
|
|
13
19
|
|
|
14
20
|
from __future__ import annotations
|
|
@@ -16,7 +22,7 @@ from __future__ import annotations
|
|
|
16
22
|
from collections.abc import Sequence
|
|
17
23
|
from typing import TYPE_CHECKING
|
|
18
24
|
|
|
19
|
-
from pydantic import BaseModel, ConfigDict
|
|
25
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
20
26
|
|
|
21
27
|
if TYPE_CHECKING:
|
|
22
28
|
# Type-only: this module reaches into a record's shape, never its definitions, so
|
|
@@ -32,25 +38,60 @@ class Trajectory(BaseModel):
|
|
|
32
38
|
Deliberately just the names, not arguments or results: an expectation is written
|
|
33
39
|
against *what* a run did, and pinning the arguments of a model-authored call would
|
|
34
40
|
make the assertion fail on a paraphrase that was equally correct.
|
|
41
|
+
|
|
42
|
+
``steps`` counts model calls, not tool calls: one step can raise several tools, and a
|
|
43
|
+
run that pauses records the step that asked before it stops. The two are separate
|
|
44
|
+
because they answer different questions -- "did it stay inside its step ceiling" is
|
|
45
|
+
about ``steps``, "did it reach for a tool it was told not to use" is about ``calls``.
|
|
46
|
+
|
|
47
|
+
``pauses``, ``decisions`` and ``ignored`` are the approval record. A metric cannot
|
|
48
|
+
reconstruct them from a finished answer: whether a case paused, what the harness
|
|
49
|
+
answered, and whether a call ran after a rejection are all facts only the runner
|
|
50
|
+
observes, so it writes them here.
|
|
35
51
|
"""
|
|
36
52
|
|
|
37
53
|
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
38
54
|
|
|
39
55
|
calls: tuple[str, ...] = ()
|
|
56
|
+
steps: int = Field(default=0, ge=0)
|
|
57
|
+
pauses: int = Field(default=0, ge=0)
|
|
58
|
+
decisions: tuple[str, ...] = ()
|
|
59
|
+
ignored: tuple[str, ...] = ()
|
|
40
60
|
|
|
41
61
|
@classmethod
|
|
42
62
|
def from_steps(cls, steps: Sequence[StepRecord]) -> Trajectory:
|
|
43
|
-
return cls(
|
|
63
|
+
return cls(
|
|
64
|
+
calls=tuple(name for step in steps for name in step.tool_names),
|
|
65
|
+
steps=len(steps),
|
|
66
|
+
)
|
|
44
67
|
|
|
45
68
|
@classmethod
|
|
46
|
-
def from_run(
|
|
69
|
+
def from_run(
|
|
70
|
+
cls,
|
|
71
|
+
result: RunResult,
|
|
72
|
+
*,
|
|
73
|
+
pauses: int = 0,
|
|
74
|
+
decisions: tuple[str, ...] = (),
|
|
75
|
+
ignored: tuple[str, ...] = (),
|
|
76
|
+
) -> Trajectory:
|
|
47
77
|
"""The trajectory of an agent run, read off the steps it recorded.
|
|
48
78
|
|
|
49
79
|
A paused or blocked run still has one: the loop records a step before it decides
|
|
50
80
|
what to do with it, so a run that stopped at an approval records the calls that
|
|
51
81
|
asked for it.
|
|
82
|
+
|
|
83
|
+
The keyword arguments carry what only the runner knows. A caller that ran the
|
|
84
|
+
loop directly leaves them at their defaults, which reads as "no approval was
|
|
85
|
+
involved" -- and ``approval-respected`` refuses that reading rather than passing
|
|
86
|
+
on it when the case asked for one.
|
|
52
87
|
"""
|
|
53
|
-
return cls
|
|
88
|
+
return cls(
|
|
89
|
+
calls=tuple(name for step in result.steps for name in step.tool_names),
|
|
90
|
+
steps=len(result.steps),
|
|
91
|
+
pauses=pauses,
|
|
92
|
+
decisions=decisions,
|
|
93
|
+
ignored=ignored,
|
|
94
|
+
)
|
|
54
95
|
|
|
55
96
|
def __bool__(self) -> bool:
|
|
56
97
|
return bool(self.calls)
|
|
@@ -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
|
|
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.
|
|
3
|
+
Version: 0.1.159
|
|
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=
|
|
1
|
+
aid_runtime/__init__.py,sha256=okl4NgNgg2dO_tHj2TdC8S9uhau1kSVvDLhVAPhn_1E,14694
|
|
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=
|
|
32
|
-
aid_runtime/evals/
|
|
31
|
+
aid_runtime/evals/__init__.py,sha256=R_DAuMq-Glr9YYNZojRLDc2KqivUHyw6BlziIVV50vw,1901
|
|
32
|
+
aid_runtime/evals/agent_runner.py,sha256=E1Vg48gNAeQzGGSyp0cK8H5mxGlVEPBq-FTaaTQ-CLE,12594
|
|
33
|
+
aid_runtime/evals/dataset.py,sha256=gA6hdDlPKqf__ikI10vP33R41Za9D7L9MVMWjNSLd8c,3930
|
|
33
34
|
aid_runtime/evals/gate.py,sha256=_nLWXvcuHwq8nE3HpiONg_wBkrzZyGrGT49ZNeKMyTY,15524
|
|
34
|
-
aid_runtime/evals/metrics.py,sha256=
|
|
35
|
+
aid_runtime/evals/metrics.py,sha256=LvzKgW-7CNxcB0MmDXakDnwdgyzjpH8ceHq7mdi8mw4,28541
|
|
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
|
-
aid_runtime/evals/trajectory.py,sha256=
|
|
38
|
-
aid_runtime/providers/__init__.py,sha256=
|
|
38
|
+
aid_runtime/evals/trajectory.py,sha256=X7ssDigfFuMkjM6mR6LGSbb03A8iNf4oRbVqeSsU7Ww,4444
|
|
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.
|
|
63
|
-
aid_runtime_python-0.1.
|
|
64
|
-
aid_runtime_python-0.1.
|
|
65
|
-
aid_runtime_python-0.1.
|
|
64
|
+
aid_runtime_python-0.1.159.dist-info/METADATA,sha256=KiPOHX68XNeLYKRZ-IsIQ-e1VL4kaiSdTZwy0hp2Je8,17163
|
|
65
|
+
aid_runtime_python-0.1.159.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
66
|
+
aid_runtime_python-0.1.159.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
|
|
67
|
+
aid_runtime_python-0.1.159.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|