aid-runtime-python 0.1.77__py3-none-any.whl → 0.1.79__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
@@ -17,8 +17,10 @@ Design boundaries worth stating up front, because they are deliberate:
17
17
  ``data`` frames with the first delta before completion. Anything not advertising
18
18
  the capability raises :class:`~aid_runtime.errors.CapabilityMismatchError`
19
19
  instead of pretending to stream.
20
- * **One HTTP provider adapter and one fake.** Breadth of vendor coverage is a
21
- Phase 2 concern; a narrow, correct seam is worth more now than a wide shallow one.
20
+ * **One narrow adapter seam, three dialects, and a fake.** Breadth of vendor
21
+ coverage stays a later concern; a correct seam is worth more than a wide shallow
22
+ one. Three dialects ship: OpenAI-compatible, Anthropic Messages, and Bedrock
23
+ Converse, alongside a deterministic fake that lets the eval gate run offline.
22
24
  """
23
25
 
24
26
  from __future__ import annotations
@@ -140,13 +142,16 @@ from aid_runtime.pipeline import (
140
142
  from aid_runtime.prompts import Example, PromptRegistry, PromptTemplate, RenderedPrompt
141
143
  from aid_runtime.providers import (
142
144
  ANTHROPIC_VERSION,
145
+ BEDROCK_SERVICE,
143
146
  DEFAULT_ANTHROPIC_BASE_URL,
144
147
  DEFAULT_BASE_URL,
145
148
  AnthropicProvider,
149
+ BedrockProvider,
146
150
  FakeProvider,
147
151
  OpenAICompatibleProvider,
148
152
  Provider,
149
153
  ScriptedTurn,
154
+ default_bedrock_base_url,
150
155
  )
151
156
  from aid_runtime.retrieval import (
152
157
  DEFAULT_CANDIDATE_FACTOR,
@@ -272,11 +277,12 @@ from aid_runtime.types import (
272
277
  )
273
278
 
274
279
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
275
- __version__ = "0.1.77"
280
+ __version__ = "0.1.79"
276
281
 
277
282
  __all__ = [
278
283
  "ANTHROPIC_VERSION",
279
284
  "ATTRIBUTES",
285
+ "BEDROCK_SERVICE",
280
286
  "DEFAULT_ANTHROPIC_BASE_URL",
281
287
  "DEFAULT_BASE_URL",
282
288
  "DEFAULT_CANDIDATE_FACTOR",
@@ -301,6 +307,7 @@ __all__ = [
301
307
  "AidRuntimeError",
302
308
  "AnthropicProvider",
303
309
  "BaselineGate",
310
+ "BedrockProvider",
304
311
  "Budget",
305
312
  "BudgetExceededError",
306
313
  "Capability",
@@ -462,6 +469,7 @@ __all__ = [
462
469
  "chunker_for",
463
470
  "cite",
464
471
  "create_store",
472
+ "default_bedrock_base_url",
465
473
  "default_metrics",
466
474
  "embedder_for",
467
475
  "emit_step",
@@ -1,9 +1,11 @@
1
1
  """Provider adapters.
2
2
 
