aid-runtime-python 0.1.80__py3-none-any.whl → 0.1.82__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 +14 -4
- aid_runtime/providers/__init__.py +17 -6
- aid_runtime/providers/vertex.py +448 -0
- {aid_runtime_python-0.1.80.dist-info → aid_runtime_python-0.1.82.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.80.dist-info → aid_runtime_python-0.1.82.dist-info}/RECORD +7 -6
- {aid_runtime_python-0.1.80.dist-info → aid_runtime_python-0.1.82.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.80.dist-info → aid_runtime_python-0.1.82.dist-info}/top_level.txt +0 -0
aid_runtime/__init__.py
CHANGED
|
@@ -17,10 +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 narrow adapter seam,
|
|
20
|
+
* **One narrow adapter seam, four dialects, and a fake.** Breadth of vendor
|
|
21
21
|
coverage stays a later concern; a correct seam is worth more than a wide shallow
|
|
22
|
-
one.
|
|
23
|
-
|
|
22
|
+
one. Four dialects ship: OpenAI-compatible, Anthropic Messages, Bedrock Converse,
|
|
23
|
+
and Vertex AI, alongside a deterministic fake that lets the eval gate run offline.
|
|
24
24
|
"""
|
|
25
25
|
|
|
26
26
|
from __future__ import annotations
|
|
@@ -145,13 +145,18 @@ from aid_runtime.providers import (
|
|
|
145
145
|
BEDROCK_SERVICE,
|
|
146
146
|
DEFAULT_ANTHROPIC_BASE_URL,
|
|
147
147
|
DEFAULT_BASE_URL,
|
|
148
|
+
DEFAULT_VERTEX_LOCATION,
|
|
149
|
+
METADATA_TOKEN_URL,
|
|
150
|
+
VERTEX_TOKEN_ENV,
|
|
148
151
|
AnthropicProvider,
|
|
149
152
|
BedrockProvider,
|
|
150
153
|
FakeProvider,
|
|
151
154
|
OpenAICompatibleProvider,
|
|
152
155
|
Provider,
|
|
153
156
|
ScriptedTurn,
|
|
157
|
+
VertexProvider,
|
|
154
158
|
default_bedrock_base_url,
|
|
159
|
+
default_vertex_base_url,
|
|
155
160
|
)
|
|
156
161
|
from aid_runtime.retrieval import (
|
|
157
162
|
DEFAULT_CANDIDATE_FACTOR,
|
|
@@ -277,7 +282,7 @@ from aid_runtime.types import (
|
|
|
277
282
|
)
|
|
278
283
|
|
|
279
284
|
#: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
|
|
280
|
-
__version__ = "0.1.
|
|
285
|
+
__version__ = "0.1.82"
|
|
281
286
|
|
|
282
287
|
__all__ = [
|
|
283
288
|
"ANTHROPIC_VERSION",
|
|
@@ -286,6 +291,7 @@ __all__ = [
|
|
|
286
291
|
"DEFAULT_ANTHROPIC_BASE_URL",
|
|
287
292
|
"DEFAULT_BASE_URL",
|
|
288
293
|
"DEFAULT_CANDIDATE_FACTOR",
|
|
294
|
+
"DEFAULT_VERTEX_LOCATION",
|
|
289
295
|
"DEPTH_KEY",
|
|
290
296
|
"EMITTED_KEY",
|
|
291
297
|
"GEN_AI_OPERATION_CHAT",
|
|
@@ -293,11 +299,13 @@ __all__ = [
|
|
|
293
299
|
"ITEM_KEY",
|
|
294
300
|
"LIMITER_KEY",
|
|
295
301
|
"MAX_STEP_DEPTH",
|
|
302
|
+
"METADATA_TOKEN_URL",
|
|
296
303
|
"PRINCIPAL_KEY",
|
|
297
304
|
"REDUCED_KEY",
|
|
298
305
|
"RESERVED_KEYS",
|
|
299
306
|
"STEPS_KEY",
|
|
300
307
|
"TRACE_DIR_ENV",
|
|
308
|
+
"VERTEX_TOKEN_ENV",
|
|
301
309
|
"AgentBudgetDegradedError",
|
|
302
310
|
"AgentCheckpoint",
|
|
303
311
|
"AgentDefinition",
|
|
@@ -455,6 +463,7 @@ __all__ = [
|
|
|
455
463
|
"UnknownModelAliasError",
|
|
456
464
|
"VectorStore",
|
|
457
465
|
"VectorStoreSpec",
|
|
466
|
+
"VertexProvider",
|
|
458
467
|
"__version__",
|
|
459
468
|
"agent_span",
|
|
460
469
|
"aid_attributes",
|
|
@@ -471,6 +480,7 @@ __all__ = [
|
|
|
471
480
|
"create_store",
|
|
472
481
|
"default_bedrock_base_url",
|
|
473
482
|
"default_metrics",
|
|
483
|
+
"default_vertex_base_url",
|
|
474
484
|
"embedder_for",
|
|
475
485
|
"emit_step",
|
|
476
486
|
"estimate_cost_usd",
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
"""Provider adapters.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
Azure's compatible endpoint), Anthropic's Messages API,
|
|
5
|
-
Converse API,
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
is still out of scope.
|
|
3
|
+
Four wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM
|
|
4
|
+
and Azure's compatible endpoint), Anthropic's Messages API, Amazon Bedrock's
|
|
5
|
+
Converse API, and Vertex AI's ``generateContent``. Bedrock is signed with SigV4
|
|
6
|
+
and Vertex is OAuth2-bearer, which is why neither can be an OpenAI-compatible
|
|
7
|
+
base URL. A fifth, deterministic fake serves tests and the eval-gate fixture.
|
|
9
8
|
"""
|
|
10
9
|
|
|
11
10
|
from __future__ import annotations
|
|
@@ -24,18 +23,30 @@ from aid_runtime.providers.bedrock import (
|
|
|
24
23
|
)
|
|
25
24
|
from aid_runtime.providers.fake import FakeProvider, ScriptedTurn
|
|
26
25
|
from aid_runtime.providers.http import DEFAULT_BASE_URL, OpenAICompatibleProvider
|
|
26
|
+
from aid_runtime.providers.vertex import (
|
|
27
|
+
DEFAULT_VERTEX_LOCATION,
|
|
28
|
+
METADATA_TOKEN_URL,
|
|
29
|
+
VERTEX_TOKEN_ENV,
|
|
30
|
+
VertexProvider,
|
|
31
|
+
default_vertex_base_url,
|
|
32
|
+
)
|
|
27
33
|
|
|
28
34
|
__all__ = [
|
|
29
35
|
"ANTHROPIC_VERSION",
|
|
30
36
|
"BEDROCK_SERVICE",
|
|
31
37
|
"DEFAULT_ANTHROPIC_BASE_URL",
|
|
32
38
|
"DEFAULT_BASE_URL",
|
|
39
|
+
"DEFAULT_VERTEX_LOCATION",
|
|
40
|
+
"METADATA_TOKEN_URL",
|
|
41
|
+
"VERTEX_TOKEN_ENV",
|
|
33
42
|
"AnthropicProvider",
|
|
34
43
|
"BedrockProvider",
|
|
35
44
|
"FakeProvider",
|
|
36
45
|
"OpenAICompatibleProvider",
|
|
37
46
|
"Provider",
|
|
38
47
|
"ScriptedTurn",
|
|
48
|
+
"VertexProvider",
|
|
39
49
|
"default_bedrock_base_url",
|
|
50
|
+
"default_vertex_base_url",
|
|
40
51
|
"rfc3986",
|
|
41
52
|
]
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
"""Vertex AI adapter for Gemini models.
|
|
2
|
+
|
|
3
|
+
Vertex speaks its own dialect: ``contents`` of ``parts`` rather than messages,
|
|
4
|
+
Google-shaped tool declarations, and a dedicated streaming endpoint. It is
|
|
5
|
+
authenticated with an OAuth2 bearer token, not an API key -- the token is
|
|
6
|
+
resolved once per call from an explicit value, an environment variable, or the
|
|
7
|
+
GCE metadata server that Cloud Run and Cloud Functions provide.
|
|
8
|
+
|
|
9
|
+
Deliberately no cryptography dependency: on GCP the metadata server mints the
|
|
10
|
+
token, and off GCP a developer supplies one (``gcloud auth print-access-token``).
|
|
11
|
+
A service-account JSON file would need RS256 signing, which is a dependency the
|
|
12
|
+
runtime does not otherwise carry.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from aid_runtime.errors import ProviderError, ProviderResponseError
|
|
26
|
+
from aid_runtime.types import (
|
|
27
|
+
Capability,
|
|
28
|
+
CompletionRequest,
|
|
29
|
+
CompletionResponse,
|
|
30
|
+
FinishReason,
|
|
31
|
+
Message,
|
|
32
|
+
ModelSpec,
|
|
33
|
+
StreamChunk,
|
|
34
|
+
TokenUsage,
|
|
35
|
+
ToolCall,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"DEFAULT_VERTEX_LOCATION",
|
|
40
|
+
"METADATA_TOKEN_URL",
|
|
41
|
+
"VERTEX_TOKEN_ENV",
|
|
42
|
+
"VertexProvider",
|
|
43
|
+
"default_vertex_base_url",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
DEFAULT_VERTEX_LOCATION = "us-central1"
|
|
47
|
+
METADATA_TOKEN_URL = (
|
|
48
|
+
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" # noqa: S105
|
|
49
|
+
)
|
|
50
|
+
VERTEX_TOKEN_ENV = "GOOGLE_ACCESS_TOKEN" # noqa: S105
|
|
51
|
+
|
|
52
|
+
_RETRYABLE_STATUS = frozenset({408, 409, 424, 425, 429, 500, 502, 503, 504})
|
|
53
|
+
_FINISH_REASONS: dict[str, FinishReason] = {
|
|
54
|
+
"STOP": "stop",
|
|
55
|
+
"MAX_TOKENS": "length",
|
|
56
|
+
"SAFETY": "content-filter",
|
|
57
|
+
"RECITATION": "content-filter",
|
|
58
|
+
"BLOCKLIST": "content-filter",
|
|
59
|
+
"PROHIBITED_CONTENT": "content-filter",
|
|
60
|
+
"SPII": "content-filter",
|
|
61
|
+
"MALFORMED_FUNCTION_CALL": "error",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def default_vertex_base_url(location: str) -> str:
|
|
66
|
+
return f"https://{location}-aiplatform.googleapis.com"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class VertexProvider:
|
|
70
|
+
"""Gemini on Vertex AI over ``generateContent`` / ``streamGenerateContent``."""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
*,
|
|
75
|
+
project: str | None = None,
|
|
76
|
+
location: str | None = None,
|
|
77
|
+
access_token: str | None = None,
|
|
78
|
+
base_url: str | None = None,
|
|
79
|
+
name: str = "google",
|
|
80
|
+
timeout_seconds: float = 60.0,
|
|
81
|
+
max_attempts: int = 3,
|
|
82
|
+
backoff_seconds: float = 0.5,
|
|
83
|
+
client: httpx.AsyncClient | None = None,
|
|
84
|
+
token_provider: Callable[[], Awaitable[str]] | None = None,
|
|
85
|
+
) -> None:
|
|
86
|
+
self._name = name
|
|
87
|
+
self._project = project
|
|
88
|
+
self._location = location
|
|
89
|
+
self._access_token = access_token
|
|
90
|
+
self._base_url = base_url
|
|
91
|
+
self._timeout = timeout_seconds
|
|
92
|
+
self._max_attempts = max_attempts
|
|
93
|
+
self._backoff = backoff_seconds
|
|
94
|
+
self._client = client
|
|
95
|
+
self._owns_client = client is None
|
|
96
|
+
self._token_provider = token_provider
|
|
97
|
+
self._cached_token: tuple[str, float] | None = None
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def name(self) -> str:
|
|
101
|
+
return self._name
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def capabilities(self) -> frozenset[Capability]:
|
|
105
|
+
return frozenset(
|
|
106
|
+
{Capability.STREAMING, Capability.STRUCTURED_OUTPUT, Capability.TOOL_CALLING}
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
|
|
110
|
+
body = await self._post(self._url(model, stream=False), self._build_payload(request, model))
|
|
111
|
+
return self._parse(body, model)
|
|
112
|
+
|
|
113
|
+
async def stream(
|
|
114
|
+
self, request: CompletionRequest, *, model: ModelSpec
|
|
115
|
+
) -> AsyncIterator[StreamChunk]:
|
|
116
|
+
client = self._ensure_client()
|
|
117
|
+
headers = await self._headers()
|
|
118
|
+
payload = self._build_payload(request, model)
|
|
119
|
+
url = self._url(model, stream=True)
|
|
120
|
+
|
|
121
|
+
usage: TokenUsage | None = None
|
|
122
|
+
finish: FinishReason | None = None
|
|
123
|
+
last_error: Exception | None = None
|
|
124
|
+
for attempt in range(1, self._max_attempts + 1):
|
|
125
|
+
try:
|
|
126
|
+
async with client.stream("POST", url, json=payload, headers=headers) as response:
|
|
127
|
+
if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
|
|
128
|
+
last_error = ProviderError(f"{self._name} returned {response.status_code}")
|
|
129
|
+
await response.aread()
|
|
130
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
131
|
+
continue
|
|
132
|
+
if response.status_code >= 400:
|
|
133
|
+
detail = (await response.aread()).decode("utf-8", "replace")
|
|
134
|
+
raise ProviderError(
|
|
135
|
+
f"{self._name} returned {response.status_code}: {detail[:500]}"
|
|
136
|
+
)
|
|
137
|
+
async for line in response.aiter_lines():
|
|
138
|
+
if not line.startswith("data:"):
|
|
139
|
+
continue
|
|
140
|
+
data = line[len("data:") :].strip()
|
|
141
|
+
if not data or data == "[DONE]":
|
|
142
|
+
continue
|
|
143
|
+
try:
|
|
144
|
+
chunk = json.loads(data)
|
|
145
|
+
except json.JSONDecodeError as exc:
|
|
146
|
+
raise ProviderResponseError(
|
|
147
|
+
f"{self._name} streamed non-JSON", data
|
|
148
|
+
) from exc
|
|
149
|
+
if not isinstance(chunk, dict):
|
|
150
|
+
continue
|
|
151
|
+
text, _calls, reason, chunk_usage = _read_candidate(chunk, model)
|
|
152
|
+
if chunk_usage is not None:
|
|
153
|
+
usage = chunk_usage
|
|
154
|
+
if reason is not None:
|
|
155
|
+
finish = reason
|
|
156
|
+
if text:
|
|
157
|
+
yield StreamChunk(delta=text)
|
|
158
|
+
except httpx.TransportError as exc:
|
|
159
|
+
last_error = exc
|
|
160
|
+
if attempt == self._max_attempts:
|
|
161
|
+
break
|
|
162
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
163
|
+
continue
|
|
164
|
+
else:
|
|
165
|
+
yield StreamChunk(
|
|
166
|
+
finish_reason=finish or "stop",
|
|
167
|
+
usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
|
|
168
|
+
)
|
|
169
|
+
return
|
|
170
|
+
|
|
171
|
+
raise ProviderError(
|
|
172
|
+
f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
|
|
173
|
+
) from last_error
|
|
174
|
+
|
|
175
|
+
async def aclose(self) -> None:
|
|
176
|
+
if self._client is not None and self._owns_client:
|
|
177
|
+
await self._client.aclose()
|
|
178
|
+
self._client = None
|
|
179
|
+
|
|
180
|
+
def _ensure_client(self) -> httpx.AsyncClient:
|
|
181
|
+
if self._client is None:
|
|
182
|
+
self._client = httpx.AsyncClient(timeout=self._timeout)
|
|
183
|
+
self._owns_client = True
|
|
184
|
+
return self._client
|
|
185
|
+
|
|
186
|
+
def _resolve_project(self) -> str:
|
|
187
|
+
if self._project:
|
|
188
|
+
return self._project
|
|
189
|
+
for key in ("GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "GOOGLE_PROJECT_ID"):
|
|
190
|
+
value = _env(key)
|
|
191
|
+
if value:
|
|
192
|
+
return value
|
|
193
|
+
raise ProviderError(
|
|
194
|
+
f"{self._name} needs a project: set model provider 'project' or GOOGLE_CLOUD_PROJECT"
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def _resolve_location(self) -> str:
|
|
198
|
+
if self._location:
|
|
199
|
+
return self._location
|
|
200
|
+
for key in ("GOOGLE_CLOUD_REGION", "VERTEX_LOCATION", "GOOGLE_CLOUD_LOCATION"):
|
|
201
|
+
value = _env(key)
|
|
202
|
+
if value:
|
|
203
|
+
return value
|
|
204
|
+
return DEFAULT_VERTEX_LOCATION
|
|
205
|
+
|
|
206
|
+
def _url(self, model: ModelSpec, *, stream: bool) -> str:
|
|
207
|
+
location = self._resolve_location()
|
|
208
|
+
base = (self._base_url or default_vertex_base_url(location)).rstrip("/")
|
|
209
|
+
project = self._resolve_project()
|
|
210
|
+
method = "streamGenerateContent?alt=sse" if stream else "generateContent"
|
|
211
|
+
return (
|
|
212
|
+
f"{base}/v1/projects/{project}/locations/{location}"
|
|
213
|
+
f"/publishers/google/models/{model.name}:{method}"
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
async def _token(self) -> str:
|
|
217
|
+
if self._access_token:
|
|
218
|
+
return self._access_token
|
|
219
|
+
env_token = _env(VERTEX_TOKEN_ENV) or _env("VERTEX_ACCESS_TOKEN")
|
|
220
|
+
if env_token:
|
|
221
|
+
return env_token
|
|
222
|
+
if self._cached_token is not None:
|
|
223
|
+
token, expires_at = self._cached_token
|
|
224
|
+
if expires_at - asyncio.get_running_loop().time() > 60:
|
|
225
|
+
return token
|
|
226
|
+
token, expires_in = await self._mint_token()
|
|
227
|
+
self._cached_token = (token, asyncio.get_running_loop().time() + expires_in)
|
|
228
|
+
return token
|
|
229
|
+
|
|
230
|
+
async def _mint_token(self) -> tuple[str, float]:
|
|
231
|
+
if self._token_provider is not None:
|
|
232
|
+
return await self._token_provider(), 300.0
|
|
233
|
+
|
|
234
|
+
client = self._ensure_client()
|
|
235
|
+
try:
|
|
236
|
+
response = await client.get(METADATA_TOKEN_URL, headers={"Metadata-Flavor": "Google"})
|
|
237
|
+
except httpx.TransportError as exc:
|
|
238
|
+
raise ProviderError(
|
|
239
|
+
f"{self._name} has no credentials: set {VERTEX_TOKEN_ENV} or run on GCP "
|
|
240
|
+
f"where the metadata server mints a token ({exc})"
|
|
241
|
+
) from exc
|
|
242
|
+
if response.status_code >= 400:
|
|
243
|
+
raise ProviderError(
|
|
244
|
+
f"{self._name} metadata token request returned {response.status_code}: "
|
|
245
|
+
f"{response.text[:200]}"
|
|
246
|
+
)
|
|
247
|
+
try:
|
|
248
|
+
body = response.json()
|
|
249
|
+
except json.JSONDecodeError as exc:
|
|
250
|
+
raise ProviderResponseError(
|
|
251
|
+
f"{self._name} metadata token is not JSON", response.text
|
|
252
|
+
) from exc
|
|
253
|
+
token = body.get("access_token") if isinstance(body, dict) else None
|
|
254
|
+
if not isinstance(token, str) or not token:
|
|
255
|
+
raise ProviderResponseError(
|
|
256
|
+
f"{self._name} metadata response had no access_token", response.text
|
|
257
|
+
)
|
|
258
|
+
expires_in = body.get("expires_in", 300)
|
|
259
|
+
return token, float(expires_in) if isinstance(expires_in, (int, float)) else 300.0
|
|
260
|
+
|
|
261
|
+
async def _headers(self) -> dict[str, str]:
|
|
262
|
+
return {
|
|
263
|
+
"authorization": f"Bearer {await self._token()}",
|
|
264
|
+
"content-type": "application/json",
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
def _build_payload(self, request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
|
|
268
|
+
generation_config: dict[str, Any] = {"maxOutputTokens": _max_tokens(request, model)}
|
|
269
|
+
if request.temperature is not None:
|
|
270
|
+
generation_config["temperature"] = request.temperature
|
|
271
|
+
if request.stop:
|
|
272
|
+
generation_config["stopSequences"] = list(request.stop)
|
|
273
|
+
payload: dict[str, Any] = {
|
|
274
|
+
"contents": _wire_contents(request.messages),
|
|
275
|
+
"generationConfig": generation_config,
|
|
276
|
+
}
|
|
277
|
+
system = _system_prompt(request.messages)
|
|
278
|
+
if system:
|
|
279
|
+
payload["systemInstruction"] = {"parts": [{"text": system}]}
|
|
280
|
+
if request.tools:
|
|
281
|
+
payload["tools"] = [
|
|
282
|
+
{
|
|
283
|
+
"functionDeclarations": [
|
|
284
|
+
{
|
|
285
|
+
"name": tool.name,
|
|
286
|
+
"description": tool.description,
|
|
287
|
+
"parameters": tool.parameters or {"type": "object", "properties": {}},
|
|
288
|
+
}
|
|
289
|
+
for tool in request.tools
|
|
290
|
+
]
|
|
291
|
+
}
|
|
292
|
+
]
|
|
293
|
+
return payload
|
|
294
|
+
|
|
295
|
+
async def _post(self, url: str, payload: dict[str, Any]) -> str:
|
|
296
|
+
client = self._ensure_client()
|
|
297
|
+
headers = await self._headers()
|
|
298
|
+
last_error: Exception | None = None
|
|
299
|
+
for attempt in range(1, self._max_attempts + 1):
|
|
300
|
+
try:
|
|
301
|
+
response = await client.post(url, json=payload, headers=headers)
|
|
302
|
+
except httpx.TransportError as exc:
|
|
303
|
+
last_error = exc
|
|
304
|
+
if attempt == self._max_attempts:
|
|
305
|
+
break
|
|
306
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
307
|
+
continue
|
|
308
|
+
|
|
309
|
+
if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
|
|
310
|
+
last_error = ProviderError(
|
|
311
|
+
f"{self._name} returned {response.status_code}: {response.text[:500]}"
|
|
312
|
+
)
|
|
313
|
+
await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
|
|
314
|
+
continue
|
|
315
|
+
|
|
316
|
+
if response.status_code >= 400:
|
|
317
|
+
raise ProviderError(
|
|
318
|
+
f"{self._name} returned {response.status_code}: {response.text[:500]}"
|
|
319
|
+
)
|
|
320
|
+
return response.text
|
|
321
|
+
|
|
322
|
+
raise ProviderError(
|
|
323
|
+
f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
|
|
324
|
+
) from last_error
|
|
325
|
+
|
|
326
|
+
def _parse(self, text: str, model: ModelSpec) -> CompletionResponse:
|
|
327
|
+
try:
|
|
328
|
+
body = json.loads(text)
|
|
329
|
+
except json.JSONDecodeError as exc:
|
|
330
|
+
raise ProviderResponseError(
|
|
331
|
+
f"{self._name} returned a body that is not JSON", text
|
|
332
|
+
) from exc
|
|
333
|
+
if not isinstance(body, dict):
|
|
334
|
+
raise ProviderResponseError(
|
|
335
|
+
f"{self._name} returned a JSON body that is not an object", text
|
|
336
|
+
)
|
|
337
|
+
result, calls, reason, usage = _read_candidate(body, model)
|
|
338
|
+
if result == "" and not calls and reason is None:
|
|
339
|
+
raise ProviderResponseError(f"{self._name} returned no candidates", text)
|
|
340
|
+
return CompletionResponse(
|
|
341
|
+
text=result,
|
|
342
|
+
model=model.name,
|
|
343
|
+
provider=self._name,
|
|
344
|
+
usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
|
|
345
|
+
tool_calls=tuple(calls),
|
|
346
|
+
finish_reason=reason or ("tool-calls" if calls else "stop"),
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _read_candidate(
|
|
351
|
+
body: dict[str, Any], model: ModelSpec
|
|
352
|
+
) -> tuple[str, list[ToolCall], FinishReason | None, TokenUsage | None]:
|
|
353
|
+
"""Read the first candidate into text, calls, finish reason and usage."""
|
|
354
|
+
candidates = body.get("candidates")
|
|
355
|
+
candidate = candidates[0] if isinstance(candidates, list) and candidates else None
|
|
356
|
+
content = candidate.get("content") if isinstance(candidate, dict) else None
|
|
357
|
+
parts = content.get("parts") if isinstance(content, dict) else None
|
|
358
|
+
|
|
359
|
+
text_parts: list[str] = []
|
|
360
|
+
calls: list[ToolCall] = []
|
|
361
|
+
if isinstance(parts, list):
|
|
362
|
+
for index, part in enumerate(parts):
|
|
363
|
+
if not isinstance(part, dict):
|
|
364
|
+
continue
|
|
365
|
+
value = part.get("text")
|
|
366
|
+
if isinstance(value, str):
|
|
367
|
+
text_parts.append(value)
|
|
368
|
+
continue
|
|
369
|
+
call = part.get("functionCall")
|
|
370
|
+
if not isinstance(call, dict):
|
|
371
|
+
continue
|
|
372
|
+
name = call.get("name")
|
|
373
|
+
if not isinstance(name, str) or not name:
|
|
374
|
+
continue
|
|
375
|
+
arguments = call.get("args")
|
|
376
|
+
calls.append(
|
|
377
|
+
ToolCall(
|
|
378
|
+
id=f"{model.name}-call-{index}",
|
|
379
|
+
name=name,
|
|
380
|
+
arguments=arguments if isinstance(arguments, dict) else {},
|
|
381
|
+
)
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
reason: FinishReason | None = None
|
|
385
|
+
raw_reason = candidate.get("finishReason") if isinstance(candidate, dict) else None
|
|
386
|
+
if isinstance(raw_reason, str):
|
|
387
|
+
reason = _FINISH_REASONS.get(raw_reason, "stop")
|
|
388
|
+
|
|
389
|
+
usage: TokenUsage | None = None
|
|
390
|
+
raw_usage = body.get("usageMetadata")
|
|
391
|
+
if isinstance(raw_usage, dict):
|
|
392
|
+
usage = TokenUsage(
|
|
393
|
+
input_tokens=int(raw_usage.get("promptTokenCount") or 0),
|
|
394
|
+
output_tokens=int(raw_usage.get("candidatesTokenCount") or 0),
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
# Gemini reports the reason alongside the call; the call is the better signal.
|
|
398
|
+
if calls and reason in (None, "stop"):
|
|
399
|
+
reason = "tool-calls"
|
|
400
|
+
return "".join(text_parts), calls, reason, usage
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _wire_contents(messages: tuple[Message, ...]) -> list[dict[str, Any]]:
|
|
404
|
+
contents: list[dict[str, Any]] = []
|
|
405
|
+
for message in messages:
|
|
406
|
+
if message.role == "system":
|
|
407
|
+
continue
|
|
408
|
+
if message.role == "tool":
|
|
409
|
+
contents.append(
|
|
410
|
+
{
|
|
411
|
+
"role": "user",
|
|
412
|
+
"parts": [
|
|
413
|
+
{
|
|
414
|
+
"functionResponse": {
|
|
415
|
+
"name": message.name or "tool",
|
|
416
|
+
"response": {"content": message.content},
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
],
|
|
420
|
+
}
|
|
421
|
+
)
|
|
422
|
+
continue
|
|
423
|
+
parts: list[dict[str, Any]] = []
|
|
424
|
+
if message.content:
|
|
425
|
+
parts.append({"text": message.content})
|
|
426
|
+
for call in message.tool_calls:
|
|
427
|
+
parts.append({"functionCall": {"name": call.name, "args": call.arguments}})
|
|
428
|
+
if not parts:
|
|
429
|
+
parts.append({"text": ""})
|
|
430
|
+
contents.append(
|
|
431
|
+
{"role": "model" if message.role == "assistant" else "user", "parts": parts}
|
|
432
|
+
)
|
|
433
|
+
return contents
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _system_prompt(messages: tuple[Message, ...]) -> str:
|
|
437
|
+
return "\n".join(message.content for message in messages if message.role == "system")
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _max_tokens(request: CompletionRequest, model: ModelSpec) -> int:
|
|
441
|
+
if request.max_output_tokens is not None:
|
|
442
|
+
return min(request.max_output_tokens, model.max_output_tokens)
|
|
443
|
+
return model.max_output_tokens
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _env(key: str) -> str | None:
|
|
447
|
+
value = os.environ.get(key)
|
|
448
|
+
return value if value else None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: aid-runtime-python
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.82
|
|
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=
|
|
1
|
+
aid_runtime/__init__.py,sha256=zH-EyRU5G4y8QkFjbvX87PWtYBk_R_RE9yMbi1N9GQs,11863
|
|
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,12 +30,13 @@ 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=
|
|
33
|
+
aid_runtime/providers/__init__.py,sha256=5PA3A5IRabcxYS0r75Byol2RHcC4ZZ3gi-boJV0sjWQ,1516
|
|
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
36
|
aid_runtime/providers/bedrock.py,sha256=WkfWFg94kLFJ9q04CEkXCc-HqoVqHivAmhy511-WtIA,20834
|
|
37
37
|
aid_runtime/providers/fake.py,sha256=oAcpaDOUIp7lmKGEEWG5ktagstg2dvoHR-9xaUeCDLo,9526
|
|
38
38
|
aid_runtime/providers/http.py,sha256=c5DLmX1FqtAUO01MqDf0m82x8zHD480LyL-QtTrxnn4,13168
|
|
39
|
+
aid_runtime/providers/vertex.py,sha256=u5qqSIZeT19plVEPR1p3bpcTtSv2IwMOK2X45fXlic4,17505
|
|
39
40
|
aid_runtime/retrieval/__init__.py,sha256=LR6qyiE7pY9QsB1h4g9j1W7acpSINFbgxA9U1otLt90,4580
|
|
40
41
|
aid_runtime/retrieval/chunking.py,sha256=GMJvY1GoIua-FkpCH1S5qNmUrWSaSbl6sBJPCrSDAg4,8296
|
|
41
42
|
aid_runtime/retrieval/citations.py,sha256=UL9fsxLTzzO0n8tEW3X2O5erJ0hrk08NYMkZ9Pk8Jdg,4287
|
|
@@ -49,7 +50,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
|
|
|
49
50
|
aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
|
|
50
51
|
aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
|
|
51
52
|
aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
|
|
52
|
-
aid_runtime_python-0.1.
|
|
53
|
-
aid_runtime_python-0.1.
|
|
54
|
-
aid_runtime_python-0.1.
|
|
55
|
-
aid_runtime_python-0.1.
|
|
53
|
+
aid_runtime_python-0.1.82.dist-info/METADATA,sha256=4XO4BSLJymw21lxHHVeIafZNtwCsnMYaQ1pj5oP9Ccc,15559
|
|
54
|
+
aid_runtime_python-0.1.82.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
55
|
+
aid_runtime_python-0.1.82.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
|
|
56
|
+
aid_runtime_python-0.1.82.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|