aid-runtime-python 0.1.97__py3-none-any.whl → 0.1.98__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 +1 -1
- aid_runtime/agents/__init__.py +14 -0
- aid_runtime/agents/guardrails.py +115 -49
- aid_runtime/agents/ir.py +107 -1
- aid_runtime/agents/managed.py +324 -0
- aid_runtime/providers/bedrock.py +98 -48
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.98.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.98.dist-info}/RECORD +10 -9
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.98.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.98.dist-info}/top_level.txt +0 -0
aid_runtime/__init__.py
CHANGED
aid_runtime/agents/__init__.py
CHANGED
|
@@ -29,6 +29,7 @@ from aid_runtime.agents.guardrails import (
|
|
|
29
29
|
)
|
|
30
30
|
from aid_runtime.agents.ir import (
|
|
31
31
|
AgentDefinition,
|
|
32
|
+
BedrockGuardrailPolicy,
|
|
32
33
|
DecisionDefinition,
|
|
33
34
|
GuardrailDefinition,
|
|
34
35
|
HumanApproval,
|
|
@@ -37,6 +38,13 @@ from aid_runtime.agents.ir import (
|
|
|
37
38
|
ToolSpec,
|
|
38
39
|
)
|
|
39
40
|
from aid_runtime.agents.loop import AgentRuntime
|
|
41
|
+
from aid_runtime.agents.managed import (
|
|
42
|
+
BedrockGuardrailClient,
|
|
43
|
+
GuardrailClient,
|
|
44
|
+
GuardrailOutcome,
|
|
45
|
+
ManagedGuardrailSettings,
|
|
46
|
+
managed_guardrail_settings,
|
|
47
|
+
)
|
|
40
48
|
from aid_runtime.agents.memory import (
|
|
41
49
|
IMPLEMENTED_MEMORY_KINDS,
|
|
42
50
|
MEMORY_SCOPES,
|
|
@@ -67,18 +75,23 @@ __all__ = [
|
|
|
67
75
|
"AgentCheckpoint",
|
|
68
76
|
"AgentDefinition",
|
|
69
77
|
"AgentRuntime",
|
|
78
|
+
"BedrockGuardrailClient",
|
|
79
|
+
"BedrockGuardrailPolicy",
|
|
70
80
|
"DecisionAsker",
|
|
71
81
|
"DecisionDefinition",
|
|
72
82
|
"Detection",
|
|
73
83
|
"FileMemoryStore",
|
|
84
|
+
"GuardrailClient",
|
|
74
85
|
"GuardrailDefinition",
|
|
75
86
|
"GuardrailEngine",
|
|
76
87
|
"GuardrailEscalation",
|
|
88
|
+
"GuardrailOutcome",
|
|
77
89
|
"GuardrailRecord",
|
|
78
90
|
"GuardrailVerdict",
|
|
79
91
|
"HumanApproval",
|
|
80
92
|
"HumanDecision",
|
|
81
93
|
"InProcessMemoryStore",
|
|
94
|
+
"ManagedGuardrailSettings",
|
|
82
95
|
"MemoryDefinition",
|
|
83
96
|
"MemoryStore",
|
|
84
97
|
"PendingApproval",
|
|
@@ -93,6 +106,7 @@ __all__ = [
|
|
|
93
106
|
"check_memory_supported",
|
|
94
107
|
"detect",
|
|
95
108
|
"evaluate_policy",
|
|
109
|
+
"managed_guardrail_settings",
|
|
96
110
|
"policy_source",
|
|
97
111
|
"render_context",
|
|
98
112
|
]
|
aid_runtime/agents/guardrails.py
CHANGED
|
@@ -50,6 +50,7 @@ from typing import Any, Literal, Protocol, cast
|
|
|
50
50
|
from pydantic import BaseModel, ConfigDict
|
|
51
51
|
|
|
52
52
|
from aid_runtime.agents.ir import DecisionDefinition, GuardrailDefinition
|
|
53
|
+
from aid_runtime.agents.managed import BedrockGuardrailClient, GuardrailClient
|
|
53
54
|
from aid_runtime.decisions import DecisionClient, DecisionQuestion, DecisionResponse
|
|
54
55
|
from aid_runtime.errors import ConfigurationError, GuardrailBlockedError
|
|
55
56
|
|
|
@@ -77,6 +78,9 @@ ACTION_REDACT: GuardrailAction = "redact"
|
|
|
77
78
|
ACTION_FLAG: GuardrailAction = "flag"
|
|
78
79
|
ACTION_ESCALATE: GuardrailAction = "escalate"
|
|
79
80
|
|
|
81
|
+
#: The one managed engine. ``builtin`` is the default and needs no name here.
|
|
82
|
+
ENGINE_BEDROCK = "bedrock"
|
|
83
|
+
|
|
80
84
|
GUARDRAIL_STAGES: tuple[GuardrailStage, ...] = ("input", "retrieval", "tool-call", "output")
|
|
81
85
|
GUARDRAIL_ACTIONS: tuple[GuardrailAction, ...] = (
|
|
82
86
|
ACTION_BLOCK,
|
|
@@ -323,6 +327,7 @@ class GuardrailEngine:
|
|
|
323
327
|
guardrails: Mapping[str, GuardrailDefinition] | None = None,
|
|
324
328
|
decisions: Mapping[str, DecisionDefinition] | None = None,
|
|
325
329
|
client_factory: Callable[[], DecisionAsker] | None = None,
|
|
330
|
+
guardrail_client_factory: Callable[[], GuardrailClient] | None = None,
|
|
326
331
|
) -> None:
|
|
327
332
|
self._declared = dict(guardrails or {})
|
|
328
333
|
self._decisions = dict(decisions or {})
|
|
@@ -330,10 +335,19 @@ class GuardrailEngine:
|
|
|
330
335
|
#: boot when no request reaches a decision-backed guardrail.
|
|
331
336
|
self._client_factory = client_factory or DecisionClient
|
|
332
337
|
self._client: DecisionAsker | None = None
|
|
338
|
+
#: Same rule for a managed engine: a document with no ``engine: bedrock``
|
|
339
|
+
#: guardrail must never require Bedrock credentials to start.
|
|
340
|
+
self._guardrail_client_factory = guardrail_client_factory or BedrockGuardrailClient
|
|
341
|
+
self._guardrail_client: GuardrailClient | None = None
|
|
333
342
|
|
|
334
343
|
def declared(self, guardrail_id: str) -> GuardrailDefinition | None:
|
|
335
344
|
return self._declared.get(guardrail_id)
|
|
336
345
|
|
|
346
|
+
def _managed(self) -> GuardrailClient:
|
|
347
|
+
if self._guardrail_client is None:
|
|
348
|
+
self._guardrail_client = self._guardrail_client_factory()
|
|
349
|
+
return self._guardrail_client
|
|
350
|
+
|
|
337
351
|
def check_input(
|
|
338
352
|
self,
|
|
339
353
|
guardrails: Sequence[GuardrailDefinition],
|
|
@@ -346,33 +360,74 @@ class GuardrailEngine:
|
|
|
346
360
|
guardrails: Sequence[GuardrailDefinition],
|
|
347
361
|
text: str,
|
|
348
362
|
) -> GuardrailVerdict:
|
|
349
|
-
"""The ``input`` stage
|
|
363
|
+
"""The ``input`` stage when a guardrail needs more than a detector.
|
|
364
|
+
|
|
365
|
+
The async twin of :meth:`check_input`: decisions and managed engines are the
|
|
366
|
+
two guardrails that need a round trip, and both are awaited here. A caller
|
|
367
|
+
that has neither can keep using the synchronous method.
|
|
368
|
+
"""
|
|
369
|
+
return await self._check_async("input", guardrails, {"text": text}, tool_id=None)
|
|
370
|
+
|
|
371
|
+
async def check_output_async(
|
|
372
|
+
self,
|
|
373
|
+
guardrails: Sequence[GuardrailDefinition],
|
|
374
|
+
text: str,
|
|
375
|
+
) -> GuardrailVerdict:
|
|
376
|
+
"""The ``output`` stage: managed engines only, since a decision guards input.
|
|
350
377
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
378
|
+
The response text is what ``ApplyGuardrail`` rewrites, so a managed
|
|
379
|
+
``redact`` returns the provider's rewritten text rather than a local mask.
|
|
380
|
+
"""
|
|
381
|
+
return await self._check_async("output", guardrails, {"text": text}, tool_id=None)
|
|
382
|
+
|
|
383
|
+
async def _check_async(
|
|
384
|
+
self,
|
|
385
|
+
stage: GuardrailStage,
|
|
386
|
+
guardrails: Sequence[GuardrailDefinition],
|
|
387
|
+
payload: Mapping[str, Any],
|
|
388
|
+
tool_id: str | None,
|
|
389
|
+
) -> GuardrailVerdict:
|
|
390
|
+
"""One stage, allowing the guardrails that need an await.
|
|
356
391
|
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
392
|
+
Order and precedence are the synchronous path's: a policy hit is recorded
|
|
393
|
+
before any network check is considered, declaration order still decides
|
|
394
|
+
between comparable actions, and ``block`` still outranks it.
|
|
360
395
|
"""
|
|
361
|
-
|
|
362
|
-
applicable = [
|
|
396
|
+
text = _text_of(payload)
|
|
397
|
+
applicable = [
|
|
398
|
+
guardrail
|
|
399
|
+
for guardrail in guardrails
|
|
400
|
+
if stage in guardrail.stages and _covers(guardrail, stage, tool_id)
|
|
401
|
+
]
|
|
363
402
|
records: list[GuardrailRecord] = []
|
|
364
403
|
fired: list[GuardrailDefinition] = []
|
|
404
|
+
rewritten: dict[str, str] = {}
|
|
365
405
|
for guardrail in applicable:
|
|
366
|
-
policies = _firing_policies(guardrail,
|
|
406
|
+
policies = _firing_policies(guardrail, stage, payload)
|
|
367
407
|
record: GuardrailRecord | None = None
|
|
368
408
|
if policies:
|
|
369
409
|
record = GuardrailRecord(
|
|
370
410
|
guardrail=guardrail.id,
|
|
371
|
-
stage=
|
|
411
|
+
stage=stage,
|
|
372
412
|
action=_action(guardrail),
|
|
373
413
|
policies=policies,
|
|
374
414
|
message=guardrail.message,
|
|
375
415
|
)
|
|
416
|
+
elif guardrail.engine == ENGINE_BEDROCK:
|
|
417
|
+
outcome = await self._managed().apply(
|
|
418
|
+
source="INPUT" if stage == "input" else "OUTPUT",
|
|
419
|
+
text=text,
|
|
420
|
+
)
|
|
421
|
+
if outcome.intervened:
|
|
422
|
+
if outcome.text is not None:
|
|
423
|
+
rewritten[guardrail.id] = outcome.text
|
|
424
|
+
record = GuardrailRecord(
|
|
425
|
+
guardrail=guardrail.id,
|
|
426
|
+
stage=stage,
|
|
427
|
+
action=_action(guardrail),
|
|
428
|
+
policies=outcome.policies,
|
|
429
|
+
message=guardrail.message or ", ".join(outcome.policies),
|
|
430
|
+
)
|
|
376
431
|
elif guardrail.decision is not None:
|
|
377
432
|
record = await self._ask_decision(guardrail, text)
|
|
378
433
|
if record is None:
|
|
@@ -380,25 +435,7 @@ class GuardrailEngine:
|
|
|
380
435
|
fired.append(guardrail)
|
|
381
436
|
records.append(record)
|
|
382
437
|
|
|
383
|
-
|
|
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
|
-
)
|
|
438
|
+
return _assemble(stage, payload, fired, records, rewritten)
|
|
402
439
|
|
|
403
440
|
async def _ask_decision(
|
|
404
441
|
self,
|
|
@@ -550,6 +587,15 @@ class GuardrailEngine:
|
|
|
550
587
|
records: list[GuardrailRecord] = []
|
|
551
588
|
fired: list[GuardrailDefinition] = []
|
|
552
589
|
for guardrail in applicable:
|
|
590
|
+
if guardrail.engine != "builtin":
|
|
591
|
+
# Fail closed rather than skip: a synchronous caller cannot await the
|
|
592
|
+
# provider, and returning "no violation" would be an allow nobody
|
|
593
|
+
# declared. The generated pipeline calls the async variant instead.
|
|
594
|
+
raise GuardrailBlockedError(
|
|
595
|
+
guardrail.id,
|
|
596
|
+
stage,
|
|
597
|
+
f"guardrail uses engine {guardrail.engine!r}, which needs the async check",
|
|
598
|
+
)
|
|
553
599
|
policies = _firing_policies(guardrail, stage, payload)
|
|
554
600
|
if not policies:
|
|
555
601
|
continue
|
|
@@ -564,29 +610,49 @@ class GuardrailEngine:
|
|
|
564
610
|
)
|
|
565
611
|
)
|
|
566
612
|
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
613
|
+
return _assemble(stage, payload, fired, records)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _assemble(
|
|
617
|
+
stage: GuardrailStage,
|
|
618
|
+
payload: Mapping[str, Any],
|
|
619
|
+
fired: Sequence[GuardrailDefinition],
|
|
620
|
+
records: Sequence[GuardrailRecord],
|
|
621
|
+
rewritten: Mapping[str, str] | None = None,
|
|
622
|
+
) -> GuardrailVerdict:
|
|
623
|
+
"""Turn the records a stage produced into the verdict the pipeline acts on.
|
|
624
|
+
|
|
625
|
+
``rewritten`` maps a managed guardrail to the provider's replacement text. Only
|
|
626
|
+
the deciding guardrail's text is substituted: a provider that anonymised one
|
|
627
|
+
policy's spans did not necessarily see the others.
|
|
628
|
+
"""
|
|
629
|
+
deciding = _decide(records)
|
|
630
|
+
if deciding is None:
|
|
631
|
+
return GuardrailVerdict(
|
|
632
|
+
stage=stage,
|
|
633
|
+
text=_text_of(payload),
|
|
634
|
+
arguments=dict(payload),
|
|
635
|
+
)
|
|
574
636
|
|
|
575
|
-
|
|
576
|
-
|
|
637
|
+
redacted = payload
|
|
638
|
+
if deciding.action == ACTION_REDACT:
|
|
639
|
+
replacement = (rewritten or {}).get(deciding.guardrail)
|
|
640
|
+
if replacement is not None:
|
|
641
|
+
redacted = {**payload, "text": replacement}
|
|
642
|
+
else:
|
|
577
643
|
redacted = _redact(
|
|
578
644
|
stage,
|
|
579
645
|
[guardrail for guardrail in fired if guardrail.action == ACTION_REDACT],
|
|
580
646
|
payload,
|
|
581
647
|
)
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
648
|
+
return GuardrailVerdict(
|
|
649
|
+
stage=stage,
|
|
650
|
+
records=tuple(records),
|
|
651
|
+
action=deciding.action,
|
|
652
|
+
deciding=deciding,
|
|
653
|
+
text=_text_of(redacted),
|
|
654
|
+
arguments=dict(redacted),
|
|
655
|
+
)
|
|
590
656
|
|
|
591
657
|
|
|
592
658
|
def _covers(guardrail: GuardrailDefinition, stage: str, tool_id: str | None) -> bool:
|
aid_runtime/agents/ir.py
CHANGED
|
@@ -28,6 +28,7 @@ from aid_runtime.types import (
|
|
|
28
28
|
|
|
29
29
|
__all__ = [
|
|
30
30
|
"AgentDefinition",
|
|
31
|
+
"BedrockGuardrailPolicy",
|
|
31
32
|
"DecisionDefinition",
|
|
32
33
|
"GuardrailDefinition",
|
|
33
34
|
"HumanApproval",
|
|
@@ -57,6 +58,29 @@ _ON_BUDGET_EXHAUSTED = frozenset({"fail", "degrade"})
|
|
|
57
58
|
#: rejects it again rather than trusting that every document came through a gate.
|
|
58
59
|
_GUARDRAIL_STAGES = frozenset({"input", "output", "retrieval", "tool-call"})
|
|
59
60
|
_GUARDRAIL_ACTIONS = frozenset({"block", "redact", "flag", "escalate"})
|
|
61
|
+
_GUARDRAIL_ENGINES = frozenset({"builtin", "bedrock"})
|
|
62
|
+
_BEDROCK_CONTENT_FILTERS = frozenset(
|
|
63
|
+
{"sexual", "violence", "hate", "insults", "misconduct", "prompt-attack"}
|
|
64
|
+
)
|
|
65
|
+
_BEDROCK_CONTENT_STRENGTHS = frozenset({"low", "medium", "high"})
|
|
66
|
+
_BEDROCK_PII_ENTITIES = frozenset(
|
|
67
|
+
{
|
|
68
|
+
"email",
|
|
69
|
+
"phone",
|
|
70
|
+
"name",
|
|
71
|
+
"address",
|
|
72
|
+
"ssn",
|
|
73
|
+
"credit-card",
|
|
74
|
+
"bank-account",
|
|
75
|
+
"passport",
|
|
76
|
+
"drivers-license",
|
|
77
|
+
"ip-address",
|
|
78
|
+
"url",
|
|
79
|
+
"aws-access-key",
|
|
80
|
+
"aws-secret-key",
|
|
81
|
+
}
|
|
82
|
+
)
|
|
83
|
+
|
|
60
84
|
_GUARDRAIL_POLICIES = frozenset(
|
|
61
85
|
{
|
|
62
86
|
"pii-detect",
|
|
@@ -100,6 +124,22 @@ class DecisionDefinition:
|
|
|
100
124
|
criteria: tuple[str, ...]
|
|
101
125
|
|
|
102
126
|
|
|
127
|
+
@dataclass(frozen=True, slots=True)
|
|
128
|
+
class BedrockGuardrailPolicy:
|
|
129
|
+
"""The policy a managed guardrail asks Bedrock to enforce.
|
|
130
|
+
|
|
131
|
+
The IR's vocabulary is kept here, not AWS's: lowercase content filters and
|
|
132
|
+
strengths, hyphenated entity names. ``agents.managed`` is the one place that
|
|
133
|
+
maps it to the wire enums, which is what keeps the conversion testable without
|
|
134
|
+
an AWS call and stops the generator from owning a second copy of the table.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
content: tuple[tuple[str, str], ...] = ()
|
|
138
|
+
topics: tuple[tuple[str, str], ...] = ()
|
|
139
|
+
words: tuple[str, ...] = ()
|
|
140
|
+
pii: tuple[str, ...] = ()
|
|
141
|
+
|
|
142
|
+
|
|
103
143
|
@dataclass(frozen=True, slots=True)
|
|
104
144
|
class GuardrailDefinition:
|
|
105
145
|
"""One resolved guardrail: where it runs, what it detects, and what it does.
|
|
@@ -111,6 +151,9 @@ class GuardrailDefinition:
|
|
|
111
151
|
``on_decision`` maps each of its labels to an outcome. ``allow`` is the one
|
|
112
152
|
outcome that produces no record; the rest are guardrail actions. The trailing
|
|
113
153
|
defaults keep every keyword call site written before decisions existed valid.
|
|
154
|
+
|
|
155
|
+
``engine`` is ``builtin`` (this process runs the detectors) or ``bedrock`` (the
|
|
156
|
+
managed service evaluates ``bedrock`` instead, and ``policies`` stays empty).
|
|
114
157
|
"""
|
|
115
158
|
|
|
116
159
|
id: str
|
|
@@ -125,6 +168,8 @@ class GuardrailDefinition:
|
|
|
125
168
|
decision: str | None = None
|
|
126
169
|
on_decision: tuple[tuple[str, str], ...] = ()
|
|
127
170
|
min_confidence: float = 0.0
|
|
171
|
+
engine: str = "builtin"
|
|
172
|
+
bedrock: BedrockGuardrailPolicy | None = None
|
|
128
173
|
|
|
129
174
|
|
|
130
175
|
@dataclass(frozen=True, slots=True)
|
|
@@ -391,12 +436,27 @@ def _guardrail(
|
|
|
391
436
|
raise ConfigurationError(
|
|
392
437
|
f"{where} has action {action!r}; expected one of {sorted(_GUARDRAIL_ACTIONS)}"
|
|
393
438
|
)
|
|
439
|
+
engine = _str(entry.get("engine")) or "builtin"
|
|
440
|
+
if engine not in _GUARDRAIL_ENGINES:
|
|
441
|
+
raise ConfigurationError(
|
|
442
|
+
f"{where} has engine {engine!r}; expected one of {sorted(_GUARDRAIL_ENGINES)}"
|
|
443
|
+
)
|
|
444
|
+
bedrock = _bedrock_policy(entry.get("bedrock"), where) if engine == "bedrock" else None
|
|
445
|
+
if engine == "bedrock" and bedrock is None:
|
|
446
|
+
raise ConfigurationError(
|
|
447
|
+
f"{where} uses engine 'bedrock' with no bedrock policy; name at least one of "
|
|
448
|
+
"content, topics, words, pii"
|
|
449
|
+
)
|
|
394
450
|
redact = tuple(_str_list(entry.get("redact"), f"{where} redact"))
|
|
395
|
-
if action == "redact" and not redact:
|
|
451
|
+
if action == "redact" and not redact and engine == "builtin":
|
|
396
452
|
raise ConfigurationError(
|
|
397
453
|
f"{where} uses action 'redact' with no redact fields; a redaction that names "
|
|
398
454
|
"no field cannot redact anything"
|
|
399
455
|
)
|
|
456
|
+
if action == "redact" and engine == "bedrock":
|
|
457
|
+
# The managed service rewrites the one field it is given, so a managed
|
|
458
|
+
# redaction is always over the prompt text.
|
|
459
|
+
redact = ("text",)
|
|
400
460
|
tool_ids = tuple(_str_list(entry.get("tools"), f"{where} tools"))
|
|
401
461
|
missing = sorted(set(tool_ids) - set(tools))
|
|
402
462
|
if missing:
|
|
@@ -415,6 +475,52 @@ def _guardrail(
|
|
|
415
475
|
message=_required_str(on_fail, "message", f"{where} onFail"),
|
|
416
476
|
fallback_prompt=_str(on_fail.get("fallbackPrompt")),
|
|
417
477
|
log=on_fail.get("log") is True,
|
|
478
|
+
engine=engine,
|
|
479
|
+
bedrock=bedrock,
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _bedrock_policy(raw: Any, where: str) -> BedrockGuardrailPolicy | None:
|
|
484
|
+
"""The managed policy, with each name checked against the closed vocabulary.
|
|
485
|
+
|
|
486
|
+
The build-time gate already refuses an unknown name; repeating the check here
|
|
487
|
+
is what keeps a hand-written document from reaching the wire, where the
|
|
488
|
+
service would answer with a validation error naming its own enum instead of
|
|
489
|
+
the spec's word.
|
|
490
|
+
"""
|
|
491
|
+
if not isinstance(raw, Mapping):
|
|
492
|
+
return None
|
|
493
|
+
content: list[tuple[str, str]] = []
|
|
494
|
+
content_raw = raw.get("content")
|
|
495
|
+
if isinstance(content_raw, Mapping):
|
|
496
|
+
for name, strength in content_raw.items():
|
|
497
|
+
if name not in _BEDROCK_CONTENT_FILTERS:
|
|
498
|
+
raise ConfigurationError(f"{where} names unknown content filter {name!r}")
|
|
499
|
+
if strength not in _BEDROCK_CONTENT_STRENGTHS:
|
|
500
|
+
raise ConfigurationError(
|
|
501
|
+
f"{where} gives {name!r} strength {strength!r}; expected one of "
|
|
502
|
+
f"{sorted(_BEDROCK_CONTENT_STRENGTHS)}"
|
|
503
|
+
)
|
|
504
|
+
content.append((name, strength))
|
|
505
|
+
topics: list[tuple[str, str]] = []
|
|
506
|
+
topics_raw = raw.get("topics")
|
|
507
|
+
if isinstance(topics_raw, Mapping):
|
|
508
|
+
topics = [(name, definition) for name, definition in topics_raw.items()]
|
|
509
|
+
words = tuple(_str_list(raw.get("words"), f"{where} bedrock.words"))
|
|
510
|
+
pii_raw = _str_list(raw.get("pii"), f"{where} bedrock.pii")
|
|
511
|
+
unknown_pii = sorted(set(pii_raw) - _BEDROCK_PII_ENTITIES)
|
|
512
|
+
if unknown_pii:
|
|
513
|
+
raise ConfigurationError(
|
|
514
|
+
f"{where} names unknown PII entities {unknown_pii}; expected a subset of "
|
|
515
|
+
f"{sorted(_BEDROCK_PII_ENTITIES)}"
|
|
516
|
+
)
|
|
517
|
+
if not content and not topics and not words and not pii_raw:
|
|
518
|
+
return None
|
|
519
|
+
return BedrockGuardrailPolicy(
|
|
520
|
+
content=tuple(content),
|
|
521
|
+
topics=tuple(topics),
|
|
522
|
+
words=words,
|
|
523
|
+
pii=tuple(pii_raw),
|
|
418
524
|
)
|
|
419
525
|
|
|
420
526
|
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""The managed-guardrail adapter: ``ApplyGuardrail``, and the policy names it takes.
|
|
2
|
+
|
|
3
|
+
A ``bedrock`` guardrail is evaluated by AWS, not by this process. The deployment
|
|
4
|
+
creates the policy and a numbered version; the app knows only
|
|
5
|
+
``BEDROCK_GUARDRAIL_ID`` and ``BEDROCK_GUARDRAIL_VERSION``. That split is what
|
|
6
|
+
keeps an account number out of the spec: the spec says *what* to refuse, the
|
|
7
|
+
deployment says *where* the resource lives, and neither has to know the other's
|
|
8
|
+
identifier.
|
|
9
|
+
|
|
10
|
+
Two decisions this module owns:
|
|
11
|
+
|
|
12
|
+
**The IR's vocabulary, not AWS's, is the input.** ``content``/``strength``/``pii``
|
|
13
|
+
arrive as the spec spells them -- ``prompt-attack: high``, ``credit-card`` -- and
|
|
14
|
+
this is the one table that maps them to ``PROMPT_ATTACK`` and
|
|
15
|
+
``CREDIT_DEBIT_CARD_NUMBER``. The generator therefore never carries a second copy
|
|
16
|
+
of the provider's enum, and a test can pin the mapping without an AWS call.
|
|
17
|
+
|
|
18
|
+
**Every failure is a block.** A non-2xx answer, a body this module cannot read, an
|
|
19
|
+
unknown ``action``, a missing identifier: each raises, and
|
|
20
|
+
:class:`~aid_runtime.agents.guardrails.GuardrailEngine` turns that into a
|
|
21
|
+
:class:`~aid_runtime.errors.GuardrailBlockedError`. There is no path from "the
|
|
22
|
+
managed check did not run" to "the text was fine".
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from datetime import UTC, datetime
|
|
33
|
+
from typing import Any, Protocol
|
|
34
|
+
|
|
35
|
+
import httpx
|
|
36
|
+
|
|
37
|
+
from aid_runtime.errors import ConfigurationError, ProviderError, ProviderResponseError
|
|
38
|
+
from aid_runtime.providers.bedrock import BedrockProvider, rfc3986, sigv4_headers
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"CONTENT_STRENGTHS",
|
|
42
|
+
"CONTENT_TYPES",
|
|
43
|
+
"GUARDRAIL_ID_ENV",
|
|
44
|
+
"GUARDRAIL_VERSION_ENV",
|
|
45
|
+
"PII_TYPES",
|
|
46
|
+
"BedrockGuardrailClient",
|
|
47
|
+
"GuardrailClient",
|
|
48
|
+
"GuardrailOutcome",
|
|
49
|
+
"ManagedGuardrailSettings",
|
|
50
|
+
"managed_guardrail_settings",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
GUARDRAIL_ID_ENV = "BEDROCK_GUARDRAIL_ID"
|
|
54
|
+
GUARDRAIL_VERSION_ENV = "BEDROCK_GUARDRAIL_VERSION"
|
|
55
|
+
|
|
56
|
+
#: One entry per ``BedrockContentFilter`` in ``packages/ir/src/shapes.ts``.
|
|
57
|
+
CONTENT_TYPES: Mapping[str, str] = {
|
|
58
|
+
"sexual": "SEXUAL",
|
|
59
|
+
"violence": "VIOLENCE",
|
|
60
|
+
"hate": "HATE",
|
|
61
|
+
"insults": "INSULTS",
|
|
62
|
+
"misconduct": "MISCONDUCT",
|
|
63
|
+
"prompt-attack": "PROMPT_ATTACK",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
CONTENT_STRENGTHS: Mapping[str, str] = {
|
|
67
|
+
"low": "LOW",
|
|
68
|
+
"medium": "MEDIUM",
|
|
69
|
+
"high": "HIGH",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
#: One entry per ``BedrockPiiEntity``. Names with a jurisdiction are the ones AWS
|
|
73
|
+
#: spells out; the rest are the entity type verbatim.
|
|
74
|
+
PII_TYPES: Mapping[str, str] = {
|
|
75
|
+
"email": "EMAIL",
|
|
76
|
+
"phone": "PHONE",
|
|
77
|
+
"name": "NAME",
|
|
78
|
+
"address": "ADDRESS",
|
|
79
|
+
"ssn": "US_SOCIAL_SECURITY_NUMBER",
|
|
80
|
+
"credit-card": "CREDIT_DEBIT_CARD_NUMBER",
|
|
81
|
+
"bank-account": "US_BANK_ACCOUNT_NUMBER",
|
|
82
|
+
"passport": "PASSPORT_NUMBER",
|
|
83
|
+
"drivers-license": "DRIVERS_LICENSE_NUMBER",
|
|
84
|
+
"ip-address": "IP_ADDRESS",
|
|
85
|
+
"url": "URL",
|
|
86
|
+
"aws-access-key": "AWS_ACCESS_KEY",
|
|
87
|
+
"aws-secret-key": "AWS_SECRET_KEY",
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
_SOURCES = frozenset({"INPUT", "OUTPUT"})
|
|
91
|
+
_RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True, slots=True)
|
|
95
|
+
class ManagedGuardrailSettings:
|
|
96
|
+
"""Where the deployment put the managed guardrail."""
|
|
97
|
+
|
|
98
|
+
id: str
|
|
99
|
+
version: str
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def managed_guardrail_settings() -> ManagedGuardrailSettings:
|
|
103
|
+
"""Read the two environment names, or explain which one is missing.
|
|
104
|
+
|
|
105
|
+
``DRAFT`` is refused on purpose: AWS lets an app call a draft, and a draft
|
|
106
|
+
changes under it. A deployment ships a numbered version, so the version this
|
|
107
|
+
process names is the policy it actually enforces.
|
|
108
|
+
"""
|
|
109
|
+
guardrail_id = os.environ.get(GUARDRAIL_ID_ENV)
|
|
110
|
+
version = os.environ.get(GUARDRAIL_VERSION_ENV)
|
|
111
|
+
missing = [
|
|
112
|
+
name
|
|
113
|
+
for name, value in ((GUARDRAIL_ID_ENV, guardrail_id), (GUARDRAIL_VERSION_ENV, version))
|
|
114
|
+
if not value
|
|
115
|
+
]
|
|
116
|
+
if missing:
|
|
117
|
+
raise ConfigurationError(
|
|
118
|
+
"the spec declares a managed guardrail, so "
|
|
119
|
+
+ " and ".join(missing)
|
|
120
|
+
+ " must be set: the deployment creates the resource, the app only names it"
|
|
121
|
+
)
|
|
122
|
+
if version == "DRAFT":
|
|
123
|
+
raise ConfigurationError(
|
|
124
|
+
f"{GUARDRAIL_VERSION_ENV}=DRAFT is not a pinned policy; name the numbered "
|
|
125
|
+
"version the deployment created"
|
|
126
|
+
)
|
|
127
|
+
return ManagedGuardrailSettings(id=guardrail_id or "", version=version or "")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True, slots=True)
|
|
131
|
+
class GuardrailOutcome:
|
|
132
|
+
"""One ``ApplyGuardrail`` answer, in terms the engine can act on.
|
|
133
|
+
|
|
134
|
+
``text`` is the service's rewritten content, present when the policy
|
|
135
|
+
anonymised something. ``policies`` names what fired, for the audit trail:
|
|
136
|
+
``content:HATE``, ``pii:EMAIL``, ``topic:investments``.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
intervened: bool
|
|
140
|
+
policies: tuple[str, ...] = ()
|
|
141
|
+
text: str | None = None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class GuardrailClient(Protocol):
|
|
145
|
+
"""The one call the engine makes, so a test double need not sign anything."""
|
|
146
|
+
|
|
147
|
+
async def apply(self, *, source: str, text: str) -> GuardrailOutcome: ...
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class BedrockGuardrailClient:
|
|
151
|
+
"""``POST /guardrail/{id}/version/{version}/apply`` with SigV4.
|
|
152
|
+
|
|
153
|
+
Retries once -- the summary's "retry once on throttling" -- and then gives up
|
|
154
|
+
loudly. A retry is worth it for a throttled control-plane call; a third
|
|
155
|
+
attempt would keep a user waiting for a check that is failing closed anyway.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
def __init__(
|
|
159
|
+
self,
|
|
160
|
+
*,
|
|
161
|
+
settings: ManagedGuardrailSettings | None = None,
|
|
162
|
+
provider: BedrockProvider | None = None,
|
|
163
|
+
region: str | None = None,
|
|
164
|
+
base_url: str | None = None,
|
|
165
|
+
client: httpx.AsyncClient | None = None,
|
|
166
|
+
timeout_seconds: float = 15.0,
|
|
167
|
+
max_attempts: int = 2,
|
|
168
|
+
backoff_seconds: float = 0.25,
|
|
169
|
+
now: Callable[[], datetime] | None = None,
|
|
170
|
+
) -> None:
|
|
171
|
+
if max_attempts < 1:
|
|
172
|
+
raise ValueError("max_attempts must be at least 1")
|
|
173
|
+
self._settings = settings
|
|
174
|
+
self._base_url = base_url.rstrip("/") if base_url is not None else None
|
|
175
|
+
self._max_attempts = max_attempts
|
|
176
|
+
self._backoff = backoff_seconds
|
|
177
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
178
|
+
self._owns_client = provider is None and client is None
|
|
179
|
+
self._provider = provider or BedrockProvider(
|
|
180
|
+
region=region,
|
|
181
|
+
timeout_seconds=timeout_seconds,
|
|
182
|
+
max_attempts=1,
|
|
183
|
+
client=client,
|
|
184
|
+
name="bedrock-guardrail",
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def settings(self) -> ManagedGuardrailSettings:
|
|
189
|
+
if self._settings is None:
|
|
190
|
+
self._settings = managed_guardrail_settings()
|
|
191
|
+
return self._settings
|
|
192
|
+
|
|
193
|
+
async def aclose(self) -> None:
|
|
194
|
+
if self._owns_client:
|
|
195
|
+
await self._provider.aclose()
|
|
196
|
+
|
|
197
|
+
async def apply(self, *, source: str, text: str) -> GuardrailOutcome:
|
|
198
|
+
if source not in _SOURCES:
|
|
199
|
+
raise ValueError(f"source must be INPUT or OUTPUT, not {source!r}")
|
|
200
|
+
settings = self.settings
|
|
201
|
+
region = self._provider.resolve_region()
|
|
202
|
+
credentials = await self._provider.credentials()
|
|
203
|
+
payload = json.dumps(
|
|
204
|
+
{"source": source, "content": [{"text": {"text": text}}]},
|
|
205
|
+
separators=(",", ":"),
|
|
206
|
+
)
|
|
207
|
+
url = self._url(region, settings)
|
|
208
|
+
headers = sigv4_headers(
|
|
209
|
+
url=url,
|
|
210
|
+
body=payload,
|
|
211
|
+
region=region,
|
|
212
|
+
credentials=credentials,
|
|
213
|
+
moment=self._now(),
|
|
214
|
+
)
|
|
215
|
+
answer = await self._post(url, headers, payload)
|
|
216
|
+
return _parse(answer)
|
|
217
|
+
|
|
218
|
+
def _url(self, region: str, settings: ManagedGuardrailSettings) -> str:
|
|
219
|
+
base = self._base_url or f"https://bedrock.{region}.amazonaws.com"
|
|
220
|
+
return f"{base}/guardrail/{rfc3986(settings.id)}/version/{rfc3986(settings.version)}/apply"
|
|
221
|
+
|
|
222
|
+
async def _post(self, url: str, headers: dict[str, str], body: str) -> str:
|
|
223
|
+
last_error: Exception | None = None
|
|
224
|
+
for attempt in range(1, self._max_attempts + 1):
|
|
225
|
+
try:
|
|
226
|
+
response = await self._provider.send(url, body=body, headers=headers)
|
|
227
|
+
except httpx.TransportError as exc:
|
|
228
|
+
last_error = exc
|
|
229
|
+
if attempt == self._max_attempts:
|
|
230
|
+
break
|
|
231
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
232
|
+
continue
|
|
233
|
+
if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
|
|
234
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
235
|
+
continue
|
|
236
|
+
if response.status_code >= 400:
|
|
237
|
+
raise ProviderError(
|
|
238
|
+
f"the managed guardrail returned {response.status_code}: {response.text[:500]}"
|
|
239
|
+
)
|
|
240
|
+
return response.text
|
|
241
|
+
raise ProviderError(f"the managed guardrail could not be reached: {last_error}")
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _parse(body: str) -> GuardrailOutcome:
|
|
245
|
+
try:
|
|
246
|
+
answer = json.loads(body)
|
|
247
|
+
except json.JSONDecodeError as exc:
|
|
248
|
+
raise ProviderResponseError("the managed guardrail returned a non-JSON body", body) from exc
|
|
249
|
+
if not isinstance(answer, dict):
|
|
250
|
+
raise ProviderResponseError("the managed guardrail returned no object", body)
|
|
251
|
+
action = answer.get("action")
|
|
252
|
+
if action == "NONE":
|
|
253
|
+
return GuardrailOutcome(intervened=False)
|
|
254
|
+
if action != "GUARDRAIL_INTERVENED":
|
|
255
|
+
raise ProviderResponseError(
|
|
256
|
+
f"the managed guardrail returned unknown action {action!r}", body
|
|
257
|
+
)
|
|
258
|
+
return GuardrailOutcome(
|
|
259
|
+
intervened=True,
|
|
260
|
+
policies=_policy_labels(answer.get("assessments")),
|
|
261
|
+
text=_output_text(answer.get("outputs")),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _output_text(outputs: Any) -> str | None:
|
|
266
|
+
if not isinstance(outputs, list) or not outputs:
|
|
267
|
+
return None
|
|
268
|
+
first = outputs[0]
|
|
269
|
+
if isinstance(first, Mapping):
|
|
270
|
+
text = first.get("text")
|
|
271
|
+
if isinstance(text, str):
|
|
272
|
+
return text
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _policy_labels(assessments: Any) -> tuple[str, ...]:
|
|
277
|
+
"""What fired, named the way the spec would name it.
|
|
278
|
+
|
|
279
|
+
AWS reports an assessment per policy family, each with its own list shape.
|
|
280
|
+
Flattening them into ``family:value`` strings is enough for a log line and a
|
|
281
|
+
trace event, and avoids inventing a second schema for the audit trail.
|
|
282
|
+
"""
|
|
283
|
+
labels: list[str] = []
|
|
284
|
+
if not isinstance(assessments, Sequence) or isinstance(assessments, (str, bytes)):
|
|
285
|
+
return ()
|
|
286
|
+
|
|
287
|
+
def add(label: str | None) -> None:
|
|
288
|
+
if label is not None and label not in labels:
|
|
289
|
+
labels.append(label)
|
|
290
|
+
|
|
291
|
+
for assessment in assessments:
|
|
292
|
+
if not isinstance(assessment, Mapping):
|
|
293
|
+
continue
|
|
294
|
+
content = assessment.get("contentPolicy")
|
|
295
|
+
if isinstance(content, Mapping):
|
|
296
|
+
for entry in _entries(content.get("filters")):
|
|
297
|
+
add(_prefixed("content", entry.get("type")))
|
|
298
|
+
topics = assessment.get("topicPolicy")
|
|
299
|
+
if isinstance(topics, Mapping):
|
|
300
|
+
for entry in _entries(topics.get("topics")):
|
|
301
|
+
add(_prefixed("topic", entry.get("name")))
|
|
302
|
+
words = assessment.get("wordPolicy")
|
|
303
|
+
if isinstance(words, Mapping):
|
|
304
|
+
for entry in _entries(words.get("customWords")):
|
|
305
|
+
add(_prefixed("word", entry.get("match")))
|
|
306
|
+
for entry in _entries(words.get("managedWordLists")):
|
|
307
|
+
add(_prefixed("word", entry.get("type")))
|
|
308
|
+
sensitive = assessment.get("sensitiveInformationPolicy")
|
|
309
|
+
if isinstance(sensitive, Mapping):
|
|
310
|
+
for entry in _entries(sensitive.get("piiEntities")):
|
|
311
|
+
add(_prefixed("pii", entry.get("type")))
|
|
312
|
+
for entry in _entries(sensitive.get("regexes")):
|
|
313
|
+
add(_prefixed("regex", entry.get("name")))
|
|
314
|
+
return tuple(labels)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _entries(value: Any) -> tuple[Mapping[str, Any], ...]:
|
|
318
|
+
if not isinstance(value, list):
|
|
319
|
+
return ()
|
|
320
|
+
return tuple(entry for entry in value if isinstance(entry, Mapping))
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _prefixed(family: str, value: Any) -> str | None:
|
|
324
|
+
return f"{family}:{value}" if isinstance(value, str) and value else None
|
aid_runtime/providers/bedrock.py
CHANGED
|
@@ -49,7 +49,13 @@ from aid_runtime.types import (
|
|
|
49
49
|
ToolCall,
|
|
50
50
|
)
|
|
51
51
|
|
|
52
|
-
__all__ = [
|
|
52
|
+
__all__ = [
|
|
53
|
+
"BEDROCK_SERVICE",
|
|
54
|
+
"BedrockProvider",
|
|
55
|
+
"default_bedrock_base_url",
|
|
56
|
+
"rfc3986",
|
|
57
|
+
"sigv4_headers",
|
|
58
|
+
]
|
|
53
59
|
|
|
54
60
|
BEDROCK_SERVICE = "bedrock"
|
|
55
61
|
|
|
@@ -88,6 +94,72 @@ def _sha256_hex(value: str) -> str:
|
|
|
88
94
|
return hashlib.sha256(value.encode()).hexdigest()
|
|
89
95
|
|
|
90
96
|
|
|
97
|
+
def sigv4_headers(
|
|
98
|
+
*,
|
|
99
|
+
url: str,
|
|
100
|
+
body: str,
|
|
101
|
+
region: str,
|
|
102
|
+
credentials: dict[str, Any],
|
|
103
|
+
moment: datetime,
|
|
104
|
+
service: str = BEDROCK_SERVICE,
|
|
105
|
+
) -> dict[str, str]:
|
|
106
|
+
"""The SigV4 headers for one JSON ``POST`` to ``url``.
|
|
107
|
+
|
|
108
|
+
Shared by the model adapter and the managed-guardrail adapter because both
|
|
109
|
+
sign with the ``bedrock`` service name -- Converse is served by
|
|
110
|
+
``bedrock-runtime`` but signed as ``bedrock``, and ``ApplyGuardrail`` is served
|
|
111
|
+
by ``bedrock`` itself. Keeping one signer means a fix to the canonical request
|
|
112
|
+
cannot land in one caller and miss the other.
|
|
113
|
+
"""
|
|
114
|
+
stamp = _amz_date(moment)
|
|
115
|
+
date = stamp[:8]
|
|
116
|
+
parsed = urlparse(url)
|
|
117
|
+
host = parsed.netloc
|
|
118
|
+
canonical_headers: list[tuple[str, str]] = [
|
|
119
|
+
("content-type", "application/json"),
|
|
120
|
+
("host", host),
|
|
121
|
+
("x-amz-date", stamp),
|
|
122
|
+
]
|
|
123
|
+
token = credentials.get("session_token")
|
|
124
|
+
if isinstance(token, str):
|
|
125
|
+
canonical_headers.append(("x-amz-security-token", token))
|
|
126
|
+
signed_headers = ";".join(header for header, _ in canonical_headers)
|
|
127
|
+
canonical_request = "\n".join(
|
|
128
|
+
[
|
|
129
|
+
"POST",
|
|
130
|
+
parsed.path,
|
|
131
|
+
"",
|
|
132
|
+
"".join(f"{header}:{value}\n" for header, value in canonical_headers),
|
|
133
|
+
signed_headers,
|
|
134
|
+
_sha256_hex(body),
|
|
135
|
+
]
|
|
136
|
+
)
|
|
137
|
+
scope = f"{date}/{region}/{service}/aws4_request"
|
|
138
|
+
string_to_sign = "\n".join(["AWS4-HMAC-SHA256", stamp, scope, _sha256_hex(canonical_request)])
|
|
139
|
+
signing_key = _hmac(
|
|
140
|
+
_hmac(
|
|
141
|
+
_hmac(
|
|
142
|
+
_hmac(f"AWS4{credentials['secret_access_key']}", date),
|
|
143
|
+
region,
|
|
144
|
+
),
|
|
145
|
+
service,
|
|
146
|
+
),
|
|
147
|
+
"aws4_request",
|
|
148
|
+
)
|
|
149
|
+
signature = hmac.new(signing_key, string_to_sign.encode(), hashlib.sha256).hexdigest()
|
|
150
|
+
headers = {
|
|
151
|
+
"content-type": "application/json",
|
|
152
|
+
"x-amz-date": stamp,
|
|
153
|
+
"authorization": (
|
|
154
|
+
f"AWS4-HMAC-SHA256 Credential={credentials['access_key_id']}/{scope}, "
|
|
155
|
+
f"SignedHeaders={signed_headers}, Signature={signature}"
|
|
156
|
+
),
|
|
157
|
+
}
|
|
158
|
+
if isinstance(token, str):
|
|
159
|
+
headers["x-amz-security-token"] = token
|
|
160
|
+
return headers
|
|
161
|
+
|
|
162
|
+
|
|
91
163
|
def _hmac(key: bytes | str, value: str) -> bytes:
|
|
92
164
|
if isinstance(key, str):
|
|
93
165
|
key = key.encode()
|
|
@@ -290,56 +362,34 @@ class BedrockProvider:
|
|
|
290
362
|
credentials: dict[str, Any],
|
|
291
363
|
moment: datetime,
|
|
292
364
|
) -> dict[str, str]:
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
]
|
|
302
|
-
token = credentials.get("session_token")
|
|
303
|
-
if isinstance(token, str):
|
|
304
|
-
canonical_headers.append(("x-amz-security-token", token))
|
|
305
|
-
signed_headers = ";".join(header for header, _ in canonical_headers)
|
|
306
|
-
canonical_request = "\n".join(
|
|
307
|
-
[
|
|
308
|
-
"POST",
|
|
309
|
-
parsed.path,
|
|
310
|
-
"",
|
|
311
|
-
"".join(f"{header}:{value}\n" for header, value in canonical_headers),
|
|
312
|
-
signed_headers,
|
|
313
|
-
_sha256_hex(body),
|
|
314
|
-
]
|
|
315
|
-
)
|
|
316
|
-
scope = f"{date}/{region}/{BEDROCK_SERVICE}/aws4_request"
|
|
317
|
-
string_to_sign = "\n".join(
|
|
318
|
-
["AWS4-HMAC-SHA256", stamp, scope, _sha256_hex(canonical_request)]
|
|
319
|
-
)
|
|
320
|
-
signing_key = _hmac(
|
|
321
|
-
_hmac(
|
|
322
|
-
_hmac(
|
|
323
|
-
_hmac(f"AWS4{credentials['secret_access_key']}", date),
|
|
324
|
-
region,
|
|
325
|
-
),
|
|
326
|
-
BEDROCK_SERVICE,
|
|
327
|
-
),
|
|
328
|
-
"aws4_request",
|
|
329
|
-
)
|
|
330
|
-
signature = hmac.new(signing_key, string_to_sign.encode(), hashlib.sha256).hexdigest()
|
|
331
|
-
headers = {
|
|
332
|
-
"content-type": "application/json",
|
|
333
|
-
"x-amz-date": stamp,
|
|
334
|
-
"authorization": (
|
|
335
|
-
f"AWS4-HMAC-SHA256 Credential={credentials['access_key_id']}/{scope}, "
|
|
336
|
-
f"SignedHeaders={signed_headers}, Signature={signature}"
|
|
365
|
+
return {
|
|
366
|
+
**sigv4_headers(
|
|
367
|
+
url=url,
|
|
368
|
+
body=body,
|
|
369
|
+
region=region,
|
|
370
|
+
credentials=credentials,
|
|
371
|
+
moment=moment,
|
|
372
|
+
service=BEDROCK_SERVICE,
|
|
337
373
|
),
|
|
338
374
|
**self._extra_headers,
|
|
339
375
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
376
|
+
|
|
377
|
+
def resolve_region(self) -> str:
|
|
378
|
+
"""The region this adapter signs for, or a :class:`ProviderError`."""
|
|
379
|
+
return self._resolve_region()
|
|
380
|
+
|
|
381
|
+
async def send(self, url: str, *, body: str, headers: dict[str, str]) -> httpx.Response:
|
|
382
|
+
"""One signed POST, uninterpreted: shared with the managed-guardrail adapter."""
|
|
383
|
+
return await self._client.post(url, content=body, headers=headers)
|
|
384
|
+
|
|
385
|
+
async def credentials(self) -> dict[str, Any]:
|
|
386
|
+
"""The SigV4 credentials, resolved lazily.
|
|
387
|
+
|
|
388
|
+
Public because the managed-guardrail adapter signs with the same identity:
|
|
389
|
+
a deployment that can invoke a model can also apply a guardrail, and
|
|
390
|
+
reading the role twice would be two chances to read it differently.
|
|
391
|
+
"""
|
|
392
|
+
return await self._credentials()
|
|
343
393
|
|
|
344
394
|
def _build_payload(self, request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
|
|
345
395
|
inference_config: dict[str, Any] = {"maxTokens": _max_tokens(request, model)}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: aid-runtime-python
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.98
|
|
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=7onRmZ5BIz7a_RInLHIzUNWNCpj8iLHdPTVt767sfWI,12721
|
|
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
|
|
@@ -15,13 +15,14 @@ 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=q7v1GQ0FaYOq4uWfGMhloXwQb3fXjxE0ixi6Yij9OJQ,9624
|
|
17
17
|
aid_runtime/types.py,sha256=cVYgmacDIhStQT5dX_X67-q57sPBBaWC5nybtGVqVsw,10389
|
|
18
|
-
aid_runtime/agents/__init__.py,sha256=
|
|
18
|
+
aid_runtime/agents/__init__.py,sha256=hna-peyTFCRuF9TM9_lKy5b4O12cJnsQPrMcDncSCcg,2865
|
|
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=
|
|
23
|
-
aid_runtime/agents/ir.py,sha256=
|
|
22
|
+
aid_runtime/agents/guardrails.py,sha256=FC8RX8YUeUHgw9Kh24NavkSIkaXayPeVpFri-OZGi0Y,30200
|
|
23
|
+
aid_runtime/agents/ir.py,sha256=pDWIia4t7rzRqJO3ZBsOrl24_uBTWT03NFKOEPV1JrU,29355
|
|
24
24
|
aid_runtime/agents/loop.py,sha256=T-QnC9BQ9K3RyZfHdAuzWiwMXBpQjDLGdHrLgf2fnFM,52608
|
|
25
|
+
aid_runtime/agents/managed.py,sha256=8AEv8HV_EOFZIzjBE92_dB_xsNffn2k0P3ccd-TM5oQ,12143
|
|
25
26
|
aid_runtime/agents/memory.py,sha256=6_D6k2bzAiR2euNvzr6HB28wsUUq-R-WTQc12gkB8ao,9156
|
|
26
27
|
aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
|
|
27
28
|
aid_runtime/agents/state.py,sha256=4itT7BWv2JKSeWpRrDyxLguOOVnz9gGH_qgRdCbWCaw,6086
|
|
@@ -34,7 +35,7 @@ aid_runtime/evals/runner.py,sha256=Lkl-kAVxegPO40pCBUcprRBKvfL6bjYzVf__xe6Z-Mc,7
|
|
|
34
35
|
aid_runtime/providers/__init__.py,sha256=MQ-vU_QeeUgfqMlwLi0layJBhmvbZat9gIkDFcFl7Pg,1827
|
|
35
36
|
aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
|
|
36
37
|
aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
|
|
37
|
-
aid_runtime/providers/bedrock.py,sha256=
|
|
38
|
+
aid_runtime/providers/bedrock.py,sha256=rzObHf3gD0YRopYVBm0gYlO3OrsJwU7m0OD3pOxIwJE,22338
|
|
38
39
|
aid_runtime/providers/fake.py,sha256=oAcpaDOUIp7lmKGEEWG5ktagstg2dvoHR-9xaUeCDLo,9526
|
|
39
40
|
aid_runtime/providers/gemini.py,sha256=gM4Kvgz6lnFbHgYYhyVCBTFTcGAKfiNuj7lS1XSldnU,3975
|
|
40
41
|
aid_runtime/providers/gemini_wire.py,sha256=ZwIiYuAVihszE0c90-uAbSn6_hdMa2Md4asySIYeQTw,13032
|
|
@@ -53,7 +54,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
|
|
|
53
54
|
aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
|
|
54
55
|
aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
|
|
55
56
|
aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
|
|
56
|
-
aid_runtime_python-0.1.
|
|
57
|
-
aid_runtime_python-0.1.
|
|
58
|
-
aid_runtime_python-0.1.
|
|
59
|
-
aid_runtime_python-0.1.
|
|
57
|
+
aid_runtime_python-0.1.98.dist-info/METADATA,sha256=B5XoK9tGxO9q6FGH28PUjmOL6Znwre8WxsPxuDYsX2o,17005
|
|
58
|
+
aid_runtime_python-0.1.98.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
59
|
+
aid_runtime_python-0.1.98.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
|
|
60
|
+
aid_runtime_python-0.1.98.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|