aid-runtime-python 0.1.170__py3-none-any.whl → 0.1.171__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
@@ -357,7 +357,7 @@ from aid_runtime.types import (
357
357
  )
358
358
 
359
359
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
360
- __version__ = "0.1.170"
360
+ __version__ = "0.1.171"
361
361
 
362
362
  __all__ = [
363
363
  "AGENT_LABEL",
@@ -15,10 +15,14 @@ dialects. Three translations are structural rather than cosmetic:
15
15
  - tool results are ``toolResult`` blocks in a ``user`` turn, and adjacent results
16
16
  are merged into one turn so the conversation keeps alternating roles.
17
17
 
18
- There is no ``stream``: ``/converse-stream`` frames events in AWS's binary
19
- event-stream format (length-prefixed records with CRC32) rather than SSE, which
20
- is out of scope for this adapter. ``STREAMING`` is therefore not advertised, and
21
- the capability gate refuses a spec that asks for it instead of failing mid-run.
18
+ ``stream`` uses ``ConverseStream`` on the same host and identity, so it reuses
19
+ this adapter's region, credential chain and signature. Bedrock does not speak
20
+ SSE: ``/converse-stream`` frames events in AWS's binary event-stream format --
21
+ length-prefixed records with a CRC32 over the prelude and one over the whole
22
+ message -- so the adapter decodes and checksums frames and turns
23
+ ``contentBlockDelta.text``, ``messageStop`` and ``metadata.usage`` into
24
+ :class:`StreamChunk`. Tool calls are not reported, because :class:`StreamChunk`
25
+ has no field for them; a caller that needs tool calls uses :meth:`complete`.
22
26
 
23
27
  ``EMBEDDINGS`` *is* advertised: Titan models answer on ``InvokeModel``, which is
24
28
  the uninterpreted sibling of ``complete`` sharing this adapter's region,
@@ -33,7 +37,8 @@ import hashlib
33
37
  import hmac
34
38
  import json
35
39
  import os
36
- from collections.abc import AsyncIterator, Callable, Sequence
40
+ import zlib
41
+ from collections.abc import AsyncIterator, Callable, Iterator, Sequence
37
42
  from datetime import UTC, datetime
38
43
  from typing import Any
39
44
  from urllib.parse import quote, urlparse
@@ -185,6 +190,163 @@ def _is_object(value: Any) -> bool:
185
190
  return isinstance(value, dict)
186
191
 
187
192
 
193
+ # AWS frames an event as total_length | headers_length | prelude CRC32 | headers |
194
+ # payload | message CRC32, every integer big-endian and each CRC32 computed over the
195
+ # bytes before it. Frames are neither length-delimited by a separator nor aligned, so
196
+ # the decoder buffers until a whole frame is present.
197
+ _PRELUDE_BYTES = 12
198
+ _MESSAGE_CRC_BYTES = 4
199
+
200
+
201
+ def _crc32(value: bytes) -> int:
202
+ return zlib.crc32(value) & 0xFFFFFFFF
203
+
204
+
205
+ class EventStreamDecoder:
206
+ """Decode AWS's binary event-stream bytes into ``{headers, payload}`` messages.
207
+
208
+ Both checksums are verified. A frame that is corrupt, truncated mid-prelude or a
209
+ length that no frame could have raises rather than being parsed into an event that
210
+ looks plausible and silently corrupts the answer.
211
+ """
212
+
213
+ def __init__(self, name: str = "bedrock") -> None:
214
+ self._name = name
215
+ self._buffer = bytearray()
216
+
217
+ def feed(self, data: bytes) -> Iterator[dict[str, Any]]:
218
+ """Append bytes and yield every complete message now available."""
219
+ self._buffer.extend(data)
220
+ while True:
221
+ message = self._take()
222
+ if message is None:
223
+ return
224
+ yield message
225
+
226
+ def _take(self) -> dict[str, Any] | None:
227
+ if len(self._buffer) < _PRELUDE_BYTES:
228
+ return None
229
+ total = int.from_bytes(self._buffer[0:4], "big")
230
+ headers_length = int.from_bytes(self._buffer[4:8], "big")
231
+ if _crc32(bytes(self._buffer[0:8])) != int.from_bytes(self._buffer[8:12], "big"):
232
+ raise ProviderResponseError(
233
+ f"{self._name} streamed a frame whose prelude checksum does not match",
234
+ self._buffer[:12].hex(),
235
+ )
236
+ if total < _PRELUDE_BYTES + _MESSAGE_CRC_BYTES or (
237
+ headers_length > total - _PRELUDE_BYTES - _MESSAGE_CRC_BYTES
238
+ ):
239
+ raise ProviderResponseError(
240
+ f"{self._name} streamed a frame with impossible lengths",
241
+ f"total_length={total} headers_length={headers_length}",
242
+ )
243
+ if len(self._buffer) < total:
244
+ return None
245
+ frame = bytes(self._buffer[:total])
246
+ del self._buffer[:total]
247
+ body = frame[:-_MESSAGE_CRC_BYTES]
248
+ trailer = int.from_bytes(frame[-_MESSAGE_CRC_BYTES:], "big")
249
+ if _crc32(body) != trailer:
250
+ raise ProviderResponseError(
251
+ f"{self._name} streamed a frame whose message checksum does not match",
252
+ frame.hex()[:500],
253
+ )
254
+ payload = frame[_PRELUDE_BYTES + headers_length : -_MESSAGE_CRC_BYTES]
255
+ return {
256
+ "headers": _event_headers(self._name, frame, headers_length),
257
+ "payload": _event_payload(self._name, payload),
258
+ }
259
+
260
+
261
+ def _event_payload(name: str, payload: bytes) -> dict[str, Any]:
262
+ if not payload:
263
+ return {}
264
+ try:
265
+ body = json.loads(payload)
266
+ except json.JSONDecodeError as exc:
267
+ raise ProviderResponseError(
268
+ f"{name} streamed an event whose payload is not JSON",
269
+ payload[:500].decode(errors="replace"),
270
+ ) from exc
271
+ if not isinstance(body, dict):
272
+ raise ProviderResponseError(
273
+ f"{name} streamed an event whose payload is not a JSON object",
274
+ payload[:500].decode(errors="replace"),
275
+ )
276
+ return body
277
+
278
+
279
+ def _event_headers(name: str, frame: bytes, headers_length: int) -> dict[str, Any]:
280
+ """Read the frame's headers: name length, name, value type, then the typed value."""
281
+ headers: dict[str, Any] = {}
282
+ offset = _PRELUDE_BYTES
283
+ end = _PRELUDE_BYTES + headers_length
284
+ while offset < end:
285
+ name_length = frame[offset]
286
+ offset += 1
287
+ header = frame[offset : offset + name_length].decode(errors="replace")
288
+ offset += name_length
289
+ value_type = frame[offset]
290
+ offset += 1
291
+ if value_type == 0:
292
+ headers[header] = True
293
+ elif value_type == 1:
294
+ headers[header] = False
295
+ elif value_type in {2, 6, 7}:
296
+ length = int.from_bytes(frame[offset : offset + 2], "big")
297
+ offset += 2
298
+ raw = frame[offset : offset + length]
299
+ offset += length
300
+ headers[header] = raw if value_type == 6 else raw.decode(errors="replace")
301
+ elif value_type in {3, 4, 5, 8}:
302
+ width = {3: 2, 4: 4, 5: 8, 8: 8}[value_type]
303
+ headers[header] = int.from_bytes(frame[offset : offset + width], "big", signed=True)
304
+ offset += width
305
+ elif value_type == 9:
306
+ headers[header] = frame[offset : offset + 16].hex()
307
+ offset += 16
308
+ else:
309
+ raise ProviderResponseError(
310
+ f"{name} streamed a header with an unknown value type {value_type}", header
311
+ )
312
+ if offset > end:
313
+ raise ProviderResponseError(
314
+ f"{name} streamed a frame whose headers run past their own length",
315
+ f"headers_length={headers_length} read={offset - _PRELUDE_BYTES}",
316
+ )
317
+ return headers
318
+
319
+
320
+ def _converse_stream_chunk(name: str, message: dict[str, Any]) -> StreamChunk | None:
321
+ """One decoded frame as the portable chunk type, or ``None`` for frames to skip."""
322
+ headers = message.get("headers") or {}
323
+ payload = message.get("payload") or {}
324
+ if headers.get(":message-type") in {"exception", "error"}:
325
+ kind = headers.get(":exception-type") or headers.get(":error-code") or "error"
326
+ raise ProviderResponseError(
327
+ f"{name} streamed an error event ({kind}): {payload.get('message')}",
328
+ json.dumps(payload, separators=(",", ":"))[:500],
329
+ )
330
+ event = headers.get(":event-type")
331
+ if event == "contentBlockDelta":
332
+ delta = payload.get("delta")
333
+ text = delta.get("text") if isinstance(delta, dict) else None
334
+ return StreamChunk(delta=text) if isinstance(text, str) else None
335
+ if event == "messageStop":
336
+ return StreamChunk(finish_reason=_finish_reason(payload.get("stopReason"), False))
337
+ if event == "metadata":
338
+ raw = payload.get("usage")
339
+ if not isinstance(raw, dict):
340
+ return None
341
+ return StreamChunk(
342
+ usage=TokenUsage(
343
+ input_tokens=int(raw.get("inputTokens") or 0),
344
+ output_tokens=int(raw.get("outputTokens") or 0),
345
+ )
346
+ )
347
+ return None
348
+
349
+
188
350
  class BedrockProvider:
189
351
  """Calls ``POST /model/{id}/converse`` on the regional Bedrock runtime."""
190
352
 
@@ -235,8 +397,15 @@ class BedrockProvider:
235
397
  def capabilities(self) -> frozenset[Capability]:
236
398
  # Embeddings are served by InvokeModel on this same host and identity, so the
237
399
  # method that backs them is on this adapter rather than a separate client.
400
+ # Streaming is ConverseStream: the same call over AWS's binary event-stream
401
+ # framing instead of a whole body.
238
402
  return frozenset(
239
- {Capability.TOOL_CALLING, Capability.STRUCTURED_OUTPUT, Capability.EMBEDDINGS}
403
+ {
404
+ Capability.TOOL_CALLING,
405
+ Capability.STRUCTURED_OUTPUT,
406
+ Capability.EMBEDDINGS,
407
+ Capability.STREAMING,
408
+ }
240
409
  )
241
410
 
242
411
  async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
@@ -251,18 +420,33 @@ class BedrockProvider:
251
420
  async def stream(
252
421
  self, request: CompletionRequest, *, model: ModelSpec
253
422
  ) -> AsyncIterator[StreamChunk]:
254
- """Refuse: ``/converse-stream`` is not SSE.
423
+ """Stream one call from ``/converse-stream``.
255
424
 
256
- Streaming here would mean decoding AWS's binary event-stream framing and
257
- computing per-frame CRC32 checksums. Until that exists, refusing is better
258
- than silently buffering a "stream" the caller believes is incremental.
425
+ One attempt, like the sibling adapters: a stream that has already emitted text
426
+ cannot be replayed, so a failure is raised once rather than retried mid-stream.
427
+ Tool calls are not reported here because :class:`StreamChunk` has no field for
428
+ them; the gateway that needs tool calls uses :meth:`complete`.
259
429
  """
260
- del request, model
261
- raise ProviderError(
262
- f"{self._name} does not stream: Bedrock frames events in AWS's binary "
263
- "event-stream format, which this adapter does not decode; use complete()"
264
- )
265
- yield # type: ignore[unreachable] # pragma: no cover - keeps this an async generator
430
+ body = json.dumps(self._build_payload(request, model), separators=(",", ":"))
431
+ region = self._resolve_region()
432
+ credentials = await self._credentials()
433
+ url = self._endpoint(model, region, "converse-stream")
434
+ headers = self._headers(url, body, region, credentials, self._now())
435
+ decoder = EventStreamDecoder(self._name)
436
+ try:
437
+ async with self._client.stream("POST", url, content=body, headers=headers) as response:
438
+ if response.status_code >= 400:
439
+ await response.aread()
440
+ raise ProviderError(
441
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
442
+ )
443
+ async for raw in response.aiter_bytes():
444
+ for message in decoder.feed(raw):
445
+ chunk = _converse_stream_chunk(self._name, message)
446
+ if chunk is not None:
447
+ yield chunk
448
+ except httpx.TransportError as exc:
449
+ raise ProviderError(f"{self._name} stream failed: {exc}") from exc
266
450
 
267
451
  async def aclose(self) -> None:
268
452
  if self._closed:
@@ -282,9 +466,9 @@ class BedrockProvider:
282
466
  )
283
467
  return region
284
468
 
285
- def _endpoint(self, model: ModelSpec, region: str) -> str:
469
+ def _endpoint(self, model: ModelSpec, region: str, operation: str = "converse") -> str:
286
470
  base = self._base_url or default_bedrock_base_url(region)
287
- return f"{base}/model/{rfc3986(model.name)}/converse"
471
+ return f"{base}/model/{rfc3986(model.name)}/{operation}"
288
472
 
289
473
  async def _credentials(self) -> dict[str, Any]:
290
474
  """Static credentials, else the environment, else the container endpoint.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.170
3
+ Version: 0.1.171
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=q0IHKxwuhMPz-ZCt_YFmyW4Vm6XWKloJjDRyXUI4YIs,15277
1
+ aid_runtime/__init__.py,sha256=lXR4m2jUXGG1Ugr0yRt0CkP_QisCu_SdgYmwDwRzFqU,15277
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
@@ -41,7 +41,7 @@ aid_runtime/evals/trajectory.py,sha256=X7ssDigfFuMkjM6mR6LGSbb03A8iNf4oRbVqeSsU7
41
41
  aid_runtime/providers/__init__.py,sha256=SgCBtvERTy1y6BAkenH2vYiQH0rE883KDvIWewdNOdA,2334
42
42
  aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
43
43
  aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
44
- aid_runtime/providers/bedrock.py,sha256=mb-sF5u3Y3Dp_FBgrAublA7sKtExhWrWGOA5p9o0_HA,24515
44
+ aid_runtime/providers/bedrock.py,sha256=fGQjD1_Brtc66_uaUGu_JfgLyxA3JXV62EFxrSyQRuo,32359
45
45
  aid_runtime/providers/fake.py,sha256=oAcpaDOUIp7lmKGEEWG5ktagstg2dvoHR-9xaUeCDLo,9526
46
46
  aid_runtime/providers/gemini.py,sha256=gM4Kvgz6lnFbHgYYhyVCBTFTcGAKfiNuj7lS1XSldnU,3975
47
47
  aid_runtime/providers/gemini_wire.py,sha256=ZwIiYuAVihszE0c90-uAbSn6_hdMa2Md4asySIYeQTw,13032
@@ -63,7 +63,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
63
63
  aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
64
64
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
65
65
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
66
- aid_runtime_python-0.1.170.dist-info/METADATA,sha256=YICCkM9QbjFYfPGxMPMvDiHed5I7pkda3meS5p-gPVg,17163
67
- aid_runtime_python-0.1.170.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
- aid_runtime_python-0.1.170.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
- aid_runtime_python-0.1.170.dist-info/RECORD,,
66
+ aid_runtime_python-0.1.171.dist-info/METADATA,sha256=ur-Hv8rDAAKTq0PQ0_0ugvmLP60ukmaBClMo7qaVO3c,17163
67
+ aid_runtime_python-0.1.171.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
+ aid_runtime_python-0.1.171.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
+ aid_runtime_python-0.1.171.dist-info/RECORD,,