aid-runtime-python 0.1.95__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 +13 -1
- aid_runtime/decisions.py +38 -2
- aid_runtime/providers/__init__.py +14 -4
- aid_runtime/providers/gemini.py +113 -0
- aid_runtime/providers/gemini_wire.py +345 -0
- aid_runtime/providers/vertex.py +23 -271
- aid_runtime/retrieval/__init__.py +2 -0
- aid_runtime/retrieval/embedding.py +182 -29
- aid_runtime/tracing.py +26 -6
- {aid_runtime_python-0.1.95.dist-info → aid_runtime_python-0.1.97.dist-info}/METADATA +1 -1
- {aid_runtime_python-0.1.95.dist-info → aid_runtime_python-0.1.97.dist-info}/RECORD +13 -11
- {aid_runtime_python-0.1.95.dist-info → aid_runtime_python-0.1.97.dist-info}/WHEEL +0 -0
- {aid_runtime_python-0.1.95.dist-info → aid_runtime_python-0.1.97.dist-info}/top_level.txt +0 -0
aid_runtime/providers/vertex.py
CHANGED
|
@@ -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.
|
|
5
|
-
|
|
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
|
|
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
|
-
|
|
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),
|
|
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
|
-
|
|
328
|
-
|
|
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
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
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 =
|
|
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
|
-
|
|
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
|
+
)
|