aid-runtime-python 0.1.96__py3-none-any.whl → 0.1.97__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
@@ -160,12 +160,15 @@ from aid_runtime.providers import (
160
160
  BEDROCK_SERVICE,
161
161
  DEFAULT_ANTHROPIC_BASE_URL,
162
162
  DEFAULT_BASE_URL,
163
+ DEFAULT_GEMINI_BASE_URL,
163
164
  DEFAULT_VERTEX_LOCATION,
165
+ GEMINI_API_KEY_ENV,
164
166
  METADATA_TOKEN_URL,
165
167
  VERTEX_TOKEN_ENV,
166
168
  AnthropicProvider,
167
169
  BedrockProvider,
168
170
  FakeProvider,
171
+ GeminiProvider,
169
172
  OpenAICompatibleProvider,
170
173
  Provider,
171
174
  ScriptedTurn,
@@ -191,6 +194,7 @@ from aid_runtime.retrieval import (
191
194
  FakeDeterministicEmbedder,
192
195
  FileConnector,
193
196
  FixedChunker,
197
+ GeminiEmbedder,
194
198
  IndexSpec,
195
199
  IngestReport,
196
200
  InMemoryVectorStore,
@@ -297,7 +301,7 @@ from aid_runtime.types import (
297
301
  )
298
302
 
299
303
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
300
- __version__ = "0.1.96"
304
+ __version__ = "0.1.97"
301
305
 
302
306
  __all__ = [
303
307
  "ANTHROPIC_VERSION",
@@ -306,10 +310,12 @@ __all__ = [
306
310
  "DEFAULT_ANTHROPIC_BASE_URL",
307
311
  "DEFAULT_BASE_URL",
308
312
  "DEFAULT_CANDIDATE_FACTOR",
313
+ "DEFAULT_GEMINI_BASE_URL",
309
314
  "DEFAULT_TYPESAFE_BASE_URL",
310
315
  "DEFAULT_VERTEX_LOCATION",
311
316
  "DEPTH_KEY",
312
317
  "EMITTED_KEY",
318
+ "GEMINI_API_KEY_ENV",
313
319
  "GEN_AI_OPERATION_CHAT",
314
320
  "INDEX_KEY",
315
321
  "ITEM_KEY",
@@ -387,6 +393,8 @@ __all__ = [
387
393
  "GateConfigurationError",
388
394
  "GateResult",
389
395
  "GatewayRunner",
396
+ "GeminiEmbedder",
397
+ "GeminiProvider",
390
398
  "GenerationResult",
391
399
  "GuardrailBlockedError",
392
400
  "HumanApproval",
@@ -1,10 +1,12 @@
1
1
  """Provider adapters.
2
2
 
3
- Four wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM
3
+ Five wire dialects ship: OpenAI-compatible (which covers vLLM, Ollama, LiteLLM
4
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.
5
+ Converse API, and Gemini's ``generateContent`` -- which the Vertex AI adapter
6
+ serves over an OAuth2 bearer token and the Gemini API adapter serves with one API
7
+ key. Bedrock is signed with SigV4 and Vertex is OAuth2-bearer, which is why
8
+ neither can be an OpenAI-compatible base URL. A sixth, deterministic fake serves
9
+ tests and the eval-gate fixture.
8
10
  """
9
11
 
10
12
  from __future__ import annotations
@@ -22,6 +24,11 @@ from aid_runtime.providers.bedrock import (
22
24
  rfc3986,
23
25
  )
24
26
  from aid_runtime.providers.fake import FakeProvider, ScriptedTurn
27
+ from aid_runtime.providers.gemini import (
28
+ DEFAULT_GEMINI_BASE_URL,
29
+ GEMINI_API_KEY_ENV,
30
+ GeminiProvider,
31
+ )
25
32
  from aid_runtime.providers.http import DEFAULT_BASE_URL, OpenAICompatibleProvider
26
33
  from aid_runtime.providers.vertex import (
27
34
  DEFAULT_VERTEX_LOCATION,
@@ -36,12 +43,15 @@ __all__ = [
36
43
  "BEDROCK_SERVICE",
37
44
  "DEFAULT_ANTHROPIC_BASE_URL",
38
45
  "DEFAULT_BASE_URL",
46
+ "DEFAULT_GEMINI_BASE_URL",
39
47
  "DEFAULT_VERTEX_LOCATION",
48
+ "GEMINI_API_KEY_ENV",
40
49
  "METADATA_TOKEN_URL",
41
50
  "VERTEX_TOKEN_ENV",
42
51
  "AnthropicProvider",
43
52
  "BedrockProvider",
44
53
  "FakeProvider",
54
+ "GeminiProvider",
45
55
  "OpenAICompatibleProvider",
46
56
  "Provider",
47
57
  "ScriptedTurn",
@@ -0,0 +1,113 @@
1
+ """Gemini API adapter -- the public Gemini service, not Vertex AI.
2
+
3
+ Same wire as Vertex (``contents`` of ``parts``, ``functionDeclarations``,
4
+ ``systemInstruction``), so the translation lives in ``gemini_wire``. What differs is
5
+ everything around it: one API key instead of an OAuth2 token, a fixed host with no
6
+ project or location, and the ``v1beta`` endpoint.
7
+
8
+ The API key travels in ``x-goog-api-key`` rather than a query string. Google's own
9
+ docs offer ``?key=`` as well, but a query string ends up in access logs, proxy
10
+ history and error reports far more readily than a header does.
11
+
12
+ A wrong key comes back as ``400 FAILED_PRECONDITION``, so 400 is never retried.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+
19
+ import httpx
20
+
21
+ from aid_runtime.errors import ProviderError, ProviderResponseError
22
+ from aid_runtime.providers.gemini_wire import (
23
+ GeminiWireClient,
24
+ build_payload,
25
+ decode_body,
26
+ read_candidate,
27
+ )
28
+ from aid_runtime.types import (
29
+ Capability,
30
+ CompletionRequest,
31
+ CompletionResponse,
32
+ ModelSpec,
33
+ TokenUsage,
34
+ )
35
+
36
+ __all__ = ["DEFAULT_GEMINI_BASE_URL", "GEMINI_API_KEY_ENV", "GeminiProvider"]
37
+
38
+ DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com"
39
+ GEMINI_API_KEY_ENV = "GEMINI_API_KEY"
40
+
41
+
42
+ class GeminiProvider(GeminiWireClient):
43
+ """Gemini over ``generateContent`` / ``streamGenerateContent``.
44
+
45
+ ``DEFAULT_RETRYABLE_STATUS`` deliberately omits 400: this service answers
46
+ ``400 FAILED_PRECONDITION`` for a bad API key, and retrying that only spends money.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ *,
52
+ api_key: str | None = None,
53
+ base_url: str | None = None,
54
+ name: str = "gemini",
55
+ timeout_seconds: float = 60.0,
56
+ max_attempts: int = 3,
57
+ backoff_seconds: float = 0.5,
58
+ client: httpx.AsyncClient | None = None,
59
+ ) -> None:
60
+ super().__init__(
61
+ name=name,
62
+ timeout_seconds=timeout_seconds,
63
+ max_attempts=max_attempts,
64
+ backoff_seconds=backoff_seconds,
65
+ client=client,
66
+ )
67
+ self._api_key = api_key
68
+ self._base_url = base_url
69
+
70
+ @property
71
+ def capabilities(self) -> frozenset[Capability]:
72
+ return frozenset(
73
+ {Capability.STREAMING, Capability.STRUCTURED_OUTPUT, Capability.TOOL_CALLING}
74
+ )
75
+
76
+ async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
77
+ body = await self._post(self._url(model, stream=False), build_payload(request, model))
78
+ return self._parse(body, model)
79
+
80
+ def _url(self, model: ModelSpec, *, stream: bool) -> str:
81
+ base = (self._base_url or DEFAULT_GEMINI_BASE_URL).rstrip("/")
82
+ method = "streamGenerateContent?alt=sse" if stream else "generateContent"
83
+ return f"{base}/v1beta/models/{model.name}:{method}"
84
+
85
+ async def _headers(self) -> dict[str, str]:
86
+ return {
87
+ "x-goog-api-key": self._key(),
88
+ "content-type": "application/json",
89
+ }
90
+
91
+ def _key(self) -> str:
92
+ if self._api_key:
93
+ return self._api_key
94
+ env_key = os.environ.get(GEMINI_API_KEY_ENV)
95
+ if env_key:
96
+ return env_key
97
+ raise ProviderError(
98
+ f"{self._name} has no API key: set model provider 'apiKeyEnv' or {GEMINI_API_KEY_ENV}"
99
+ )
100
+
101
+ def _parse(self, text: str, model: ModelSpec) -> CompletionResponse:
102
+ body = decode_body(text, self._name)
103
+ result, calls, reason, usage = read_candidate(body, model)
104
+ if result == "" and not calls and reason is None:
105
+ raise ProviderResponseError(f"{self._name} returned no candidates", text)
106
+ return CompletionResponse(
107
+ text=result,
108
+ model=model.name,
109
+ provider=self._name,
110
+ usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
111
+ tool_calls=tuple(calls),
112
+ finish_reason=reason or ("tool-calls" if calls else "stop"),
113
+ )
@@ -0,0 +1,345 @@
1
+ """The Gemini wire dialect shared by the Vertex and Gemini API adapters.
2
+
3
+ Both services take the same request body -- ``contents`` of ``parts``, Google-shaped
4
+ tool declarations, ``systemInstruction``, ``generationConfig`` -- and answer with the
5
+ same ``candidates`` and ``usageMetadata``. They differ only in the endpoint, the
6
+ credentials and the embedding method, so the translation and the retry loop live here
7
+ once and each adapter supplies its URL and auth headers. A test builds one request
8
+ through both adapters and asserts the bodies are byte-identical, which is what keeps
9
+ these functions honest.
10
+
11
+ This module is internal: it is not re-exported from ``aid_runtime``.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import json
18
+ from collections.abc import AsyncIterator
19
+ from typing import Any
20
+
21
+ import httpx
22
+
23
+ from aid_runtime.errors import ProviderError, ProviderResponseError
24
+ from aid_runtime.types import (
25
+ CompletionRequest,
26
+ FinishReason,
27
+ Message,
28
+ ModelSpec,
29
+ StreamChunk,
30
+ TokenUsage,
31
+ ToolCall,
32
+ )
33
+
34
+ __all__ = [
35
+ "DEFAULT_RETRYABLE_STATUS",
36
+ "GeminiWireClient",
37
+ "build_payload",
38
+ "decode_body",
39
+ "finish_reason",
40
+ "read_candidate",
41
+ "system_prompt",
42
+ "usage",
43
+ "wire_contents",
44
+ ]
45
+
46
+ DEFAULT_RETRYABLE_STATUS = frozenset({408, 409, 424, 425, 429, 500, 502, 503, 504})
47
+
48
+ FINISH_REASONS: dict[str, FinishReason] = {
49
+ "STOP": "stop",
50
+ "MAX_TOKENS": "length",
51
+ "SAFETY": "content-filter",
52
+ "RECITATION": "content-filter",
53
+ "BLOCKLIST": "content-filter",
54
+ "PROHIBITED_CONTENT": "content-filter",
55
+ "SPII": "content-filter",
56
+ "MALFORMED_FUNCTION_CALL": "error",
57
+ }
58
+
59
+
60
+ def build_payload(request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
61
+ """Translate a completion request into the body both Gemini endpoints accept."""
62
+ generation_config: dict[str, Any] = {"maxOutputTokens": _max_tokens(request, model)}
63
+ if request.temperature is not None:
64
+ generation_config["temperature"] = request.temperature
65
+ if request.stop:
66
+ generation_config["stopSequences"] = list(request.stop)
67
+ payload: dict[str, Any] = {
68
+ "contents": wire_contents(request.messages),
69
+ "generationConfig": generation_config,
70
+ }
71
+ system = system_prompt(request.messages)
72
+ if system:
73
+ payload["systemInstruction"] = {"parts": [{"text": system}]}
74
+ if request.tools:
75
+ payload["tools"] = [
76
+ {
77
+ "functionDeclarations": [
78
+ {
79
+ "name": tool.name,
80
+ "description": tool.description,
81
+ "parameters": tool.parameters or {"type": "object", "properties": {}},
82
+ }
83
+ for tool in request.tools
84
+ ]
85
+ }
86
+ ]
87
+ return payload
88
+
89
+
90
+ def wire_contents(messages: tuple[Message, ...]) -> list[dict[str, Any]]:
91
+ """Render the message list as ``contents``; system turns move to ``systemInstruction``."""
92
+ contents: list[dict[str, Any]] = []
93
+ for message in messages:
94
+ if message.role == "system":
95
+ continue
96
+ if message.role == "tool":
97
+ contents.append(
98
+ {
99
+ "role": "user",
100
+ "parts": [
101
+ {
102
+ "functionResponse": {
103
+ "name": message.name or "tool",
104
+ "response": {"content": message.content},
105
+ }
106
+ }
107
+ ],
108
+ }
109
+ )
110
+ continue
111
+ parts: list[dict[str, Any]] = []
112
+ if message.content:
113
+ parts.append({"text": message.content})
114
+ for call in message.tool_calls:
115
+ parts.append({"functionCall": {"name": call.name, "args": call.arguments}})
116
+ if not parts:
117
+ parts.append({"text": ""})
118
+ contents.append(
119
+ {"role": "model" if message.role == "assistant" else "user", "parts": parts}
120
+ )
121
+ return contents
122
+
123
+
124
+ def system_prompt(messages: tuple[Message, ...]) -> str:
125
+ return "\n".join(message.content for message in messages if message.role == "system")
126
+
127
+
128
+ def finish_reason(raw: str) -> FinishReason:
129
+ return FINISH_REASONS.get(raw, "stop")
130
+
131
+
132
+ def usage(body: dict[str, Any]) -> TokenUsage | None:
133
+ raw = body.get("usageMetadata")
134
+ if not isinstance(raw, dict):
135
+ return None
136
+ return TokenUsage(
137
+ input_tokens=int(raw.get("promptTokenCount") or 0),
138
+ output_tokens=int(raw.get("candidatesTokenCount") or 0),
139
+ )
140
+
141
+
142
+ def read_candidate(
143
+ body: dict[str, Any], model: ModelSpec
144
+ ) -> tuple[str, list[ToolCall], FinishReason | None, TokenUsage | None]:
145
+ """Read the first candidate into text, calls, finish reason and usage."""
146
+ candidates = body.get("candidates")
147
+ candidate = candidates[0] if isinstance(candidates, list) and candidates else None
148
+ content = candidate.get("content") if isinstance(candidate, dict) else None
149
+ parts = content.get("parts") if isinstance(content, dict) else None
150
+
151
+ text_parts: list[str] = []
152
+ calls: list[ToolCall] = []
153
+ if isinstance(parts, list):
154
+ for index, part in enumerate(parts):
155
+ if not isinstance(part, dict):
156
+ continue
157
+ value = part.get("text")
158
+ if isinstance(value, str):
159
+ text_parts.append(value)
160
+ continue
161
+ call = part.get("functionCall")
162
+ if not isinstance(call, dict):
163
+ continue
164
+ name = call.get("name")
165
+ if not isinstance(name, str) or not name:
166
+ continue
167
+ arguments = call.get("args")
168
+ calls.append(
169
+ ToolCall(
170
+ id=f"{model.name}-call-{index}",
171
+ name=name,
172
+ arguments=arguments if isinstance(arguments, dict) else {},
173
+ )
174
+ )
175
+
176
+ reason: FinishReason | None = None
177
+ raw_reason = candidate.get("finishReason") if isinstance(candidate, dict) else None
178
+ if isinstance(raw_reason, str):
179
+ reason = finish_reason(raw_reason)
180
+
181
+ # Gemini reports the reason alongside the call; the call is the better signal.
182
+ if calls and reason in (None, "stop"):
183
+ reason = "tool-calls"
184
+ return "".join(text_parts), calls, reason, usage(body)
185
+
186
+
187
+ def decode_body(text: str, provider: str) -> dict[str, Any]:
188
+ """Parse a non-streamed body, refusing anything that is not a JSON object."""
189
+ try:
190
+ body = json.loads(text)
191
+ except json.JSONDecodeError as exc:
192
+ raise ProviderResponseError(f"{provider} returned a body that is not JSON", text) from exc
193
+ if not isinstance(body, dict):
194
+ raise ProviderResponseError(f"{provider} returned a JSON body that is not an object", text)
195
+ return body
196
+
197
+
198
+ def _max_tokens(request: CompletionRequest, model: ModelSpec) -> int:
199
+ if request.max_output_tokens is not None:
200
+ return min(request.max_output_tokens, model.max_output_tokens)
201
+ return model.max_output_tokens
202
+
203
+
204
+ class GeminiWireClient:
205
+ """The HTTP half of the Gemini dialect; adapters supply ``_url`` and ``_headers``.
206
+
207
+ The retry policy is per adapter because a status means different things to each
208
+ service: a transport failure or a 429 is worth another attempt on both, but the
209
+ Gemini API also answers ``400 FAILED_PRECONDITION`` for a bad key, so callers must
210
+ be able to narrow ``_retryable_status`` without touching this loop.
211
+ """
212
+
213
+ def __init__(
214
+ self,
215
+ *,
216
+ name: str,
217
+ timeout_seconds: float = 60.0,
218
+ max_attempts: int = 3,
219
+ backoff_seconds: float = 0.5,
220
+ client: httpx.AsyncClient | None = None,
221
+ ) -> None:
222
+ self._name = name
223
+ self._timeout = timeout_seconds
224
+ self._max_attempts = max_attempts
225
+ self._backoff = backoff_seconds
226
+ self._client = client
227
+ self._owns_client = client is None
228
+ self._retryable_status = DEFAULT_RETRYABLE_STATUS
229
+
230
+ @property
231
+ def name(self) -> str:
232
+ return self._name
233
+
234
+ async def aclose(self) -> None:
235
+ if self._client is not None and self._owns_client:
236
+ await self._client.aclose()
237
+ self._client = None
238
+
239
+ def _ensure_client(self) -> httpx.AsyncClient:
240
+ if self._client is None:
241
+ self._client = httpx.AsyncClient(timeout=self._timeout)
242
+ self._owns_client = True
243
+ return self._client
244
+
245
+ def _url(self, model: ModelSpec, *, stream: bool) -> str:
246
+ raise NotImplementedError
247
+
248
+ async def _headers(self) -> dict[str, str]:
249
+ raise NotImplementedError
250
+
251
+ async def stream(
252
+ self, request: CompletionRequest, *, model: ModelSpec
253
+ ) -> AsyncIterator[StreamChunk]:
254
+ client = self._ensure_client()
255
+ headers = await self._headers()
256
+ payload = build_payload(request, model)
257
+ url = self._url(model, stream=True)
258
+
259
+ usage: TokenUsage | None = None
260
+ finish: FinishReason | None = None
261
+ last_error: Exception | None = None
262
+ for attempt in range(1, self._max_attempts + 1):
263
+ try:
264
+ async with client.stream("POST", url, json=payload, headers=headers) as response:
265
+ if (
266
+ response.status_code in self._retryable_status
267
+ and attempt < self._max_attempts
268
+ ):
269
+ last_error = ProviderError(f"{self._name} returned {response.status_code}")
270
+ await response.aread()
271
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
272
+ continue
273
+ if response.status_code >= 400:
274
+ detail = (await response.aread()).decode("utf-8", "replace")
275
+ raise ProviderError(
276
+ f"{self._name} returned {response.status_code}: {detail[:500]}"
277
+ )
278
+ async for line in response.aiter_lines():
279
+ if not line.startswith("data:"):
280
+ continue
281
+ data = line[len("data:") :].strip()
282
+ if not data or data == "[DONE]":
283
+ continue
284
+ try:
285
+ chunk = json.loads(data)
286
+ except json.JSONDecodeError as exc:
287
+ raise ProviderResponseError(
288
+ f"{self._name} streamed non-JSON", data
289
+ ) from exc
290
+ if not isinstance(chunk, dict):
291
+ continue
292
+ text, _calls, reason, chunk_usage = read_candidate(chunk, model)
293
+ if chunk_usage is not None:
294
+ usage = chunk_usage
295
+ if reason is not None:
296
+ finish = reason
297
+ if text:
298
+ yield StreamChunk(delta=text)
299
+ except httpx.TransportError as exc:
300
+ last_error = exc
301
+ if attempt == self._max_attempts:
302
+ break
303
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
304
+ continue
305
+ else:
306
+ yield StreamChunk(
307
+ finish_reason=finish or "stop",
308
+ usage=usage or TokenUsage(input_tokens=0, output_tokens=0),
309
+ )
310
+ return
311
+
312
+ raise ProviderError(
313
+ f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
314
+ ) from last_error
315
+
316
+ async def _post(self, url: str, payload: dict[str, Any]) -> str:
317
+ client = self._ensure_client()
318
+ headers = await self._headers()
319
+ last_error: Exception | None = None
320
+ for attempt in range(1, self._max_attempts + 1):
321
+ try:
322
+ response = await client.post(url, json=payload, headers=headers)
323
+ except httpx.TransportError as exc:
324
+ last_error = exc
325
+ if attempt == self._max_attempts:
326
+ break
327
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
328
+ continue
329
+
330
+ if response.status_code in self._retryable_status and attempt < self._max_attempts:
331
+ last_error = ProviderError(
332
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
333
+ )
334
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
335
+ continue
336
+
337
+ if response.status_code >= 400:
338
+ raise ProviderError(
339
+ f"{self._name} returned {response.status_code}: {response.text[:500]}"
340
+ )
341
+ return response.text
342
+
343
+ raise ProviderError(
344
+ f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
345
+ ) from last_error
@@ -1,8 +1,11 @@
1
1
  """Vertex AI adapter for Gemini models.
2
2
 
3
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
4
+ Google-shaped tool declarations, and a dedicated streaming endpoint. That wire
5
+ translation is shared with the Gemini API adapter in ``gemini_wire``; this module
6
+ keeps only what is Vertex-specific -- the project/location URL and the OAuth2 token.
7
+
8
+ It is authenticated with an OAuth2 bearer token, not an API key -- the token is
6
9
  resolved once per call from an explicit value, an environment variable, or the
7
10
  GCE metadata server that Cloud Run and Cloud Functions provide.
8
11
 
@@ -17,22 +20,23 @@ from __future__ import annotations
17
20
  import asyncio
18
21
  import json
19
22
  import os
20
- from collections.abc import AsyncIterator, Awaitable, Callable
21
- from typing import Any
23
+ from collections.abc import Awaitable, Callable
22
24
 
23
25
  import httpx
24
26
 
25
27
  from aid_runtime.errors import ProviderError, ProviderResponseError
28
+ from aid_runtime.providers.gemini_wire import (
29
+ GeminiWireClient,
30
+ build_payload,
31
+ decode_body,
32
+ read_candidate,
33
+ )
26
34
  from aid_runtime.types import (
27
35
  Capability,
28
36
  CompletionRequest,
29
37
  CompletionResponse,
30
- FinishReason,
31
- Message,
32
38
  ModelSpec,
33
- StreamChunk,
34
39
  TokenUsage,
35
- ToolCall,
36
40
  )
37
41
 
38
42
  __all__ = [
@@ -49,24 +53,12 @@ METADATA_TOKEN_URL = (
49
53
  )
50
54
  VERTEX_TOKEN_ENV = "GOOGLE_ACCESS_TOKEN" # noqa: S105
51
55
 
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
56
 
65
57
  def default_vertex_base_url(location: str) -> str:
66
58
  return f"https://{location}-aiplatform.googleapis.com"
67
59
 
68
60
 
69
- class VertexProvider:
61
+ class VertexProvider(GeminiWireClient):
70
62
  """Gemini on Vertex AI over ``generateContent`` / ``streamGenerateContent``."""
71
63
 
72
64
  def __init__(
@@ -83,23 +75,20 @@ class VertexProvider:
83
75
  client: httpx.AsyncClient | None = None,
84
76
  token_provider: Callable[[], Awaitable[str]] | None = None,
85
77
  ) -> None:
86
- self._name = name
78
+ super().__init__(
79
+ name=name,
80
+ timeout_seconds=timeout_seconds,
81
+ max_attempts=max_attempts,
82
+ backoff_seconds=backoff_seconds,
83
+ client=client,
84
+ )
87
85
  self._project = project
88
86
  self._location = location
89
87
  self._access_token = access_token
90
88
  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
89
  self._token_provider = token_provider
97
90
  self._cached_token: tuple[str, float] | None = None
98
91
 
99
- @property
100
- def name(self) -> str:
101
- return self._name
102
-
103
92
  @property
104
93
  def capabilities(self) -> frozenset[Capability]:
105
94
  return frozenset(
@@ -107,82 +96,9 @@ class VertexProvider:
107
96
  )
108
97
 
109
98
  async def complete(self, request: CompletionRequest, *, model: ModelSpec) -> CompletionResponse:
110
- body = await self._post(self._url(model, stream=False), self._build_payload(request, model))
99
+ body = await self._post(self._url(model, stream=False), build_payload(request, model))
111
100
  return self._parse(body, model)
112
101
 
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
102
  def _resolve_project(self) -> str:
187
103
  if self._project:
188
104
  return self._project
@@ -264,77 +180,9 @@ class VertexProvider:
264
180
  "content-type": "application/json",
265
181
  }
266
182
 
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
183
  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)
184
+ body = decode_body(text, self._name)
185
+ result, calls, reason, usage = read_candidate(body, model)
338
186
  if result == "" and not calls and reason is None:
339
187
  raise ProviderResponseError(f"{self._name} returned no candidates", text)
340
188
  return CompletionResponse(
@@ -347,102 +195,6 @@ class VertexProvider:
347
195
  )
348
196
 
349
197
 
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
198
  def _env(key: str) -> str | None:
447
199
  value = os.environ.get(key)
448
200
  return value if value else None
@@ -46,6 +46,7 @@ from aid_runtime.retrieval.embedding import (
46
46
  Embedder,
47
47
  EmbeddingBatch,
48
48
  FakeDeterministicEmbedder,
49
+ GeminiEmbedder,
49
50
  OpenAICompatibleEmbedder,
50
51
  embedder_for,
51
52
  estimate_tokens,
@@ -121,6 +122,7 @@ __all__ = [
121
122
  "FakeDeterministicEmbedder",
122
123
  "FileConnector",
123
124
  "FixedChunker",
125
+ "GeminiEmbedder",
124
126
  "InMemoryVectorStore",
125
127
  "IndexSpec",
126
128
  "IngestReport",
@@ -20,6 +20,7 @@ import asyncio
20
20
  import hashlib
21
21
  import json
22
22
  import math
23
+ import os
23
24
  from collections.abc import Mapping, Sequence
24
25
  from typing import Any, Protocol, runtime_checkable
25
26
 
@@ -27,6 +28,7 @@ import httpx
27
28
  from pydantic import BaseModel, ConfigDict
28
29
 
29
30
  from aid_runtime.errors import ConfigurationError, ProviderError, ProviderResponseError
31
+ from aid_runtime.providers.gemini import DEFAULT_GEMINI_BASE_URL, GEMINI_API_KEY_ENV
30
32
  from aid_runtime.providers.http import DEFAULT_BASE_URL
31
33
  from aid_runtime.retrieval.types import PinnedEmbedding
32
34
  from aid_runtime.types import TokenUsage
@@ -35,6 +37,7 @@ __all__ = [
35
37
  "Embedder",
36
38
  "EmbeddingBatch",
37
39
  "FakeDeterministicEmbedder",
40
+ "GeminiEmbedder",
38
41
  "OpenAICompatibleEmbedder",
39
42
  "embedder_for",
40
43
  "estimate_tokens",
@@ -50,6 +53,12 @@ _RETRYABLE_STATUS = frozenset({408, 409, 425, 429, 500, 502, 503, 504})
50
53
  #: offline estimate and an offline charge cannot disagree about what a text costs.
51
54
  _CHARS_PER_TOKEN = 4
52
55
 
56
+ #: ``batchEmbedContents`` accepts at most 100 inputs per call.
57
+ _GEMINI_BATCH_LIMIT = 100
58
+
59
+ #: Only these embedding models take ``outputDimensionality``; older ones reject it.
60
+ _GEMINI_DIMENSIONED_MODELS = frozenset({"gemini-embedding-001"})
61
+
53
62
 
54
63
  class EmbeddingBatch(BaseModel):
55
64
  """Vectors plus the usage that prices them."""
@@ -196,32 +205,15 @@ class OpenAICompatibleEmbedder:
196
205
  return headers
197
206
 
198
207
  async def _post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
199
- url = f"{self._base_url}{path}"
200
- last_error: Exception | None = None
201
- for attempt in range(1, self._max_attempts + 1):
202
- try:
203
- response = await self._client.post(url, json=payload, headers=self._headers())
204
- except httpx.TransportError as error:
205
- last_error = error
206
- else:
207
- if response.status_code < 400:
208
- return _as_object(response, self._name)
209
- failure = ProviderError(
210
- f"{self._name} returned HTTP {response.status_code}: {response.text[:200]}"
211
- )
212
- # A status outside the retryable set is a decision, not a hiccup:
213
- # retrying a 400 only wastes the caller's time.
214
- if response.status_code not in _RETRYABLE_STATUS:
215
- raise failure
216
- last_error = failure
217
- if attempt < self._max_attempts:
218
- await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
219
- # Chained rather than formatted away: the transport error carries the reason
220
- # (DNS, TLS, refused connection), and a caller catching the ProviderError
221
- # should still be able to see it, as the chat provider's callers can.
222
- raise ProviderError(
223
- f"{self._name} failed after {self._max_attempts} attempt(s): {last_error}"
224
- ) from last_error
208
+ return await _post_json(
209
+ self._client,
210
+ f"{self._base_url}{path}",
211
+ payload,
212
+ self._headers(),
213
+ name=self._name,
214
+ max_attempts=self._max_attempts,
215
+ backoff=self._backoff,
216
+ )
225
217
 
226
218
  def _parse(self, body: dict[str, Any], model: PinnedEmbedding) -> EmbeddingBatch:
227
219
  entries = body.get("data")
@@ -264,6 +256,160 @@ class OpenAICompatibleEmbedder:
264
256
  )
265
257
 
266
258
 
259
+ class GeminiEmbedder:
260
+ """``batchEmbedContents`` on the Gemini API.
261
+
262
+ Not an OpenAI-compatible endpoint with a different base URL: the body nests the
263
+ text in ``content.parts[].text``, the response is ``embeddings[].values`` rather
264
+ than ``data[].embedding``, and the key travels in ``x-goog-api-key``. The batch
265
+ limit is 100 inputs per call, so a larger batch is split and reassembled in order.
266
+
267
+ The response carries no token counts, so usage is the same offline estimate the
268
+ fake adapter uses; it is a budget signal, not a bill.
269
+ """
270
+
271
+ def __init__(
272
+ self,
273
+ *,
274
+ base_url: str = DEFAULT_GEMINI_BASE_URL,
275
+ api_key: str | None = None,
276
+ name: str = "gemini-embedder",
277
+ timeout_seconds: float = 60.0,
278
+ max_attempts: int = 3,
279
+ backoff_seconds: float = 0.5,
280
+ client: httpx.AsyncClient | None = None,
281
+ ) -> None:
282
+ if not base_url.startswith(("http://", "https://")):
283
+ raise ConfigurationError(f"base_url must be an absolute http(s) URL, got {base_url!r}")
284
+ if max_attempts < 1:
285
+ raise ConfigurationError("max_attempts must be at least 1")
286
+ self._base_url = base_url.rstrip("/")
287
+ self._api_key = api_key
288
+ self._name = name
289
+ self._max_attempts = max_attempts
290
+ self._backoff = backoff_seconds
291
+ self._owns_client = client is None
292
+ self._client = client or httpx.AsyncClient(timeout=timeout_seconds)
293
+ self._closed = False
294
+
295
+ @property
296
+ def name(self) -> str:
297
+ return self._name
298
+
299
+ async def embed(self, texts: Sequence[str], *, model: PinnedEmbedding) -> EmbeddingBatch:
300
+ vectors: list[tuple[float, ...]] = []
301
+ for start in range(0, len(texts), _GEMINI_BATCH_LIMIT):
302
+ batch = list(texts[start : start + _GEMINI_BATCH_LIMIT])
303
+ body = await self._post(model, batch)
304
+ vectors.extend(self._parse(body, model, len(batch)))
305
+ return EmbeddingBatch(
306
+ vectors=tuple(vectors),
307
+ usage=TokenUsage(
308
+ input_tokens=sum(estimate_tokens(text) for text in texts),
309
+ output_tokens=0,
310
+ ),
311
+ )
312
+
313
+ async def aclose(self) -> None:
314
+ if self._closed:
315
+ return
316
+ self._closed = True
317
+ if self._owns_client:
318
+ await self._client.aclose()
319
+
320
+ def _headers(self) -> dict[str, str]:
321
+ api_key = self._api_key or os.environ.get(GEMINI_API_KEY_ENV)
322
+ if not api_key:
323
+ raise ProviderError(
324
+ f"{self._name} has no API key: set embedding provider 'apiKeyEnv' or "
325
+ f"{GEMINI_API_KEY_ENV}"
326
+ )
327
+ return {"x-goog-api-key": api_key, "content-type": "application/json"}
328
+
329
+ async def _post(self, model: PinnedEmbedding, texts: list[str]) -> dict[str, Any]:
330
+ requests: list[dict[str, Any]] = [
331
+ {"model": f"models/{model.model_id}", "content": {"parts": [{"text": text}]}}
332
+ for text in texts
333
+ ]
334
+ if model.model_id in _GEMINI_DIMENSIONED_MODELS:
335
+ for entry in requests:
336
+ entry["outputDimensionality"] = model.dimensions
337
+ return await _post_json(
338
+ self._client,
339
+ f"{self._base_url}/v1beta/models/{model.model_id}:batchEmbedContents",
340
+ {"requests": requests},
341
+ self._headers(),
342
+ name=self._name,
343
+ max_attempts=self._max_attempts,
344
+ backoff=self._backoff,
345
+ )
346
+
347
+ def _parse(
348
+ self, body: dict[str, Any], model: PinnedEmbedding, expected: int
349
+ ) -> list[tuple[float, ...]]:
350
+ entries = body.get("embeddings")
351
+ if not isinstance(entries, list) or len(entries) != expected:
352
+ raise ProviderResponseError(
353
+ f"{self._name} returned {len(entries) if isinstance(entries, list) else 0} "
354
+ f"embeddings for {expected} input(s)"
355
+ )
356
+ vectors: list[tuple[float, ...]] = []
357
+ for entry in entries:
358
+ values = entry.get("values") if isinstance(entry, dict) else None
359
+ if not isinstance(values, list):
360
+ raise ProviderResponseError(f"{self._name} returned a non-list embedding")
361
+ try:
362
+ vector = tuple(float(value) for value in values)
363
+ except (TypeError, ValueError) as error:
364
+ raise ProviderResponseError(
365
+ f"{self._name} returned a non-numeric embedding"
366
+ ) from error
367
+ if len(vector) != model.dimensions:
368
+ raise ProviderResponseError(
369
+ f"{self._name} returned {len(vector)} dimensions for {model.model_id!r} but "
370
+ f"{model.dimensions} are pinned; the pin and the response must agree"
371
+ )
372
+ vectors.append(vector)
373
+ return vectors
374
+
375
+
376
+ async def _post_json(
377
+ client: httpx.AsyncClient,
378
+ url: str,
379
+ payload: dict[str, Any],
380
+ headers: Mapping[str, str],
381
+ *,
382
+ name: str,
383
+ max_attempts: int,
384
+ backoff: float,
385
+ ) -> dict[str, Any]:
386
+ last_error: Exception | None = None
387
+ for attempt in range(1, max_attempts + 1):
388
+ try:
389
+ response = await client.post(url, json=payload, headers=dict(headers))
390
+ except httpx.TransportError as error:
391
+ last_error = error
392
+ else:
393
+ if response.status_code < 400:
394
+ return _as_object(response, name)
395
+ failure = ProviderError(
396
+ f"{name} returned HTTP {response.status_code}: {response.text[:200]}"
397
+ )
398
+ # A status outside the retryable set is a decision, not a hiccup: retrying
399
+ # a 400 only wastes the caller's time.
400
+ if response.status_code not in _RETRYABLE_STATUS:
401
+ raise failure
402
+ last_error = failure
403
+ if attempt < max_attempts:
404
+ await asyncio.sleep(backoff * 2 ** (attempt - 1))
405
+ # Chained rather than formatted away: the transport error carries the reason (DNS,
406
+ # TLS, refused connection), and a caller catching the ProviderError should still be
407
+ # able to see it, as the chat provider's callers can.
408
+ raise ProviderError(
409
+ f"{name} failed after {max_attempts} attempt(s): {last_error}"
410
+ ) from last_error
411
+
412
+
267
413
  def _as_object(response: httpx.Response, name: str) -> dict[str, Any]:
268
414
  try:
269
415
  body = response.json()
@@ -278,7 +424,7 @@ def embedder_for(
278
424
  model: PinnedEmbedding,
279
425
  *,
280
426
  api_key: str | None = None,
281
- base_url: str = DEFAULT_BASE_URL,
427
+ base_url: str | None = None,
282
428
  client: httpx.AsyncClient | None = None,
283
429
  ) -> Embedder:
284
430
  """Pick the adapter for a pinned embedding model.
@@ -286,8 +432,15 @@ def embedder_for(
286
432
  This selects a *provider*, never a model: the model id and its width arrive
287
433
  already pinned, and are passed straight through to whichever adapter is chosen.
288
434
  ``fake`` is chosen for the same reason the spec can declare it -- so a gate runs
289
- keyless and offline.
435
+ keyless and offline. Each hosted adapter keeps its own default host, so ``base_url``
436
+ is only passed through when the caller supplied one.
290
437
  """
291
438
  if model.provider == "fake":
292
439
  return FakeDeterministicEmbedder()
293
- return OpenAICompatibleEmbedder(base_url=base_url, api_key=api_key, client=client)
440
+ if model.provider == "gemini":
441
+ return GeminiEmbedder(
442
+ base_url=base_url or DEFAULT_GEMINI_BASE_URL, api_key=api_key, client=client
443
+ )
444
+ return OpenAICompatibleEmbedder(
445
+ base_url=base_url or DEFAULT_BASE_URL, api_key=api_key, client=client
446
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.96
3
+ Version: 0.1.97
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=uwsi41AfQfY4kN68MjH06XNsfD4Ruj6vY28mdrFRDD4,12527
1
+ aid_runtime/__init__.py,sha256=QdZBCHUS4GSs2iemRtX2gCePiA4Qesa4qNrnbF-vHBY,12721
2
2
  aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
3
3
  aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
4
4
  aid_runtime/control.py,sha256=y6wPn0fqYJv0nVSsjzpzfiaq1Y7zBoMxCpdrEuqkfvg,17529
@@ -31,18 +31,20 @@ aid_runtime/evals/gate.py,sha256=_nLWXvcuHwq8nE3HpiONg_wBkrzZyGrGT49ZNeKMyTY,155
31
31
  aid_runtime/evals/metrics.py,sha256=il9lzJa-hir59pw9Muyg9MhDuozUqAQaO1Tb75CxBKc,14185
32
32
  aid_runtime/evals/predicate.py,sha256=JaeN1LJFpliI4JHYdFPtXfjH5_Aad-2-U3ZC6_hManE,8726
33
33
  aid_runtime/evals/runner.py,sha256=Lkl-kAVxegPO40pCBUcprRBKvfL6bjYzVf__xe6Z-Mc,7951
34
- aid_runtime/providers/__init__.py,sha256=5PA3A5IRabcxYS0r75Byol2RHcC4ZZ3gi-boJV0sjWQ,1516
34
+ aid_runtime/providers/__init__.py,sha256=MQ-vU_QeeUgfqMlwLi0layJBhmvbZat9gIkDFcFl7Pg,1827
35
35
  aid_runtime/providers/anthropic.py,sha256=xh_fJyujnFRcknEHFRxA5M-izeR2hJtit-865RrISOQ,15853
36
36
  aid_runtime/providers/base.py,sha256=1VYTZ_V9FR6f6pS0MB3LFeu-Zzv4toQvm3CwAQNbeT0,1851
37
37
  aid_runtime/providers/bedrock.py,sha256=WkfWFg94kLFJ9q04CEkXCc-HqoVqHivAmhy511-WtIA,20834
38
38
  aid_runtime/providers/fake.py,sha256=oAcpaDOUIp7lmKGEEWG5ktagstg2dvoHR-9xaUeCDLo,9526
39
+ aid_runtime/providers/gemini.py,sha256=gM4Kvgz6lnFbHgYYhyVCBTFTcGAKfiNuj7lS1XSldnU,3975
40
+ aid_runtime/providers/gemini_wire.py,sha256=ZwIiYuAVihszE0c90-uAbSn6_hdMa2Md4asySIYeQTw,13032
39
41
  aid_runtime/providers/http.py,sha256=c5DLmX1FqtAUO01MqDf0m82x8zHD480LyL-QtTrxnn4,13168
40
- aid_runtime/providers/vertex.py,sha256=u5qqSIZeT19plVEPR1p3bpcTtSv2IwMOK2X45fXlic4,17505
41
- aid_runtime/retrieval/__init__.py,sha256=LR6qyiE7pY9QsB1h4g9j1W7acpSINFbgxA9U1otLt90,4580
42
+ aid_runtime/providers/vertex.py,sha256=zWBDXeP6kBo89KkCVbAkeiqDm6_4ujBdL0Ebk9W-vPM,7421
43
+ aid_runtime/retrieval/__init__.py,sha256=OalGNdkqKW9pxEJd2FGGArC3Ejg6EUxgOKrOZp4vtLI,4622
42
44
  aid_runtime/retrieval/chunking.py,sha256=GMJvY1GoIua-FkpCH1S5qNmUrWSaSbl6sBJPCrSDAg4,8296
43
45
  aid_runtime/retrieval/citations.py,sha256=UL9fsxLTzzO0n8tEW3X2O5erJ0hrk08NYMkZ9Pk8Jdg,4287
44
46
  aid_runtime/retrieval/connectors.py,sha256=JNEwq6S8zKX1GdlWe4Gn2Rdon87DWXlG_WNQfZTlN34,4744
45
- aid_runtime/retrieval/embedding.py,sha256=ZPjALe_nEzYpa8N5COExPGrojjZFX8awTz6vzJYfx_4,12374
47
+ aid_runtime/retrieval/embedding.py,sha256=nKyk70iPDlSq_-W7cbm1cHy3rbH7LHSq8ulcssjGMlY,18203
46
48
  aid_runtime/retrieval/gate.py,sha256=3avH1Gwp7iv7mMOskmNbk70Yq85tXwJrKVrQAKKI4Js,4840
47
49
  aid_runtime/retrieval/hybrid.py,sha256=-GIBeI3njT5uaEvSeq2t151Zlv2yOPHOPje4TJLNVyU,5804
48
50
  aid_runtime/retrieval/metrics.py,sha256=LN36BIXzpbhkG9grzE0q5wncgXt_Y85-b5jGJ038-3Y,7904
@@ -51,7 +53,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
51
53
  aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
52
54
  aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
53
55
  aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
54
- aid_runtime_python-0.1.96.dist-info/METADATA,sha256=ezB_vP8FTKeo4AlhZQI5f5eXj_lrDFRBFBlWCf3XWnw,17005
55
- aid_runtime_python-0.1.96.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
56
- aid_runtime_python-0.1.96.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
57
- aid_runtime_python-0.1.96.dist-info/RECORD,,
56
+ aid_runtime_python-0.1.97.dist-info/METADATA,sha256=D3a3XhXFnqtqiHdmPz1J87ONeselqEgnFiRfl2PS6bE,17005
57
+ aid_runtime_python-0.1.97.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
58
+ aid_runtime_python-0.1.97.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
59
+ aid_runtime_python-0.1.97.dist-info/RECORD,,