aid-runtime-python 0.1.88__py3-none-any.whl → 0.1.90__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
@@ -294,7 +294,7 @@ from aid_runtime.types import (
294
294
  )
295
295
 
296
296
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
297
- __version__ = "0.1.88"
297
+ __version__ = "0.1.90"
298
298
 
299
299
  __all__ = [
300
300
  "ANTHROPIC_VERSION",
@@ -19,6 +19,7 @@ from aid_runtime.agents.guardrails import (
19
19
  DETECTORS,
20
20
  GUARDRAIL_ACTIONS,
21
21
  GUARDRAIL_STAGES,
22
+ DecisionAsker,
22
23
  Detection,
23
24
  GuardrailEngine,
24
25
  GuardrailEscalation,
@@ -28,6 +29,7 @@ from aid_runtime.agents.guardrails import (
28
29
  )
29
30
  from aid_runtime.agents.ir import (
30
31
  AgentDefinition,
32
+ DecisionDefinition,
31
33
  GuardrailDefinition,
32
34
  HumanApproval,
33
35
  MemoryDefinition,
@@ -65,6 +67,8 @@ __all__ = [
65
67
  "AgentCheckpoint",
66
68
  "AgentDefinition",
67
69
  "AgentRuntime",
70
+ "DecisionAsker",
71
+ "DecisionDefinition",
68
72
  "Detection",
69
73
  "FileMemoryStore",
70
74
  "GuardrailDefinition",
@@ -43,13 +43,14 @@ detector matched, and the run carried on because the spec said the run may.
43
43
  from __future__ import annotations
44
44
 
45
45
  import re
46
- from collections.abc import Mapping, Sequence
46
+ from collections.abc import Callable, Mapping, Sequence
47
47
  from dataclasses import dataclass, field
48
- from typing import Any, Literal
48
+ from typing import Any, Literal, Protocol, cast
49
49
 
50
50
  from pydantic import BaseModel, ConfigDict
51
51
 
52
- from aid_runtime.agents.ir import GuardrailDefinition
52
+ from aid_runtime.agents.ir import DecisionDefinition, GuardrailDefinition
53
+ from aid_runtime.decisions import DecisionClient, DecisionQuestion, DecisionResponse
53
54
  from aid_runtime.errors import ConfigurationError, GuardrailBlockedError
54
55
 
55
56
  __all__ = [
@@ -108,6 +109,11 @@ class GuardrailRecord(BaseModel):
108
109
  action: GuardrailAction
109
110
  policies: tuple[str, ...]
110
111
  message: str
112
+ #: Set when a decision answered rather than a detector, so a reviewer can tell
113
+ #: "the classifier said block" from "the regex matched" without the log message.
114
+ decision: str | None = None
115
+ label: str | None = None
116
+ confidence: float | None = None
111
117
 
112
118
 
113
119
  class GuardrailEscalation(BaseModel):
@@ -243,6 +249,10 @@ DETECTORS: Mapping[str, tuple[re.Pattern[str], ...]] = {
243
249
  #: safe -- which is why a ``redact`` guardrail over them fails closed below.
244
250
  _REDACTABLE = frozenset({"pii-detect", "pii-redact", "secret-scan"})
245
251
 
252
+ #: The outcomes a decision label may map to. ``allow`` is the one that records
253
+ #: nothing; ``redact`` is absent because a label cannot name the field to rewrite.
254
+ _DECISION_OUTCOMES = frozenset({"allow", "block", "flag", "escalate"})
255
+
246
256
 
247
257
  def detect(policy: str, text: str) -> tuple[Detection, ...]:
248
258
  """Every match of ``policy`` in ``text``, in document order.
@@ -287,6 +297,19 @@ def _texts(payload: Mapping[str, Any]) -> tuple[tuple[str, str], ...]:
287
297
  )
288
298
 
289
299
 
300
+ class DecisionAsker(Protocol):
301
+ """The one call the engine makes, so a test double need not subclass the client."""
302
+
303
+ async def decide(
304
+ self,
305
+ *,
306
+ model: str,
307
+ state: Any,
308
+ questions: Mapping[str, DecisionQuestion],
309
+ reproducible: bool = False,
310
+ ) -> DecisionResponse: ...
311
+
312
+
290
313
  class GuardrailEngine:
291
314
  """Evaluates an agent's guardrails at one stage.
292
315
 
@@ -295,8 +318,18 @@ class GuardrailEngine:
295
318
  same way, which is what makes the corpus results reproducible.
296
319
  """
297
320
 
298
- def __init__(self, guardrails: Mapping[str, GuardrailDefinition] | None = None) -> None:
321
+ def __init__(
322
+ self,
323
+ guardrails: Mapping[str, GuardrailDefinition] | None = None,
324
+ decisions: Mapping[str, DecisionDefinition] | None = None,
325
+ client_factory: Callable[[], DecisionAsker] | None = None,
326
+ ) -> None:
299
327
  self._declared = dict(guardrails or {})
328
+ self._decisions = dict(decisions or {})
329
+ #: Built on first use, not at import: an app with no TypeSafe key must still
330
+ #: boot when no request reaches a decision-backed guardrail.
331
+ self._client_factory = client_factory or DecisionClient
332
+ self._client: DecisionAsker | None = None
300
333
 
301
334
  def declared(self, guardrail_id: str) -> GuardrailDefinition | None:
302
335
  return self._declared.get(guardrail_id)
@@ -308,6 +341,154 @@ class GuardrailEngine:
308
341
  ) -> GuardrailVerdict:
309
342
  return self._check("input", guardrails, {"text": text}, tool_id=None)
310
343
 
344
+ async def check_input_async(
345
+ self,
346
+ guardrails: Sequence[GuardrailDefinition],
347
+ text: str,
348
+ ) -> GuardrailVerdict:
349
+ """The ``input`` stage with decisions: the same rules, one awaitable question.
350
+
351
+ This is the only stage a decision may guard, so it is the only stage with an
352
+ async twin; ``check_input`` stays synchronous and unchanged for callers that
353
+ have no network check to make. Order is preserved across both kinds of
354
+ guardrail -- declaration order still decides between comparable actions, and
355
+ ``block`` still outranks it.
356
+
357
+ A guardrail that declares both policies and a decision asks the decision only
358
+ when its policies found nothing: asking a model about input a detector already
359
+ refused would spend tokens to learn what the detector said.
360
+ """
361
+ payload: Mapping[str, Any] = {"text": text}
362
+ applicable = [guardrail for guardrail in guardrails if "input" in guardrail.stages]
363
+ records: list[GuardrailRecord] = []
364
+ fired: list[GuardrailDefinition] = []
365
+ for guardrail in applicable:
366
+ policies = _firing_policies(guardrail, "input", payload)
367
+ record: GuardrailRecord | None = None
368
+ if policies:
369
+ record = GuardrailRecord(
370
+ guardrail=guardrail.id,
371
+ stage="input",
372
+ action=_action(guardrail),
373
+ policies=policies,
374
+ message=guardrail.message,
375
+ )
376
+ elif guardrail.decision is not None:
377
+ record = await self._ask_decision(guardrail, text)
378
+ if record is None:
379
+ continue
380
+ fired.append(guardrail)
381
+ records.append(record)
382
+
383
+ deciding = _decide(records)
384
+ if deciding is None:
385
+ return GuardrailVerdict(stage="input", text=text, arguments=dict(payload))
386
+
387
+ redacted = payload
388
+ if deciding.action == ACTION_REDACT:
389
+ redacted = _redact(
390
+ "input",
391
+ [guardrail for guardrail in fired if guardrail.action == ACTION_REDACT],
392
+ payload,
393
+ )
394
+ return GuardrailVerdict(
395
+ stage="input",
396
+ records=tuple(records),
397
+ action=deciding.action,
398
+ deciding=deciding,
399
+ text=_text_of(redacted),
400
+ arguments=dict(redacted),
401
+ )
402
+
403
+ async def _ask_decision(
404
+ self,
405
+ guardrail: GuardrailDefinition,
406
+ text: str,
407
+ ) -> GuardrailRecord | None:
408
+ """Ask one ``choice`` decision and turn its label into a record, or ``None``.
409
+
410
+ Everything that is not a usable answer is a :class:`GuardrailBlockedError`:
411
+ an undeclared decision, an unmapped label, a confidence below the declared
412
+ floor, or a call that raised. That is the same rule the policy path follows
413
+ -- there is no path from "the check could not run" to "no violation found".
414
+ """
415
+ name = guardrail.decision or ""
416
+ definition = self._decisions.get(name)
417
+ if definition is None:
418
+ raise GuardrailBlockedError(
419
+ guardrail.id,
420
+ "input",
421
+ f"decision {name!r} has no definition in this runtime",
422
+ )
423
+ outcomes = dict(guardrail.on_decision)
424
+ if not outcomes:
425
+ raise GuardrailBlockedError(
426
+ guardrail.id,
427
+ "input",
428
+ f"decision {name!r} maps no answer label, so no answer could be acted on",
429
+ )
430
+ if self._client is None:
431
+ self._client = self._client_factory()
432
+ question = DecisionQuestion(
433
+ type="choice",
434
+ instructions=definition.instructions,
435
+ criteria=definition.criteria,
436
+ )
437
+ try:
438
+ response = await self._client.decide(
439
+ model=definition.model,
440
+ state=text,
441
+ questions={name: question},
442
+ )
443
+ except Exception as error:
444
+ raise GuardrailBlockedError(
445
+ guardrail.id,
446
+ "input",
447
+ f"decision {name!r} could not answer: {error}",
448
+ ) from error
449
+
450
+ answer = response.answers.get(name)
451
+ if answer is None:
452
+ raise GuardrailBlockedError(
453
+ guardrail.id,
454
+ "input",
455
+ f"decision {name!r} returned no answer for its own question",
456
+ )
457
+ label = answer.choice
458
+ if label is None or label not in outcomes:
459
+ raise GuardrailBlockedError(
460
+ guardrail.id,
461
+ "input",
462
+ f"decision {name!r} answered {label!r}, which this guardrail does not map",
463
+ )
464
+ if answer.confidence is not None and answer.confidence < guardrail.min_confidence:
465
+ raise GuardrailBlockedError(
466
+ guardrail.id,
467
+ "input",
468
+ f"decision {name!r} answered {label!r} with confidence "
469
+ f"{answer.confidence:.2f}, below the declared minimum "
470
+ f"{guardrail.min_confidence:.2f}",
471
+ )
472
+ outcome = outcomes[label]
473
+ if outcome not in _DECISION_OUTCOMES:
474
+ raise GuardrailBlockedError(
475
+ guardrail.id,
476
+ "input",
477
+ f"decision {name!r} maps {label!r} to unknown outcome {outcome!r}",
478
+ )
479
+ if outcome == "allow":
480
+ return None
481
+ return GuardrailRecord(
482
+ guardrail=guardrail.id,
483
+ stage="input",
484
+ action=cast(GuardrailAction, outcome),
485
+ policies=(),
486
+ message=guardrail.message,
487
+ decision=name,
488
+ label=label,
489
+ confidence=answer.confidence,
490
+ )
491
+
311
492
  def check_output(
312
493
  self,
313
494
  guardrails: Sequence[GuardrailDefinition],
aid_runtime/agents/ir.py CHANGED
@@ -28,6 +28,7 @@ from aid_runtime.types import (
28
28
 
29
29
  __all__ = [
30
30
  "AgentDefinition",
31
+ "DecisionDefinition",
31
32
  "GuardrailDefinition",
32
33
  "HumanApproval",
33
34
  "MemoryDefinition",
@@ -83,12 +84,32 @@ class ToolSpec:
83
84
  auth: Mapping[str, Any] | None
84
85
 
85
86
 
87
+ @dataclass(frozen=True, slots=True)
88
+ class DecisionDefinition:
89
+ """A ``choice`` decision a guardrail asks, resolved from the IR's ``decisions``.
90
+
91
+ Only the fields an input guardrail needs are here: the model that answers, the
92
+ question, and the labels an ``on_decision`` map may name. ``score`` and ``noul``
93
+ questions have no labels, so the spec gate refuses them as guardrail sources.
94
+ """
95
+
96
+ id: str
97
+ model: str
98
+ instructions: str
99
+ criteria: tuple[str, ...]
100
+
101
+
86
102
  @dataclass(frozen=True, slots=True)
87
103
  class GuardrailDefinition:
88
104
  """One resolved guardrail: where it runs, what it detects, and what it does.
89
105
 
90
106
  ``tools`` holds tool *ids*, because that is how the IR scopes a tool-call
91
107
  guardrail; the loop translates a model's tool *name* to the id before asking.
108
+
109
+ ``decision`` names a ``choice`` decision to ask at the ``input`` stage, and
110
+ ``on_decision`` maps each of its labels to an outcome. ``allow`` is the one
111
+ outcome that produces no record; the rest are guardrail actions. The trailing
112
+ defaults keep every keyword call site written before decisions existed valid.
92
113
  """
93
114
 
94
115
  id: str
@@ -100,6 +121,9 @@ class GuardrailDefinition:
100
121
  message: str
101
122
  fallback_prompt: str | None
102
123
  log: bool
124
+ decision: str | None = None
125
+ on_decision: tuple[tuple[str, str], ...] = ()
126
+ min_confidence: float = 0.0
103
127
 
104
128
 
105
129
  @dataclass(frozen=True, slots=True)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.88
3
+ Version: 0.1.90
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=FgQcgywbdRWxhMbEQCSjSHF8udchK5lpYbXjb84eDtg,12397
1
+ aid_runtime/__init__.py,sha256=WzBKUskmFzQqPhyEIknBarXRKy4UzZg3y7GTjqF_GNc,12397
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=u4U97QFdYSSjOPY3D6f1-GZhkGhygEdR-apdgw_jJok,13797
@@ -15,12 +15,12 @@ aid_runtime/structured.py,sha256=Uga-VoGJN56lUtr-M3nmUjAKGF32cAAk-p7WceUgPzg,506
15
15
  aid_runtime/tools.py,sha256=7LeaPI5aJioNe3vexUv94tvIRpOwxj1Ujt723qvO3UI,9906
16
16
  aid_runtime/tracing.py,sha256=WEnmXRfRPEb5eRpH2JWZlnim7V4IHDv4SV2HS_qjUrU,9081
17
17
  aid_runtime/types.py,sha256=cVYgmacDIhStQT5dX_X67-q57sPBBaWC5nybtGVqVsw,10389
18
- aid_runtime/agents/__init__.py,sha256=XOOecYSBtWzD0Ylaurbz3w2Tuffpzc_5nNeMIznCucU,2398
18
+ aid_runtime/agents/__init__.py,sha256=Qkcjm0YokmObQWRB3G_xFd_LI4sku_GajDbE_7TzyF8,2488
19
19
  aid_runtime/agents/chat_model.py,sha256=fZdCmSpoECuBVGZE1s8NmT2erT33RhDuLh3yJM6kAJE,14808
20
20
  aid_runtime/agents/deep_agents.py,sha256=ZM6ZSc92arCvtsYGsIGdF-NryqN_tvXtRqbdlHaGpeE,26948
21
21
  aid_runtime/agents/engine.py,sha256=RQUV49u7MLDmirnFv8YsRGdIutzUGsGaLA6Y2JT5wj0,4129
22
- aid_runtime/agents/guardrails.py,sha256=RM_iR_h7LQiulN8KA6scKeCyoTxECqywqJO0eLHPpKQ,19363
23
- aid_runtime/agents/ir.py,sha256=BaIGEzwHSQnP2q7s1GjNwRTICju9LsPGdAcsboA4KSw,24151
22
+ aid_runtime/agents/guardrails.py,sha256=XwllB-33HE65FJumCMx--LGDVNfWjLrrupQHfUbCAG8,26624
23
+ aid_runtime/agents/ir.py,sha256=E9N7G7ZBFDmQ0tQ_QNn3_zuCHlduo9tTOzqh4uwHsok,25104
24
24
  aid_runtime/agents/loop.py,sha256=T-QnC9BQ9K3RyZfHdAuzWiwMXBpQjDLGdHrLgf2fnFM,52608
25
25
  aid_runtime/agents/memory.py,sha256=6_D6k2bzAiR2euNvzr6HB28wsUUq-R-WTQc12gkB8ao,9156
26
26
  aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
@@ -51,7 +51,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
51
51
  aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
52
52
  aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
53
53
  aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
54
- aid_runtime_python-0.1.88.dist-info/METADATA,sha256=tGtqZyQBllXWYbNe6CSM6MFyJ8R9gw3PaNGUAnRZuCA,17005
55
- aid_runtime_python-0.1.88.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
56
- aid_runtime_python-0.1.88.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
57
- aid_runtime_python-0.1.88.dist-info/RECORD,,
54
+ aid_runtime_python-0.1.90.dist-info/METADATA,sha256=XIt1xD9qo9sLvPo8IenXbpFIG1MGoYliesdmxCqKHbw,17005
55
+ aid_runtime_python-0.1.90.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
56
+ aid_runtime_python-0.1.90.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
57
+ aid_runtime_python-0.1.90.dist-info/RECORD,,