itself 0.2.0__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.
itself/inference.py ADDED
@@ -0,0 +1,1571 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Provider-neutral structured inference over OpenAI-compatible endpoints.
5
+
6
+ The concrete client in this module speaks the widely implemented Chat
7
+ Completions wire format. Its HTTP transport, credential source, artifact sink,
8
+ and structured-output behavior are explicit and replaceable. Model output is
9
+ always parsed locally as strict JSON and validated against the caller's schema.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import re
18
+ import socket
19
+ import stat
20
+ import tempfile
21
+ import threading
22
+ import time
23
+ from collections.abc import Callable, Iterator, Mapping, Sequence
24
+ from contextlib import suppress
25
+ from copy import deepcopy
26
+ from dataclasses import dataclass, field
27
+ from datetime import UTC, datetime
28
+ from email.message import Message
29
+ from enum import StrEnum
30
+ from functools import cache
31
+ from http.client import (
32
+ HTTPConnection,
33
+ HTTPException,
34
+ HTTPMessage,
35
+ HTTPResponse,
36
+ HTTPSConnection,
37
+ InvalidURL,
38
+ )
39
+ from pathlib import Path
40
+ from types import MappingProxyType
41
+ from typing import IO, Final, Protocol, cast
42
+ from urllib.error import HTTPError, URLError
43
+ from urllib.parse import urlsplit
44
+ from urllib.request import (
45
+ AbstractHTTPHandler,
46
+ BaseHandler,
47
+ HTTPHandler,
48
+ HTTPRedirectHandler,
49
+ HTTPSHandler,
50
+ OpenerDirector,
51
+ ProxyHandler,
52
+ Request,
53
+ build_opener,
54
+ )
55
+
56
+ from jsonschema import Draft202012Validator, FormatChecker
57
+ from jsonschema.exceptions import SchemaError, ValidationError
58
+
59
+ from ._endpoints import (
60
+ HEADER_NAME_PATTERN,
61
+ IDENTIFIER_PATTERN,
62
+ content_type,
63
+ defensive_extra_body,
64
+ endpoint_url,
65
+ frozen_extra_headers,
66
+ frozen_query_parameters,
67
+ is_loopback_hostname,
68
+ normalized_base_url,
69
+ normalized_resource_path,
70
+ token_counts,
71
+ validate_deadline,
72
+ validate_timeout,
73
+ )
74
+ from ._filesystem import publish_path_no_replace
75
+ from ._json import strict_json_loads
76
+ from .types import JsonObject, JsonValue
77
+
78
+ ADAPTER_ID: Final = "openai-compatible-chat-completions"
79
+ ADAPTER_VERSION: Final = "0.3.1"
80
+
81
+ _ENVIRONMENT_NAME_PATTERN: Final = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
82
+ _CREDENTIAL_VALUE_PATTERN: Final = re.compile(
83
+ r"[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?"
84
+ )
85
+ _RESERVED_BODY_FIELDS: Final = frozenset(
86
+ {"messages", "model", "response_format", "stream"}
87
+ )
88
+
89
+
90
+ class StructuredOutputMode(StrEnum):
91
+ """How a compatible endpoint is asked to produce structured output."""
92
+
93
+ JSON_SCHEMA = "json_schema"
94
+ JSON_OBJECT = "json_object"
95
+ PROMPTED_JSON = "prompted_json"
96
+
97
+
98
+ def _validated_output_mode(value: object) -> StructuredOutputMode:
99
+ if not isinstance(value, StructuredOutputMode):
100
+ raise ValueError("mode must be a StructuredOutputMode")
101
+ return value
102
+
103
+
104
+ class InferenceFailure(StrEnum):
105
+ """Stable failure stages for one structured-inference attempt."""
106
+
107
+ CONFIGURATION = "configuration"
108
+ TRANSPORT = "transport"
109
+ RESPONSE_TOO_LARGE = "response_too_large"
110
+ HTTP_AUTHENTICATION = "http_authentication"
111
+ HTTP_AUTHORIZATION = "http_authorization"
112
+ HTTP_RATE_LIMIT = "http_rate_limit"
113
+ HTTP_SERVER = "http_server"
114
+ HTTP_STATUS = "http_status"
115
+ REFUSAL = "refusal"
116
+ INCOMPLETE = "incomplete"
117
+ RESPONSE_ENVELOPE = "response_envelope"
118
+ RESPONSE_JSON = "response_json"
119
+ RESPONSE_SCHEMA = "response_schema"
120
+ RESPONSE_USAGE = "response_usage"
121
+ ARTIFACT = "artifact"
122
+
123
+
124
+ _RETRYABLE_FAILURES: Final = frozenset(
125
+ {
126
+ InferenceFailure.TRANSPORT,
127
+ InferenceFailure.HTTP_RATE_LIMIT,
128
+ InferenceFailure.HTTP_SERVER,
129
+ }
130
+ )
131
+
132
+
133
+ def _empty_headers() -> Mapping[str, str]:
134
+ return {}
135
+
136
+
137
+ def _empty_body() -> Mapping[str, JsonValue]:
138
+ return {}
139
+
140
+
141
+ def _empty_query() -> Mapping[str, str]:
142
+ return {}
143
+
144
+
145
+ def _default_finish_reasons() -> Sequence[str]:
146
+ return ("stop",)
147
+
148
+
149
+ class _SchemaValidator(Protocol):
150
+ """Typed surface used from the partially typed jsonschema dependency."""
151
+
152
+ def iter_errors(self, instance: JsonValue) -> Iterator[ValidationError]: ...
153
+
154
+
155
+ @dataclass(frozen=True, slots=True)
156
+ class ArtifactReference:
157
+ """Immutable reference to one captured provider response."""
158
+
159
+ uri: str
160
+ media_type: str
161
+ sha256: str
162
+ captured_at: str
163
+
164
+ def to_json_object(self) -> JsonObject:
165
+ """Return the protocol-friendly artifact representation."""
166
+
167
+ return {
168
+ "uri": self.uri,
169
+ "media_type": self.media_type,
170
+ "digest": {
171
+ "algorithm": "sha256",
172
+ "value": self.sha256,
173
+ },
174
+ "captured_at": self.captured_at,
175
+ }
176
+
177
+
178
+ class InferenceError(RuntimeError):
179
+ """Sanitized failure from one explicit inference attempt."""
180
+
181
+ def __init__(
182
+ self,
183
+ failure: InferenceFailure,
184
+ detail: str,
185
+ *,
186
+ status_code: int | None = None,
187
+ artifact: ArtifactReference | None = None,
188
+ ) -> None:
189
+ self.failure: InferenceFailure = failure
190
+ self.detail: str = detail
191
+ self.status_code: int | None = status_code
192
+ self.artifact: ArtifactReference | None = artifact
193
+ super().__init__(f"{failure.value}: {detail}")
194
+
195
+ def __reduce__(
196
+ self,
197
+ ) -> tuple[type[InferenceError], tuple[InferenceFailure, str], dict[str, object]]:
198
+ # The default reduction replays only the rendered message, which cannot
199
+ # rebuild an error that requires its failure and detail.
200
+ return (type(self), (self.failure, self.detail), self.__dict__)
201
+
202
+ @property
203
+ def retryable(self) -> bool:
204
+ """Whether a later, separately recorded attempt may be reasonable."""
205
+
206
+ return self.failure in _RETRYABLE_FAILURES
207
+
208
+
209
+ @dataclass(frozen=True, slots=True)
210
+ class EnvironmentCredential:
211
+ """Load one HTTP credential from an environment variable at call time."""
212
+
213
+ variable: str
214
+ header: str = "Authorization"
215
+ prefix: str = "Bearer "
216
+
217
+ def __post_init__(self) -> None:
218
+ if _ENVIRONMENT_NAME_PATTERN.fullmatch(self.variable) is None:
219
+ raise ValueError("credential variable must be an environment variable name")
220
+ if HEADER_NAME_PATTERN.fullmatch(self.header) is None:
221
+ raise ValueError("credential header must be a valid HTTP field name")
222
+ if "\r" in self.prefix or "\n" in self.prefix:
223
+ raise ValueError("credential prefix must be a single line")
224
+ if any(not " " <= character <= "~" for character in self.prefix):
225
+ raise ValueError("credential prefix must be printable ASCII")
226
+
227
+ def render(self, environment: Mapping[str, str]) -> tuple[str, str]:
228
+ """Resolve the secret only while rendering a request header."""
229
+
230
+ value = environment.get(self.variable)
231
+ # A traceback keeps each frame's local variables, which tools that
232
+ # record them would otherwise capture, so the secret and the whole
233
+ # environment are dropped before an error leaves this frame.
234
+ if value is None or not value.strip():
235
+ del value, environment
236
+ raise InferenceError(
237
+ InferenceFailure.CONFIGURATION,
238
+ f"credential environment variable {self.variable!r} "
239
+ "is missing or empty",
240
+ )
241
+ rendered = f"{self.prefix}{value}"
242
+ # http.client would either raise with the secret in its message or send
243
+ # a folded header line, so the value is refused here without echoing it.
244
+ if _CREDENTIAL_VALUE_PATTERN.fullmatch(rendered) is None:
245
+ del value, rendered, environment
246
+ raise InferenceError(
247
+ InferenceFailure.CONFIGURATION,
248
+ f"credential environment variable {self.variable!r} must be "
249
+ "printable ASCII without line breaks or trailing whitespace",
250
+ )
251
+ return self.header, rendered
252
+
253
+
254
+ @dataclass(frozen=True, slots=True)
255
+ class OpenAICompatibleEndpoint:
256
+ """One declared Chat Completions endpoint and model configuration."""
257
+
258
+ actor_id: str
259
+ base_url: str
260
+ model: str
261
+ credential: EnvironmentCredential | None = None
262
+ resource_path: str = "chat/completions"
263
+ query_parameters: Mapping[str, str] = field(
264
+ default_factory=_empty_query,
265
+ repr=False,
266
+ )
267
+ timeout_seconds: float = 90.0
268
+ max_output_tokens: int | None = 2_048
269
+ max_output_tokens_field: str = "max_tokens"
270
+ accepted_finish_reasons: Sequence[str] = field(
271
+ default_factory=_default_finish_reasons,
272
+ )
273
+ stream: bool = False
274
+ allow_insecure_http: bool = False
275
+ extra_headers: Mapping[str, str] = field(
276
+ default_factory=_empty_headers,
277
+ repr=False,
278
+ )
279
+ extra_body: Mapping[str, JsonValue] = field(
280
+ default_factory=_empty_body,
281
+ repr=False,
282
+ )
283
+ deadline_seconds: float | None = None
284
+
285
+ def __post_init__(self) -> None:
286
+ if IDENTIFIER_PATTERN.fullmatch(self.actor_id) is None:
287
+ raise ValueError("actor_id must be a valid identifier")
288
+
289
+ object.__setattr__(
290
+ self,
291
+ "base_url",
292
+ normalized_base_url(
293
+ self.base_url,
294
+ credential_bearing=self.credential is not None,
295
+ allow_insecure_http=self.allow_insecure_http,
296
+ ),
297
+ )
298
+ object.__setattr__(
299
+ self,
300
+ "resource_path",
301
+ normalized_resource_path(self.resource_path),
302
+ )
303
+
304
+ if not self.model or self.model != self.model.strip():
305
+ raise ValueError("model must be non-empty without outer space")
306
+ validate_timeout(self.timeout_seconds)
307
+ validate_deadline(self.deadline_seconds)
308
+ if self.max_output_tokens is not None and (
309
+ isinstance(self.max_output_tokens, bool) or self.max_output_tokens <= 0
310
+ ):
311
+ raise ValueError("max_output_tokens must be positive or None")
312
+ if IDENTIFIER_PATTERN.fullmatch(self.max_output_tokens_field) is None:
313
+ raise ValueError("max_output_tokens_field must be a valid field name")
314
+
315
+ finish_reasons = tuple(self.accepted_finish_reasons)
316
+ if not finish_reasons or any(
317
+ not reason or reason != reason.strip() for reason in finish_reasons
318
+ ):
319
+ raise ValueError("accepted_finish_reasons must contain non-empty values")
320
+ if len(finish_reasons) != len(set(finish_reasons)):
321
+ raise ValueError("accepted_finish_reasons must not contain duplicates")
322
+ object.__setattr__(self, "accepted_finish_reasons", finish_reasons)
323
+ if type(self.stream) is not bool:
324
+ raise ValueError("stream must be a boolean")
325
+
326
+ object.__setattr__(
327
+ self,
328
+ "query_parameters",
329
+ frozen_query_parameters(self.query_parameters),
330
+ )
331
+ object.__setattr__(
332
+ self,
333
+ "extra_headers",
334
+ frozen_extra_headers(
335
+ self.extra_headers,
336
+ credential_header=(
337
+ None if self.credential is None else self.credential.header
338
+ ),
339
+ ),
340
+ )
341
+ reserved_body_fields = set(_RESERVED_BODY_FIELDS)
342
+ if self.max_output_tokens is not None:
343
+ reserved_body_fields.add(self.max_output_tokens_field)
344
+ object.__setattr__(
345
+ self,
346
+ "extra_body",
347
+ defensive_extra_body(self.extra_body, reserved=reserved_body_fields),
348
+ )
349
+
350
+ @property
351
+ def url(self) -> str:
352
+ """Return the fully rendered endpoint URL without credentials."""
353
+
354
+ return endpoint_url(self.base_url, self.resource_path, self.query_parameters)
355
+
356
+
357
+ @dataclass(frozen=True, slots=True, init=False)
358
+ class StructuredOutputProfile:
359
+ """Provider-neutral instructions and schema for one JSON output."""
360
+
361
+ profile_id: str
362
+ schema_name: str
363
+ system_prompt: str
364
+ user_instruction: str
365
+ input_label: str
366
+ mode: StructuredOutputMode
367
+ _schema: JsonObject = field(repr=False)
368
+
369
+ def __init__(
370
+ self,
371
+ profile_id: str,
372
+ schema_name: str,
373
+ system_prompt: str,
374
+ user_instruction: str,
375
+ input_label: str,
376
+ schema: Mapping[str, JsonValue],
377
+ mode: StructuredOutputMode = StructuredOutputMode.JSON_SCHEMA,
378
+ ) -> None:
379
+ for field_name, value in (
380
+ ("profile_id", profile_id),
381
+ ("schema_name", schema_name),
382
+ ):
383
+ if IDENTIFIER_PATTERN.fullmatch(value) is None:
384
+ raise ValueError(f"{field_name} must be a valid identifier")
385
+ for field_name, value in (
386
+ ("system_prompt", system_prompt),
387
+ ("user_instruction", user_instruction),
388
+ ("input_label", input_label),
389
+ ):
390
+ if not value or value != value.strip():
391
+ raise ValueError(f"{field_name} must be non-empty without outer space")
392
+ schema_value = deepcopy(dict(schema))
393
+ try:
394
+ json.dumps(schema_value, allow_nan=False)
395
+ Draft202012Validator.check_schema(schema_value)
396
+ except (TypeError, ValueError, SchemaError) as error:
397
+ raise ValueError(
398
+ "profile schema must be valid finite JSON Schema"
399
+ ) from error
400
+ object.__setattr__(self, "profile_id", profile_id)
401
+ object.__setattr__(self, "schema_name", schema_name)
402
+ object.__setattr__(self, "system_prompt", system_prompt)
403
+ object.__setattr__(self, "user_instruction", user_instruction)
404
+ object.__setattr__(self, "input_label", input_label)
405
+ object.__setattr__(self, "mode", _validated_output_mode(mode))
406
+ object.__setattr__(self, "_schema", schema_value)
407
+
408
+ def schema_json(self) -> JsonObject:
409
+ """Return a defensive copy of the output schema."""
410
+
411
+ return deepcopy(self._schema)
412
+
413
+
414
+ def build_chat_completions_payload(
415
+ endpoint: OpenAICompatibleEndpoint,
416
+ input_value: JsonValue,
417
+ profile: StructuredOutputProfile,
418
+ ) -> JsonObject:
419
+ """Render one structured-output request without credentials."""
420
+
421
+ schema = profile.schema_json()
422
+ input_json = json.dumps(
423
+ input_value,
424
+ allow_nan=False,
425
+ ensure_ascii=False,
426
+ indent=2,
427
+ sort_keys=True,
428
+ )
429
+ schema_json = json.dumps(
430
+ schema,
431
+ allow_nan=False,
432
+ ensure_ascii=False,
433
+ indent=2,
434
+ sort_keys=True,
435
+ )
436
+ user_prompt = (
437
+ f"{profile.user_instruction}\n\n"
438
+ f"{profile.input_label}\n{input_json}\n\n"
439
+ f"OUTPUT SCHEMA\n{schema_json}"
440
+ )
441
+ payload: JsonObject = deepcopy(dict(endpoint.extra_body))
442
+ payload.update(
443
+ {
444
+ "model": endpoint.model,
445
+ "messages": [
446
+ {"role": "system", "content": profile.system_prompt},
447
+ {"role": "user", "content": user_prompt},
448
+ ],
449
+ "stream": endpoint.stream,
450
+ }
451
+ )
452
+ if endpoint.max_output_tokens is not None:
453
+ payload[endpoint.max_output_tokens_field] = endpoint.max_output_tokens
454
+ if profile.mode is StructuredOutputMode.JSON_SCHEMA:
455
+ payload["response_format"] = {
456
+ "type": "json_schema",
457
+ "json_schema": {
458
+ "name": profile.schema_name,
459
+ "strict": True,
460
+ "schema": schema,
461
+ },
462
+ }
463
+ elif profile.mode is StructuredOutputMode.JSON_OBJECT:
464
+ payload["response_format"] = {"type": "json_object"}
465
+ return payload
466
+
467
+
468
+ @dataclass(frozen=True, slots=True)
469
+ class HttpRequest:
470
+ """One rendered HTTP request; secret-bearing fields are repr-hidden."""
471
+
472
+ url: str
473
+ headers: Mapping[str, str] = field(repr=False)
474
+ body: bytes = field(repr=False)
475
+ timeout_seconds: float
476
+ deadline_seconds: float | None = None
477
+
478
+ def __post_init__(self) -> None:
479
+ object.__setattr__(self, "headers", MappingProxyType(dict(self.headers)))
480
+
481
+
482
+ @dataclass(frozen=True, slots=True)
483
+ class HttpResponse:
484
+ """Bounded HTTP response captured by a transport."""
485
+
486
+ status_code: int
487
+ headers: Mapping[str, str]
488
+ body: bytes
489
+
490
+ def __post_init__(self) -> None:
491
+ object.__setattr__(self, "headers", MappingProxyType(dict(self.headers)))
492
+
493
+
494
+ class HttpTransport(Protocol):
495
+ """Minimal synchronous HTTP boundary used by the compatible client."""
496
+
497
+ def send(self, request: HttpRequest, /) -> HttpResponse:
498
+ """Send one request without implicit retry."""
499
+
500
+ ...
501
+
502
+
503
+ class _NoRedirectHandler(HTTPRedirectHandler):
504
+ def redirect_request(
505
+ self,
506
+ req: Request,
507
+ fp: IO[bytes],
508
+ code: int,
509
+ msg: str,
510
+ headers: HTTPMessage,
511
+ newurl: str,
512
+ ) -> None:
513
+ del req, fp, code, msg, headers, newurl
514
+ return None
515
+
516
+
517
+ @cache
518
+ def _direct_opener() -> OpenerDirector:
519
+ """Return the shared opener for loopback hosts, which never uses a proxy."""
520
+
521
+ return build_opener(ProxyHandler({}), _NoRedirectHandler())
522
+
523
+
524
+ class _SocketTracker:
525
+ """One request's connections, shut down together when its deadline passes.
526
+
527
+ The tracker holds a duplicate descriptor of each socket from the moment it
528
+ connects. Shutting a duplicate down ends the shared connection, so the
529
+ deadline also covers a proxy's CONNECT exchange and the TLS handshake, and
530
+ it still reaches the connection after TLS has taken over the original
531
+ socket object. The lock keeps shutdown and close from racing, so a
532
+ descriptor number is never used after it is released.
533
+ """
534
+
535
+ def __init__(self) -> None:
536
+ self._lock = threading.Lock()
537
+ self._sockets: list[socket.socket] = []
538
+ self.expired = threading.Event()
539
+
540
+ def add(self, connection_socket: socket.socket) -> None:
541
+ with self._lock:
542
+ duplicate = connection_socket.dup()
543
+ self._sockets.append(duplicate)
544
+ # A connection that opens after the deadline is shut down at once.
545
+ if self.expired.is_set():
546
+ _shut_down(duplicate)
547
+
548
+ def expire(self) -> None:
549
+ with self._lock:
550
+ self.expired.set()
551
+ for duplicate in self._sockets:
552
+ _shut_down(duplicate)
553
+
554
+ def close(self) -> None:
555
+ with self._lock:
556
+ for duplicate in self._sockets:
557
+ duplicate.close()
558
+ self._sockets.clear()
559
+
560
+
561
+ def _shut_down(connection_socket: socket.socket) -> None:
562
+ with suppress(OSError):
563
+ connection_socket.shutdown(socket.SHUT_RDWR)
564
+
565
+
566
+ def _tracked_socket_factory(
567
+ tracker: _SocketTracker,
568
+ ) -> Callable[[tuple[str, int], float | None, tuple[str, int] | None], socket.socket]:
569
+ def create(
570
+ address: tuple[str, int],
571
+ timeout: float | None,
572
+ source_address: tuple[str, int] | None,
573
+ ) -> socket.socket:
574
+ connection_socket = socket.create_connection(address, timeout, source_address)
575
+ try:
576
+ tracker.add(connection_socket)
577
+ except BaseException:
578
+ connection_socket.close()
579
+ raise
580
+ return connection_socket
581
+
582
+ return create
583
+
584
+
585
+ class _TrackedHTTPConnection(HTTPConnection):
586
+ def __init__(
587
+ self,
588
+ host: str,
589
+ *,
590
+ tracker: _SocketTracker,
591
+ port: int | None = None,
592
+ timeout: float | None = None,
593
+ source_address: tuple[str, int] | None = None,
594
+ blocksize: int = 8192,
595
+ ) -> None:
596
+ super().__init__(
597
+ host,
598
+ port=port,
599
+ timeout=timeout,
600
+ source_address=source_address,
601
+ blocksize=blocksize,
602
+ )
603
+ # Every Python release this package supports opens the socket, and
604
+ # any proxy tunnel, through this factory attribute.
605
+ self._create_connection = _tracked_socket_factory(tracker)
606
+
607
+
608
+ class _TrackedHTTPSConnection(HTTPSConnection):
609
+ def __init__(
610
+ self,
611
+ host: str,
612
+ *,
613
+ tracker: _SocketTracker,
614
+ port: int | None = None,
615
+ timeout: float | None = None,
616
+ source_address: tuple[str, int] | None = None,
617
+ blocksize: int = 8192,
618
+ ) -> None:
619
+ # No context is passed, so certificates are trusted exactly as they
620
+ # are for requests without a deadline.
621
+ super().__init__(
622
+ host,
623
+ port=port,
624
+ timeout=timeout,
625
+ source_address=source_address,
626
+ blocksize=blocksize,
627
+ )
628
+ self._create_connection = _tracked_socket_factory(tracker)
629
+
630
+
631
+ class _TrackedHTTPHandler(HTTPHandler):
632
+ def __init__(self, tracker: _SocketTracker) -> None:
633
+ super().__init__()
634
+ self._tracker = tracker
635
+
636
+ def http_open(self, req: Request) -> HTTPResponse:
637
+ tracker = self._tracker
638
+
639
+ def connection(
640
+ host: str,
641
+ /,
642
+ *,
643
+ port: int | None = None,
644
+ timeout: float | None = None,
645
+ source_address: tuple[str, int] | None = None,
646
+ blocksize: int = 8192,
647
+ ) -> HTTPConnection:
648
+ return _TrackedHTTPConnection(
649
+ host,
650
+ tracker=tracker,
651
+ port=port,
652
+ timeout=timeout,
653
+ source_address=source_address,
654
+ blocksize=blocksize,
655
+ )
656
+
657
+ return self.do_open(connection, req)
658
+
659
+
660
+ class _TrackedHTTPSHandler(HTTPSHandler):
661
+ def __init__(self, tracker: _SocketTracker) -> None:
662
+ # HTTPSHandler would load a trust store here for connections that this
663
+ # handler never makes. Each tracked connection loads its own through
664
+ # the standard hook, so a plain HTTP request loads none.
665
+ AbstractHTTPHandler.__init__(self)
666
+ self._tracker = tracker
667
+
668
+ def https_open(self, req: Request) -> HTTPResponse:
669
+ tracker = self._tracker
670
+
671
+ def connection(
672
+ host: str,
673
+ /,
674
+ *,
675
+ port: int | None = None,
676
+ timeout: float | None = None,
677
+ source_address: tuple[str, int] | None = None,
678
+ blocksize: int = 8192,
679
+ ) -> HTTPConnection:
680
+ return _TrackedHTTPSConnection(
681
+ host,
682
+ tracker=tracker,
683
+ port=port,
684
+ timeout=timeout,
685
+ source_address=source_address,
686
+ blocksize=blocksize,
687
+ )
688
+
689
+ return self.do_open(connection, req)
690
+
691
+
692
+ def _opener(url: str, tracker: _SocketTracker | None = None) -> OpenerDirector:
693
+ loopback = is_loopback_hostname(urlsplit(url).hostname)
694
+ if tracker is None:
695
+ if loopback:
696
+ return _direct_opener()
697
+ # Other hosts honor the proxy environment, which is read on every request.
698
+ return build_opener(_NoRedirectHandler())
699
+ handlers: list[BaseHandler] = [
700
+ _NoRedirectHandler(),
701
+ _TrackedHTTPHandler(tracker),
702
+ _TrackedHTTPSHandler(tracker),
703
+ ]
704
+ if loopback:
705
+ handlers.insert(0, ProxyHandler({}))
706
+ return build_opener(*handlers)
707
+
708
+
709
+ @dataclass(frozen=True, slots=True)
710
+ class UrllibHttpTransport:
711
+ """Standard-library transport with bounded reads, no redirect, and no retry."""
712
+
713
+ max_response_bytes: int = 2_000_000
714
+
715
+ def __post_init__(self) -> None:
716
+ if isinstance(self.max_response_bytes, bool) or self.max_response_bytes <= 0:
717
+ raise ValueError("max_response_bytes must be a positive integer")
718
+
719
+ def _read_body(self, response: object) -> bytes:
720
+ read = getattr(response, "read", None)
721
+ if not callable(read):
722
+ raise InferenceError(
723
+ InferenceFailure.TRANSPORT,
724
+ "HTTP response does not expose a readable body",
725
+ )
726
+ body: object = read(self.max_response_bytes + 1)
727
+ if not isinstance(body, bytes):
728
+ raise InferenceError(
729
+ InferenceFailure.TRANSPORT,
730
+ "HTTP response body was not bytes",
731
+ )
732
+ if len(body) > self.max_response_bytes:
733
+ raise InferenceError(
734
+ InferenceFailure.RESPONSE_TOO_LARGE,
735
+ "inference endpoint response exceeded the configured byte limit",
736
+ )
737
+ # A bounded read does not raise when a declared Content-Length is cut
738
+ # short, so the undelivered remainder is checked explicitly.
739
+ remaining: object = getattr(response, "length", None)
740
+ if isinstance(remaining, int) and remaining > 0:
741
+ raise InferenceError(
742
+ InferenceFailure.TRANSPORT,
743
+ "inference endpoint response ended before its declared length",
744
+ )
745
+ return body
746
+
747
+ @staticmethod
748
+ def _headers(response: object) -> Mapping[str, str]:
749
+ headers = getattr(response, "headers", None)
750
+ if isinstance(headers, Message):
751
+ items = cast(list[tuple[str, str]], headers.items())
752
+ return dict(items)
753
+ if isinstance(headers, Mapping):
754
+ values = cast(Mapping[object, object], headers)
755
+ return {str(name): str(value) for name, value in values.items()}
756
+ return {}
757
+
758
+ def send(self, request: HttpRequest, /) -> HttpResponse:
759
+ """Send one POST and return success or HTTP-error bodies uniformly.
760
+
761
+ ``timeout_seconds`` bounds each socket operation, including each
762
+ connection attempt. When the request carries ``deadline_seconds``, a
763
+ timer also shuts the connection down once that much time has passed,
764
+ however the peer keeps it busy, from the moment the socket connects:
765
+ a proxy's CONNECT exchange and the TLS handshake count against it.
766
+ Host name resolution is bounded by neither setting.
767
+ """
768
+
769
+ if urlsplit(request.url).scheme not in {"http", "https"}:
770
+ raise InferenceError(
771
+ InferenceFailure.CONFIGURATION,
772
+ "inference transport requests must use HTTP or HTTPS",
773
+ )
774
+ try:
775
+ validate_timeout(request.timeout_seconds)
776
+ validate_deadline(request.deadline_seconds)
777
+ except ValueError as error:
778
+ raise InferenceError(InferenceFailure.CONFIGURATION, str(error)) from None
779
+ wire_request = Request(
780
+ request.url,
781
+ data=request.body,
782
+ headers=dict(request.headers),
783
+ method="POST",
784
+ )
785
+ if request.deadline_seconds is None:
786
+ return self._exchange(
787
+ _opener(request.url),
788
+ wire_request,
789
+ request.timeout_seconds,
790
+ )
791
+
792
+ tracker = _SocketTracker()
793
+ timer = threading.Timer(request.deadline_seconds, tracker.expire)
794
+ timer.daemon = True
795
+ timer.start()
796
+ try:
797
+ response = self._exchange(
798
+ _opener(request.url, tracker),
799
+ wire_request,
800
+ request.timeout_seconds,
801
+ )
802
+ except InferenceError:
803
+ if tracker.expired.is_set():
804
+ raise InferenceError(
805
+ InferenceFailure.TRANSPORT,
806
+ "inference endpoint exceeded the request deadline",
807
+ ) from None
808
+ raise
809
+ finally:
810
+ timer.cancel()
811
+ tracker.close()
812
+ # A shut-down connection can still end in a complete-looking response.
813
+ if tracker.expired.is_set():
814
+ raise InferenceError(
815
+ InferenceFailure.TRANSPORT,
816
+ "inference endpoint exceeded the request deadline",
817
+ )
818
+ return response
819
+
820
+ def _exchange(
821
+ self,
822
+ opener: OpenerDirector,
823
+ wire_request: Request,
824
+ timeout_seconds: float,
825
+ ) -> HttpResponse:
826
+ try:
827
+ try:
828
+ with opener.open(
829
+ wire_request,
830
+ timeout=timeout_seconds,
831
+ ) as response:
832
+ return HttpResponse(
833
+ status_code=response.status,
834
+ headers=self._headers(response),
835
+ body=self._read_body(response),
836
+ )
837
+ except HTTPError as error:
838
+ with error:
839
+ return HttpResponse(
840
+ status_code=error.code,
841
+ headers=self._headers(error),
842
+ body=self._read_body(error),
843
+ )
844
+ except InvalidURL:
845
+ raise InferenceError(
846
+ InferenceFailure.CONFIGURATION,
847
+ "inference request URL is not a valid HTTP request target",
848
+ ) from None
849
+ except UnicodeError:
850
+ raise InferenceError(
851
+ InferenceFailure.CONFIGURATION,
852
+ "inference request URL or headers cannot be encoded for HTTP",
853
+ ) from None
854
+ except (TimeoutError, URLError, OSError, HTTPException) as error:
855
+ raise InferenceError(
856
+ InferenceFailure.TRANSPORT,
857
+ "inference endpoint request failed",
858
+ ) from error
859
+
860
+
861
+ class ArtifactSink(Protocol):
862
+ """Capture an untrusted provider response under an operator policy."""
863
+
864
+ def capture(
865
+ self,
866
+ content: bytes,
867
+ /,
868
+ *,
869
+ media_type: str,
870
+ captured_at: datetime,
871
+ ) -> ArtifactReference:
872
+ """Persist bytes and return their immutable reference and digest."""
873
+
874
+ ...
875
+
876
+
877
+ def _require_private_artifact_directory(path: Path) -> None:
878
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
879
+ metadata = path.lstat()
880
+ if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode):
881
+ raise OSError("artifact root must be a directory, not a symbolic link")
882
+ if os.name == "posix" and stat.S_IMODE(metadata.st_mode) & (
883
+ stat.S_IRWXG | stat.S_IRWXO
884
+ ):
885
+ raise PermissionError("artifact root must not grant group or other permissions")
886
+
887
+
888
+ def _validate_existing_artifact(path: Path, content: bytes) -> None:
889
+ metadata = path.lstat()
890
+ if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode):
891
+ raise OSError("artifact path must be a regular file, not a symlink")
892
+ if os.name == "posix" and stat.S_IMODE(metadata.st_mode) & (
893
+ stat.S_IRWXG | stat.S_IRWXO
894
+ ):
895
+ raise PermissionError("artifact file must not grant group or other permissions")
896
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
897
+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
898
+ descriptor = os.open(path, flags)
899
+ try:
900
+ opened_metadata = os.fstat(descriptor)
901
+ if not stat.S_ISREG(opened_metadata.st_mode) or (
902
+ opened_metadata.st_dev,
903
+ opened_metadata.st_ino,
904
+ ) != (metadata.st_dev, metadata.st_ino):
905
+ raise OSError("artifact path changed while opening")
906
+ except BaseException:
907
+ os.close(descriptor)
908
+ raise
909
+ with os.fdopen(descriptor, "rb") as handle:
910
+ observed = handle.read(len(content) + 1)
911
+ final_size = os.fstat(handle.fileno()).st_size
912
+ if (
913
+ metadata.st_size != len(content)
914
+ or final_size != metadata.st_size
915
+ or observed != content
916
+ ):
917
+ raise OSError("content-addressed artifact digest collision")
918
+
919
+
920
+ @dataclass(frozen=True, slots=True)
921
+ class DirectoryArtifactSink:
922
+ """Content-addressed local response sink with private file permissions."""
923
+
924
+ root: Path
925
+ uri_prefix: str | None = None
926
+
927
+ def __post_init__(self) -> None:
928
+ object.__setattr__(self, "root", Path(self.root))
929
+ if self.uri_prefix is None:
930
+ return
931
+ prefix = self.uri_prefix
932
+ if (
933
+ not prefix
934
+ or prefix != prefix.strip()
935
+ or prefix.startswith("/")
936
+ or prefix.endswith("/")
937
+ or "\\" in prefix
938
+ or any(part in {"", ".", ".."} for part in prefix.split("/"))
939
+ ):
940
+ raise ValueError("uri_prefix must be a normalized relative URI path")
941
+ parsed_prefix = urlsplit(prefix)
942
+ if parsed_prefix.scheme or parsed_prefix.netloc or parsed_prefix.query:
943
+ raise ValueError("uri_prefix must be a normalized relative URI path")
944
+ if parsed_prefix.fragment:
945
+ raise ValueError("uri_prefix must not contain a fragment")
946
+
947
+ def capture(
948
+ self,
949
+ content: bytes,
950
+ /,
951
+ *,
952
+ media_type: str,
953
+ captured_at: datetime,
954
+ ) -> ArtifactReference:
955
+ """Atomically capture exact response bytes under their SHA-256 digest."""
956
+
957
+ if captured_at.tzinfo is None or captured_at.utcoffset() is None:
958
+ raise ValueError("captured_at must be timezone-aware")
959
+ normalized_media_type = media_type.strip()
960
+ if not normalized_media_type:
961
+ raise ValueError("media_type must be non-empty")
962
+
963
+ digest = hashlib.sha256(content).hexdigest()
964
+ suffix = ".json" if normalized_media_type == "application/json" else ".bin"
965
+ _require_private_artifact_directory(self.root)
966
+ path = self.root / f"sha256-{digest}{suffix}"
967
+
968
+ try:
969
+ metadata = path.lstat()
970
+ except FileNotFoundError:
971
+ metadata = None
972
+
973
+ if metadata is not None:
974
+ _validate_existing_artifact(path, content)
975
+ else:
976
+ descriptor, temporary_name = tempfile.mkstemp(
977
+ dir=self.root,
978
+ prefix=".artifact-",
979
+ suffix=".tmp",
980
+ )
981
+ temporary_path = Path(temporary_name)
982
+ try:
983
+ with os.fdopen(descriptor, "wb") as handle:
984
+ # Windows has no fchmod before Python 3.13 and no POSIX modes.
985
+ if os.name == "posix":
986
+ os.fchmod(handle.fileno(), stat.S_IRUSR | stat.S_IWUSR)
987
+ handle.write(content)
988
+ handle.flush()
989
+ os.fsync(handle.fileno())
990
+ try:
991
+ publish_path_no_replace(temporary_path, path)
992
+ except FileExistsError:
993
+ _validate_existing_artifact(path, content)
994
+ finally:
995
+ temporary_path.unlink(missing_ok=True)
996
+
997
+ timestamp = captured_at.astimezone(UTC).isoformat().replace("+00:00", "Z")
998
+ uri = (
999
+ path.resolve().as_uri()
1000
+ if self.uri_prefix is None
1001
+ else f"{self.uri_prefix}/{path.name}"
1002
+ )
1003
+ return ArtifactReference(
1004
+ uri=uri,
1005
+ media_type=normalized_media_type,
1006
+ sha256=digest,
1007
+ captured_at=timestamp,
1008
+ )
1009
+
1010
+
1011
+ def _object(value: JsonValue) -> JsonObject:
1012
+ if not isinstance(value, dict):
1013
+ raise TypeError("expected a JSON object")
1014
+ return value
1015
+
1016
+
1017
+ def _array(value: JsonValue) -> list[JsonValue]:
1018
+ if not isinstance(value, list):
1019
+ raise TypeError("expected a JSON array")
1020
+ return value
1021
+
1022
+
1023
+ def _string(value: JsonValue) -> str:
1024
+ if not isinstance(value, str):
1025
+ raise TypeError("expected a JSON string")
1026
+ return value
1027
+
1028
+
1029
+ def _http_failure(status_code: int) -> InferenceFailure:
1030
+ if status_code == 401:
1031
+ return InferenceFailure.HTTP_AUTHENTICATION
1032
+ if status_code == 403:
1033
+ return InferenceFailure.HTTP_AUTHORIZATION
1034
+ if status_code == 429:
1035
+ return InferenceFailure.HTTP_RATE_LIMIT
1036
+ if 500 <= status_code <= 599:
1037
+ return InferenceFailure.HTTP_SERVER
1038
+ return InferenceFailure.HTTP_STATUS
1039
+
1040
+
1041
+ def _utc_now() -> datetime:
1042
+ return datetime.now(UTC)
1043
+
1044
+
1045
+ @dataclass(frozen=True, slots=True)
1046
+ class InferenceIdentity:
1047
+ """Requested and provider-reported identity for one model invocation."""
1048
+
1049
+ actor_id: str
1050
+ adapter_id: str
1051
+ adapter_version: str
1052
+ requested_model: str
1053
+ resolved_model: str | None = None
1054
+
1055
+
1056
+ @dataclass(frozen=True, slots=True)
1057
+ class InferenceUsage:
1058
+ """Provider-reported token counts plus locally measured elapsed time."""
1059
+
1060
+ input_tokens: int | None
1061
+ output_tokens: int | None
1062
+ total_tokens: int | None
1063
+ wall_time_ms: int
1064
+
1065
+ def __post_init__(self) -> None:
1066
+ for name, value in (
1067
+ ("input_tokens", self.input_tokens),
1068
+ ("output_tokens", self.output_tokens),
1069
+ ("total_tokens", self.total_tokens),
1070
+ ("wall_time_ms", self.wall_time_ms),
1071
+ ):
1072
+ if value is not None and (isinstance(value, bool) or value < 0):
1073
+ raise ValueError(f"{name} must be a non-negative integer or None")
1074
+
1075
+
1076
+ @dataclass(frozen=True, slots=True, init=False)
1077
+ class StructuredInferenceResult:
1078
+ """One schema-validated JSON output with observed provenance and cost."""
1079
+
1080
+ _value: JsonValue = field(repr=False)
1081
+ identity: InferenceIdentity
1082
+ raw_response: ArtifactReference
1083
+ usage: InferenceUsage
1084
+ profile_id: str
1085
+
1086
+ def __init__(
1087
+ self,
1088
+ value: JsonValue,
1089
+ identity: InferenceIdentity,
1090
+ raw_response: ArtifactReference,
1091
+ usage: InferenceUsage,
1092
+ profile_id: str,
1093
+ ) -> None:
1094
+ object.__setattr__(self, "_value", deepcopy(value))
1095
+ object.__setattr__(self, "identity", identity)
1096
+ object.__setattr__(self, "raw_response", raw_response)
1097
+ object.__setattr__(self, "usage", usage)
1098
+ object.__setattr__(self, "profile_id", profile_id)
1099
+
1100
+ @property
1101
+ def value(self) -> JsonValue:
1102
+ """Return a defensive copy of the parsed model value."""
1103
+
1104
+ return deepcopy(self._value)
1105
+
1106
+
1107
+ class StructuredInferenceAdapter(Protocol):
1108
+ """Provider-neutral boundary implemented by structured inference adapters."""
1109
+
1110
+ def invoke(
1111
+ self,
1112
+ input_value: JsonValue,
1113
+ profile: StructuredOutputProfile,
1114
+ ) -> StructuredInferenceResult:
1115
+ """Return one captured and schema-validated structured output."""
1116
+
1117
+ ...
1118
+
1119
+
1120
+ @dataclass(frozen=True, slots=True)
1121
+ class _Completion:
1122
+ content: str
1123
+ resolved_model: str | None
1124
+ input_tokens: int | None
1125
+ output_tokens: int | None
1126
+ total_tokens: int | None
1127
+
1128
+
1129
+ def _message_content(value: JsonValue) -> str:
1130
+ if isinstance(value, str):
1131
+ return value
1132
+ parts = _array(value)
1133
+ texts: list[str] = []
1134
+ for item in parts:
1135
+ part = _object(item)
1136
+ part_type = part.get("type")
1137
+ if part_type not in {"text", "output_text"}:
1138
+ raise TypeError("message content contained a non-text part")
1139
+ texts.append(_string(part.get("text")))
1140
+ if not texts:
1141
+ raise TypeError("message content did not contain text")
1142
+ return "".join(texts)
1143
+
1144
+
1145
+ def _sse_data_events(body: bytes) -> tuple[str, ...]:
1146
+ """Decode one complete bounded SSE response into ordered data fields."""
1147
+
1148
+ text = body.decode("utf-8")
1149
+ normalized = text.replace("\r\n", "\n").replace("\r", "\n")
1150
+ events: list[str] = []
1151
+ for block in normalized.split("\n\n"):
1152
+ if not block:
1153
+ continue
1154
+ data_lines: list[str] = []
1155
+ for line in block.split("\n"):
1156
+ if not line or line.startswith(":"):
1157
+ continue
1158
+ field, separator, raw_value = line.partition(":")
1159
+ value = (
1160
+ raw_value[1:] if separator and raw_value.startswith(" ") else raw_value
1161
+ )
1162
+ if field == "data":
1163
+ data_lines.append(value)
1164
+ if data_lines:
1165
+ events.append("\n".join(data_lines))
1166
+ if not events or events[-1] != "[DONE]" or "[DONE]" in events[:-1]:
1167
+ raise ValueError("SSE response did not end with one terminal marker")
1168
+ return tuple(events[:-1])
1169
+
1170
+
1171
+ @dataclass(frozen=True, slots=True)
1172
+ class StructuredInferenceClient:
1173
+ """Perform one observable JSON call through a compatible endpoint."""
1174
+
1175
+ endpoint: OpenAICompatibleEndpoint
1176
+ artifact_sink: ArtifactSink
1177
+ transport: HttpTransport = field(default_factory=UrllibHttpTransport)
1178
+ environment: Mapping[str, str] = field(
1179
+ default_factory=lambda: os.environ,
1180
+ repr=False,
1181
+ compare=False,
1182
+ )
1183
+ now: Callable[[], datetime] = field(
1184
+ default=_utc_now,
1185
+ repr=False,
1186
+ compare=False,
1187
+ )
1188
+ monotonic_ns: Callable[[], int] = field(
1189
+ default=time.monotonic_ns,
1190
+ repr=False,
1191
+ compare=False,
1192
+ )
1193
+
1194
+ def _request(
1195
+ self,
1196
+ input_value: JsonValue,
1197
+ profile: StructuredOutputProfile,
1198
+ ) -> HttpRequest:
1199
+ try:
1200
+ payload = build_chat_completions_payload(
1201
+ self.endpoint,
1202
+ input_value,
1203
+ profile,
1204
+ )
1205
+ body = json.dumps(
1206
+ payload,
1207
+ allow_nan=False,
1208
+ ensure_ascii=False,
1209
+ separators=(",", ":"),
1210
+ sort_keys=True,
1211
+ ).encode("utf-8")
1212
+ except (TypeError, ValueError) as error:
1213
+ raise InferenceError(
1214
+ InferenceFailure.CONFIGURATION,
1215
+ "inference input could not be serialized as finite JSON",
1216
+ ) from error
1217
+ headers = {
1218
+ "Accept": (
1219
+ "text/event-stream" if self.endpoint.stream else "application/json"
1220
+ ),
1221
+ "Content-Type": "application/json",
1222
+ "User-Agent": f"itself-inference/{ADAPTER_VERSION}",
1223
+ **self.endpoint.extra_headers,
1224
+ }
1225
+ if self.endpoint.credential is not None:
1226
+ name, value = self.endpoint.credential.render(self.environment)
1227
+ headers[name] = value
1228
+ return HttpRequest(
1229
+ url=self.endpoint.url,
1230
+ headers=headers,
1231
+ body=body,
1232
+ timeout_seconds=self.endpoint.timeout_seconds,
1233
+ deadline_seconds=self.endpoint.deadline_seconds,
1234
+ )
1235
+
1236
+ def _capture(
1237
+ self,
1238
+ response: HttpResponse,
1239
+ captured_at: datetime,
1240
+ ) -> ArtifactReference:
1241
+ try:
1242
+ return self.artifact_sink.capture(
1243
+ response.body,
1244
+ media_type=content_type(response.headers),
1245
+ captured_at=captured_at,
1246
+ )
1247
+ except (OSError, ValueError) as error:
1248
+ raise InferenceError(
1249
+ InferenceFailure.ARTIFACT,
1250
+ "provider response artifact capture failed",
1251
+ ) from error
1252
+
1253
+ def _completion(
1254
+ self,
1255
+ response: HttpResponse,
1256
+ artifact: ArtifactReference,
1257
+ ) -> _Completion:
1258
+ if self.endpoint.stream:
1259
+ return self._streaming_completion(response, artifact)
1260
+ try:
1261
+ envelope = _object(strict_json_loads(response.body))
1262
+ choices = _array(envelope["choices"])
1263
+ if len(choices) != 1:
1264
+ raise TypeError("expected exactly one completion choice")
1265
+ choice = _object(choices[0])
1266
+ message = _object(choice["message"])
1267
+ finish_reason = _string(choice["finish_reason"])
1268
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError, UnicodeError):
1269
+ raise InferenceError(
1270
+ InferenceFailure.RESPONSE_ENVELOPE,
1271
+ "provider returned a malformed Chat Completions envelope",
1272
+ artifact=artifact,
1273
+ ) from None
1274
+
1275
+ refusal = message.get("refusal")
1276
+ if isinstance(refusal, str) and refusal:
1277
+ raise InferenceError(
1278
+ InferenceFailure.REFUSAL,
1279
+ "model refused the structured inference request",
1280
+ artifact=artifact,
1281
+ )
1282
+ if finish_reason == "content_filter":
1283
+ raise InferenceError(
1284
+ InferenceFailure.REFUSAL,
1285
+ "provider content filtering stopped the model response",
1286
+ artifact=artifact,
1287
+ )
1288
+ if finish_reason not in self.endpoint.accepted_finish_reasons:
1289
+ detail = (
1290
+ "model output was truncated"
1291
+ if finish_reason == "length"
1292
+ else "model completion did not finish in an accepted state"
1293
+ )
1294
+ raise InferenceError(
1295
+ InferenceFailure.INCOMPLETE,
1296
+ detail,
1297
+ artifact=artifact,
1298
+ )
1299
+
1300
+ try:
1301
+ content = _message_content(message["content"])
1302
+ except (KeyError, TypeError):
1303
+ raise InferenceError(
1304
+ InferenceFailure.RESPONSE_ENVELOPE,
1305
+ "provider completion did not contain one text response",
1306
+ artifact=artifact,
1307
+ ) from None
1308
+
1309
+ input_tokens: int | None = None
1310
+ output_tokens: int | None = None
1311
+ total_tokens: int | None = None
1312
+ usage_value = envelope.get("usage")
1313
+ if usage_value is not None:
1314
+ try:
1315
+ input_tokens, output_tokens, total_tokens = token_counts(usage_value)
1316
+ except TypeError:
1317
+ raise InferenceError(
1318
+ InferenceFailure.RESPONSE_USAGE,
1319
+ "provider returned malformed token usage",
1320
+ artifact=artifact,
1321
+ ) from None
1322
+
1323
+ resolved_model_value = envelope.get("model")
1324
+ resolved_model = (
1325
+ resolved_model_value if isinstance(resolved_model_value, str) else None
1326
+ )
1327
+ return _Completion(
1328
+ content=content,
1329
+ resolved_model=resolved_model,
1330
+ input_tokens=input_tokens,
1331
+ output_tokens=output_tokens,
1332
+ total_tokens=total_tokens,
1333
+ )
1334
+
1335
+ def _streaming_completion(
1336
+ self,
1337
+ response: HttpResponse,
1338
+ artifact: ArtifactReference,
1339
+ ) -> _Completion:
1340
+ """Assemble one fully captured OpenAI-compatible SSE completion."""
1341
+
1342
+ try:
1343
+ events = _sse_data_events(response.body)
1344
+ except (UnicodeError, ValueError):
1345
+ raise InferenceError(
1346
+ InferenceFailure.RESPONSE_ENVELOPE,
1347
+ "provider returned a malformed Chat Completions event stream",
1348
+ artifact=artifact,
1349
+ ) from None
1350
+
1351
+ content_parts: list[str] = []
1352
+ finish_reason: str | None = None
1353
+ resolved_model: str | None = None
1354
+ usage_counts: tuple[int | None, int | None, int | None] | None = None
1355
+ saw_choice = False
1356
+
1357
+ for event in events:
1358
+ try:
1359
+ chunk = _object(strict_json_loads(event))
1360
+ choices = _array(chunk["choices"])
1361
+ except (
1362
+ KeyError,
1363
+ TypeError,
1364
+ ValueError,
1365
+ json.JSONDecodeError,
1366
+ UnicodeError,
1367
+ ):
1368
+ raise InferenceError(
1369
+ InferenceFailure.RESPONSE_ENVELOPE,
1370
+ "provider returned a malformed Chat Completions event",
1371
+ artifact=artifact,
1372
+ ) from None
1373
+
1374
+ model_value = chunk.get("model")
1375
+ if isinstance(model_value, str):
1376
+ if resolved_model is not None and model_value != resolved_model:
1377
+ raise InferenceError(
1378
+ InferenceFailure.RESPONSE_ENVELOPE,
1379
+ "provider changed model identity within one event stream",
1380
+ artifact=artifact,
1381
+ )
1382
+ resolved_model = model_value
1383
+
1384
+ usage_value = chunk.get("usage")
1385
+ if usage_value is not None:
1386
+ try:
1387
+ observed_usage = token_counts(usage_value)
1388
+ except TypeError:
1389
+ raise InferenceError(
1390
+ InferenceFailure.RESPONSE_USAGE,
1391
+ "provider returned malformed streaming token usage",
1392
+ artifact=artifact,
1393
+ ) from None
1394
+ if usage_counts is not None and observed_usage != usage_counts:
1395
+ raise InferenceError(
1396
+ InferenceFailure.RESPONSE_USAGE,
1397
+ "provider changed token usage within one event stream",
1398
+ artifact=artifact,
1399
+ )
1400
+ usage_counts = observed_usage
1401
+
1402
+ if not choices:
1403
+ continue
1404
+ if len(choices) != 1:
1405
+ raise InferenceError(
1406
+ InferenceFailure.RESPONSE_ENVELOPE,
1407
+ "provider event did not contain exactly one completion choice",
1408
+ artifact=artifact,
1409
+ )
1410
+ saw_choice = True
1411
+ try:
1412
+ choice = _object(choices[0])
1413
+ if choice.get("index") != 0:
1414
+ raise TypeError("stream choice index was not zero")
1415
+ delta = _object(choice["delta"])
1416
+ event_finish_reason = choice.get("finish_reason")
1417
+ if event_finish_reason is not None:
1418
+ event_finish_reason = _string(event_finish_reason)
1419
+ except (KeyError, TypeError):
1420
+ raise InferenceError(
1421
+ InferenceFailure.RESPONSE_ENVELOPE,
1422
+ "provider event contained a malformed completion delta",
1423
+ artifact=artifact,
1424
+ ) from None
1425
+
1426
+ refusal = delta.get("refusal")
1427
+ if isinstance(refusal, str) and refusal:
1428
+ raise InferenceError(
1429
+ InferenceFailure.REFUSAL,
1430
+ "model refused the structured inference request",
1431
+ artifact=artifact,
1432
+ )
1433
+ content_value = delta.get("content")
1434
+ if content_value is not None:
1435
+ try:
1436
+ content_parts.append(_message_content(content_value))
1437
+ except TypeError:
1438
+ raise InferenceError(
1439
+ InferenceFailure.RESPONSE_ENVELOPE,
1440
+ "provider completion delta did not contain text",
1441
+ artifact=artifact,
1442
+ ) from None
1443
+
1444
+ if event_finish_reason is not None:
1445
+ if finish_reason is not None and event_finish_reason != finish_reason:
1446
+ raise InferenceError(
1447
+ InferenceFailure.RESPONSE_ENVELOPE,
1448
+ "provider changed the finish reason within one event stream",
1449
+ artifact=artifact,
1450
+ )
1451
+ finish_reason = event_finish_reason
1452
+
1453
+ if not saw_choice or finish_reason is None:
1454
+ raise InferenceError(
1455
+ InferenceFailure.RESPONSE_ENVELOPE,
1456
+ "provider event stream did not contain one finished completion",
1457
+ artifact=artifact,
1458
+ )
1459
+ if finish_reason == "content_filter":
1460
+ raise InferenceError(
1461
+ InferenceFailure.REFUSAL,
1462
+ "provider content filtering stopped the model response",
1463
+ artifact=artifact,
1464
+ )
1465
+ if finish_reason not in self.endpoint.accepted_finish_reasons:
1466
+ detail = (
1467
+ "model output was truncated"
1468
+ if finish_reason == "length"
1469
+ else "model completion did not finish in an accepted state"
1470
+ )
1471
+ raise InferenceError(
1472
+ InferenceFailure.INCOMPLETE,
1473
+ detail,
1474
+ artifact=artifact,
1475
+ )
1476
+ if not content_parts:
1477
+ raise InferenceError(
1478
+ InferenceFailure.RESPONSE_ENVELOPE,
1479
+ "provider event stream did not contain one text response",
1480
+ artifact=artifact,
1481
+ )
1482
+
1483
+ input_tokens, output_tokens, total_tokens = (
1484
+ (None, None, None) if usage_counts is None else usage_counts
1485
+ )
1486
+ return _Completion(
1487
+ content="".join(content_parts),
1488
+ resolved_model=resolved_model,
1489
+ input_tokens=input_tokens,
1490
+ output_tokens=output_tokens,
1491
+ total_tokens=total_tokens,
1492
+ )
1493
+
1494
+ @staticmethod
1495
+ def _validate_output(
1496
+ value: JsonValue,
1497
+ profile: StructuredOutputProfile,
1498
+ artifact: ArtifactReference,
1499
+ ) -> None:
1500
+ validator = cast(
1501
+ _SchemaValidator,
1502
+ Draft202012Validator(
1503
+ profile.schema_json(),
1504
+ format_checker=FormatChecker(),
1505
+ ),
1506
+ )
1507
+ if next(validator.iter_errors(value), None) is not None:
1508
+ raise InferenceError(
1509
+ InferenceFailure.RESPONSE_SCHEMA,
1510
+ "model output did not satisfy the declared JSON Schema",
1511
+ artifact=artifact,
1512
+ )
1513
+
1514
+ def invoke(
1515
+ self,
1516
+ input_value: JsonValue,
1517
+ profile: StructuredOutputProfile,
1518
+ ) -> StructuredInferenceResult:
1519
+ """Execute, capture, strictly parse, and schema-validate one attempt."""
1520
+
1521
+ http_request = self._request(input_value, profile)
1522
+ started_at = self.monotonic_ns()
1523
+ try:
1524
+ response = self.transport.send(http_request)
1525
+ except InferenceError:
1526
+ raise
1527
+ except Exception as error:
1528
+ raise InferenceError(
1529
+ InferenceFailure.TRANSPORT,
1530
+ "custom inference transport failed",
1531
+ ) from error
1532
+ elapsed_ns = max(0, self.monotonic_ns() - started_at)
1533
+ artifact = self._capture(response, self.now())
1534
+
1535
+ if not 200 <= response.status_code <= 299:
1536
+ raise InferenceError(
1537
+ _http_failure(response.status_code),
1538
+ f"inference endpoint returned HTTP {response.status_code}",
1539
+ status_code=response.status_code,
1540
+ artifact=artifact,
1541
+ )
1542
+
1543
+ completion = self._completion(response, artifact)
1544
+ try:
1545
+ value = strict_json_loads(completion.content)
1546
+ except (ValueError, json.JSONDecodeError, UnicodeError):
1547
+ raise InferenceError(
1548
+ InferenceFailure.RESPONSE_JSON,
1549
+ "model content was not one strict JSON document",
1550
+ artifact=artifact,
1551
+ ) from None
1552
+ self._validate_output(value, profile, artifact)
1553
+
1554
+ return StructuredInferenceResult(
1555
+ value=value,
1556
+ identity=InferenceIdentity(
1557
+ actor_id=self.endpoint.actor_id,
1558
+ adapter_id=ADAPTER_ID,
1559
+ adapter_version=ADAPTER_VERSION,
1560
+ requested_model=self.endpoint.model,
1561
+ resolved_model=completion.resolved_model,
1562
+ ),
1563
+ raw_response=artifact,
1564
+ usage=InferenceUsage(
1565
+ input_tokens=completion.input_tokens,
1566
+ output_tokens=completion.output_tokens,
1567
+ total_tokens=completion.total_tokens,
1568
+ wall_time_ms=elapsed_ns // 1_000_000,
1569
+ ),
1570
+ profile_id=profile.profile_id,
1571
+ )