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 CHANGED
@@ -72,6 +72,7 @@ from aid_runtime.cost import (
72
72
  )
73
73
  from aid_runtime.decisions import (
74
74
  DEFAULT_TYPESAFE_BASE_URL,
75
+ JEV_INPUT_USD_PER_MTOK,
75
76
  JEV_MOVING_ALIASES,
76
77
  TYPESAFE_API_KEY_ENVS,
77
78
  TYPESAFE_BASE_URL_ENV,
@@ -79,6 +80,7 @@ from aid_runtime.decisions import (
79
80
  DecisionClient,
80
81
  DecisionQuestion,
81
82
  DecisionResponse,
83
+ decision_cost_usd,
82
84
  decision_key,
83
85
  is_reproducible_model,
84
86
  )
@@ -158,12 +160,15 @@ from aid_runtime.providers import (
158
160
  BEDROCK_SERVICE,
159
161
  DEFAULT_ANTHROPIC_BASE_URL,
160
162
  DEFAULT_BASE_URL,
163
+ DEFAULT_GEMINI_BASE_URL,
161
164
  DEFAULT_VERTEX_LOCATION,
165
+ GEMINI_API_KEY_ENV,
162
166
  METADATA_TOKEN_URL,
163
167
  VERTEX_TOKEN_ENV,
164
168
  AnthropicProvider,
165
169
  BedrockProvider,
166
170
  FakeProvider,
171
+ GeminiProvider,
167
172
  OpenAICompatibleProvider,
168
173
  Provider,
169
174
  ScriptedTurn,
@@ -189,6 +194,7 @@ from aid_runtime.retrieval import (
189
194
  FakeDeterministicEmbedder,
190
195
  FileConnector,
191
196
  FixedChunker,
197
+ GeminiEmbedder,
192
198
  IndexSpec,
193
199
  IngestReport,
194
200
  InMemoryVectorStore,
@@ -295,7 +301,7 @@ from aid_runtime.types import (
295
301
  )
296
302
 
297
303
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
298
- __version__ = "0.1.95"
304
+ __version__ = "0.1.97"
299
305
 
300
306
  __all__ = [
301
307
  "ANTHROPIC_VERSION",
@@ -304,13 +310,16 @@ __all__ = [
304
310
  "DEFAULT_ANTHROPIC_BASE_URL",
305
311
  "DEFAULT_BASE_URL",
306
312
  "DEFAULT_CANDIDATE_FACTOR",
313
+ "DEFAULT_GEMINI_BASE_URL",
307
314
  "DEFAULT_TYPESAFE_BASE_URL",
308
315
  "DEFAULT_VERTEX_LOCATION",
309
316
  "DEPTH_KEY",
310
317
  "EMITTED_KEY",
318
+ "GEMINI_API_KEY_ENV",
311
319
  "GEN_AI_OPERATION_CHAT",
312
320
  "INDEX_KEY",
313
321
  "ITEM_KEY",
322
+ "JEV_INPUT_USD_PER_MTOK",
314
323
  "JEV_MOVING_ALIASES",
315
324
  "LIMITER_KEY",
316
325
  "MAX_STEP_DEPTH",
@@ -384,6 +393,8 @@ __all__ = [
384
393
  "GateConfigurationError",
385
394
  "GateResult",
386
395
  "GatewayRunner",
396
+ "GeminiEmbedder",
397
+ "GeminiProvider",
387
398
  "GenerationResult",
388
399
  "GuardrailBlockedError",
389
400
  "HumanApproval",
@@ -499,6 +510,7 @@ __all__ = [
499
510
  "chunker_for",
500
511
  "cite",
501
512
  "create_store",
513
+ "decision_cost_usd",
502
514
  "decision_key",
503
515
  "default_bedrock_base_url",
504
516
  "default_metrics",
aid_runtime/decisions.py CHANGED
@@ -38,9 +38,12 @@ from typing import Any, Literal
38
38
  import httpx
39
39
 
40
40
  from aid_runtime.errors import ConfigurationError, ProviderError, ProviderResponseError
41
+ from aid_runtime.tracing import llm_span, record_attributes, record_cost, record_usage
42
+ from aid_runtime.types import TokenUsage
41
43
 
42
44
  __all__ = [
43
45
  "DEFAULT_TYPESAFE_BASE_URL",
46
+ "JEV_INPUT_USD_PER_MTOK",
44
47
  "JEV_MOVING_ALIASES",
45
48
  "TYPESAFE_API_KEY_ENVS",
46
49
  "TYPESAFE_BASE_URL_ENV",
@@ -48,6 +51,7 @@ __all__ = [
48
51
  "DecisionClient",
49
52
  "DecisionQuestion",
50
53
  "DecisionResponse",
54
+ "decision_cost_usd",
51
55
  "decision_key",
52
56
  "is_reproducible_model",
53
57
  ]
@@ -64,6 +68,11 @@ TYPESAFE_BASE_URL_ENV = "TYPESAFE_BASE_URL"
64
68
  #: ``reproducible=True``.
65
69
  JEV_MOVING_ALIASES = frozenset({"jev-latest", "jev-preview"})
66
70
 
71
+ #: Jev bills input tokens at $42 per billion ($0.042 per million) and states that
72
+ #: output tokens are free. A call therefore needs an input row only, and a
73
+ #: decision run must never be reported as unpriceable.
74
+ JEV_INPUT_USD_PER_MTOK = 0.042
75
+
67
76
  QuestionType = Literal["choice", "score", "noul"]
68
77
 
69
78
  _QUESTION_TYPES: frozenset[str] = frozenset({"choice", "score", "noul"})
@@ -93,6 +102,19 @@ def is_reproducible_model(model: str) -> bool:
93
102
  return model not in JEV_MOVING_ALIASES
94
103
 
95
104
 
105
+ def decision_cost_usd(input_tokens: int | None) -> float:
106
+ """Price one decision call from its input tokens alone.
107
+
108
+ Output tokens are free by contract, so they are deliberately not part of the
109
+ arithmetic: a caller that passed a total would overcharge the run. ``None``
110
+ means the vendor reported no usage; :meth:`DecisionClient.decide` then records
111
+ no cost at all, so the call stays unknown rather than free.
112
+ """
113
+ if input_tokens is None:
114
+ return 0.0
115
+ return (input_tokens / 1_000_000) * JEV_INPUT_USD_PER_MTOK
116
+
117
+
96
118
  @dataclass(frozen=True, slots=True)
97
119
  class DecisionQuestion:
98
120
  """One typed question.
@@ -228,8 +250,22 @@ class DecisionClient:
228
250
  "state": state,
229
251
  "questions": {key: question.as_payload() for key, question in questions.items()},
230
252
  }
231
- body = await self._post(payload)
232
- return self._parse(body, questions)
253
+ # A decision is billed like any other model call, so it gets the same
254
+ # span: `aid cost` and the eval budget read `aid.cost.usd` off it.
255
+ with llm_span(model=model, provider=self._name, operation="decision") as span:
256
+ body = await self._post(payload)
257
+ response = self._parse(body, questions)
258
+ if response.input_tokens is not None:
259
+ usage = TokenUsage(
260
+ input_tokens=response.input_tokens,
261
+ output_tokens=response.output_tokens or 0,
262
+ )
263
+ record_usage(span, usage)
264
+ record_cost(span, decision_cost_usd(usage.input_tokens))
265
+ # The vendor echoes the version that actually answered, which is the
266
+ # only record of what a moving alias resolved to.
267
+ record_attributes(span, response_model=response.model)
268
+ return response
233
269
 
234
270
  async def close(self) -> None:
235
271
  if self._closed:
@@ -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