aid-runtime-python 0.1.73__py3-none-any.whl → 0.1.75__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
@@ -139,7 +139,10 @@ from aid_runtime.pipeline import (
139
139
  )
140
140
  from aid_runtime.prompts import Example, PromptRegistry, PromptTemplate, RenderedPrompt
141
141
  from aid_runtime.providers import (
142
+ ANTHROPIC_VERSION,
143
+ DEFAULT_ANTHROPIC_BASE_URL,
142
144
  DEFAULT_BASE_URL,
145
+ AnthropicProvider,
143
146
  FakeProvider,
144
147
  OpenAICompatibleProvider,
145
148
  Provider,
@@ -269,10 +272,12 @@ from aid_runtime.types import (
269
272
  )
270
273
 
271
274
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
272
- __version__ = "0.1.73"
275
+ __version__ = "0.1.75"
273
276
 
274
277
  __all__ = [
278
+ "ANTHROPIC_VERSION",
275
279
  "ATTRIBUTES",
280
+ "DEFAULT_ANTHROPIC_BASE_URL",
276
281
  "DEFAULT_BASE_URL",
277
282
  "DEFAULT_CANDIDATE_FACTOR",
278
283
  "DEPTH_KEY",
@@ -294,6 +299,7 @@ __all__ = [
294
299
  "AgentRuntime",
295
300
  "AgentTransferCycleError",
296
301
  "AidRuntimeError",
302
+ "AnthropicProvider",
297
303
  "BaselineGate",
298
304
  "Budget",
299
305
  "BudgetExceededError",
@@ -1,18 +1,27 @@
1
1
  """Provider adapters.
2
2
 
3
- Exactly two ship in Phase 0: one real HTTP adapter and one deterministic fake for
4
- tests and the eval-gate fixture. Provider breadth (Anthropic, Azure, Bedrock) is
5
- deliberately out of scope.
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.
6
7
  """
7
8
 
8
9
  from __future__ import annotations
9
10
 
11
+ from aid_runtime.providers.anthropic import (
12
+ ANTHROPIC_VERSION,
13
+ DEFAULT_ANTHROPIC_BASE_URL,
14
+ AnthropicProvider,
15
+ )
10
16
  from aid_runtime.providers.base import Provider
11
17
  from aid_runtime.providers.fake import FakeProvider, ScriptedTurn
12
18
  from aid_runtime.providers.http import DEFAULT_BASE_URL, OpenAICompatibleProvider
13
19
 
14
20
  __all__ = [
21
+ "ANTHROPIC_VERSION",
22
+ "DEFAULT_ANTHROPIC_BASE_URL",
15
23
  "DEFAULT_BASE_URL",
24
+ "AnthropicProvider",
16
25
  "FakeProvider",
17
26
  "OpenAICompatibleProvider",
18
27
  "Provider",
@@ -0,0 +1,415 @@
1
+ """Anthropic's Messages API adapter.
2
+
3
+ A second dialect, not a second abstraction: the runtime's shapes go in, one HTTP
4
+ call goes out. The differences from the OpenAI-compatible adapter that actually
5
+ matter are here and nowhere else:
6
+
7
+ - the system prompt is a top-level ``system`` field, not a message;
8
+ - ``max_tokens`` is required, so the adapter always sends one;
9
+ - a tool result is a ``user`` message containing a ``tool_result`` block, and the
10
+ assistant turn that asked for it carries a ``tool_use`` block with the same id;
11
+ - ``stop_reason`` is ``end_turn`` / ``max_tokens`` / ``tool_use`` / ``stop_sequence``.
12
+
13
+ There is no embeddings endpoint, so ``EMBEDDINGS`` is deliberately not advertised:
14
+ a spec that binds an embedding model to this provider should fail negotiation
15
+ rather than fail at call time.
16
+
17
+ Authentication is ``x-api-key`` plus a dated ``anthropic-version`` header, which
18
+ is why this cannot be expressed as ``OpenAICompatibleProvider`` with a different
19
+ ``base_url``.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import json
26
+ from collections.abc import AsyncIterator, Sequence
27
+ from typing import Any
28
+
29
+ import httpx
30
+
31
+ from aid_runtime.errors import ProviderError, ProviderResponseError
32
+ from aid_runtime.types import (
33
+ Capability,
34
+ CompletionRequest,
35
+ CompletionResponse,
36
+ FinishReason,
37
+ Message,
38
+ ModelSpec,
39
+ StreamChunk,
40
+ TokenUsage,
41
+ ToolCall,
42
+ )
43
+
44
+ __all__ = ["ANTHROPIC_VERSION", "DEFAULT_ANTHROPIC_BASE_URL", "AnthropicProvider"]
45
+
46
+ DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1"
47
+
48
+ # Pinned rather than configurable: a wire version is a compatibility claim, and
49
+ # letting an env var change it would make the adapter's tests test something else.
50
+ ANTHROPIC_VERSION = "2023-06-01"
51
+
52
+ # 529 is Anthropic's "overloaded" status and is not an HTTP standard code, so it has
53
+ # to be listed explicitly or a busy provider would look like a client error.
54
+ _RETRYABLE_STATUS = frozenset({408, 409, 425, 429, 500, 502, 503, 504, 529})
55
+
56
+ _FINISH_REASONS: dict[str, FinishReason] = {
57
+ "end_turn": "stop",
58
+ "stop_sequence": "stop",
59
+ "max_tokens": "length",
60
+ "tool_use": "tool-calls",
61
+ "refusal": "content-filter",
62
+ }
63
+
64
+
65
+ # A thinking-only or otherwise empty assistant turn is legal in Anthropic's API;
66
+ # without this the request would be rejected for sending an empty text block.
67
+ def _text_block(text: str) -> dict[str, Any] | None:
68
+ return {"type": "text", "text": text} if text else None
69
+
70
+
71
+ class AnthropicProvider:
72
+ """Calls ``POST {base_url}/messages`` and maps the response back."""
73
+
74
+ def __init__(
75
+ self,
76
+ *,
77
+ api_key: str | None = None,
78
+ base_url: str = DEFAULT_ANTHROPIC_BASE_URL,
79
+ name: str = "anthropic",
80
+ timeout_seconds: float = 60.0,
81
+ max_attempts: int = 3,
82
+ backoff_seconds: float = 0.5,
83
+ client: httpx.AsyncClient | None = None,
84
+ api_version: str = ANTHROPIC_VERSION,
85
+ extra_headers: dict[str, str] | None = None,
86
+ ) -> None:
87
+ if not base_url.startswith(("http://", "https://")):
88
+ raise ValueError(f"base_url must be an absolute http(s) URL, got {base_url!r}")
89
+ if max_attempts < 1:
90
+ raise ValueError("max_attempts must be at least 1")
91
+ self._name = name
92
+ self._base_url = base_url.rstrip("/")
93
+ self._api_key = api_key
94
+ self._api_version = api_version
95
+ self._timeout = timeout_seconds
96
+ self._max_attempts = max_attempts
97
+ self._backoff = backoff_seconds
98
+ self._extra_headers = dict(extra_headers or {})
99
+ self._owns_client = client is None
100
+ self._client = client or httpx.AsyncClient(timeout=timeout_seconds)
101
+ self._closed = False
102
+
103
+ @property
104
+ def name(self) -> str:
105
+ return self._name
106
+
107
+ @property
108
+ def capabilities(self) -> frozenset[Capability]:
109
+ return frozenset(
110
+ {
111
+ Capability.TOOL_CALLING,
112
+ Capability.STRUCTURED_OUTPUT,
113
+ Capability.STREAMING,
114
+ }
115
+ )
116
+
117
+ async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
118
+ payload = self._build_payload(request, model)
119
+ body = await self._post("/messages", payload)
120
+ return self._parse(body, model)
121
+
122
+ async def stream(
123
+ self, request: CompletionRequest, *, model: ModelSpec
124
+ ) -> AsyncIterator[StreamChunk]:
125
+ """Stream one call as Anthropic's named SSE events.
126
+
127
+ One attempt, like the OpenAI adapter: a stream that has already emitted text
128
+ cannot be replayed, so an error is raised once rather than retried mid-stream.
129
+
130
+ Tool calls are not reported here because :class:`StreamChunk` has no field for
131
+ them; the gateway that needs tool calls uses :meth:`complete`.
132
+ """
133
+ payload = self._build_payload(request, model)
134
+ payload["stream"] = True
135
+ url = f"{self._base_url}/messages"
136
+ try:
137
+ async with self._client.stream(
138
+ "POST", url, json=payload, headers=self._headers()
139
+ ) as response:
140
+ if response.status_code >= 400:
141
+ await response.aread()
142
+ raise ProviderError(
143
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
144
+ )
145
+ async for line in response.aiter_lines():
146
+ if not line.startswith("data:"):
147
+ continue
148
+ data = line[len("data:") :].strip()
149
+ if not data:
150
+ continue
151
+ try:
152
+ event = json.loads(data)
153
+ except json.JSONDecodeError as exc:
154
+ raise ProviderResponseError(
155
+ f"{self._name} streamed non-JSON", data
156
+ ) from exc
157
+ if not isinstance(event, dict):
158
+ raise ProviderResponseError(
159
+ f"{self._name} streamed a non-object body", data
160
+ )
161
+ chunk = self._parse_stream_event(event)
162
+ if chunk is not None:
163
+ yield chunk
164
+ except httpx.TransportError as exc:
165
+ raise ProviderError(f"{self._name} stream failed: {exc}") from exc
166
+
167
+ async def aclose(self) -> None:
168
+ if self._closed:
169
+ return
170
+ self._closed = True
171
+ if self._owns_client:
172
+ await self._client.aclose()
173
+
174
+ def _headers(self) -> dict[str, str]:
175
+ headers = {
176
+ "content-type": "application/json",
177
+ "anthropic-version": self._api_version,
178
+ **self._extra_headers,
179
+ }
180
+ if self._api_key:
181
+ headers["x-api-key"] = self._api_key
182
+ return headers
183
+
184
+ def _build_payload(self, request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
185
+ system, messages = _split_system(request.messages)
186
+ payload: dict[str, Any] = {
187
+ "model": model.name,
188
+ "max_tokens": _max_tokens(request, model),
189
+ "messages": messages,
190
+ }
191
+ if system:
192
+ payload["system"] = system
193
+ if request.temperature is not None:
194
+ payload["temperature"] = request.temperature
195
+ if request.stop:
196
+ payload["stop_sequences"] = list(request.stop)
197
+ if request.tools:
198
+ payload["tools"] = [
199
+ {
200
+ "name": tool.name,
201
+ "description": tool.description,
202
+ "input_schema": tool.parameters or {"type": "object", "properties": {}},
203
+ }
204
+ for tool in request.tools
205
+ ]
206
+ return payload
207
+
208
+ async def _post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
209
+ url = f"{self._base_url}{path}"
210
+ last_error: Exception | None = None
211
+ for attempt in range(1, self._max_attempts + 1):
212
+ try:
213
+ response = await self._client.post(url, json=payload, headers=self._headers())
214
+ except httpx.TransportError as exc:
215
+ last_error = exc
216
+ if attempt == self._max_attempts:
217
+ break
218
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
219
+ continue
220
+
221
+ if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
222
+ last_error = ProviderError(f"{self._name} returned {response.status_code}")
223
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
224
+ continue
225
+
226
+ if response.status_code >= 400:
227
+ raise ProviderError(
228
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
229
+ )
230
+
231
+ try:
232
+ decoded = response.json()
233
+ except json.JSONDecodeError as exc:
234
+ raise ProviderResponseError(
235
+ f"{self._name} returned non-JSON", response.text
236
+ ) from exc
237
+ if not isinstance(decoded, dict):
238
+ raise ProviderResponseError(
239
+ f"{self._name} returned a non-object body", response.text
240
+ )
241
+ return decoded
242
+
243
+ raise ProviderError(
244
+ f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
245
+ ) from last_error
246
+
247
+ def _parse(self, body: dict[str, Any], model: ModelSpec) -> CompletionResponse:
248
+ blocks = body.get("content")
249
+ if not isinstance(blocks, list):
250
+ raise ProviderResponseError(
251
+ f"{self._name} returned no content blocks", json.dumps(body, sort_keys=True)
252
+ )
253
+
254
+ text_parts: list[str] = []
255
+ calls: list[ToolCall] = []
256
+ for block in blocks:
257
+ if not isinstance(block, dict):
258
+ continue
259
+ kind = block.get("type")
260
+ if kind == "text":
261
+ value = block.get("text")
262
+ if isinstance(value, str):
263
+ text_parts.append(value)
264
+ elif kind == "tool_use":
265
+ call_id = block.get("id")
266
+ call_name = block.get("name")
267
+ if (
268
+ isinstance(call_id, str)
269
+ and call_id
270
+ and isinstance(call_name, str)
271
+ and call_name
272
+ ):
273
+ raw_input = block.get("input")
274
+ calls.append(
275
+ ToolCall(
276
+ id=call_id,
277
+ name=call_name,
278
+ arguments=raw_input if isinstance(raw_input, dict) else {},
279
+ )
280
+ )
281
+
282
+ raw_usage = body.get("usage")
283
+ usage = TokenUsage(input_tokens=0, output_tokens=0)
284
+ if isinstance(raw_usage, dict):
285
+ usage = TokenUsage(
286
+ input_tokens=int(raw_usage.get("input_tokens") or 0),
287
+ output_tokens=int(raw_usage.get("output_tokens") or 0),
288
+ )
289
+
290
+ return CompletionResponse(
291
+ text="".join(text_parts),
292
+ model=str(body.get("model") or model.name),
293
+ provider=self._name,
294
+ usage=usage,
295
+ tool_calls=tuple(calls),
296
+ finish_reason=_finish_reason(body.get("stop_reason")),
297
+ )
298
+
299
+ def _parse_stream_event(self, event: dict[str, Any]) -> StreamChunk | None:
300
+ kind = event.get("type")
301
+
302
+ if kind == "message_start":
303
+ message = event.get("message")
304
+ raw_usage = message.get("usage") if isinstance(message, dict) else None
305
+ if isinstance(raw_usage, dict):
306
+ return StreamChunk(
307
+ usage=TokenUsage(
308
+ input_tokens=int(raw_usage.get("input_tokens") or 0),
309
+ output_tokens=0,
310
+ )
311
+ )
312
+ return None
313
+
314
+ if kind == "content_block_delta":
315
+ delta = event.get("delta")
316
+ if isinstance(delta, dict) and delta.get("type") == "text_delta":
317
+ text = delta.get("text")
318
+ if isinstance(text, str) and text:
319
+ return StreamChunk(delta=text)
320
+ return None
321
+
322
+ if kind == "message_delta":
323
+ delta = event.get("delta")
324
+ raw_usage = event.get("usage")
325
+ finish: FinishReason | None = None
326
+ if isinstance(delta, dict):
327
+ reason = delta.get("stop_reason")
328
+ if isinstance(reason, str) and reason:
329
+ finish = _finish_reason(reason)
330
+ usage = None
331
+ if isinstance(raw_usage, dict):
332
+ usage = TokenUsage(
333
+ input_tokens=int(raw_usage.get("input_tokens") or 0),
334
+ output_tokens=int(raw_usage.get("output_tokens") or 0),
335
+ )
336
+ if finish is None and usage is None:
337
+ return None
338
+ return StreamChunk(finish_reason=finish, usage=usage)
339
+
340
+ return None
341
+
342
+
343
+ def _max_tokens(request: CompletionRequest, model: ModelSpec) -> int:
344
+ """Anthropic requires the field; a request without a cap still needs a number.
345
+
346
+ The model's own ceiling is the smallest value that cannot truncate something the
347
+ model was willing to write, so it is the default rather than an arbitrary 1024.
348
+ """
349
+ if request.max_output_tokens is not None:
350
+ return min(request.max_output_tokens, model.max_output_tokens)
351
+ return model.max_output_tokens
352
+
353
+
354
+ def _split_system(
355
+ messages: Sequence[Message],
356
+ ) -> tuple[str, list[dict[str, Any]]]:
357
+ """Hoist system prompts and fold tool results into user turns.
358
+
359
+ Anthropic has no ``tool`` role: an observation is a ``user`` message whose content
360
+ is a ``tool_result`` block. Adjacent results are merged into one turn, because the
361
+ API expects every ``tool_use`` of an assistant turn to be answered together.
362
+ """
363
+ system_parts: list[str] = []
364
+ turns: list[dict[str, Any]] = []
365
+
366
+ for message in messages:
367
+ if message.role == "system":
368
+ if message.content:
369
+ system_parts.append(message.content)
370
+ continue
371
+
372
+ if message.role == "tool":
373
+ results: list[dict[str, Any]] = [
374
+ {
375
+ "type": "tool_result",
376
+ "tool_use_id": message.tool_call_id or "",
377
+ "content": message.content,
378
+ }
379
+ ]
380
+ last = turns[-1] if turns else None
381
+ if (
382
+ last is not None
383
+ and last.get("role") == "user"
384
+ and isinstance(last.get("content"), list)
385
+ and all(block.get("type") == "tool_result" for block in last["content"])
386
+ ):
387
+ last["content"].extend(results)
388
+ else:
389
+ turns.append({"role": "user", "content": results})
390
+ continue
391
+
392
+ if message.role == "assistant" and message.tool_calls:
393
+ blocks: list[dict[str, Any]] = []
394
+ text = _text_block(message.content)
395
+ if text is not None:
396
+ blocks.append(text)
397
+ blocks.extend(
398
+ {
399
+ "type": "tool_use",
400
+ "id": call.id,
401
+ "name": call.name,
402
+ "input": call.arguments,
403
+ }
404
+ for call in message.tool_calls
405
+ )
406
+ turns.append({"role": "assistant", "content": blocks})
407
+ continue
408
+
409
+ turns.append({"role": message.role, "content": message.content})
410
+
411
+ return "\n\n".join(system_parts), turns
412
+
413
+
414
+ def _finish_reason(raw: Any) -> FinishReason:
415
+ return _FINISH_REASONS.get(raw, "stop") if isinstance(raw, str) else "stop"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.73
3
+ Version: 0.1.75
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=9HVKB8wIy0cwbxIK1062Ak1i5EQUpSN6ReDTqCAUimc,11128
1
+ aid_runtime/__init__.py,sha256=xltZN8C5A2Dffzy0y5rHN9w8QIlfLPahOxzpI9J95X0,11290
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,7 +30,8 @@ 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=KkRkwVRZwZ5H_Rqke8EsipxyMgYuwODB9CGXiHL_gDE,577
33
+ aid_runtime/providers/__init__.py,sha256=5saaMSjm5ajWWOJ-TDOtKIySepEFt13n0jRw2B34UDc,892
34
+ aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
34
35
  aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
35
36
  aid_runtime/providers/fake.py,sha256=oAcpaDOUIp7lmKGEEWG5ktagstg2dvoHR-9xaUeCDLo,9526
36
37
  aid_runtime/providers/http.py,sha256=c5DLmX1FqtAUO01MqDf0m82x8zHD480LyL-QtTrxnn4,13168
@@ -47,7 +48,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
47
48
  aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
48
49
  aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
49
50
  aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
50
- aid_runtime_python-0.1.73.dist-info/METADATA,sha256=wxP5iSGgfVWQI941SSfMtAwDecfK4MmcVxE5G_ilM7Q,15559
51
- aid_runtime_python-0.1.73.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
52
- aid_runtime_python-0.1.73.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
53
- aid_runtime_python-0.1.73.dist-info/RECORD,,
51
+ aid_runtime_python-0.1.75.dist-info/METADATA,sha256=9CH7_9-hp9fi2U7Aa75tkkHCq33OCyEbJWWnzRBefaU,15559
52
+ aid_runtime_python-0.1.75.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
53
+ aid_runtime_python-0.1.75.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
54
+ aid_runtime_python-0.1.75.dist-info/RECORD,,