3
- Two wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM and
4
- Azure's compatible endpoint) and Anthropic's Messages API, plus one deterministic
5
- fake for tests and the eval-gate fixture. Bedrock and Vertex are transport
6
- adapters over the same seam and are still out of scope.
3
+ Three wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM and
4
+ Azure's compatible endpoint), Anthropic's Messages API, and Amazon Bedrock's
5
+ Converse API, plus one deterministic fake for tests and the eval-gate fixture.
6
+ Bedrock is signed with SigV4 rather than keyed, which is why it cannot be an
7
+ OpenAI-compatible base URL. Vertex is a transport adapter over the same seam and
8
+ is still out of scope.
7
9
  """
8
10
 
9
11
  from __future__ import annotations
@@ -14,16 +16,26 @@ from aid_runtime.providers.anthropic import (
14
16
  AnthropicProvider,
15
17
  )
16
18
  from aid_runtime.providers.base import Provider
19
+ from aid_runtime.providers.bedrock import (
20
+ BEDROCK_SERVICE,
21
+ BedrockProvider,
22
+ default_bedrock_base_url,
23
+ rfc3986,
24
+ )
17
25
  from aid_runtime.providers.fake import FakeProvider, ScriptedTurn
18
26
  from aid_runtime.providers.http import DEFAULT_BASE_URL, OpenAICompatibleProvider
19
27
 
20
28
  __all__ = [
21
29
  "ANTHROPIC_VERSION",
30
+ "BEDROCK_SERVICE",
22
31
  "DEFAULT_ANTHROPIC_BASE_URL",
23
32
  "DEFAULT_BASE_URL",
24
33
  "AnthropicProvider",
34
+ "BedrockProvider",
25
35
  "FakeProvider",
26
36
  "OpenAICompatibleProvider",
27
37
  "Provider",
28
38
  "ScriptedTurn",
39
+ "default_bedrock_base_url",
40
+ "rfc3986",
29
41
  ]
@@ -0,0 +1,540 @@
1
+ """Amazon Bedrock's Converse API adapter.
2
+
3
+ Bedrock is not an endpoint that accepts an API key, so it cannot be an
4
+ OpenAI-compatible ``base_url``. Every request is SigV4-signed with credentials
5
+ the environment supplies, which also means an empty secret is a *valid*
6
+ configuration: on ECS the task role hands the container temporary credentials
7
+ through the container credentials endpoint, and no ``api_key_env`` exists.
8
+
9
+ Converse is the portable surface: one request shape covers every model Bedrock
10
+ serves, so this adapter knows nothing about Anthropic, Llama or Titan wire
11
+ dialects. Three translations are structural rather than cosmetic:
12
+
13
+ - Converse has no system role; the prompt is a top-level ``system`` array;
14
+ - ``inferenceConfig.maxTokens`` is required, so the adapter always sends one;
15
+ - tool results are ``toolResult`` blocks in a ``user`` turn, and adjacent results
16
+ are merged into one turn so the conversation keeps alternating roles.
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.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import contextlib
28
+ import hashlib
29
+ import hmac
30
+ import json
31
+ import os
32
+ from collections.abc import AsyncIterator, Callable, Sequence
33
+ from datetime import UTC, datetime
34
+ from typing import Any
35
+ from urllib.parse import quote, urlparse
36
+
37
+ import httpx
38
+
39
+ from aid_runtime.errors import ProviderError, ProviderResponseError
40
+ from aid_runtime.types import (
41
+ Capability,
42
+ CompletionRequest,
43
+ CompletionResponse,
44
+ FinishReason,
45
+ Message,
46
+ ModelSpec,
47
+ StreamChunk,
48
+ TokenUsage,
49
+ ToolCall,
50
+ )
51
+
52
+ __all__ = ["BEDROCK_SERVICE", "BedrockProvider", "default_bedrock_base_url", "rfc3986"]
53
+
54
+ BEDROCK_SERVICE = "bedrock"
55
+
56
+ # Bedrock's "dependency failed" is not a standard client error, so omitting it
57
+ # would make a transient model-side failure permanent.
58
+ _RETRYABLE_STATUS = frozenset({408, 409, 424, 425, 429, 500, 502, 503, 504})
59
+
60
+ _FINISH_REASONS: dict[str, FinishReason] = {
61
+ "end_turn": "stop",
62
+ "stop_sequence": "stop",
63
+ "max_tokens": "length",
64
+ "tool_use": "tool-calls",
65
+ "guardrail_intervened": "content-filter",
66
+ "content_filtered": "content-filter",
67
+ }
68
+
69
+ # Refresh container credentials this long before they expire.
70
+ _CREDENTIAL_REFRESH_SECONDS = 5 * 60
71
+
72
+
73
+ def default_bedrock_base_url(region: str) -> str:
74
+ """The regional runtime host, used when no base URL is configured."""
75
+ return f"https://bedrock-runtime.{region}.amazonaws.com"
76
+
77
+
78
+ def rfc3986(value: str) -> str:
79
+ """Percent-encode one path segment the way SigV4 defines it.
80
+
81
+ ``quote`` leaves ``!*'()`` alone by default and AWS does not: a signature over a
82
+ path the server decodes differently fails with ``SignatureDoesNotMatch``.
83
+ """
84
+ return quote(value, safe="")
85
+
86
+
87
+ def _sha256_hex(value: str) -> str:
88
+ return hashlib.sha256(value.encode()).hexdigest()
89
+
90
+
91
+ def _hmac(key: bytes | str, value: str) -> bytes:
92
+ if isinstance(key, str):
93
+ key = key.encode()
94
+ return hmac.new(key, value.encode(), hashlib.sha256).digest()
95
+
96
+
97
+ def _amz_date(moment: datetime) -> str:
98
+ return moment.astimezone(UTC).strftime("%Y%m%dT%H%M%SZ")
99
+
100
+
101
+ def _is_object(value: Any) -> bool:
102
+ return isinstance(value, dict)
103
+
104
+
105
+ class BedrockProvider:
106
+ """Calls ``POST /model/{id}/converse`` on the regional Bedrock runtime."""
107
+
108
+ def __init__(
109
+ self,
110
+ *,
111
+ region: str | None = None,
112
+ access_key_id: str | None = None,
113
+ secret_access_key: str | None = None,
114
+ session_token: str | None = None,
115
+ base_url: str | None = None,
116
+ name: str = "bedrock",
117
+ timeout_seconds: float = 60.0,
118
+ max_attempts: int = 3,
119
+ backoff_seconds: float = 0.5,
120
+ client: httpx.AsyncClient | None = None,
121
+ extra_headers: dict[str, str] | None = None,
122
+ now: Callable[[], datetime] | None = None,
123
+ ) -> None:
124
+ if max_attempts < 1:
125
+ raise ValueError("max_attempts must be at least 1")
126
+ self._region = region
127
+ self._static: dict[str, Any] | None = None
128
+ if access_key_id is not None and secret_access_key is not None:
129
+ self._static = {
130
+ "access_key_id": access_key_id,
131
+ "secret_access_key": secret_access_key,
132
+ }
133
+ if session_token is not None:
134
+ self._static["session_token"] = session_token
135
+ self._base_url = base_url.rstrip("/") if base_url is not None else None
136
+ self._name = name
137
+ self._timeout = timeout_seconds
138
+ self._max_attempts = max_attempts
139
+ self._backoff = backoff_seconds
140
+ self._extra_headers = dict(extra_headers or {})
141
+ self._owns_client = client is None
142
+ self._client = client or httpx.AsyncClient(timeout=timeout_seconds)
143
+ self._now = now or (lambda: datetime.now(UTC))
144
+ self._cached: dict[str, Any] | None = None
145
+ self._closed = False
146
+
147
+ @property
148
+ def name(self) -> str:
149
+ return self._name
150
+
151
+ @property
152
+ def capabilities(self) -> frozenset[Capability]:
153
+ return frozenset({Capability.TOOL_CALLING, Capability.STRUCTURED_OUTPUT})
154
+
155
+ async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
156
+ body = json.dumps(self._build_payload(request, model), separators=(",", ":"))
157
+ region = self._resolve_region()
158
+ credentials = await self._credentials()
159
+ url = self._endpoint(model, region)
160
+ headers = self._headers(url, body, region, credentials, self._now())
161
+ text = await self._post(url, headers, body)
162
+ return self._parse(text, model)
163
+
164
+ async def stream(
165
+ self, request: CompletionRequest, *, model: ModelSpec
166
+ ) -> AsyncIterator[StreamChunk]:
167
+ """Refuse: ``/converse-stream`` is not SSE.
168
+
169
+ Streaming here would mean decoding AWS's binary event-stream framing and
170
+ computing per-frame CRC32 checksums. Until that exists, refusing is better
171
+ than silently buffering a "stream" the caller believes is incremental.
172
+ """
173
+ del request, model
174
+ raise ProviderError(
175
+ f"{self._name} does not stream: Bedrock frames events in AWS's binary "
176
+ "event-stream format, which this adapter does not decode; use complete()"
177
+ )
178
+ yield # type: ignore[unreachable] # pragma: no cover - keeps this an async generator
179
+
180
+ async def aclose(self) -> None:
181
+ if self._closed:
182
+ return
183
+ self._closed = True
184
+ if self._owns_client:
185
+ await self._client.aclose()
186
+
187
+ def _resolve_region(self) -> str:
188
+ region = (
189
+ self._region or os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION")
190
+ )
191
+ if not region:
192
+ raise ProviderError(
193
+ f"{self._name} needs a region: pass region, or set AWS_REGION "
194
+ "(Bedrock model ids are regional)"
195
+ )
196
+ return region
197
+
198
+ def _endpoint(self, model: ModelSpec, region: str) -> str:
199
+ base = self._base_url or default_bedrock_base_url(region)
200
+ return f"{base}/model/{rfc3986(model.name)}/converse"
201
+
202
+ async def _credentials(self) -> dict[str, Any]:
203
+ """Static credentials, else the environment, else the container endpoint.
204
+
205
+ Resolution is lazy so importing a generated app cannot fail when a role
206
+ supplies credentials only once the process is running.
207
+ """
208
+ if self._static is not None:
209
+ return self._static
210
+ if self._cached is not None:
211
+ expires_at = self._cached.get("expires_at")
212
+ refresh_at = self._now().timestamp() + _CREDENTIAL_REFRESH_SECONDS
213
+ if expires_at is None or expires_at > refresh_at:
214
+ return self._cached
215
+
216
+ access_key_id = os.environ.get("AWS_ACCESS_KEY_ID")
217
+ secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY")
218
+ if access_key_id and secret_access_key:
219
+ credentials: dict[str, Any] = {
220
+ "access_key_id": access_key_id,
221
+ "secret_access_key": secret_access_key,
222
+ }
223
+ token = os.environ.get("AWS_SESSION_TOKEN")
224
+ if token is not None:
225
+ credentials["session_token"] = token
226
+ return credentials
227
+
228
+ relative = os.environ.get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
229
+ full = os.environ.get("AWS_CONTAINER_CREDENTIALS_FULL_URI")
230
+ url = f"http://169.254.170.2{relative}" if relative else full
231
+ if url:
232
+ fetched = await self._fetch_credentials(url)
233
+ self._cached = fetched
234
+ return fetched
235
+
236
+ raise ProviderError(
237
+ f"{self._name} has no credentials: set AWS_ACCESS_KEY_ID and "
238
+ "AWS_SECRET_ACCESS_KEY, or run where AWS_CONTAINER_CREDENTIALS_RELATIVE_URI "
239
+ "is set (a task role)"
240
+ )
241
+
242
+ async def _fetch_credentials(self, url: str) -> dict[str, Any]:
243
+ try:
244
+ response = await self._client.get(url)
245
+ except httpx.TransportError as exc:
246
+ raise ProviderError(
247
+ f"{self._name} could not reach the container credentials endpoint: {exc}"
248
+ ) from exc
249
+ if response.status_code >= 400:
250
+ raise ProviderError(
251
+ f"{self._name} container credentials endpoint returned "
252
+ f"{response.status_code}: {response.text[:500]}"
253
+ )
254
+ try:
255
+ body = response.json()
256
+ except json.JSONDecodeError as exc:
257
+ raise ProviderResponseError(
258
+ f"{self._name} credentials endpoint returned a non-JSON body",
259
+ response.text,
260
+ ) from exc
261
+ if not _is_object(body):
262
+ raise ProviderResponseError(
263
+ f"{self._name} credentials endpoint returned no object", response.text
264
+ )
265
+ access_key_id = body.get("AccessKeyId")
266
+ secret_access_key = body.get("SecretAccessKey")
267
+ if not isinstance(access_key_id, str) or not isinstance(secret_access_key, str):
268
+ raise ProviderResponseError(
269
+ f"{self._name} credentials endpoint returned no AccessKeyId/SecretAccessKey",
270
+ json.dumps(body, sort_keys=True),
271
+ )
272
+ credentials: dict[str, Any] = {
273
+ "access_key_id": access_key_id,
274
+ "secret_access_key": secret_access_key,
275
+ }
276
+ token = body.get("Token")
277
+ if isinstance(token, str) and token:
278
+ credentials["session_token"] = token
279
+ expiration = body.get("Expiration")
280
+ if isinstance(expiration, str):
281
+ with contextlib.suppress(ValueError):
282
+ credentials["expires_at"] = _parse_iso(expiration)
283
+ return credentials
284
+
285
+ def _headers(
286
+ self,
287
+ url: str,
288
+ body: str,
289
+ region: str,
290
+ credentials: dict[str, Any],
291
+ moment: datetime,
292
+ ) -> dict[str, str]:
293
+ stamp = _amz_date(moment)
294
+ date = stamp[:8]
295
+ parsed = urlparse(url)
296
+ host = parsed.netloc
297
+ canonical_headers: list[tuple[str, str]] = [
298
+ ("content-type", "application/json"),
299
+ ("host", host),
300
+ ("x-amz-date", stamp),
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}"
337
+ ),
338
+ **self._extra_headers,
339
+ }
340
+ if isinstance(token, str):
341
+ headers["x-amz-security-token"] = token
342
+ return headers
343
+
344
+ def _build_payload(self, request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
345
+ inference_config: dict[str, Any] = {"maxTokens": _max_tokens(request, model)}
346
+ if request.temperature is not None:
347
+ inference_config["temperature"] = request.temperature
348
+ if request.stop:
349
+ inference_config["stopSequences"] = list(request.stop)
350
+ payload: dict[str, Any] = {
351
+ "messages": _wire_messages(self._name, request.messages),
352
+ "inferenceConfig": inference_config,
353
+ }
354
+ system = _system_prompt(request.messages)
355
+ if system:
356
+ payload["system"] = [{"text": system}]
357
+ if request.tools:
358
+ payload["toolConfig"] = {
359
+ "tools": [
360
+ {
361
+ "toolSpec": {
362
+ "name": tool.name,
363
+ "description": tool.description,
364
+ "inputSchema": {
365
+ "json": tool.parameters or {"type": "object", "properties": {}}
366
+ },
367
+ }
368
+ }
369
+ for tool in request.tools
370
+ ]
371
+ }
372
+ return payload
373
+
374
+ async def _post(self, url: str, headers: dict[str, str], body: str) -> str:
375
+ last_error: Exception | None = None
376
+ for attempt in range(1, self._max_attempts + 1):
377
+ try:
378
+ response = await self._client.post(url, content=body, headers=headers)
379
+ except httpx.TransportError as exc:
380
+ last_error = exc
381
+ if attempt == self._max_attempts:
382
+ break
383
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
384
+ continue
385
+
386
+ if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
387
+ last_error = ProviderError(
388
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
389
+ )
390
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
391
+ continue
392
+
393
+ if response.status_code >= 400:
394
+ raise ProviderError(
395
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
396
+ )
397
+ return response.text
398
+
399
+ raise ProviderError(
400
+ f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
401
+ ) from last_error
402
+
403
+ def _parse(self, text: str, model: ModelSpec) -> CompletionResponse:
404
+ try:
405
+ body = json.loads(text)
406
+ except json.JSONDecodeError as exc:
407
+ raise ProviderResponseError(
408
+ f"{self._name} returned a body that is not JSON", text
409
+ ) from exc
410
+ if not isinstance(body, dict):
411
+ raise ProviderResponseError(
412
+ f"{self._name} returned a JSON body that is not an object", text
413
+ )
414
+ output = body.get("output")
415
+ message = output.get("message") if isinstance(output, dict) else None
416
+ blocks = message.get("content") if isinstance(message, dict) else None
417
+ if not isinstance(blocks, list):
418
+ raise ProviderResponseError(f"{self._name} returned no content blocks", text)
419
+
420
+ text_parts: list[str] = []
421
+ calls: list[ToolCall] = []
422
+ for block in blocks:
423
+ if not isinstance(block, dict):
424
+ continue
425
+ value = block.get("text")
426
+ if isinstance(value, str):
427
+ text_parts.append(value)
428
+ continue
429
+ tool_use = block.get("toolUse")
430
+ if not isinstance(tool_use, dict):
431
+ continue
432
+ call_id = tool_use.get("toolUseId")
433
+ call_name = tool_use.get("name")
434
+ if not isinstance(call_id, str) or not call_id:
435
+ continue
436
+ if not isinstance(call_name, str) or not call_name:
437
+ continue
438
+ raw_input = tool_use.get("input")
439
+ calls.append(
440
+ ToolCall(
441
+ id=call_id,
442
+ name=call_name,
443
+ arguments=raw_input if isinstance(raw_input, dict) else {},
444
+ )
445
+ )
446
+
447
+ raw_usage = body.get("usage")
448
+ usage = TokenUsage(input_tokens=0, output_tokens=0)
449
+ if isinstance(raw_usage, dict):
450
+ usage = TokenUsage(
451
+ input_tokens=int(raw_usage.get("inputTokens") or 0),
452
+ output_tokens=int(raw_usage.get("outputTokens") or 0),
453
+ )
454
+
455
+ return CompletionResponse(
456
+ text="".join(text_parts),
457
+ model=model.name,
458
+ provider=self._name,
459
+ usage=usage,
460
+ tool_calls=tuple(calls),
461
+ finish_reason=_finish_reason(body.get("stopReason"), bool(calls)),
462
+ )
463
+
464
+
465
+ def _parse_iso(value: str) -> float:
466
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
467
+
468
+
469
+ def _max_tokens(request: CompletionRequest, model: ModelSpec) -> int:
470
+ """Converse requires the field; a request without a cap still needs a number."""
471
+ if request.max_output_tokens is not None:
472
+ return min(request.max_output_tokens, model.max_output_tokens)
473
+ return model.max_output_tokens
474
+
475
+
476
+ def _system_prompt(messages: Sequence[Message]) -> str:
477
+ """Converse takes one ``system`` array, so adjacent system turns are joined."""
478
+ parts = [
479
+ message.content for message in messages if message.role == "system" and message.content
480
+ ]
481
+ return "\n\n".join(parts)
482
+
483
+
484
+ def _wire_messages(name: str, messages: Sequence[Message]) -> list[dict[str, Any]]:
485
+ """Translate the portable message list into the wire shape.
486
+
487
+ An assistant turn carrying tool calls sends ``toolUse`` blocks, or the following
488
+ ``toolResult`` has no caller; adjacent ``tool`` turns collapse into one ``user``
489
+ turn, because Converse requires the conversation to alternate roles.
490
+ """
491
+ wire: list[dict[str, Any]] = []
492
+ previous_was_tool_result = False
493
+ for message in messages:
494
+ if message.role == "system":
495
+ continue
496
+ if message.role == "tool":
497
+ if message.tool_call_id is None:
498
+ raise ProviderError(f"{name} cannot send a tool result without a tool_call_id")
499
+ block = {
500
+ "toolResult": {
501
+ "toolUseId": message.tool_call_id,
502
+ "content": [{"text": message.content}],
503
+ }
504
+ }
505
+ if previous_was_tool_result and wire:
506
+ wire[-1]["content"].append(block)
507
+ else:
508
+ wire.append({"role": "user", "content": [block]})
509
+ previous_was_tool_result = True
510
+ continue
511
+ previous_was_tool_result = False
512
+ if message.role == "user":
513
+ # Converse rejects an empty text block, so an empty turn is dropped.
514
+ if not message.content:
515
+ continue
516
+ wire.append({"role": "user", "content": [{"text": message.content}]})
517
+ continue
518
+ blocks: list[dict[str, Any]] = []
519
+ if message.content:
520
+ blocks.append({"text": message.content})
521
+ blocks.extend(
522
+ {
523
+ "toolUse": {
524
+ "toolUseId": call.id,
525
+ "name": call.name,
526
+ "input": call.arguments,
527
+ }
528
+ }
529
+ for call in message.tool_calls
530
+ )
531
+ if not blocks:
532
+ continue
533
+ wire.append({"role": "assistant", "content": blocks})
534
+ return wire
535
+
536
+
537
+ def _finish_reason(raw: Any, saw_tool_call: bool) -> FinishReason:
538
+ if not isinstance(raw, str):
539
+ return "tool-calls" if saw_tool_call else "stop"
540
+ return _FINISH_REASONS.get(raw, "stop")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.77
3
+ Version: 0.1.79
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=yO6FLBc7uBtm1RmeO4lYYH1-VluaBbCWRwXSve83PA0,11290
1
+ aid_runtime/__init__.py,sha256=obl3XP4UH4dhY8CYJ2l-miIIsT1Ky04O69JZCakl4Rw,11596
2
2
  aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
3
3
  aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
4
4
  aid_runtime/control.py,sha256=u4U97QFdYSSjOPY3D6f1-GZhkGhygEdR-apdgw_jJok,13797
@@ -30,9 +30,10 @@ aid_runtime/evals/gate.py,sha256=_nLWXvcuHwq8nE3HpiONg_wBkrzZyGrGT49ZNeKMyTY,155
30
30
  aid_runtime/evals/metrics.py,sha256=Z-rLJjG0dBTdTJTVGTt8WzE0avyYkIG_Ot8sLDaD99Y,10631
31
31
  aid_runtime/evals/predicate.py,sha256=JaeN1LJFpliI4JHYdFPtXfjH5_Aad-2-U3ZC6_hManE,8726
32
32
  aid_runtime/evals/runner.py,sha256=Lkl-kAVxegPO40pCBUcprRBKvfL6bjYzVf__xe6Z-Mc,7951
33
- aid_runtime/providers/__init__.py,sha256=5saaMSjm5ajWWOJ-TDOtKIySepEFt13n0jRw2B34UDc,892
33
+ aid_runtime/providers/__init__.py,sha256=sT08XXxm6Nuor826WMac9pPASwjrWDocACZnpS6zCwM,1242
34
34
  aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
35
35
  aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
36
+ aid_runtime/providers/bedrock.py,sha256=WkfWFg94kLFJ9q04CEkXCc-HqoVqHivAmhy511-WtIA,20834
36
37
  aid_runtime/providers/fake.py,sha256=oAcpaDOUIp7lmKGEEWG5ktagstg2dvoHR-9xaUeCDLo,9526
37
38
  aid_runtime/providers/http.py,sha256=c5DLmX1FqtAUO01MqDf0m82x8zHD480LyL-QtTrxnn4,13168
38
39
  aid_runtime/retrieval/__init__.py,sha256=LR6qyiE7pY9QsB1h4g9j1W7acpSINFbgxA9U1otLt90,4580
@@ -48,7 +49,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
48
49
  aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
49
50
  aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
50
51
  aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
51
- aid_runtime_python-0.1.77.dist-info/METADATA,sha256=I5-MvItNNT5Mgzg5UJTRoVit0y5atlOQlU6LaCl3d6Q,15559
52
- aid_runtime_python-0.1.77.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
53
- aid_runtime_python-0.1.77.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
54
- aid_runtime_python-0.1.77.dist-info/RECORD,,
52
+ aid_runtime_python-0.1.79.dist-info/METADATA,sha256=7njIcxHpci-Rq-mPg1Tkj_R2dv5AFc1PN_LNoshdv0M,15559
53
+ aid_runtime_python-0.1.79.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
54
+ aid_runtime_python-0.1.79.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
55
+ aid_runtime_python-0.1.79.dist-info/RECORD,,