aid-runtime-python 0.1.96__py3-none-any.whl → 0.1.98__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.
@@ -0,0 +1,324 @@
1
+ """The managed-guardrail adapter: ``ApplyGuardrail``, and the policy names it takes.
2
+
3
+ A ``bedrock`` guardrail is evaluated by AWS, not by this process. The deployment
4
+ creates the policy and a numbered version; the app knows only
5
+ ``BEDROCK_GUARDRAIL_ID`` and ``BEDROCK_GUARDRAIL_VERSION``. That split is what
6
+ keeps an account number out of the spec: the spec says *what* to refuse, the
7
+ deployment says *where* the resource lives, and neither has to know the other's
8
+ identifier.
9
+
10
+ Two decisions this module owns:
11
+
12
+ **The IR's vocabulary, not AWS's, is the input.** ``content``/``strength``/``pii``
13
+ arrive as the spec spells them -- ``prompt-attack: high``, ``credit-card`` -- and
14
+ this is the one table that maps them to ``PROMPT_ATTACK`` and
15
+ ``CREDIT_DEBIT_CARD_NUMBER``. The generator therefore never carries a second copy
16
+ of the provider's enum, and a test can pin the mapping without an AWS call.
17
+
18
+ **Every failure is a block.** A non-2xx answer, a body this module cannot read, an
19
+ unknown ``action``, a missing identifier: each raises, and
20
+ :class:`~aid_runtime.agents.guardrails.GuardrailEngine` turns that into a
21
+ :class:`~aid_runtime.errors.GuardrailBlockedError`. There is no path from "the
22
+ managed check did not run" to "the text was fine".
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import json
29
+ import os
30
+ from collections.abc import Callable, Mapping, Sequence
31
+ from dataclasses import dataclass
32
+ from datetime import UTC, datetime
33
+ from typing import Any, Protocol
34
+
35
+ import httpx
36
+
37
+ from aid_runtime.errors import ConfigurationError, ProviderError, ProviderResponseError
38
+ from aid_runtime.providers.bedrock import BedrockProvider, rfc3986, sigv4_headers
39
+
40
+ __all__ = [
41
+ "CONTENT_STRENGTHS",
42
+ "CONTENT_TYPES",
43
+ "GUARDRAIL_ID_ENV",
44
+ "GUARDRAIL_VERSION_ENV",
45
+ "PII_TYPES",
46
+ "BedrockGuardrailClient",
47
+ "GuardrailClient",
48
+ "GuardrailOutcome",
49
+ "ManagedGuardrailSettings",
50
+ "managed_guardrail_settings",
51
+ ]
52
+
53
+ GUARDRAIL_ID_ENV = "BEDROCK_GUARDRAIL_ID"
54
+ GUARDRAIL_VERSION_ENV = "BEDROCK_GUARDRAIL_VERSION"
55
+
56
+ #: One entry per ``BedrockContentFilter`` in ``packages/ir/src/shapes.ts``.
57
+ CONTENT_TYPES: Mapping[str, str] = {
58
+ "sexual": "SEXUAL",
59
+ "violence": "VIOLENCE",
60
+ "hate": "HATE",
61
+ "insults": "INSULTS",
62
+ "misconduct": "MISCONDUCT",
63
+ "prompt-attack": "PROMPT_ATTACK",
64
+ }
65
+
66
+ CONTENT_STRENGTHS: Mapping[str, str] = {
67
+ "low": "LOW",
68
+ "medium": "MEDIUM",
69
+ "high": "HIGH",
70
+ }
71
+
72
+ #: One entry per ``BedrockPiiEntity``. Names with a jurisdiction are the ones AWS
73
+ #: spells out; the rest are the entity type verbatim.
74
+ PII_TYPES: Mapping[str, str] = {
75
+ "email": "EMAIL",
76
+ "phone": "PHONE",
77
+ "name": "NAME",
78
+ "address": "ADDRESS",
79
+ "ssn": "US_SOCIAL_SECURITY_NUMBER",
80
+ "credit-card": "CREDIT_DEBIT_CARD_NUMBER",
81
+ "bank-account": "US_BANK_ACCOUNT_NUMBER",
82
+ "passport": "PASSPORT_NUMBER",
83
+ "drivers-license": "DRIVERS_LICENSE_NUMBER",
84
+ "ip-address": "IP_ADDRESS",
85
+ "url": "URL",
86
+ "aws-access-key": "AWS_ACCESS_KEY",
87
+ "aws-secret-key": "AWS_SECRET_KEY",
88
+ }
89
+
90
+ _SOURCES = frozenset({"INPUT", "OUTPUT"})
91
+ _RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
92
+
93
+
94
+ @dataclass(frozen=True, slots=True)
95
+ class ManagedGuardrailSettings:
96
+ """Where the deployment put the managed guardrail."""
97
+
98
+ id: str
99
+ version: str
100
+
101
+
102
+ def managed_guardrail_settings() -> ManagedGuardrailSettings:
103
+ """Read the two environment names, or explain which one is missing.
104
+
105
+ ``DRAFT`` is refused on purpose: AWS lets an app call a draft, and a draft
106
+ changes under it. A deployment ships a numbered version, so the version this
107
+ process names is the policy it actually enforces.
108
+ """
109
+ guardrail_id = os.environ.get(GUARDRAIL_ID_ENV)
110
+ version = os.environ.get(GUARDRAIL_VERSION_ENV)
111
+ missing = [
112
+ name
113
+ for name, value in ((GUARDRAIL_ID_ENV, guardrail_id), (GUARDRAIL_VERSION_ENV, version))
114
+ if not value
115
+ ]
116
+ if missing:
117
+ raise ConfigurationError(
118
+ "the spec declares a managed guardrail, so "
119
+ + " and ".join(missing)
120
+ + " must be set: the deployment creates the resource, the app only names it"
121
+ )
122
+ if version == "DRAFT":
123
+ raise ConfigurationError(
124
+ f"{GUARDRAIL_VERSION_ENV}=DRAFT is not a pinned policy; name the numbered "
125
+ "version the deployment created"
126
+ )
127
+ return ManagedGuardrailSettings(id=guardrail_id or "", version=version or "")
128
+
129
+
130
+ @dataclass(frozen=True, slots=True)
131
+ class GuardrailOutcome:
132
+ """One ``ApplyGuardrail`` answer, in terms the engine can act on.
133
+
134
+ ``text`` is the service's rewritten content, present when the policy
135
+ anonymised something. ``policies`` names what fired, for the audit trail:
136
+ ``content:HATE``, ``pii:EMAIL``, ``topic:investments``.
137
+ """
138
+
139
+ intervened: bool
140
+ policies: tuple[str, ...] = ()
141
+ text: str | None = None
142
+
143
+
144
+ class GuardrailClient(Protocol):
145
+ """The one call the engine makes, so a test double need not sign anything."""
146
+
147
+ async def apply(self, *, source: str, text: str) -> GuardrailOutcome: ...
148
+
149
+
150
+ class BedrockGuardrailClient:
151
+ """``POST /guardrail/{id}/version/{version}/apply`` with SigV4.
152
+
153
+ Retries once -- the summary's "retry once on throttling" -- and then gives up
154
+ loudly. A retry is worth it for a throttled control-plane call; a third
155
+ attempt would keep a user waiting for a check that is failing closed anyway.
156
+ """
157
+
158
+ def __init__(
159
+ self,
160
+ *,
161
+ settings: ManagedGuardrailSettings | None = None,
162
+ provider: BedrockProvider | None = None,
163
+ region: str | None = None,
164
+ base_url: str | None = None,
165
+ client: httpx.AsyncClient | None = None,
166
+ timeout_seconds: float = 15.0,
167
+ max_attempts: int = 2,
168
+ backoff_seconds: float = 0.25,
169
+ now: Callable[[], datetime] | None = None,
170
+ ) -> None:
171
+ if max_attempts < 1:
172
+ raise ValueError("max_attempts must be at least 1")
173
+ self._settings = settings
174
+ self._base_url = base_url.rstrip("/") if base_url is not None else None
175
+ self._max_attempts = max_attempts
176
+ self._backoff = backoff_seconds
177
+ self._now = now or (lambda: datetime.now(UTC))
178
+ self._owns_client = provider is None and client is None
179
+ self._provider = provider or BedrockProvider(
180
+ region=region,
181
+ timeout_seconds=timeout_seconds,
182
+ max_attempts=1,
183
+ client=client,
184
+ name="bedrock-guardrail",
185
+ )
186
+
187
+ @property
188
+ def settings(self) -> ManagedGuardrailSettings:
189
+ if self._settings is None:
190
+ self._settings = managed_guardrail_settings()
191
+ return self._settings
192
+
193
+ async def aclose(self) -> None:
194
+ if self._owns_client:
195
+ await self._provider.aclose()
196
+
197
+ async def apply(self, *, source: str, text: str) -> GuardrailOutcome:
198
+ if source not in _SOURCES:
199
+ raise ValueError(f"source must be INPUT or OUTPUT, not {source!r}")
200
+ settings = self.settings
201
+ region = self._provider.resolve_region()
202
+ credentials = await self._provider.credentials()
203
+ payload = json.dumps(
204
+ {"source": source, "content": [{"text": {"text": text}}]},
205
+ separators=(",", ":"),
206
+ )
207
+ url = self._url(region, settings)
208
+ headers = sigv4_headers(
209
+ url=url,
210
+ body=payload,
211
+ region=region,
212
+ credentials=credentials,
213
+ moment=self._now(),
214
+ )
215
+ answer = await self._post(url, headers, payload)
216
+ return _parse(answer)
217
+
218
+ def _url(self, region: str, settings: ManagedGuardrailSettings) -> str:
219
+ base = self._base_url or f"https://bedrock.{region}.amazonaws.com"
220
+ return f"{base}/guardrail/{rfc3986(settings.id)}/version/{rfc3986(settings.version)}/apply"
221
+
222
+ async def _post(self, url: str, headers: dict[str, str], body: str) -> str:
223
+ last_error: Exception | None = None
224
+ for attempt in range(1, self._max_attempts + 1):
225
+ try:
226
+ response = await self._provider.send(url, body=body, headers=headers)
227
+ except httpx.TransportError as exc:
228
+ last_error = exc
229
+ if attempt == self._max_attempts:
230
+ break
231
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
232
+ continue
233
+ if response.status_code in _RETRYABLE_STATUS and attempt < self._max_attempts:
234
+ await asyncio.sleep(self._backoff * 2 ** (attempt - 1))
235
+ continue
236
+ if response.status_code >= 400:
237
+ raise ProviderError(
238
+ f"the managed guardrail returned {response.status_code}: {response.text[:500]}"
239
+ )
240
+ return response.text
241
+ raise ProviderError(f"the managed guardrail could not be reached: {last_error}")
242
+
243
+
244
+ def _parse(body: str) -> GuardrailOutcome:
245
+ try:
246
+ answer = json.loads(body)
247
+ except json.JSONDecodeError as exc:
248
+ raise ProviderResponseError("the managed guardrail returned a non-JSON body", body) from exc
249
+ if not isinstance(answer, dict):
250
+ raise ProviderResponseError("the managed guardrail returned no object", body)
251
+ action = answer.get("action")
252
+ if action == "NONE":
253
+ return GuardrailOutcome(intervened=False)
254
+ if action != "GUARDRAIL_INTERVENED":
255
+ raise ProviderResponseError(
256
+ f"the managed guardrail returned unknown action {action!r}", body
257
+ )
258
+ return GuardrailOutcome(
259
+ intervened=True,
260
+ policies=_policy_labels(answer.get("assessments")),
261
+ text=_output_text(answer.get("outputs")),
262
+ )
263
+
264
+
265
+ def _output_text(outputs: Any) -> str | None:
266
+ if not isinstance(outputs, list) or not outputs:
267
+ return None
268
+ first = outputs[0]
269
+ if isinstance(first, Mapping):
270
+ text = first.get("text")
271
+ if isinstance(text, str):
272
+ return text
273
+ return None
274
+
275
+
276
+ def _policy_labels(assessments: Any) -> tuple[str, ...]:
277
+ """What fired, named the way the spec would name it.
278
+
279
+ AWS reports an assessment per policy family, each with its own list shape.
280
+ Flattening them into ``family:value`` strings is enough for a log line and a
281
+ trace event, and avoids inventing a second schema for the audit trail.
282
+ """
283
+ labels: list[str] = []
284
+ if not isinstance(assessments, Sequence) or isinstance(assessments, (str, bytes)):
285
+ return ()
286
+
287
+ def add(label: str | None) -> None:
288
+ if label is not None and label not in labels:
289
+ labels.append(label)
290
+
291
+ for assessment in assessments:
292
+ if not isinstance(assessment, Mapping):
293
+ continue
294
+ content = assessment.get("contentPolicy")
295
+ if isinstance(content, Mapping):
296
+ for entry in _entries(content.get("filters")):
297
+ add(_prefixed("content", entry.get("type")))
298
+ topics = assessment.get("topicPolicy")
299
+ if isinstance(topics, Mapping):
300
+ for entry in _entries(topics.get("topics")):
301
+ add(_prefixed("topic", entry.get("name")))
302
+ words = assessment.get("wordPolicy")
303
+ if isinstance(words, Mapping):
304
+ for entry in _entries(words.get("customWords")):
305
+ add(_prefixed("word", entry.get("match")))
306
+ for entry in _entries(words.get("managedWordLists")):
307
+ add(_prefixed("word", entry.get("type")))
308
+ sensitive = assessment.get("sensitiveInformationPolicy")
309
+ if isinstance(sensitive, Mapping):
310
+ for entry in _entries(sensitive.get("piiEntities")):
311
+ add(_prefixed("pii", entry.get("type")))
312
+ for entry in _entries(sensitive.get("regexes")):
313
+ add(_prefixed("regex", entry.get("name")))
314
+ return tuple(labels)
315
+
316
+
317
+ def _entries(value: Any) -> tuple[Mapping[str, Any], ...]:
318
+ if not isinstance(value, list):
319
+ return ()
320
+ return tuple(entry for entry in value if isinstance(entry, Mapping))
321
+
322
+
323
+ def _prefixed(family: str, value: Any) -> str | None:
324
+ return f"{family}:{value}" if isinstance(value, str) and value else None
@@ -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",
@@ -49,7 +49,13 @@ from aid_runtime.types import (
49
49
  ToolCall,
50
50
  )
51
51
 
52
- __all__ = ["BEDROCK_SERVICE", "BedrockProvider", "default_bedrock_base_url", "rfc3986"]
52
+ __all__ = [
53
+ "BEDROCK_SERVICE",
54
+ "BedrockProvider",
55
+ "default_bedrock_base_url",
56
+ "rfc3986",
57
+ "sigv4_headers",
58
+ ]
53
59
 
54
60
  BEDROCK_SERVICE = "bedrock"
55
61
 
@@ -88,6 +94,72 @@ def _sha256_hex(value: str) -> str:
88
94
  return hashlib.sha256(value.encode()).hexdigest()
89
95
 
90
96
 
97
+ def sigv4_headers(
98
+ *,
99
+ url: str,
100
+ body: str,
101
+ region: str,
102
+ credentials: dict[str, Any],
103
+ moment: datetime,
104
+ service: str = BEDROCK_SERVICE,
105
+ ) -> dict[str, str]:
106
+ """The SigV4 headers for one JSON ``POST`` to ``url``.
107
+
108
+ Shared by the model adapter and the managed-guardrail adapter because both
109
+ sign with the ``bedrock`` service name -- Converse is served by
110
+ ``bedrock-runtime`` but signed as ``bedrock``, and ``ApplyGuardrail`` is served
111
+ by ``bedrock`` itself. Keeping one signer means a fix to the canonical request
112
+ cannot land in one caller and miss the other.
113
+ """
114
+ stamp = _amz_date(moment)
115
+ date = stamp[:8]
116
+ parsed = urlparse(url)
117
+ host = parsed.netloc
118
+ canonical_headers: list[tuple[str, str]] = [
119
+ ("content-type", "application/json"),
120
+ ("host", host),
121
+ ("x-amz-date", stamp),
122
+ ]
123
+ token = credentials.get("session_token")
124
+ if isinstance(token, str):
125
+ canonical_headers.append(("x-amz-security-token", token))
126
+ signed_headers = ";".join(header for header, _ in canonical_headers)
127
+ canonical_request = "\n".join(
128
+ [
129
+ "POST",
130
+ parsed.path,
131
+ "",
132
+ "".join(f"{header}:{value}\n" for header, value in canonical_headers),
133
+ signed_headers,
134
+ _sha256_hex(body),
135
+ ]
136
+ )
137
+ scope = f"{date}/{region}/{service}/aws4_request"
138
+ string_to_sign = "\n".join(["AWS4-HMAC-SHA256", stamp, scope, _sha256_hex(canonical_request)])
139
+ signing_key = _hmac(
140
+ _hmac(
141
+ _hmac(
142
+ _hmac(f"AWS4{credentials['secret_access_key']}", date),
143
+ region,
144
+ ),
145
+ service,
146
+ ),
147
+ "aws4_request",
148
+ )
149
+ signature = hmac.new(signing_key, string_to_sign.encode(), hashlib.sha256).hexdigest()
150
+ headers = {
151
+ "content-type": "application/json",
152
+ "x-amz-date": stamp,
153
+ "authorization": (
154
+ f"AWS4-HMAC-SHA256 Credential={credentials['access_key_id']}/{scope}, "
155
+ f"SignedHeaders={signed_headers}, Signature={signature}"
156
+ ),
157
+ }
158
+ if isinstance(token, str):
159
+ headers["x-amz-security-token"] = token
160
+ return headers
161
+
162
+
91
163
  def _hmac(key: bytes | str, value: str) -> bytes:
92
164
  if isinstance(key, str):
93
165
  key = key.encode()
@@ -290,56 +362,34 @@ class BedrockProvider:
290
362
  credentials: dict[str, Any],
291
363
  moment: datetime,
292
364
  ) -> dict[str, str]:
293
- stamp = _amz_date(moment)
294
- date = stamp[:8]
295
- parsed = urlparse(url)
296
- host = parsed.netloc
297
- canonical_headers: list[tuple[str, str]] = [
298
- ("content-type", "application/json"),
299
- ("host", host),
300
- ("x-amz-date", stamp),
301
- ]
302
- token = credentials.get("session_token")
303
- if isinstance(token, str):
304
- canonical_headers.append(("x-amz-security-token", token))
305
- signed_headers = ";".join(header for header, _ in canonical_headers)
306
- canonical_request = "\n".join(
307
- [
308
- "POST",
309
- parsed.path,
310
- "",
311
- "".join(f"{header}:{value}\n" for header, value in canonical_headers),
312
- signed_headers,
313
- _sha256_hex(body),
314
- ]
315
- )
316
- scope = f"{date}/{region}/{BEDROCK_SERVICE}/aws4_request"
317
- string_to_sign = "\n".join(
318
- ["AWS4-HMAC-SHA256", stamp, scope, _sha256_hex(canonical_request)]
319
- )
320
- signing_key = _hmac(
321
- _hmac(
322
- _hmac(
323
- _hmac(f"AWS4{credentials['secret_access_key']}", date),
324
- region,
325
- ),
326
- BEDROCK_SERVICE,
327
- ),
328
- "aws4_request",
329
- )
330
- signature = hmac.new(signing_key, string_to_sign.encode(), hashlib.sha256).hexdigest()
331
- headers = {
332
- "content-type": "application/json",
333
- "x-amz-date": stamp,
334
- "authorization": (
335
- f"AWS4-HMAC-SHA256 Credential={credentials['access_key_id']}/{scope}, "
336
- f"SignedHeaders={signed_headers}, Signature={signature}"
365
+ return {
366
+ **sigv4_headers(
367
+ url=url,
368
+ body=body,
369
+ region=region,
370
+ credentials=credentials,
371
+ moment=moment,
372
+ service=BEDROCK_SERVICE,
337
373
  ),
338
374
  **self._extra_headers,
339
375
  }
340
- if isinstance(token, str):
341
- headers["x-amz-security-token"] = token
342
- return headers
376
+
377
+ def resolve_region(self) -> str:
378
+ """The region this adapter signs for, or a :class:`ProviderError`."""
379
+ return self._resolve_region()
380
+
381
+ async def send(self, url: str, *, body: str, headers: dict[str, str]) -> httpx.Response:
382
+ """One signed POST, uninterpreted: shared with the managed-guardrail adapter."""
383
+ return await self._client.post(url, content=body, headers=headers)
384
+
385
+ async def credentials(self) -> dict[str, Any]:
386
+ """The SigV4 credentials, resolved lazily.
387
+
388
+ Public because the managed-guardrail adapter signs with the same identity:
389
+ a deployment that can invoke a model can also apply a guardrail, and
390
+ reading the role twice would be two chances to read it differently.
391
+ """
392
+ return await self._credentials()
343
393
 
344
394
  def _build_payload(self, request: CompletionRequest, model: ModelSpec) -> dict[str, Any]:
345
395
  inference_config: dict[str, Any] = {"maxTokens": _max_tokens(request, model)}
@@ -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
+ )