aid-runtime-python 0.1.169__tar.gz → 0.1.171__tar.gz

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.
Files changed (131) hide show
  1. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/PKG-INFO +1 -1
  2. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/pyproject.toml +1 -1
  3. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/__init__.py +1 -1
  4. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/bedrock.py +202 -18
  5. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime_python.egg-info/PKG-INFO +1 -1
  6. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_bedrock_provider.py +131 -13
  7. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/README.md +0 -0
  8. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/setup.cfg +0 -0
  9. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/__init__.py +0 -0
  10. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/chat_model.py +0 -0
  11. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/deep_agents.py +0 -0
  12. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/engine.py +0 -0
  13. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/guardrails.py +0 -0
  14. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/ir.py +0 -0
  15. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/loop.py +0 -0
  16. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/managed.py +0 -0
  17. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/memory.py +0 -0
  18. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/policy.py +0 -0
  19. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/resume.py +0 -0
  20. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/agents/state.py +0 -0
  21. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/cache.py +0 -0
  22. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/concurrency.py +0 -0
  23. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/control.py +0 -0
  24. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/cost.py +0 -0
  25. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/decisions.py +0 -0
  26. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/errors.py +0 -0
  27. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/__init__.py +0 -0
  28. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/agent_runner.py +0 -0
  29. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/dataset.py +0 -0
  30. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/gate.py +0 -0
  31. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/metrics.py +0 -0
  32. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/predicate.py +0 -0
  33. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/runner.py +0 -0
  34. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/evals/trajectory.py +0 -0
  35. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/gateway.py +0 -0
  36. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/local_trace.py +0 -0
  37. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/metrics.py +0 -0
  38. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/pipeline.py +0 -0
  39. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/prompts.py +0 -0
  40. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/__init__.py +0 -0
  41. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/anthropic.py +0 -0
  42. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/base.py +0 -0
  43. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/fake.py +0 -0
  44. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/gemini.py +0 -0
  45. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/gemini_wire.py +0 -0
  46. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/http.py +0 -0
  47. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/recorded.py +0 -0
  48. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/providers/vertex.py +0 -0
  49. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/py.typed +0 -0
  50. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/redaction.py +0 -0
  51. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/__init__.py +0 -0
  52. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/chunking.py +0 -0
  53. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/citations.py +0 -0
  54. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/connectors.py +0 -0
  55. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/embedding.py +0 -0
  56. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/filters.py +0 -0
  57. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/gate.py +0 -0
  58. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/hybrid.py +0 -0
  59. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/knowledge_base.py +0 -0
  60. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/metrics.py +0 -0
  61. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/pgvector.py +0 -0
  62. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/rerank.py +0 -0
  63. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/retriever.py +0 -0
  64. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/stores.py +0 -0
  65. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/retrieval/types.py +0 -0
  66. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/steps.py +0 -0
  67. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/structured.py +0 -0
  68. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/telemetry.py +0 -0
  69. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/tools.py +0 -0
  70. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/tracing.py +0 -0
  71. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime/types.py +0 -0
  72. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime_python.egg-info/SOURCES.txt +0 -0
  73. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
  74. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime_python.egg-info/requires.txt +0 -0
  75. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
  76. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agent_eval_runner.py +0 -0
  77. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agents_budget.py +0 -0
  78. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agents_checkpoint_integrity.py +0 -0
  79. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agents_deep_agents.py +0 -0
  80. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agents_hitl.py +0 -0
  81. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agents_loop.py +0 -0
  82. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agents_memory.py +0 -0
  83. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_agents_redaction.py +0 -0
  84. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_anthropic_provider.py +0 -0
  85. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_cache.py +0 -0
  86. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_concurrency.py +0 -0
  87. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_control.py +0 -0
  88. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_cost.py +0 -0
  89. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_dataset.py +0 -0
  90. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_decisions.py +0 -0
  91. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_evals.py +0 -0
  92. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_evals_assert_gate.py +0 -0
  93. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_evals_budgets.py +0 -0
  94. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_evals_decision.py +0 -0
  95. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_evals_gate.py +0 -0
  96. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_evals_predicate.py +0 -0
  97. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_evals_trajectory.py +0 -0
  98. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_gateway.py +0 -0
  99. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_gemini_provider.py +0 -0
  100. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_guardrails.py +0 -0
  101. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_guardrails_managed.py +0 -0
  102. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_guardrails_model_armor.py +0 -0
  103. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_http_provider.py +0 -0
  104. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_local_trace.py +0 -0
  105. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_metrics.py +0 -0
  106. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_package.py +0 -0
  107. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_pipeline.py +0 -0
  108. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_prompts.py +0 -0
  109. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_recorded_provider.py +0 -0
  110. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_redaction.py +0 -0
  111. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_chunking.py +0 -0
  112. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_citations.py +0 -0
  113. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_connectors.py +0 -0
  114. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_embedding.py +0 -0
  115. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_filters.py +0 -0
  116. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_gate.py +0 -0
  117. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_hybrid.py +0 -0
  118. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_knowledge_base.py +0 -0
  119. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_metrics.py +0 -0
  120. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_rerank.py +0 -0
  121. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_stores.py +0 -0
  122. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_retrieval_types.py +0 -0
  123. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_steps.py +0 -0
  124. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_streaming.py +0 -0
  125. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_structured.py +0 -0
  126. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_telemetry.py +0 -0
  127. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_tool_permissions.py +0 -0
  128. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_tools.py +0 -0
  129. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_tracing.py +0 -0
  130. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_types.py +0 -0
  131. {aid_runtime_python-0.1.169 → aid_runtime_python-0.1.171}/tests/test_vertex_provider.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.169
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "aid-runtime-python"
7
- version = "0.1.169"
7
+ version = "0.1.171"
8
8
  description = "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."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -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.169"
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.169
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
@@ -9,6 +9,7 @@ than an argument, so the tests drive the environment instead.
9
9
  from __future__ import annotations
