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.
@@ -0,0 +1,1283 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Typed questions for decision models and a client for their endpoints.
5
+
6
+ A decision model answers closed questions about a state with probability
7
+ distributions over declared options and generates no text. The client in this
8
+ module sends ``choice``, ``noul``, and ``score`` questions to an endpoint that
9
+ implements the ``/v1/systemone`` request format. It captures each exact request
10
+ and bounded response before interpretation, validates every distribution
11
+ locally, and by default asks each ordered question a second time with its
12
+ options reversed, so that position bias is measured rather than absorbed.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import math
19
+ import os
20
+ import time
21
+ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
22
+ from copy import deepcopy
23
+ from dataclasses import dataclass, field
24
+ from datetime import UTC, datetime
25
+ from enum import StrEnum
26
+ from itertools import combinations
27
+ from typing import Final, Protocol, TypeVar, cast
28
+
29
+ from ._endpoints import (
30
+ IDENTIFIER_PATTERN,
31
+ content_type,
32
+ defensive_extra_body,
33
+ endpoint_url,
34
+ frozen_extra_headers,
35
+ frozen_query_parameters,
36
+ normalized_base_url,
37
+ normalized_resource_path,
38
+ token_counts,
39
+ validate_deadline,
40
+ validate_timeout,
41
+ )
42
+ from ._json import ensure_i_json, strict_json_loads
43
+ from .inference import (
44
+ ArtifactReference,
45
+ ArtifactSink,
46
+ EnvironmentCredential,
47
+ HttpRequest,
48
+ HttpTransport,
49
+ InferenceError,
50
+ InferenceFailure,
51
+ InferenceIdentity,
52
+ InferenceUsage,
53
+ UrllibHttpTransport,
54
+ )
55
+ from .types import JsonObject, JsonValue
56
+
57
+ DECISION_MODEL_ADAPTER_ID: Final = "systemone-compatible-decisions"
58
+ DECISION_MODEL_ADAPTER_VERSION: Final = "0.1.0"
59
+
60
+ _MAX_OPTIONS: Final = 255
61
+ _MAX_PROBABILITY_TOLERANCE: Final = 0.01
62
+ _RESERVED_BODY_FIELDS: Final = frozenset({"model", "questions", "state"})
63
+
64
+ _K = TypeVar("_K")
65
+ _V = TypeVar("_V")
66
+
67
+
68
+ class _FrozenMapping(Mapping[_K, _V]):
69
+ """An immutable mapping that keeps its order, hashes, and pickles.
70
+
71
+ Two frozen mappings are equal only with the same items in the same order,
72
+ because option order changes what a request shows and how ties break.
73
+ Compared with any other mapping, order is ignored, as between dicts.
74
+ """
75
+
76
+ __slots__ = ("_items",)
77
+
78
+ def __init__(self, items: Mapping[_K, _V]) -> None:
79
+ self._items: dict[_K, _V] = dict(items)
80
+
81
+ def __getitem__(self, key: _K) -> _V:
82
+ return self._items[key]
83
+
84
+ def __iter__(self) -> Iterator[_K]:
85
+ return iter(self._items)
86
+
87
+ def __len__(self) -> int:
88
+ return len(self._items)
89
+
90
+ def __eq__(self, other: object) -> bool:
91
+ if isinstance(other, _FrozenMapping):
92
+ other_items = cast(_FrozenMapping[object, object], other)._items
93
+ return list(self._items.items()) == list(other_items.items())
94
+ if isinstance(other, Mapping):
95
+ return self._items == dict(cast(Mapping[object, object], other))
96
+ return NotImplemented
97
+
98
+ def __hash__(self) -> int:
99
+ return hash(tuple(self._items.items()))
100
+
101
+ def __reduce__(self) -> tuple[type[_FrozenMapping[_K, _V]], tuple[dict[_K, _V]]]:
102
+ return (type(self), (dict(self._items),))
103
+
104
+ def __repr__(self) -> str:
105
+ return repr(self._items)
106
+
107
+
108
+ class DecisionQuestionType(StrEnum):
109
+ """Wire type of one decision-model question."""
110
+
111
+ CHOICE = "choice"
112
+ NOUL = "noul"
113
+ SCORE = "score"
114
+
115
+
116
+ class OptionOrder(StrEnum):
117
+ """How one request orders each question's options."""
118
+
119
+ DECLARED = "declared"
120
+ REVERSED = "reversed"
121
+
122
+
123
+ COUNTERBALANCED_ORDERS: Final[tuple[OptionOrder, ...]] = (
124
+ OptionOrder.DECLARED,
125
+ OptionOrder.REVERSED,
126
+ )
127
+
128
+
129
+ def _text(value: object, name: str) -> str:
130
+ if not isinstance(value, str) or not value or value != value.strip():
131
+ raise ValueError(f"{name} must be non-empty text without outer space")
132
+ return value
133
+
134
+
135
+ def _option_key(value: object) -> str:
136
+ if not isinstance(value, str) or IDENTIFIER_PATTERN.fullmatch(value) is None:
137
+ raise ValueError("choice option keys must be valid identifiers")
138
+ return value
139
+
140
+
141
+ def _levels(value: object) -> tuple[str, ...]:
142
+ if isinstance(value, str) or not isinstance(value, Sequence):
143
+ raise ValueError("levels must be a sequence of level descriptions")
144
+ levels = tuple(cast(Sequence[object], value))
145
+ if not 2 <= len(levels) <= _MAX_OPTIONS:
146
+ raise ValueError(f"a score question needs between 2 and {_MAX_OPTIONS} levels")
147
+ return tuple(_text(level, "score levels") for level in levels)
148
+
149
+
150
+ class DecisionQuestion:
151
+ """Common base of the typed questions a decision model answers.
152
+
153
+ The wire format defines three question types, so only ``ChoiceQuestion``,
154
+ ``NoulQuestion``, and ``ScoreQuestion`` are sent.
155
+ """
156
+
157
+ __slots__ = ()
158
+
159
+ @property
160
+ def question_type(self) -> DecisionQuestionType:
161
+ """The question's wire type."""
162
+
163
+ raise NotImplementedError
164
+
165
+ @property
166
+ def option_keys(self) -> tuple[str, ...]:
167
+ """Answer keys in declared order."""
168
+
169
+ raise NotImplementedError
170
+
171
+
172
+ @dataclass(frozen=True, slots=True)
173
+ class ChoiceQuestion(DecisionQuestion):
174
+ """Pick one declared option; the answer is a distribution over option keys.
175
+
176
+ ``criteria`` maps each option key to an optional description, in the order
177
+ the options are shown. A two-option choice question is the counterbalanced
178
+ form of a yes-or-no question.
179
+ """
180
+
181
+ instructions: str
182
+ criteria: Mapping[str, str | None]
183
+
184
+ def __post_init__(self) -> None:
185
+ _text(self.instructions, "instructions")
186
+ criteria = dict(self.criteria)
187
+ if not 2 <= len(criteria) <= _MAX_OPTIONS:
188
+ raise ValueError(
189
+ f"a choice question needs between 2 and {_MAX_OPTIONS} options"
190
+ )
191
+ for key, description in criteria.items():
192
+ _option_key(key)
193
+ if description is not None:
194
+ _text(description, "choice option descriptions")
195
+ object.__setattr__(self, "criteria", _FrozenMapping(criteria))
196
+
197
+ @property
198
+ def question_type(self) -> DecisionQuestionType:
199
+ return DecisionQuestionType.CHOICE
200
+
201
+ @property
202
+ def option_keys(self) -> tuple[str, ...]:
203
+ """Answer keys in declared order."""
204
+
205
+ return tuple(self.criteria)
206
+
207
+
208
+ @dataclass(frozen=True, slots=True)
209
+ class NoulQuestion(DecisionQuestion):
210
+ """A yes-or-no question; the answer is the probability that it is true.
211
+
212
+ Its two answers have no order on the wire, so asking it again with reversed
213
+ options cannot reveal position bias. Use a two-option ``ChoiceQuestion``
214
+ when order effects need to be measured.
215
+ """
216
+
217
+ instructions: str
218
+ true_description: str | None = None
219
+ false_description: str | None = None
220
+
221
+ def __post_init__(self) -> None:
222
+ _text(self.instructions, "instructions")
223
+ if self.true_description is not None:
224
+ _text(self.true_description, "true_description")
225
+ if self.false_description is not None:
226
+ _text(self.false_description, "false_description")
227
+
228
+ @property
229
+ def question_type(self) -> DecisionQuestionType:
230
+ return DecisionQuestionType.NOUL
231
+
232
+ @property
233
+ def option_keys(self) -> tuple[str, ...]:
234
+ """Answer keys: ``true`` then ``false``."""
235
+
236
+ return ("true", "false")
237
+
238
+
239
+ @dataclass(frozen=True, slots=True)
240
+ class ScoreQuestion(DecisionQuestion):
241
+ """Rate on an ordered rubric; the answer is a distribution over its levels.
242
+
243
+ ``levels`` run from lowest to highest. Answers key each level by its
244
+ declared index, so ``"0"`` is always the lowest level, whatever order a
245
+ request showed the levels in.
246
+ """
247
+
248
+ instructions: str
249
+ levels: Sequence[str]
250
+
251
+ def __post_init__(self) -> None:
252
+ _text(self.instructions, "instructions")
253
+ object.__setattr__(self, "levels", _levels(self.levels))
254
+
255
+ @property
256
+ def question_type(self) -> DecisionQuestionType:
257
+ return DecisionQuestionType.SCORE
258
+
259
+ @property
260
+ def option_keys(self) -> tuple[str, ...]:
261
+ """Answer keys: each level's declared index, lowest first."""
262
+
263
+ return tuple(str(index) for index in range(len(self.levels)))
264
+
265
+
266
+ def _empty_query() -> Mapping[str, str]:
267
+ return {}
268
+
269
+
270
+ def _empty_headers() -> Mapping[str, str]:
271
+ return {}
272
+
273
+
274
+ def _empty_body() -> Mapping[str, JsonValue]:
275
+ return {}
276
+
277
+
278
+ @dataclass(frozen=True, slots=True)
279
+ class DecisionModelEndpoint:
280
+ """One declared decision-model endpoint and model configuration.
281
+
282
+ ``probability_tolerance`` bounds how far a returned distribution may sum
283
+ from one and how far a choice's probability may fall below the most
284
+ probable option's. A score may sit up to the tolerance times the number
285
+ of levels minus one from its distribution's expected level, since the
286
+ expected level weights each probability by an index up to that number.
287
+ """
288
+
289
+ actor_id: str
290
+ base_url: str
291
+ model: str
292
+ credential: EnvironmentCredential | None = None
293
+ resource_path: str = "systemone"
294
+ query_parameters: Mapping[str, str] = field(
295
+ default_factory=_empty_query,
296
+ repr=False,
297
+ )
298
+ timeout_seconds: float = 90.0
299
+ probability_tolerance: float = 1e-6
300
+ allow_insecure_http: bool = False
301
+ extra_headers: Mapping[str, str] = field(
302
+ default_factory=_empty_headers,
303
+ repr=False,
304
+ )
305
+ extra_body: Mapping[str, JsonValue] = field(
306
+ default_factory=_empty_body,
307
+ repr=False,
308
+ )
309
+ deadline_seconds: float | None = None
310
+
311
+ def __post_init__(self) -> None:
312
+ if IDENTIFIER_PATTERN.fullmatch(self.actor_id) is None:
313
+ raise ValueError("actor_id must be a valid identifier")
314
+ object.__setattr__(
315
+ self,
316
+ "base_url",
317
+ normalized_base_url(
318
+ self.base_url,
319
+ credential_bearing=self.credential is not None,
320
+ allow_insecure_http=self.allow_insecure_http,
321
+ ),
322
+ )
323
+ object.__setattr__(
324
+ self,
325
+ "resource_path",
326
+ normalized_resource_path(self.resource_path),
327
+ )
328
+ if not self.model or self.model != self.model.strip():
329
+ raise ValueError("model must be non-empty without outer space")
330
+ validate_timeout(self.timeout_seconds)
331
+ validate_deadline(self.deadline_seconds)
332
+ tolerance = self.probability_tolerance
333
+ if (
334
+ isinstance(tolerance, bool)
335
+ or not math.isfinite(tolerance)
336
+ or not 0 <= tolerance <= _MAX_PROBABILITY_TOLERANCE
337
+ ):
338
+ raise ValueError(
339
+ "probability_tolerance must be between 0 and "
340
+ f"{_MAX_PROBABILITY_TOLERANCE}"
341
+ )
342
+ object.__setattr__(
343
+ self,
344
+ "query_parameters",
345
+ frozen_query_parameters(self.query_parameters),
346
+ )
347
+ object.__setattr__(
348
+ self,
349
+ "extra_headers",
350
+ frozen_extra_headers(
351
+ self.extra_headers,
352
+ credential_header=(
353
+ None if self.credential is None else self.credential.header
354
+ ),
355
+ ),
356
+ )
357
+ object.__setattr__(
358
+ self,
359
+ "extra_body",
360
+ defensive_extra_body(self.extra_body, reserved=_RESERVED_BODY_FIELDS),
361
+ )
362
+
363
+ @property
364
+ def url(self) -> str:
365
+ """Return the fully rendered endpoint URL without credentials."""
366
+
367
+ return endpoint_url(self.base_url, self.resource_path, self.query_parameters)
368
+
369
+
370
+ def _questions(value: object) -> dict[str, DecisionQuestion]:
371
+ if not isinstance(value, Mapping):
372
+ raise ValueError("questions must map question identifiers to questions")
373
+ questions: dict[str, DecisionQuestion] = {}
374
+ for question_id, question in cast(Mapping[object, object], value).items():
375
+ if (
376
+ not isinstance(question_id, str)
377
+ or IDENTIFIER_PATTERN.fullmatch(question_id) is None
378
+ ):
379
+ raise ValueError("question identifiers must be valid identifiers")
380
+ if not isinstance(question, ChoiceQuestion | NoulQuestion | ScoreQuestion):
381
+ raise ValueError(
382
+ "questions must be ChoiceQuestion, NoulQuestion, or ScoreQuestion"
383
+ )
384
+ questions[question_id] = question
385
+ if not questions:
386
+ raise ValueError("at least one question is required")
387
+ return questions
388
+
389
+
390
+ def _state(value: JsonValue) -> JsonValue:
391
+ if isinstance(value, str):
392
+ if not value.strip():
393
+ raise ValueError("state must not be empty")
394
+ elif isinstance(value, dict | list):
395
+ if not value:
396
+ raise ValueError("state must not be empty")
397
+ else:
398
+ raise ValueError("state must be JSON text, an object, or an array")
399
+ return value
400
+
401
+
402
+ def _order(value: object) -> OptionOrder:
403
+ if not isinstance(value, OptionOrder):
404
+ raise ValueError("order must be an OptionOrder")
405
+ return value
406
+
407
+
408
+ def _orders(value: object) -> tuple[OptionOrder, ...]:
409
+ if isinstance(value, str) or not isinstance(value, Sequence):
410
+ raise ValueError("orders must be a sequence of OptionOrder values")
411
+ orders = tuple(_order(order) for order in cast(Sequence[object], value))
412
+ if not orders:
413
+ raise ValueError("orders must contain at least one OptionOrder")
414
+ if len(orders) != len(set(orders)):
415
+ raise ValueError("orders must not repeat an OptionOrder")
416
+ return orders
417
+
418
+
419
+ def _wire_question(question: DecisionQuestion, order: OptionOrder) -> JsonObject:
420
+ reverse = order is OptionOrder.REVERSED
421
+ if isinstance(question, ChoiceQuestion):
422
+ options = list(question.criteria.items())
423
+ if reverse:
424
+ options.reverse()
425
+ criteria: JsonObject = dict(options)
426
+ return {
427
+ "type": question.question_type.value,
428
+ "instructions": question.instructions,
429
+ "criteria": criteria,
430
+ }
431
+ if isinstance(question, NoulQuestion):
432
+ value: JsonObject = {
433
+ "type": question.question_type.value,
434
+ "instructions": question.instructions,
435
+ }
436
+ descriptions: JsonObject = {}
437
+ if question.true_description is not None:
438
+ descriptions["true"] = question.true_description
439
+ if question.false_description is not None:
440
+ descriptions["false"] = question.false_description
441
+ if descriptions:
442
+ value["criteria"] = descriptions
443
+ return value
444
+ if isinstance(question, ScoreQuestion):
445
+ levels: list[JsonValue] = list(question.levels)
446
+ if reverse:
447
+ levels.reverse()
448
+ return {
449
+ "type": question.question_type.value,
450
+ "instructions": question.instructions,
451
+ "criteria": levels,
452
+ }
453
+ raise TypeError("unsupported decision question type")
454
+
455
+
456
+ def build_decision_payload(
457
+ endpoint: DecisionModelEndpoint,
458
+ state: JsonValue,
459
+ questions: Mapping[str, DecisionQuestion],
460
+ *,
461
+ order: OptionOrder = OptionOrder.DECLARED,
462
+ ) -> JsonObject:
463
+ """Render one decision request without credentials.
464
+
465
+ Each question's options are listed in ``order``. Serialize the payload
466
+ without sorting keys, or the options lose that order. The payload must be
467
+ I-JSON nested at most 128 levels deep, so the state nests at most 127:
468
+ every object key is a string, the request means the same thing to every
469
+ JSON reader, and its captured copy can be read back.
470
+ """
471
+
472
+ asked = _questions(questions)
473
+ selected_order = _order(order)
474
+ checked_state = _state(state)
475
+ ensure_i_json(checked_state, path="$.state")
476
+ payload: JsonObject = {
477
+ "model": endpoint.model,
478
+ "state": deepcopy(checked_state),
479
+ "questions": {
480
+ question_id: _wire_question(question, selected_order)
481
+ for question_id, question in asked.items()
482
+ },
483
+ }
484
+ payload.update(endpoint.extra_body)
485
+ # The state sits one level down, so the whole request is checked too.
486
+ ensure_i_json(payload)
487
+ return payload
488
+
489
+
490
+ def _most_likely(probabilities: Mapping[str, float]) -> str:
491
+ return max(probabilities, key=probabilities.__getitem__)
492
+
493
+
494
+ def _probability_map(
495
+ question_type: DecisionQuestionType,
496
+ value: Mapping[str, float],
497
+ ) -> _FrozenMapping[str, float]:
498
+ probabilities = dict(value)
499
+ if not probabilities:
500
+ raise ValueError("a distribution needs at least one probability")
501
+ for key, probability in probabilities.items():
502
+ runtime_key, runtime_probability = cast(object, key), cast(object, probability)
503
+ if not isinstance(runtime_key, str) or not runtime_key:
504
+ raise ValueError("distribution keys must be non-empty strings")
505
+ if (
506
+ isinstance(runtime_probability, bool)
507
+ or not isinstance(runtime_probability, int | float)
508
+ or not math.isfinite(runtime_probability)
509
+ or not 0.0 <= runtime_probability <= 1.0
510
+ ):
511
+ raise ValueError("probabilities must be finite numbers from 0 to 1")
512
+ if question_type is DecisionQuestionType.SCORE and list(probabilities) != [
513
+ str(index) for index in range(len(probabilities))
514
+ ]:
515
+ raise ValueError("score distributions are keyed by level index, lowest first")
516
+ return _FrozenMapping(
517
+ {key: float(probability) for key, probability in probabilities.items()}
518
+ )
519
+
520
+
521
+ def _expected_level(
522
+ question_type: DecisionQuestionType,
523
+ probabilities: Mapping[str, float],
524
+ ) -> float | None:
525
+ if question_type is not DecisionQuestionType.SCORE:
526
+ return None
527
+ return math.fsum(
528
+ int(level) * probability for level, probability in probabilities.items()
529
+ )
530
+
531
+
532
+ @dataclass(frozen=True, slots=True)
533
+ class DecisionModelAnswer:
534
+ """One question's validated answer from one request, in declared terms.
535
+
536
+ ``reported_confidence`` is the endpoint's own confidence figure when it
537
+ reports one; implementations define it differently.
538
+ """
539
+
540
+ question_type: DecisionQuestionType
541
+ probabilities: Mapping[str, float]
542
+ reported_confidence: float | None = None
543
+
544
+ def __post_init__(self) -> None:
545
+ question_type = DecisionQuestionType(self.question_type)
546
+ object.__setattr__(self, "question_type", question_type)
547
+ object.__setattr__(
548
+ self,
549
+ "probabilities",
550
+ _probability_map(question_type, self.probabilities),
551
+ )
552
+ confidence = cast(object, self.reported_confidence)
553
+ if confidence is not None and (
554
+ isinstance(confidence, bool)
555
+ or not isinstance(confidence, int | float)
556
+ or not math.isfinite(confidence)
557
+ or not 0.0 <= confidence <= 1.0
558
+ ):
559
+ raise ValueError("reported_confidence must be from 0 to 1, or None")
560
+
561
+ @property
562
+ def most_likely(self) -> str:
563
+ """The most probable answer key; ties go to the first declared option."""
564
+
565
+ return _most_likely(self.probabilities)
566
+
567
+ @property
568
+ def expected_level(self) -> float | None:
569
+ """The probability-weighted level index of a score answer."""
570
+
571
+ return _expected_level(self.question_type, self.probabilities)
572
+
573
+ def to_json_object(self) -> JsonObject:
574
+ """Return a JSON representation suitable for an artifact.
575
+
576
+ Canonical JSON sorts object keys, so ``option_keys`` keeps the declared
577
+ order and ``most_likely`` the tie-break it decides.
578
+ """
579
+
580
+ return {
581
+ "type": self.question_type.value,
582
+ "option_keys": list[JsonValue](self.probabilities),
583
+ "probabilities": dict[str, JsonValue](self.probabilities),
584
+ "most_likely": self.most_likely,
585
+ "reported_confidence": self.reported_confidence,
586
+ }
587
+
588
+
589
+ @dataclass(frozen=True, slots=True)
590
+ class DecisionModelEstimate:
591
+ """One question's answers combined across the requests that asked it.
592
+
593
+ ``probabilities`` is the mean distribution. With more than one request,
594
+ ``order_gap`` is the largest difference between requests in the
595
+ probability of any option, and ``order_flip`` records whether the most
596
+ likely option changed. Both are ``None`` for a question asked once.
597
+ """
598
+
599
+ question_type: DecisionQuestionType
600
+ probabilities: Mapping[str, float]
601
+ attempt_count: int
602
+ order_gap: float | None = None
603
+ order_flip: bool | None = None
604
+
605
+ def __post_init__(self) -> None:
606
+ question_type = DecisionQuestionType(self.question_type)
607
+ object.__setattr__(self, "question_type", question_type)
608
+ object.__setattr__(
609
+ self,
610
+ "probabilities",
611
+ _probability_map(question_type, self.probabilities),
612
+ )
613
+ attempt_count = cast(object, self.attempt_count)
614
+ if (
615
+ isinstance(attempt_count, bool)
616
+ or not isinstance(attempt_count, int)
617
+ or attempt_count < 1
618
+ ):
619
+ raise ValueError("attempt_count must be a positive integer")
620
+ gap, flip = cast(object, self.order_gap), cast(object, self.order_flip)
621
+ if (gap is None) != (flip is None):
622
+ raise ValueError("order_gap and order_flip are both set or both None")
623
+ if gap is not None and (
624
+ isinstance(gap, bool)
625
+ or not isinstance(gap, int | float)
626
+ or not math.isfinite(gap)
627
+ or not 0.0 <= gap <= 1.0
628
+ ):
629
+ raise ValueError("order_gap must be from 0 to 1, or None")
630
+ if flip is not None and not isinstance(flip, bool):
631
+ raise ValueError("order_flip must be a boolean, or None")
632
+
633
+ @property
634
+ def most_likely(self) -> str:
635
+ """The most probable answer key; ties go to the first declared option."""
636
+
637
+ return _most_likely(self.probabilities)
638
+
639
+ @property
640
+ def expected_level(self) -> float | None:
641
+ """The probability-weighted level index of a score estimate."""
642
+
643
+ return _expected_level(self.question_type, self.probabilities)
644
+
645
+ def to_json_object(self) -> JsonObject:
646
+ """Return a JSON representation suitable for an artifact.
647
+
648
+ Canonical JSON sorts object keys, so ``option_keys`` keeps the declared
649
+ order and ``most_likely`` the tie-break it decides.
650
+ """
651
+
652
+ return {
653
+ "type": self.question_type.value,
654
+ "option_keys": list[JsonValue](self.probabilities),
655
+ "probabilities": dict[str, JsonValue](self.probabilities),
656
+ "most_likely": self.most_likely,
657
+ "attempt_count": self.attempt_count,
658
+ "order_gap": self.order_gap,
659
+ "order_flip": self.order_flip,
660
+ }
661
+
662
+
663
+ def _identity_json(identity: InferenceIdentity) -> JsonObject:
664
+ return {
665
+ "actor_id": identity.actor_id,
666
+ "adapter_id": identity.adapter_id,
667
+ "adapter_version": identity.adapter_version,
668
+ "requested_model": identity.requested_model,
669
+ "resolved_model": identity.resolved_model,
670
+ }
671
+
672
+
673
+ def _usage_json(usage: InferenceUsage) -> JsonObject:
674
+ return {
675
+ "input_tokens": usage.input_tokens,
676
+ "output_tokens": usage.output_tokens,
677
+ "total_tokens": usage.total_tokens,
678
+ "wall_time_ms": usage.wall_time_ms,
679
+ }
680
+
681
+
682
+ @dataclass(frozen=True, slots=True)
683
+ class DecisionModelAttempt:
684
+ """One captured request, its captured response, and the validated answers."""
685
+
686
+ order: OptionOrder
687
+ identity: InferenceIdentity
688
+ request: ArtifactReference
689
+ raw_response: ArtifactReference
690
+ usage: InferenceUsage
691
+ answers: Mapping[str, DecisionModelAnswer]
692
+
693
+ def __post_init__(self) -> None:
694
+ object.__setattr__(self, "answers", _FrozenMapping(self.answers))
695
+
696
+ def to_json_object(self) -> JsonObject:
697
+ """Return a JSON representation suitable for an artifact."""
698
+
699
+ return {
700
+ "order": self.order.value,
701
+ "identity": _identity_json(self.identity),
702
+ "request": self.request.to_json_object(),
703
+ "raw_response": self.raw_response.to_json_object(),
704
+ "usage": _usage_json(self.usage),
705
+ "answers": {
706
+ question_id: answer.to_json_object()
707
+ for question_id, answer in self.answers.items()
708
+ },
709
+ }
710
+
711
+
712
+ def _total(values: Iterable[int | None]) -> int | None:
713
+ total = 0
714
+ for value in values:
715
+ if value is None:
716
+ return None
717
+ total += value
718
+ return total
719
+
720
+
721
+ @dataclass(frozen=True, slots=True)
722
+ class DecisionModelResult:
723
+ """Every attempt behind one decision and the combined estimate per question."""
724
+
725
+ identity: InferenceIdentity
726
+ attempts: tuple[DecisionModelAttempt, ...]
727
+ estimates: Mapping[str, DecisionModelEstimate]
728
+
729
+ def __post_init__(self) -> None:
730
+ object.__setattr__(self, "attempts", tuple(self.attempts))
731
+ object.__setattr__(self, "estimates", _FrozenMapping(self.estimates))
732
+
733
+ @property
734
+ def usage(self) -> InferenceUsage:
735
+ """Token counts and wall time summed over every attempt."""
736
+
737
+ return InferenceUsage(
738
+ input_tokens=_total(
739
+ attempt.usage.input_tokens for attempt in self.attempts
740
+ ),
741
+ output_tokens=_total(
742
+ attempt.usage.output_tokens for attempt in self.attempts
743
+ ),
744
+ total_tokens=_total(
745
+ attempt.usage.total_tokens for attempt in self.attempts
746
+ ),
747
+ wall_time_ms=sum(attempt.usage.wall_time_ms for attempt in self.attempts),
748
+ )
749
+
750
+ def to_json_object(self) -> JsonObject:
751
+ """Return a JSON representation suitable for an artifact."""
752
+
753
+ return {
754
+ "identity": _identity_json(self.identity),
755
+ "attempts": [attempt.to_json_object() for attempt in self.attempts],
756
+ "estimates": {
757
+ question_id: estimate.to_json_object()
758
+ for question_id, estimate in self.estimates.items()
759
+ },
760
+ }
761
+
762
+
763
+ class DecisionModelError(InferenceError):
764
+ """A failed decision request, with what was captured before it failed.
765
+
766
+ ``request`` references the captured request body when the request was
767
+ captured before the failure. For a failure inside ``decide``,
768
+ ``attempts`` holds every request of the decision that completed, so each
769
+ captured artifact of the decision stays reachable from the error.
770
+ """
771
+
772
+ def __init__(
773
+ self,
774
+ failure: InferenceFailure,
775
+ detail: str,
776
+ *,
777
+ status_code: int | None = None,
778
+ artifact: ArtifactReference | None = None,
779
+ request: ArtifactReference | None = None,
780
+ attempts: Sequence[DecisionModelAttempt] = (),
781
+ ) -> None:
782
+ super().__init__(failure, detail, status_code=status_code, artifact=artifact)
783
+ self.request: ArtifactReference | None = request
784
+ self.attempts: tuple[DecisionModelAttempt, ...] = tuple(attempts)
785
+
786
+
787
+ class DecisionModelAdapter(Protocol):
788
+ """Provider-neutral boundary implemented by decision-model adapters."""
789
+
790
+ def decide(
791
+ self,
792
+ state: JsonValue,
793
+ questions: Mapping[str, DecisionQuestion],
794
+ *,
795
+ orders: Sequence[OptionOrder] = COUNTERBALANCED_ORDERS,
796
+ ) -> DecisionModelResult:
797
+ """Return every captured attempt and a combined estimate per question."""
798
+
799
+ ...
800
+
801
+
802
+ def _probability(value: JsonValue) -> float:
803
+ if isinstance(value, bool) or not isinstance(value, int | float):
804
+ raise TypeError("expected a JSON number")
805
+ probability = float(value)
806
+ if not math.isfinite(probability) or not 0.0 <= probability <= 1.0:
807
+ raise ValueError("expected a probability between zero and one")
808
+ return probability
809
+
810
+
811
+ def _optional_probability(value: JsonValue | None) -> float | None:
812
+ return None if value is None else _probability(value)
813
+
814
+
815
+ def _distribution(
816
+ value: JsonValue,
817
+ keys: Sequence[str],
818
+ tolerance: float,
819
+ ) -> dict[str, float]:
820
+ if not isinstance(value, dict):
821
+ raise TypeError("expected a JSON object")
822
+ if len(value) != len(keys) or any(key not in value for key in keys):
823
+ raise ValueError("distribution keys do not match the question's options")
824
+ probabilities = {key: _probability(value[key]) for key in keys}
825
+ if abs(math.fsum(probabilities.values()) - 1.0) > tolerance:
826
+ raise ValueError("distribution does not sum to one")
827
+ return probabilities
828
+
829
+
830
+ def _check_legend(
831
+ question: ScoreQuestion,
832
+ order: OptionOrder,
833
+ legend: JsonValue | None,
834
+ ) -> None:
835
+ """Refuse a legend showing that the server read other levels or another order.
836
+
837
+ A legend that maps every level index to text echoes the levels as the
838
+ server read them, so it must match the levels this request showed. A
839
+ legend of any other shape stays uninterpreted in the captured response.
840
+ """
841
+
842
+ if not isinstance(legend, dict) or set(legend) != set(question.option_keys):
843
+ return
844
+ if not all(isinstance(text, str) for text in legend.values()):
845
+ return
846
+ shown = question.levels[::-1] if order is OptionOrder.REVERSED else question.levels
847
+ if any(legend[str(index)] != level for index, level in enumerate(shown)):
848
+ raise ValueError("score legend does not match the levels the request showed")
849
+
850
+
851
+ def _answer(
852
+ question: DecisionQuestion,
853
+ order: OptionOrder,
854
+ value: JsonValue,
855
+ tolerance: float,
856
+ ) -> DecisionModelAnswer:
857
+ if not isinstance(value, dict):
858
+ raise TypeError("expected a JSON object")
859
+ if value.get("type") != question.question_type.value:
860
+ raise ValueError("answer type does not match the question")
861
+ confidence = _optional_probability(value.get("confidence"))
862
+ if isinstance(question, NoulQuestion):
863
+ probability_true = _probability(value["noul"])
864
+ return DecisionModelAnswer(
865
+ question.question_type,
866
+ {"true": probability_true, "false": 1.0 - probability_true},
867
+ confidence,
868
+ )
869
+ if isinstance(question, ChoiceQuestion):
870
+ probabilities = _distribution(
871
+ value["probabilities"],
872
+ question.option_keys,
873
+ tolerance,
874
+ )
875
+ choice = value["choice"]
876
+ if not isinstance(choice, str) or choice not in probabilities:
877
+ raise ValueError("choice is not one of the question's options")
878
+ if probabilities[choice] + tolerance < max(probabilities.values()):
879
+ raise ValueError("choice is not the most probable option")
880
+ return DecisionModelAnswer(question.question_type, probabilities, confidence)
881
+ if not isinstance(question, ScoreQuestion):
882
+ raise TypeError("unsupported decision question type")
883
+
884
+ count = len(question.levels)
885
+ shown = _distribution(value["probabilities"], question.option_keys, tolerance)
886
+ score = value["score"]
887
+ if isinstance(score, bool) or not isinstance(score, int | float):
888
+ raise TypeError("expected a JSON number")
889
+ expected = math.fsum(index * shown[str(index)] for index in range(count))
890
+ if abs(score - expected) > tolerance * (count - 1):
891
+ raise ValueError("score is not the expected level of its distribution")
892
+ _check_legend(question, order, value.get("legend"))
893
+ if order is OptionOrder.REVERSED:
894
+ shown = {str(index): shown[str(count - 1 - index)] for index in range(count)}
895
+ return DecisionModelAnswer(question.question_type, shown, confidence)
896
+
897
+
898
+ @dataclass(frozen=True, slots=True)
899
+ class _ParsedResponse:
900
+ answers: dict[str, DecisionModelAnswer]
901
+ resolved_model: str | None
902
+ input_tokens: int | None
903
+ output_tokens: int | None
904
+ total_tokens: int | None
905
+
906
+
907
+ def _parsed_response(
908
+ body: bytes,
909
+ questions: Mapping[str, DecisionQuestion],
910
+ order: OptionOrder,
911
+ tolerance: float,
912
+ artifact: ArtifactReference,
913
+ request: ArtifactReference,
914
+ ) -> _ParsedResponse:
915
+ try:
916
+ envelope = strict_json_loads(body)
917
+ if not isinstance(envelope, dict):
918
+ raise TypeError("expected a JSON object")
919
+ answers = envelope["answers"]
920
+ if not isinstance(answers, dict):
921
+ raise TypeError("expected a JSON object")
922
+ except (KeyError, TypeError, ValueError):
923
+ raise DecisionModelError(
924
+ InferenceFailure.RESPONSE_ENVELOPE,
925
+ "decision endpoint returned a malformed response envelope",
926
+ artifact=artifact,
927
+ request=request,
928
+ ) from None
929
+ if len(answers) != len(questions) or any(
930
+ question_id not in answers for question_id in questions
931
+ ):
932
+ raise DecisionModelError(
933
+ InferenceFailure.RESPONSE_ENVELOPE,
934
+ "decision endpoint did not answer exactly the asked questions",
935
+ artifact=artifact,
936
+ request=request,
937
+ )
938
+ resolved_model = envelope.get("model")
939
+ if resolved_model is not None and not isinstance(resolved_model, str):
940
+ raise DecisionModelError(
941
+ InferenceFailure.RESPONSE_ENVELOPE,
942
+ "decision endpoint reported a model that is not a string",
943
+ artifact=artifact,
944
+ request=request,
945
+ )
946
+
947
+ parsed: dict[str, DecisionModelAnswer] = {}
948
+ for question_id, question in questions.items():
949
+ try:
950
+ parsed[question_id] = _answer(
951
+ question,
952
+ order,
953
+ answers[question_id],
954
+ tolerance,
955
+ )
956
+ except (KeyError, TypeError, ValueError):
957
+ raise DecisionModelError(
958
+ InferenceFailure.RESPONSE_SCHEMA,
959
+ f"decision answer {question_id!r} was not a valid "
960
+ f"{question.question_type.value} answer",
961
+ artifact=artifact,
962
+ request=request,
963
+ ) from None
964
+
965
+ input_tokens: int | None = None
966
+ output_tokens: int | None = None
967
+ total_tokens: int | None = None
968
+ usage_value = envelope.get("usage")
969
+ if usage_value is not None:
970
+ try:
971
+ input_tokens, output_tokens, total_tokens = token_counts(usage_value)
972
+ except TypeError:
973
+ raise DecisionModelError(
974
+ InferenceFailure.RESPONSE_USAGE,
975
+ "decision endpoint returned malformed token usage",
976
+ artifact=artifact,
977
+ request=request,
978
+ ) from None
979
+ return _ParsedResponse(
980
+ answers=parsed,
981
+ resolved_model=resolved_model,
982
+ input_tokens=input_tokens,
983
+ output_tokens=output_tokens,
984
+ total_tokens=total_tokens,
985
+ )
986
+
987
+
988
+ def _estimate(
989
+ question: DecisionQuestion,
990
+ answers: Sequence[DecisionModelAnswer],
991
+ ) -> DecisionModelEstimate:
992
+ keys = question.option_keys
993
+ count = len(answers)
994
+ mean = {
995
+ key: math.fsum(answer.probabilities[key] for answer in answers) / count
996
+ for key in keys
997
+ }
998
+ if count == 1:
999
+ return DecisionModelEstimate(question.question_type, mean, attempt_count=1)
1000
+ gap = max(
1001
+ abs(first.probabilities[key] - second.probabilities[key])
1002
+ for first, second in combinations(answers, 2)
1003
+ for key in keys
1004
+ )
1005
+ return DecisionModelEstimate(
1006
+ question.question_type,
1007
+ mean,
1008
+ attempt_count=count,
1009
+ order_gap=gap,
1010
+ order_flip=len({answer.most_likely for answer in answers}) > 1,
1011
+ )
1012
+
1013
+
1014
+ def _http_failure(status_code: int) -> InferenceFailure:
1015
+ """Classify an HTTP status exactly as the Chat Completions client does."""
1016
+
1017
+ if status_code == 401:
1018
+ return InferenceFailure.HTTP_AUTHENTICATION
1019
+ if status_code == 403:
1020
+ return InferenceFailure.HTTP_AUTHORIZATION
1021
+ if status_code == 429:
1022
+ return InferenceFailure.HTTP_RATE_LIMIT
1023
+ if 500 <= status_code <= 599:
1024
+ return InferenceFailure.HTTP_SERVER
1025
+ return InferenceFailure.HTTP_STATUS
1026
+
1027
+
1028
+ def _utc_now() -> datetime:
1029
+ return datetime.now(UTC)
1030
+
1031
+
1032
+ @dataclass(frozen=True, slots=True)
1033
+ class DecisionModelClient:
1034
+ """Ask typed questions of one declared decision-model endpoint."""
1035
+
1036
+ endpoint: DecisionModelEndpoint
1037
+ artifact_sink: ArtifactSink
1038
+ transport: HttpTransport = field(default_factory=UrllibHttpTransport)
1039
+ environment: Mapping[str, str] = field(
1040
+ default_factory=lambda: os.environ,
1041
+ repr=False,
1042
+ compare=False,
1043
+ )
1044
+ now: Callable[[], datetime] = field(
1045
+ default=_utc_now,
1046
+ repr=False,
1047
+ compare=False,
1048
+ )
1049
+ monotonic_ns: Callable[[], int] = field(
1050
+ default=time.monotonic_ns,
1051
+ repr=False,
1052
+ compare=False,
1053
+ )
1054
+
1055
+ def _request(
1056
+ self,
1057
+ state: JsonValue,
1058
+ questions: Mapping[str, DecisionQuestion],
1059
+ order: OptionOrder,
1060
+ ) -> HttpRequest:
1061
+ try:
1062
+ payload = build_decision_payload(
1063
+ self.endpoint,
1064
+ state,
1065
+ questions,
1066
+ order=order,
1067
+ )
1068
+ except ValueError as error:
1069
+ raise InferenceError(InferenceFailure.CONFIGURATION, str(error)) from error
1070
+ try:
1071
+ body = json.dumps(
1072
+ payload,
1073
+ allow_nan=False,
1074
+ ensure_ascii=False,
1075
+ separators=(",", ":"),
1076
+ ).encode("utf-8")
1077
+ except (TypeError, ValueError) as error:
1078
+ raise InferenceError(
1079
+ InferenceFailure.CONFIGURATION,
1080
+ "decision request could not be serialized as finite JSON",
1081
+ ) from error
1082
+ headers = {
1083
+ "Accept": "application/json",
1084
+ "Content-Type": "application/json",
1085
+ "User-Agent": f"itself-decisions/{DECISION_MODEL_ADAPTER_VERSION}",
1086
+ **self.endpoint.extra_headers,
1087
+ }
1088
+ if self.endpoint.credential is not None:
1089
+ name, value = self.endpoint.credential.render(self.environment)
1090
+ headers[name] = value
1091
+ return HttpRequest(
1092
+ url=self.endpoint.url,
1093
+ headers=headers,
1094
+ body=body,
1095
+ timeout_seconds=self.endpoint.timeout_seconds,
1096
+ deadline_seconds=self.endpoint.deadline_seconds,
1097
+ )
1098
+
1099
+ def _capture(
1100
+ self,
1101
+ content: bytes,
1102
+ media_type: str,
1103
+ detail: str,
1104
+ *,
1105
+ request: ArtifactReference | None = None,
1106
+ ) -> ArtifactReference:
1107
+ try:
1108
+ return self.artifact_sink.capture(
1109
+ content,
1110
+ media_type=media_type,
1111
+ captured_at=self.now(),
1112
+ )
1113
+ except (OSError, ValueError) as error:
1114
+ raise DecisionModelError(
1115
+ InferenceFailure.ARTIFACT,
1116
+ detail,
1117
+ request=request,
1118
+ ) from error
1119
+
1120
+ def ask(
1121
+ self,
1122
+ state: JsonValue,
1123
+ questions: Mapping[str, DecisionQuestion],
1124
+ *,
1125
+ order: OptionOrder = OptionOrder.DECLARED,
1126
+ ) -> DecisionModelAttempt:
1127
+ """Send one request, capture it and its response, and validate each answer.
1128
+
1129
+ The exact request body is captured before it is sent, and the bounded
1130
+ response bytes before they are interpreted. Nothing is retried. A
1131
+ failure after the request is captured raises ``DecisionModelError``
1132
+ with a reference to the captured request.
1133
+ """
1134
+
1135
+ try:
1136
+ asked = _questions(questions)
1137
+ selected_order = _order(order)
1138
+ except ValueError as error:
1139
+ raise InferenceError(InferenceFailure.CONFIGURATION, str(error)) from error
1140
+ http_request = self._request(state, asked, selected_order)
1141
+ request_artifact = self._capture(
1142
+ http_request.body,
1143
+ "application/json",
1144
+ "decision request artifact capture failed",
1145
+ )
1146
+ started_at = self.monotonic_ns()
1147
+ try:
1148
+ response = self.transport.send(http_request)
1149
+ except InferenceError as error:
1150
+ raise DecisionModelError(
1151
+ error.failure,
1152
+ error.detail,
1153
+ status_code=error.status_code,
1154
+ artifact=error.artifact,
1155
+ request=request_artifact,
1156
+ ) from error
1157
+ except Exception as error:
1158
+ raise DecisionModelError(
1159
+ InferenceFailure.TRANSPORT,
1160
+ "custom decision transport failed",
1161
+ request=request_artifact,
1162
+ ) from error
1163
+ elapsed_ns = max(0, self.monotonic_ns() - started_at)
1164
+ artifact = self._capture(
1165
+ response.body,
1166
+ content_type(response.headers),
1167
+ "decision response artifact capture failed",
1168
+ request=request_artifact,
1169
+ )
1170
+
1171
+ if not 200 <= response.status_code <= 299:
1172
+ raise DecisionModelError(
1173
+ _http_failure(response.status_code),
1174
+ f"decision endpoint returned HTTP {response.status_code}",
1175
+ status_code=response.status_code,
1176
+ artifact=artifact,
1177
+ request=request_artifact,
1178
+ )
1179
+
1180
+ parsed = _parsed_response(
1181
+ response.body,
1182
+ asked,
1183
+ selected_order,
1184
+ self.endpoint.probability_tolerance,
1185
+ artifact,
1186
+ request_artifact,
1187
+ )
1188
+ return DecisionModelAttempt(
1189
+ order=selected_order,
1190
+ identity=InferenceIdentity(
1191
+ actor_id=self.endpoint.actor_id,
1192
+ adapter_id=DECISION_MODEL_ADAPTER_ID,
1193
+ adapter_version=DECISION_MODEL_ADAPTER_VERSION,
1194
+ requested_model=self.endpoint.model,
1195
+ resolved_model=parsed.resolved_model,
1196
+ ),
1197
+ request=request_artifact,
1198
+ raw_response=artifact,
1199
+ usage=InferenceUsage(
1200
+ input_tokens=parsed.input_tokens,
1201
+ output_tokens=parsed.output_tokens,
1202
+ total_tokens=parsed.total_tokens,
1203
+ wall_time_ms=elapsed_ns // 1_000_000,
1204
+ ),
1205
+ answers=parsed.answers,
1206
+ )
1207
+
1208
+ def decide(
1209
+ self,
1210
+ state: JsonValue,
1211
+ questions: Mapping[str, DecisionQuestion],
1212
+ *,
1213
+ orders: Sequence[OptionOrder] = COUNTERBALANCED_ORDERS,
1214
+ ) -> DecisionModelResult:
1215
+ """Ask every question in each order, one request at a time, and combine.
1216
+
1217
+ Choice and score questions are asked once per order. A noul question
1218
+ has no option order, so only the first request asks it, and a later
1219
+ request with nothing left to ask is not sent. If a later request
1220
+ fails, the ``DecisionModelError`` it raises carries the attempts that
1221
+ completed before it, so their captured artifacts stay reachable.
1222
+ """
1223
+
1224
+ try:
1225
+ asked = _questions(questions)
1226
+ sequence = _orders(orders)
1227
+ except ValueError as error:
1228
+ raise InferenceError(InferenceFailure.CONFIGURATION, str(error)) from error
1229
+
1230
+ attempts: list[DecisionModelAttempt] = []
1231
+ for index, order in enumerate(sequence):
1232
+ subset = (
1233
+ asked
1234
+ if index == 0
1235
+ else {
1236
+ question_id: question
1237
+ for question_id, question in asked.items()
1238
+ if not isinstance(question, NoulQuestion)
1239
+ }
1240
+ )
1241
+ if not subset:
1242
+ continue
1243
+ try:
1244
+ attempts.append(self.ask(state, subset, order=order))
1245
+ except DecisionModelError as error:
1246
+ error.attempts = tuple(attempts)
1247
+ raise
1248
+ except InferenceError as error:
1249
+ if not attempts:
1250
+ raise
1251
+ raise DecisionModelError(
1252
+ error.failure,
1253
+ error.detail,
1254
+ status_code=error.status_code,
1255
+ artifact=error.artifact,
1256
+ attempts=attempts,
1257
+ ) from error
1258
+
1259
+ identity = attempts[0].identity
1260
+ for attempt in attempts[1:]:
1261
+ if attempt.identity != identity:
1262
+ raise DecisionModelError(
1263
+ InferenceFailure.RESPONSE_ENVELOPE,
1264
+ "decision endpoint did not report the same model for every request",
1265
+ artifact=attempt.raw_response,
1266
+ request=attempt.request,
1267
+ attempts=attempts,
1268
+ )
1269
+ return DecisionModelResult(
1270
+ identity=identity,
1271
+ attempts=tuple(attempts),
1272
+ estimates={
1273
+ question_id: _estimate(
1274
+ question,
1275
+ [
1276
+ attempt.answers[question_id]
1277
+ for attempt in attempts
1278
+ if question_id in attempt.answers
1279
+ ],
1280
+ )
1281
+ for question_id, question in asked.items()
1282
+ },
1283
+ )