aid-runtime-python 0.1.97__py3-none-any.whl → 0.1.99__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 +19 -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 +105 -48
- aid_runtime/retrieval/__init__.py +38 -0
- aid_runtime/retrieval/knowledge_base.py +728 -0
- aid_runtime/retrieval/retriever.py +171 -36
- aid_runtime/retrieval/types.py +173 -1
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.99.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.99.dist-info}/RECORD +14 -12
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.99.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.97.dist-info → aid_runtime_python-0.1.99.dist-info}/top_level.txt +0 -0
|
@@ -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,79 @@ 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
|
+
method: str = "POST",
|
|
106
|
+
query: str = "",
|
|
107
|
+
) -> dict[str, str]:
|
|
108
|
+
"""The SigV4 headers for one request to ``url``.
|
|
109
|
+
|
|
110
|
+
Shared by the model adapter, the managed-guardrail adapter and the managed
|
|
111
|
+
knowledge-base adapter because all three sign with the same identity. Converse is
|
|
112
|
+
served by ``bedrock-runtime`` but signed as ``bedrock``, ``ApplyGuardrail`` is served
|
|
113
|
+
by ``bedrock`` itself, and ``Retrieve`` is served by ``bedrock-agent-runtime``; the
|
|
114
|
+
service name is therefore a parameter rather than a constant. Keeping one signer
|
|
115
|
+
means a fix to the canonical request cannot land in one caller and miss the others.
|
|
116
|
+
|
|
117
|
+
``method`` and ``query`` exist for the knowledge-base adapter, whose readiness check
|
|
118
|
+
is a ``GET`` with a query string. Both are part of the canonical request, so a caller
|
|
119
|
+
that changed either without signing it would produce a signature AWS rejects.
|
|
120
|
+
"""
|
|
121
|
+
stamp = _amz_date(moment)
|
|
122
|
+
date = stamp[:8]
|
|
123
|
+
parsed = urlparse(url)
|
|
124
|
+
host = parsed.netloc
|
|
125
|
+
canonical_headers: list[tuple[str, str]] = [
|
|
126
|
+
("content-type", "application/json"),
|
|
127
|
+
("host", host),
|
|
128
|
+
("x-amz-date", stamp),
|
|
129
|
+
]
|
|
130
|
+
token = credentials.get("session_token")
|
|
131
|
+
if isinstance(token, str):
|
|
132
|
+
canonical_headers.append(("x-amz-security-token", token))
|
|
133
|
+
signed_headers = ";".join(header for header, _ in canonical_headers)
|
|
134
|
+
canonical_request = "\n".join(
|
|
135
|
+
[
|
|
136
|
+
method,
|
|
137
|
+
parsed.path,
|
|
138
|
+
query,
|
|
139
|
+
"".join(f"{header}:{value}\n" for header, value in canonical_headers),
|
|
140
|
+
signed_headers,
|
|
141
|
+
_sha256_hex(body),
|
|
142
|
+
]
|
|
143
|
+
)
|
|
144
|
+
scope = f"{date}/{region}/{service}/aws4_request"
|
|
145
|
+
string_to_sign = "\n".join(["AWS4-HMAC-SHA256", stamp, scope, _sha256_hex(canonical_request)])
|
|
146
|
+
signing_key = _hmac(
|
|
147
|
+
_hmac(
|
|
148
|
+
_hmac(
|
|
149
|
+
_hmac(f"AWS4{credentials['secret_access_key']}", date),
|
|
150
|
+
region,
|
|
151
|
+
),
|
|
152
|
+
service,
|
|
153
|
+
),
|
|
154
|
+
"aws4_request",
|
|
155
|
+
)
|
|
156
|
+
signature = hmac.new(signing_key, string_to_sign.encode(), hashlib.sha256).hexdigest()
|
|
157
|
+
headers = {
|
|
158
|
+
"content-type": "application/json",
|
|
159
|
+
"x-amz-date": stamp,
|
|
160
|
+
"authorization": (
|
|
161
|
+
f"AWS4-HMAC-SHA256 Credential={credentials['access_key_id']}/{scope}, "
|
|
162
|
+
f"SignedHeaders={signed_headers}, Signature={signature}"
|
|
163
|
+
),
|
|
164
|
+
}
|
|
165
|
+
if isinstance(token, str):
|
|
166
|
+
headers["x-amz-security-token"] = token
|
|
167
|
+
return headers
|
|
168
|
+
|
|
169
|
+
|
|
91
170
|
def _hmac(key: bytes | str, value: str) -> bytes:
|
|
92
171
|
if isinstance(key, str):
|
|
93
172
|
key = key.encode()
|
|
@@ -290,56 +369,34 @@ class BedrockProvider:
|
|
|
290
369
|
credentials: dict[str, Any],
|
|
291
370
|
moment: datetime,
|
|
292
371
|
) -> 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}"
|
|
372
|
+
return {
|
|
373
|
+
**sigv4_headers(
|
|
374
|
+
url=url,
|
|
375
|
+
body=body,
|
|
376
|
+
region=region,
|
|
377
|
+
credentials=credentials,
|
|
378
|
+
moment=moment,
|
|
379
|
+
service=BEDROCK_SERVICE,
|
|
337
380
|
),
|
|
338
381
|
**self._extra_headers,
|
|
339
382
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
383
|
+
|
|
384
|
+
def resolve_region(self) -> str:
|
|
385
|
+
"""The region this adapter signs for, or a :class:`ProviderError`."""
|
|
386
|
+
return self._resolve_region()
|
|
387
|
+
|
|
388
|
+
async def send(self, url: str, *, body: str, headers: dict[str, str]) -> httpx.Response:
|
|
389
|
+
"""One signed POST, uninterpreted: shared with the managed-guardrail adapter."""
|
|
390
|
+
return await self._client.post(url, content=body, headers=headers)
|
|
391
|
+
|
|
392
|
+
async def credentials(self) -> dict[str, Any]:
|
|
393
|
+
"""The SigV4 credentials, resolved lazily.
|
|
394
|
+
|
|
395
|
+
Public because the managed-guardrail adapter signs with the same identity:
|
|
396
|
+
a deployment that can invoke a model can also apply a guardrail, and
|
|
397
|
+
reading the role twice would be two chances to read it differently.
|
|
398
|
+
"""
|
|
399
|
+
return await self._credentials()
|
|
343
400
|
|
|
344
401
|
def _build_payload(self, request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
|
|
345
402
|
inference_config: dict[str, Any] = {"maxTokens": _max_tokens(request, model)}
|
|
@@ -60,6 +60,17 @@ from aid_runtime.retrieval.hybrid import (
|
|
|
60
60
|
rrf_score,
|
|
61
61
|
tokenize,
|
|
62
62
|
)
|
|
63
|
+
from aid_runtime.retrieval.knowledge_base import (
|
|
64
|
+
FIXTURE_ENV,
|
|
65
|
+
BedrockKnowledgeBaseClient,
|
|
66
|
+
FixtureKnowledgeBaseClient,
|
|
67
|
+
KnowledgeBaseClient,
|
|
68
|
+
KnowledgeChunk,
|
|
69
|
+
KnowledgeResult,
|
|
70
|
+
VertexKnowledgeBaseClient,
|
|
71
|
+
knowledge_base_client_for,
|
|
72
|
+
knowledge_base_env_id,
|
|
73
|
+
)
|
|
63
74
|
from aid_runtime.retrieval.metrics import (
|
|
64
75
|
CitationGrounding,
|
|
65
76
|
MeanReciprocalRank,
|
|
@@ -87,6 +98,14 @@ from aid_runtime.retrieval.types import (
|
|
|
87
98
|
EmbeddingCostProfile,
|
|
88
99
|
EmbeddingSpec,
|
|
89
100
|
IndexSpec,
|
|
101
|
+
KnowledgeBaseEngine,
|
|
102
|
+
KnowledgeBaseSpec,
|
|
103
|
+
KnowledgeChunkingSpec,
|
|
104
|
+
KnowledgeDataSourceKind,
|
|
105
|
+
KnowledgeDataSourceSpec,
|
|
106
|
+
KnowledgeVectorStoreSpec,
|
|
107
|
+
ManagedRetrieverBinding,
|
|
108
|
+
ManagedRetrieverSpec,
|
|
90
109
|
PinnedEmbedding,
|
|
91
110
|
RefreshMode,
|
|
92
111
|
RefreshSpec,
|
|
@@ -99,6 +118,7 @@ from aid_runtime.retrieval.types import (
|
|
|
99
118
|
SourceSpec,
|
|
100
119
|
StoreKind,
|
|
101
120
|
VectorStoreSpec,
|
|
121
|
+
binding_from_managed_spec,
|
|
102
122
|
binding_from_spec,
|
|
103
123
|
chunk_id_for,
|
|
104
124
|
pinned_embedding,
|
|
@@ -106,6 +126,8 @@ from aid_runtime.retrieval.types import (
|
|
|
106
126
|
|
|
107
127
|
__all__ = [
|
|
108
128
|
"DEFAULT_CANDIDATE_FACTOR",
|
|
129
|
+
"FIXTURE_ENV",
|
|
130
|
+
"BedrockKnowledgeBaseClient",
|
|
109
131
|
"Chunk",
|
|
110
132
|
"Chunker",
|
|
111
133
|
"ChunkingSpec",
|
|
@@ -122,11 +144,23 @@ __all__ = [
|
|
|
122
144
|
"FakeDeterministicEmbedder",
|
|
123
145
|
"FileConnector",
|
|
124
146
|
"FixedChunker",
|
|
147
|
+
"FixtureKnowledgeBaseClient",
|
|
125
148
|
"GeminiEmbedder",
|
|
126
149
|
"InMemoryVectorStore",
|
|
127
150
|
"IndexSpec",
|
|
128
151
|
"IngestReport",
|
|
152
|
+
"KnowledgeBaseClient",
|
|
153
|
+
"KnowledgeBaseEngine",
|
|
154
|
+
"KnowledgeBaseSpec",
|
|
155
|
+
"KnowledgeChunk",
|
|
156
|
+
"KnowledgeChunkingSpec",
|
|
157
|
+
"KnowledgeDataSourceKind",
|
|
158
|
+
"KnowledgeDataSourceSpec",
|
|
159
|
+
"KnowledgeResult",
|
|
160
|
+
"KnowledgeVectorStoreSpec",
|
|
129
161
|
"LexicalReranker",
|
|
162
|
+
"ManagedRetrieverBinding",
|
|
163
|
+
"ManagedRetrieverSpec",
|
|
130
164
|
"MeanReciprocalRank",
|
|
131
165
|
"OpenAICompatibleEmbedder",
|
|
132
166
|
"PgVectorStore",
|
|
@@ -156,7 +190,9 @@ __all__ = [
|
|
|
156
190
|
"StoreRecord",
|
|
157
191
|
"VectorStore",
|
|
158
192
|
"VectorStoreSpec",
|
|
193
|
+
"VertexKnowledgeBaseClient",
|
|
159
194
|
"assemble_context",
|
|
195
|
+
"binding_from_managed_spec",
|
|
160
196
|
"binding_from_spec",
|
|
161
197
|
"bm25_scores",
|
|
162
198
|
"chunk_document",
|
|
@@ -167,6 +203,8 @@ __all__ = [
|
|
|
167
203
|
"embedder_for",
|
|
168
204
|
"estimate_tokens",
|
|
169
205
|
"fuse",
|
|
206
|
+
"knowledge_base_client_for",
|
|
207
|
+
"knowledge_base_env_id",
|
|
170
208
|
"lexical_ranking",
|
|
171
209
|
"lexical_score",
|
|
172
210
|
"open_connector",
|