10
10
 
11
11
  import json
12
+ import zlib
12
13
  from datetime import UTC, datetime
13
14
  from typing import Any
14
15
 
@@ -627,33 +628,150 @@ async def test_rejects_a_body_with_no_content_blocks() -> None:
627
628
  await _provider(recorder).complete(_ask("x"), model=_model())
628
629
 
629
630
 
630
- def test_claims_tool_calling_structured_output_and_embeddings_but_not_streaming() -> None:
631
+ def test_claims_tool_calling_structured_output_embeddings_and_streaming() -> None:
631
632
  # Converse serves chat; embeddings ride `POST /model/{id}/invoke` because that
632
- # is where Titan lives, and `:predict`-style sizes are not involved. Streaming
633
- # is still absent: /converse-stream is a binary event stream this adapter
634
- # cannot read, and claiming it would let a spec bind a model that can only
635
- # fail when it is finally called.
633
+ # is where Titan lives, and streaming is `/converse-stream`, the same request
634
+ # body on a sibling path, so one adapter owns all four.
636
635
  subject = BedrockProvider()
637
636
  assert Capability.TOOL_CALLING in subject.capabilities
638
637
  assert Capability.STRUCTURED_OUTPUT in subject.capabilities
639
638
  assert Capability.EMBEDDINGS in subject.capabilities
640
- assert Capability.STREAMING not in subject.capabilities
639
+ assert Capability.STREAMING in subject.capabilities
640
+
641
+
642
+ def _header(name: str, value: str) -> bytes:
643
+ """One event-stream header: name length, name, value type 7 (string), value."""
644
+ raw_name = name.encode()
645
+ raw_value = value.encode()
646
+ return (
647
+ len(raw_name).to_bytes(1, "big")
648
+ + raw_name
649
+ + b"\x07"
650
+ + len(raw_value).to_bytes(2, "big")
651
+ + raw_value
652
+ )
641
653
 
642
654
 
643
- def test_names_itself_bedrock_by_default_and_honours_a_custom_name() -> None:
644
- assert BedrockProvider().name == "bedrock"
645
- assert BedrockProvider(name="stub").name == "stub"
655
+ class _Frames(httpx.AsyncByteStream):
656
+ """Deliver bytes in the pieces a test controls, so framing can be split mid-frame."""
657
+
658
+ def __init__(self, *chunks: bytes) -> None:
659
+ self._chunks = chunks
660
+
661
+ async def __aiter__(self) -> Any:
662
+ for chunk in self._chunks:
663
+ yield chunk
664
+
665
+
666
+ def _frame(event: str, payload: dict[str, Any], *, message_type: str = "event") -> bytes:
667
+ """One AWS event-stream frame: prelude, headers, JSON payload, message CRC32."""
668
+ # An exception frame names its kind in `:exception-type`; there is no `:event-type`.
669
+ kind = (":exception-type", ":event-type")[message_type == "event"]
670
+ encoded = b"".join(
671
+ _header(name, value)
672
+ for name, value in (
673
+ (":message-type", message_type),
674
+ (kind, event),
675
+ (":content-type", "application/json"),
676
+ )
677
+ )
678
+ body_bytes = json.dumps(payload, separators=(",", ":")).encode()
679
+ total = 12 + len(encoded) + len(body_bytes) + 4
680
+ prelude = total.to_bytes(4, "big") + len(encoded).to_bytes(4, "big")
681
+ prelude += (zlib.crc32(prelude) & 0xFFFFFFFF).to_bytes(4, "big")
682
+ body = prelude + encoded + body_bytes
683
+ return body + (zlib.crc32(body) & 0xFFFFFFFF).to_bytes(4, "big")
684
+
685
+
686
+ def _stream(*frames: bytes) -> httpx.Response:
687
+ return httpx.Response(200, stream=_Frames(b"".join(frames)))
688
+
689
+
690
+ @pytest.mark.asyncio
691
+ async def test_streams_text_deltas_then_the_stop_reason_and_the_usage() -> None:
692
+ recorder = Recorder(
693
+ _stream(
694
+ _frame("messageStart", {"role": "assistant"}),
695
+ _frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "Hel"}}),
696
+ _frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "lo"}}),
697
+ _frame("contentBlockStop", {"contentBlockIndex": 0}),
698
+ _frame("messageStop", {"stopReason": "end_turn"}),
699
+ _frame("metadata", {"usage": {"inputTokens": 7, "outputTokens": 2}}),
700
+ )
701
+ )
702
+
703
+ chunks = [chunk async for chunk in _provider(recorder).stream(_ask("hi"), model=_model())]
704
+
705
+ assert [chunk.delta for chunk in chunks if chunk.delta] == ["Hel", "lo"]
706
+ assert chunks[-2].finish_reason == "stop"
707
+ assert chunks[-1].usage is not None
708
+ assert chunks[-1].usage.input_tokens == 7
709
+ assert chunks[-1].usage.output_tokens == 2
710
+ request = recorder.requests[0]
711
+ assert f"/model/{rfc3986(MODEL_ID)}/converse-stream" in str(request.url)
712
+ assert "v1%3A0" in str(request.url)
713
+ assert _sent(recorder)["messages"] == [{"role": "user", "content": [{"text": "hi"}]}]
714
+
715
+
716
+ @pytest.mark.asyncio
717
+ async def test_reassembles_a_frame_delivered_in_pieces() -> None:
718
+ whole = _frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "split"}})
719
+ recorder = Recorder(httpx.Response(200, stream=_Frames(whole[:7], whole[7:19], whole[19:])))
720
+
721
+ chunks = [chunk async for chunk in _provider(recorder).stream(_ask("hi"), model=_model())]
722
+
723
+ assert "".join(chunk.delta for chunk in chunks) == "split"
724
+
725
+
726
+ @pytest.mark.asyncio
727
+ async def test_refuses_a_frame_whose_message_checksum_does_not_match() -> None:
728
+ frame = bytearray(
729
+ _frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "tampered"}})
730
+ )
731
+ frame[-5] ^= 0xFF
732
+ recorder = Recorder(_stream(bytes(frame)))
733
+
734
+ with pytest.raises(ProviderResponseError, match="message checksum does not match"):
735
+ async for _ in _provider(recorder).stream(_ask("hi"), model=_model()):
736
+ pass
646
737
 
647
738
 
648
739
  @pytest.mark.asyncio
649
- async def test_refuses_to_stream_rather_than_buffering() -> None:
650
- provider = BedrockProvider()
740
+ async def test_refuses_a_frame_whose_prelude_checksum_does_not_match() -> None:
741
+ frame = bytearray(_frame("messageStop", {"stopReason": "end_turn"}))
742
+ frame[9] ^= 0xFF
743
+ recorder = Recorder(_stream(bytes(frame)))
651
744
 
652
- with pytest.raises(ProviderError, match="does not stream"):
653
- async for _ in provider.stream(_ask("x"), model=_model()):
745
+ with pytest.raises(ProviderResponseError, match="prelude checksum does not match"):
746
+ async for _ in _provider(recorder).stream(_ask("hi"), model=_model()):
654
747
  pass
655
748
 
656
749
 
750
+ @pytest.mark.asyncio
751
+ async def test_reports_an_error_event_rather_than_ending_the_stream_quietly() -> None:
752
+ recorder = Recorder(
753
+ _stream(_frame("throttlingException", {"message": "slow down"}, message_type="exception"))
754
+ )
755
+
756
+ with pytest.raises(ProviderResponseError, match="throttlingException"):
757
+ async for _ in _provider(recorder).stream(_ask("hi"), model=_model()):
758
+ pass
759
+
760
+
761
+ @pytest.mark.asyncio
762
+ async def test_reports_a_stream_that_is_refused_before_any_event() -> None:
763
+ recorder = Recorder(httpx.Response(403, text="denied"))
764
+
765
+ with pytest.raises(ProviderError, match="403"):
766
+ async for _ in _provider(recorder).stream(_ask("hi"), model=_model()):
767
+ pass
768
+
769
+
770
+ def test_names_itself_bedrock_by_default_and_honours_a_custom_name() -> None:
771
+ assert BedrockProvider().name == "bedrock"
772
+ assert BedrockProvider(name="stub").name == "stub"
773
+
774
+
657
775
  @pytest.mark.asyncio
658
776
  async def test_closes_idempotently() -> None:
659
777
  subject = BedrockProvider()