seldon-runtime 0.1.1.dev0__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,859 @@
1
+ """Data-only contracts: imported requests, bounded programs and frozen SLOs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import re
9
+ from typing import Any, ClassVar, Literal
10
+ from uuid import UUID
11
+
12
+ from jsonschema import Draft202012Validator
13
+ from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator
14
+
15
+ from .conditional import Predicate
16
+
17
+
18
+ def canonical(value: Any) -> str:
19
+ return json.dumps(
20
+ value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
21
+ )
22
+
23
+
24
+ def digest(value: Any) -> str:
25
+ return hashlib.sha256(canonical(value).encode()).hexdigest()
26
+
27
+
28
+ def bounded_schema(schema):
29
+ """No remote resolution, recursive schemas or unbounded regex evaluation."""
30
+ count = 0
31
+
32
+ def visit(value, depth=0, refs=()):
33
+ nonlocal count
34
+ count += 1
35
+ if depth > 24 or count > 2048:
36
+ raise ValueError("schema_complexity_limit")
37
+ if isinstance(value, dict):
38
+ if any(
39
+ k in value
40
+ for k in ("pattern", "patternProperties", "$dynamicRef", "$recursiveRef", "$id")
41
+ ):
42
+ raise ValueError("unsupported_schema_keyword")
43
+ ref = value.get("$ref")
44
+ if ref:
45
+ if not isinstance(ref, str) or not ref.startswith("#/") or ref in refs:
46
+ raise ValueError("unsupported_schema_reference")
47
+ target = schema
48
+ for key in ref[2:].split("/"):
49
+ target = target[key.replace("~1", "/").replace("~0", "~")]
50
+ visit(target, depth + 1, (*refs, ref))
51
+ for key, item in value.items():
52
+ if key != "$ref":
53
+ visit(item, depth + 1, refs)
54
+ elif isinstance(value, list):
55
+ for item in value:
56
+ visit(item, depth + 1, refs)
57
+
58
+ from jsonschema.exceptions import SchemaError
59
+
60
+ try:
61
+ visit(schema)
62
+ Draft202012Validator.check_schema(schema)
63
+ except (KeyError, TypeError) as exc:
64
+ raise ValueError("invalid_schema_reference") from exc
65
+ except SchemaError as exc:
66
+ # Not a ValueError: left unconverted it escaped Plan validation and aborted
67
+ # proposal construction instead of rejecting one proposal.
68
+ raise ValueError("invalid_schema") from exc
69
+
70
+
71
+ class Contract(BaseModel):
72
+ model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False)
73
+
74
+ @property
75
+ def digest(self) -> str:
76
+ return digest(self.model_dump(mode="json"))
77
+
78
+
79
+ class Message(Contract):
80
+ role: Literal["system", "developer", "user", "assistant"]
81
+ content: str = Field(max_length=262144)
82
+
83
+
84
+ class RequestContract(Contract):
85
+ id: str = Field(pattern=r"^[a-zA-Z][a-zA-Z0-9_]{0,63}$")
86
+ model: str = Field(min_length=1, max_length=256)
87
+ messages: list[Message] = Field(min_length=1, max_length=32)
88
+ temperature: float | None = Field(default=0, ge=0, le=2)
89
+ # The selected offering validates the upper bound; imports may declare its full limit.
90
+ max_tokens: int | None = Field(default=2048, ge=1)
91
+ response_format: dict[str, Any] | None = None
92
+ tools: list[dict[str, Any]] | None = None
93
+ tool_choice: str | dict[str, Any] | None = None
94
+ parallel_tool_calls: bool | None = Field(default=None, strict=True)
95
+
96
+ @model_serializer(mode="wrap")
97
+ def compatible_dump(self, handler):
98
+ value = handler(self)
99
+ for key in ("tools", "tool_choice", "parallel_tool_calls"):
100
+ if getattr(self, key) is None:
101
+ value.pop(key, None)
102
+ return value
103
+
104
+ @model_validator(mode="after")
105
+ def check_output_tool(self):
106
+ from .tool_wire import output_tool
107
+
108
+ tool = output_tool(self.model_dump(exclude_none=True))
109
+ if tool:
110
+ bounded_schema(tool["parameters"])
111
+ return self
112
+
113
+
114
+ def reference(value: str) -> tuple[str, str]:
115
+ root, sep, path = value.partition("#")
116
+ if not sep or not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_]{0,63}", root):
117
+ raise ValueError("invalid_reference")
118
+ if path and not path.startswith("/"):
119
+ raise ValueError("invalid_pointer")
120
+ if re.search(r"~(?![01])", path):
121
+ raise ValueError("invalid_pointer")
122
+ return root, path
123
+
124
+
125
+ class Binding(Contract):
126
+ call: str
127
+ message: int = Field(ge=0, le=31)
128
+ placeholder: str = Field(min_length=1, max_length=256)
129
+ source: str
130
+
131
+
132
+ class ObjectiveCheck(Contract):
133
+ kind: Literal["collection", "quotes"]
134
+ path: str = Field(pattern=r"^(?:/.*)?$", max_length=256)
135
+ min_items: int = Field(default=0, ge=0, le=1000)
136
+ max_items: int = Field(default=1000, ge=0, le=1000)
137
+ source_field: str = Field(default="memo", min_length=1, max_length=64)
138
+ quote_field: str = Field(default="quote", min_length=1, max_length=64)
139
+ sources: dict[str, str] = Field(default_factory=dict, max_length=16)
140
+
141
+ @model_validator(mode="after")
142
+ def check(self):
143
+ reference("output#" + self.path)
144
+ if self.min_items > self.max_items or (self.kind == "quotes" and not self.sources):
145
+ raise ValueError("invalid_objective_check")
146
+ for path in self.sources.values():
147
+ reference("input#" + path)
148
+ return self
149
+
150
+
151
+ class Rubric(Contract):
152
+ # rubric-v2 replaces the memo-demo ``source_field`` default with the neutral
153
+ # "source" used by EvaluationCheck. Saved rubric-v1 contracts keep "memo".
154
+ version: Literal["rubric-v1", "rubric-v2"] = "rubric-v1"
155
+ judge_model: str = Field(min_length=1, max_length=256)
156
+ criteria: list[str] = Field(min_length=1, max_length=6)
157
+ checks: list[ObjectiveCheck] = Field(default_factory=list, max_length=8)
158
+
159
+ @model_validator(mode="after")
160
+ def check(self):
161
+ if any(not c.strip() or len(c) > 1024 for c in self.criteria):
162
+ raise ValueError("invalid_rubric")
163
+ if self.version == "rubric-v2" and any(
164
+ "source_field" not in check.model_fields_set for check in self.checks
165
+ ):
166
+ checks = [
167
+ check
168
+ if "source_field" in check.model_fields_set
169
+ else ObjectiveCheck.model_validate({**check.model_dump(), "source_field": "source"})
170
+ for check in self.checks
171
+ ]
172
+ object.__setattr__(self, "checks", checks)
173
+ return self
174
+
175
+
176
+ class EvaluationCheck(Contract):
177
+ """Configuration of bounded built-in checks, never generated executable code."""
178
+
179
+ kind: Literal["schema", "collection", "spans", "quotes", "enum", "exact", "records", "decimal"]
180
+ path: str = Field(default="", max_length=256)
181
+ source_path: str | None = Field(default=None, max_length=256)
182
+ min_items: int = Field(default=0, ge=0, le=1000)
183
+ max_items: int = Field(default=1000, ge=0, le=1000)
184
+ text_field: str = Field(default="text", min_length=1, max_length=64)
185
+ start_field: str = Field(default="start", min_length=1, max_length=64)
186
+ end_field: str = Field(default="end", min_length=1, max_length=64)
187
+ source_field: str = Field(default="source", min_length=1, max_length=64)
188
+ quote_field: str = Field(default="quote", min_length=1, max_length=64)
189
+ sources: dict[str, str] = Field(default_factory=dict, max_length=16)
190
+ allowed: list[str | int | float | bool | None] = Field(default_factory=list, max_length=128)
191
+ # evaluation-semantics-v2 only; omitted from serialization unless set.
192
+ min_chars: int = Field(default=1, ge=1, le=10000)
193
+ normalization: Literal["none", "typographic_whitespace"] = "none"
194
+ offset_unit: Literal["codepoint", "utf16"] = "codepoint"
195
+
196
+ V2_FIELDS: ClassVar[frozenset[str]] = frozenset({"min_chars", "normalization", "offset_unit"})
197
+
198
+ @model_serializer(mode="wrap")
199
+ def compatible_dump(self, handler):
200
+ value = handler(self)
201
+ for key in self.V2_FIELDS:
202
+ if key not in self.model_fields_set:
203
+ value.pop(key, None)
204
+ return value
205
+
206
+ @model_validator(mode="after")
207
+ def check(self):
208
+ reference("output#" + self.path)
209
+ if self.source_path is not None:
210
+ reference("input#" + self.source_path)
211
+ for path in self.sources.values():
212
+ reference("input#" + path)
213
+ if self.min_items > self.max_items:
214
+ raise ValueError("invalid_evaluation_check")
215
+ if self.kind == "spans" and self.source_path is None:
216
+ raise ValueError("invalid_evaluation_check")
217
+ if self.kind == "quotes" and not self.sources and self.source_path is None:
218
+ raise ValueError("invalid_evaluation_check")
219
+ if self.kind == "enum" and not self.allowed:
220
+ raise ValueError("invalid_evaluation_check")
221
+ return self
222
+
223
+
224
+ class EvaluationExample(Contract):
225
+ input_origin: Literal["synthetic", "uploaded", "recorded"] = Field(
226
+ default="uploaded", json_schema_extra=lambda schema: schema.pop("default", None)
227
+ )
228
+ label_origin: Literal["human", "reference", "judge", "unknown"] = Field(
229
+ default="unknown", json_schema_extra=lambda schema: schema.pop("default", None)
230
+ )
231
+ input: dict[str, Any]
232
+ output: Any = None
233
+ expected: Any = None
234
+ assertions: list[str] = Field(default_factory=list, max_length=6)
235
+ group: str | None = Field(default=None, min_length=1, max_length=128)
236
+ weight: float | None = Field(default=None, gt=0)
237
+ role: Literal["training", "development", "confirmation"] | None = None
238
+ value: float | None = Field(default=None, ge=0, allow_inf_nan=False)
239
+
240
+ @model_serializer(mode="wrap")
241
+ def compatible_dump(self, handler):
242
+ value = handler(self)
243
+ if self.input_origin == "uploaded":
244
+ value.pop("input_origin", None)
245
+ if self.label_origin == "unknown":
246
+ value.pop("label_origin", None)
247
+ for key in ("output", "expected", "group", "role", "value"):
248
+ if key not in self.model_fields_set:
249
+ value.pop(key, None)
250
+ if "weight" not in self.model_fields_set:
251
+ value.pop("weight", None)
252
+ return value
253
+
254
+ @model_validator(mode="after")
255
+ def check(self):
256
+ if self.weight is not None and (not math.isfinite(self.weight) or self.weight <= 0):
257
+ raise ValueError("invalid_example_weight")
258
+ if any(not a.strip() or len(a) > 2048 for a in self.assertions):
259
+ raise ValueError("invalid_evaluation_assertion")
260
+ if len(canonical(self.model_dump()).encode()) > 262144:
261
+ raise ValueError("evaluation_example_too_large")
262
+ return self
263
+
264
+
265
+ class PredictionMapping(Contract):
266
+ source: Any
267
+ target: Any
268
+
269
+
270
+ class PredictionThreshold(Contract):
271
+ """Maps a numeric score to the positive (true) or negative (false) class."""
272
+
273
+ operator: Literal["ge", "gt", "le", "lt"]
274
+ value: float = Field(allow_inf_nan=False)
275
+
276
+
277
+ TASK_METRICS = (
278
+ "exact_match",
279
+ "binary_f1",
280
+ "value_weighted_recall",
281
+ "within_tolerance",
282
+ "mean_absolute_error",
283
+ "macro_f1",
284
+ "set_f1",
285
+ "field_accuracy",
286
+ "record_f1",
287
+ "span_f1",
288
+ )
289
+
290
+
291
+ def _scalar(value):
292
+ return type(value) in {str, int, float, bool} or value is None
293
+
294
+
295
+ def _label_type_ok(metric, label):
296
+ """Type gate for evaluation-semantics-v2 labels; v1 metrics are unchanged."""
297
+ if metric in {"within_tolerance", "mean_absolute_error"}:
298
+ return type(label) in {int, float} and math.isfinite(label)
299
+ if metric == "macro_f1":
300
+ return type(label) in {str, int, bool}
301
+ if metric == "set_f1":
302
+ return isinstance(label, list) and all(_scalar(item) for item in label)
303
+ if metric == "field_accuracy":
304
+ return isinstance(label, dict)
305
+ if metric in {"record_f1", "span_f1"}:
306
+ return isinstance(label, list) and all(isinstance(item, dict) for item in label)
307
+ return True
308
+
309
+
310
+ def _pointer_list(values, *, limit):
311
+ if len(values) > limit or len(set(values)) != len(values):
312
+ raise ValueError("invalid_metric_fields")
313
+ for value in values:
314
+ if not value.startswith("/") or re.search(r"~(?![01])", value):
315
+ raise ValueError("invalid_metric_fields")
316
+
317
+
318
+ MAX_EVALUATION_EXAMPLES = 1000
319
+
320
+
321
+ class EvaluationFunction(Contract):
322
+ recording_examples_ref: str | None = Field(default=None, max_length=1024)
323
+ version: Literal["evaluation-function-v1"] = "evaluation-function-v1"
324
+ instructions: str = Field(min_length=1, max_length=8192)
325
+ criteria: list[str] = Field(default_factory=list, max_length=6)
326
+ checks: list[EvaluationCheck] = Field(default_factory=list, max_length=16)
327
+ examples: list[EvaluationExample] = Field(
328
+ default_factory=list, max_length=MAX_EVALUATION_EXAMPLES
329
+ )
330
+ metric: (
331
+ Literal[
332
+ "exact_match",
333
+ "binary_f1",
334
+ "value_weighted_recall",
335
+ "within_tolerance",
336
+ "mean_absolute_error",
337
+ "macro_f1",
338
+ "set_f1",
339
+ "field_accuracy",
340
+ "record_f1",
341
+ "span_f1",
342
+ ]
343
+ | None
344
+ ) = None
345
+ positive_label: Any = None
346
+ prediction_path: str | None = Field(default=None, max_length=1024)
347
+ prediction_map: list[PredictionMapping] = Field(default_factory=list, max_length=128)
348
+ # evaluation-semantics-v2 parameters. Each is omitted from serialization unless
349
+ # set, so v1 definitions, specs and digests stay byte-identical.
350
+ negative_label: Any = None
351
+ prediction_threshold: PredictionThreshold | None = None
352
+ absolute_tolerance: float | None = Field(default=None, ge=0, allow_inf_nan=False)
353
+ relative_tolerance: float | None = Field(default=None, ge=0, allow_inf_nan=False)
354
+ fields: list[str] = Field(default_factory=list, max_length=32)
355
+ record_key: list[str] = Field(default_factory=list, max_length=8)
356
+ empty_values: Literal["distinct", "equivalent"] = "distinct"
357
+ span_match: Literal["exact", "overlap"] = "exact"
358
+ span_start_field: str = Field(default="start", min_length=1, max_length=64)
359
+ span_end_field: str = Field(default="end", min_length=1, max_length=64)
360
+ span_label_field: str = Field(default="label", min_length=1, max_length=64)
361
+ span_source_path: str | None = Field(default=None, max_length=256)
362
+ # Explicit authority for a generated span recipe to treat context as a hint.
363
+ span_context_policy: Literal["strict", "hint"] = "strict"
364
+ offset_unit: Literal["codepoint", "utf16"] = "codepoint"
365
+ expected_role: Literal["authoritative", "reference_answer"] = "authoritative"
366
+ judge_profile: Literal["standard", "verify_derived"] = "standard"
367
+
368
+ V1_OPTIONAL: ClassVar[tuple[str, ...]] = (
369
+ "metric",
370
+ "positive_label",
371
+ "prediction_path",
372
+ "prediction_map",
373
+ )
374
+ V2_FIELDS: ClassVar[frozenset[str]] = frozenset(
375
+ {
376
+ "negative_label",
377
+ "prediction_threshold",
378
+ "absolute_tolerance",
379
+ "relative_tolerance",
380
+ "fields",
381
+ "record_key",
382
+ "empty_values",
383
+ "span_match",
384
+ "span_start_field",
385
+ "span_end_field",
386
+ "span_label_field",
387
+ "span_source_path",
388
+ "span_context_policy",
389
+ "offset_unit",
390
+ "expected_role",
391
+ "judge_profile",
392
+ }
393
+ )
394
+
395
+ @model_serializer(mode="wrap")
396
+ def compatible_dump(self, handler):
397
+ value = handler(self)
398
+ if self.recording_examples_ref is None:
399
+ value.pop("recording_examples_ref", None)
400
+ else:
401
+ # Recording payload lives in its expiring run manifest, never retained specs.
402
+ value["examples"] = [
403
+ e for e in value.get("examples", []) if e.get("input_origin") != "recorded"
404
+ ]
405
+ for key in (*self.V1_OPTIONAL, *self.V2_FIELDS):
406
+ if key not in self.model_fields_set:
407
+ value.pop(key, None)
408
+ return value
409
+
410
+ def metric_parameters(self) -> dict:
411
+ """Every explicitly set metric parameter; part of the v2 definition digest."""
412
+ return {
413
+ key: value
414
+ for key, value in self.model_dump(mode="json", exclude={"examples"}).items()
415
+ if key in self.V2_FIELDS or key in self.V1_OPTIONAL
416
+ }
417
+
418
+ @model_validator(mode="after")
419
+ def check(self):
420
+ if not self.instructions.strip() or any(
421
+ not c.strip() or len(c) > 1024 for c in self.criteria
422
+ ):
423
+ raise ValueError("invalid_evaluation")
424
+ if (
425
+ self.metric in {"binary_f1", "value_weighted_recall"}
426
+ and "positive_label" not in self.model_fields_set
427
+ ):
428
+ raise ValueError("positive_label_required")
429
+ if len(canonical(self.model_dump()).encode()) > 5 * 1024 * 1024:
430
+ raise ValueError("evaluation_examples_too_large")
431
+ if self.prediction_path is not None:
432
+ if self.prediction_path and not self.prediction_path.startswith("/"):
433
+ raise ValueError("invalid_prediction_path")
434
+ if re.search(r"~(?![01])", self.prediction_path):
435
+ raise ValueError("invalid_prediction_path")
436
+ mapping_sources = [canonical(entry.source) for entry in self.prediction_map]
437
+ if len(mapping_sources) != len(set(mapping_sources)):
438
+ raise ValueError("duplicate_prediction_mapping")
439
+ if self.prediction_threshold is not None:
440
+ if self.prediction_map:
441
+ raise ValueError("prediction_threshold_with_map")
442
+ if self.metric not in {"binary_f1", "value_weighted_recall"}:
443
+ raise ValueError("prediction_threshold_requires_binary_metric")
444
+ if "negative_label" not in self.model_fields_set:
445
+ raise ValueError("negative_label_required")
446
+ if canonical(self.negative_label) == canonical(self.positive_label):
447
+ raise ValueError("invalid_threshold_classes")
448
+ _pointer_list(self.fields, limit=32)
449
+ _pointer_list(self.record_key, limit=8)
450
+ if self.span_source_path is not None:
451
+ reference("input#" + self.span_source_path)
452
+ seen = set()
453
+ for example in self.examples:
454
+ if self.metric and "expected" not in example.model_fields_set:
455
+ raise ValueError("example_label_required")
456
+ if self.metric == "value_weighted_recall" and example.value is None:
457
+ raise ValueError("example_value_required")
458
+ if self.prediction_threshold is not None and canonical(example.expected) not in {
459
+ canonical(self.positive_label),
460
+ canonical(self.negative_label),
461
+ }:
462
+ raise ValueError("label_outside_threshold_classes")
463
+ if self.metric == "record_f1" and self.record_key:
464
+ self._check_record_keys(example.expected)
465
+ if self.metric and not _label_type_ok(self.metric, example.expected):
466
+ raise ValueError("label_type_invalid")
467
+ identity = digest(example.input)
468
+ if identity in seen:
469
+ raise ValueError("duplicate_evaluation_example")
470
+ seen.add(identity)
471
+ return self
472
+
473
+ def _check_record_keys(self, records):
474
+ from .json_pointer import pointer_value
475
+
476
+ if not isinstance(records, list):
477
+ return
478
+ keys = set()
479
+ for record in records:
480
+ key = canonical(
481
+ [pointer_value(record, pointer, default=None) for pointer in self.record_key]
482
+ )
483
+ if key in keys:
484
+ raise ValueError("duplicate_record_key")
485
+ keys.add(key)
486
+
487
+
488
+ class Preparation(Contract):
489
+ version: Literal["preparation-v1"] = "preparation-v1"
490
+ kind: Literal["description", "example", "request", "trace_call", "sdk"]
491
+ status: Literal["unresolved", "resolved"]
492
+ description: str | None = Field(default=None, min_length=1, max_length=16384)
493
+ source_version: str | None = Field(default=None, max_length=128)
494
+ source_id: str | None = Field(default=None, max_length=256)
495
+ pending_settings: list[Literal["temperature", "max_tokens"]] = Field(
496
+ default_factory=list, max_length=2
497
+ )
498
+
499
+ @model_serializer(mode="wrap")
500
+ def compatible_dump(self, handler):
501
+ value = handler(self)
502
+ if not self.pending_settings:
503
+ value.pop("pending_settings", None)
504
+ return value
505
+
506
+ @model_validator(mode="after")
507
+ def check(self):
508
+ if self.kind == "description" and not self.description:
509
+ raise ValueError("invalid_description")
510
+ return self
511
+
512
+
513
+ class ReferenceBinding(Contract):
514
+ version: Literal["function-reference-binding-v1"] = "function-reference-binding-v1"
515
+ connection_id: UUID
516
+ logical_model: str
517
+ mapping_revision: int = Field(ge=1)
518
+ provider_slug: str
519
+ endpoint_host: str
520
+ upstream_model: str
521
+
522
+ @model_serializer(mode="wrap")
523
+ def safe_identity(self, handler):
524
+ value = handler(self)
525
+ value["connection_id"] = str(self.connection_id)
526
+ return value
527
+
528
+
529
+ class FunctionSpec(Contract):
530
+ version: Literal["function-spec-v1"] = "function-spec-v1"
531
+ # Values are frozen identities; see output_limits.py before adding one.
532
+ output_token_policy: Literal[
533
+ "request",
534
+ "endpoint_max",
535
+ "bounded_8192",
536
+ "context_measured_v1",
537
+ "context_measured_v2",
538
+ ] = "request"
539
+ reference_binding: ReferenceBinding | None = None
540
+ calls: list[RequestContract] = Field(min_length=1, max_length=3)
541
+ inputs: dict[str, Any]
542
+ input_schema: dict[str, Any] | None = None
543
+ wire_mode: Literal["messages", "input_object", "template"] = "messages"
544
+ template_syntax: Literal["python_format", "jinja_variables"] | None = None
545
+ bindings: list[Binding] = Field(default_factory=list, max_length=64)
546
+ output_schema: dict[str, Any]
547
+ evaluator: Literal["exact", "records", "decimal", "rubric"] = "exact"
548
+ evaluation_pending: bool = False
549
+ rubric: Rubric | None = None
550
+ evaluation: EvaluationFunction | None = None
551
+ preparation: Preparation | None = None
552
+
553
+ @model_serializer(mode="wrap")
554
+ def compatible_dump(self, handler):
555
+ value = handler(self)
556
+ if self.reference_binding is None:
557
+ value.pop("reference_binding", None)
558
+ if self.output_token_policy == "request":
559
+ value.pop("output_token_policy", None)
560
+ if not self.evaluation_pending:
561
+ value.pop("evaluation_pending", None)
562
+ if self.rubric is None:
563
+ value.pop("rubric", None)
564
+ if self.evaluation is None:
565
+ value.pop("evaluation", None)
566
+ if self.input_schema is None:
567
+ value.pop("input_schema", None)
568
+ if self.preparation is None:
569
+ value.pop("preparation", None)
570
+ if self.template_syntax is None:
571
+ value.pop("template_syntax", None)
572
+ return value
573
+
574
+ assumptions: list[str] = Field(default_factory=list, max_length=32)
575
+
576
+ @model_validator(mode="after")
577
+ def check(self):
578
+ if self.wire_mode == "template":
579
+ from .templates import parse_template
580
+
581
+ if len(self.calls) != 1 or self.template_syntax is None:
582
+ raise ValueError("single_call_template_required")
583
+ expected = set()
584
+ for index, message in enumerate(self.calls[0].messages):
585
+ parsed = parse_template(message.content, self.template_syntax)
586
+ expected.update(
587
+ (index, token, "input#/" + name)
588
+ for token, name in zip(parsed.placeholders, parsed.names)
589
+ )
590
+ actual = {(b.message, b.placeholder, b.source) for b in self.bindings}
591
+ if actual != expected:
592
+ raise ValueError("template_binding_mismatch")
593
+ elif self.template_syntax is not None:
594
+ raise ValueError("template_mode_required")
595
+ if self.reference_binding and any(
596
+ call.model != self.reference_binding.logical_model for call in self.calls
597
+ ):
598
+ raise ValueError("reference_single_model_required")
599
+ bounded_schema(self.output_schema)
600
+ if self.input_schema is not None:
601
+ bounded_schema(self.input_schema)
602
+ if not Draft202012Validator(self.input_schema).is_valid(self.inputs):
603
+ raise ValueError("invalid_example_inputs")
604
+ if self.output_schema.get("type") not in {"object", "array"}:
605
+ raise ValueError("unsupported_evaluator")
606
+ request = self.model_dump()
607
+ request.pop("evaluation", None)
608
+ if len(canonical(request).encode()) > 262144:
609
+ raise ValueError("request_too_large")
610
+ for call in self.calls:
611
+ from .tool_wire import request_schema
612
+
613
+ schema = request_schema(call.model_dump(exclude_none=True))
614
+ if schema:
615
+ bounded_schema(schema)
616
+ if any(call.tools is not None for call in self.calls):
617
+ if len(self.calls) != 1 or self.wire_mode not in {"messages", "template"}:
618
+ raise ValueError("single_call_output_tool_required")
619
+ if request_schema(self.calls[0].model_dump(exclude_none=True)) != self.output_schema:
620
+ raise ValueError("output_tool_schema_mismatch")
621
+ ids = [c.id for c in self.calls]
622
+ if len(set(ids)) != len(ids) or "input" in ids:
623
+ raise ValueError("duplicate_call_id")
624
+ occupied = set()
625
+ for binding in self.bindings:
626
+ if binding.call not in ids:
627
+ raise ValueError("unknown_call")
628
+ call = self.calls[ids.index(binding.call)]
629
+ root, _ = reference(binding.source)
630
+ if root != "input" and root not in ids[: ids.index(binding.call)]:
631
+ raise ValueError("forward_reference")
632
+ if binding.message >= len(call.messages):
633
+ raise ValueError("missing_message")
634
+ content = call.messages[binding.message].content
635
+ if content.count(binding.placeholder) != 1 and self.wire_mode != "template":
636
+ raise ValueError("ambiguous_placeholder")
637
+ key = (binding.call, binding.message, binding.placeholder)
638
+ if key in occupied:
639
+ raise ValueError("duplicate_binding")
640
+ occupied.add(key)
641
+ for call in self.calls:
642
+ for index, message in enumerate(call.messages):
643
+ spans = sorted(
644
+ (message.content.index(b.placeholder), len(b.placeholder))
645
+ for b in self.bindings
646
+ if b.call == call.id and b.message == index
647
+ )
648
+ if any(a + length > b for (a, length), (b, _) in zip(spans, spans[1:])):
649
+ raise ValueError("overlapping_binding")
650
+ return self
651
+
652
+
653
+ class Step(Contract):
654
+ id: str = Field(pattern=r"^[a-zA-Z][a-zA-Z0-9_]{0,63}$")
655
+ op: Literal[
656
+ "branch",
657
+ "merge",
658
+ "return",
659
+ "copy",
660
+ "parse_json",
661
+ "object",
662
+ "lookup",
663
+ "compare",
664
+ "filter",
665
+ "map",
666
+ "decimal_sum",
667
+ "decimal_add",
668
+ "decimal_multiply",
669
+ "generated_kernel",
670
+ "llm",
671
+ "choice",
672
+ "extract",
673
+ "normalize_text",
674
+ "chunk_text",
675
+ "retrieve_candidates",
676
+ "exact_links",
677
+ "resolve_links",
678
+ "assemble_records",
679
+ "align_spans",
680
+ "project_records",
681
+ "merge_spans",
682
+ "merge_records",
683
+ "merge_labels",
684
+ ]
685
+ inputs: list[str] = Field(default_factory=list, max_length=32)
686
+ config: dict[str, Any] = Field(default_factory=dict)
687
+ model: str | None = None
688
+ call: str | None = None
689
+ instruction_mode: Literal["original_call_ref", "append_instruction", "replacement_messages"] = (
690
+ "original_call_ref"
691
+ )
692
+ prompt: str | None = Field(default=None, max_length=16384)
693
+ messages: list[Message] | None = None
694
+ output_schema: dict[str, Any] | None = None
695
+ output_binding: Literal["call", "stage"] = "call"
696
+ # Fan a paid step out over a chunk array. Omitted unless set, so older
697
+ # plan digests stay byte-identical.
698
+ over: str | None = None
699
+ max_chunks: int | None = Field(default=None, ge=1, le=16)
700
+
701
+ next: str | None = None
702
+ predicate: Predicate | None = None
703
+ true_next: str | None = None
704
+ false_next: str | None = None
705
+ incoming: dict[str, str] | None = None
706
+ bind_call: str | None = None
707
+
708
+ @model_serializer(mode="wrap")
709
+ def compatible_dump(self, handler):
710
+ value = handler(self)
711
+ for key in ("next", "predicate", "true_next", "false_next", "incoming", "bind_call"):
712
+ if getattr(self, key) is None:
713
+ value.pop(key, None)
714
+ if self.output_binding == "call":
715
+ value.pop("output_binding", None)
716
+ if self.over is None:
717
+ value.pop("over", None)
718
+ if self.max_chunks is None:
719
+ value.pop("max_chunks", None)
720
+ return value
721
+
722
+
723
+ QUESTION_TYPES = frozenset({"boolean", "choice", "noul", "score"})
724
+
725
+ SCORE_LEVELS = (2, 10)
726
+
727
+
728
+ def check_question(question) -> None:
729
+ """Raise ``invalid_primitive_configuration`` for a question this image cannot serve.
730
+
731
+ ``noul``: ``{"type", "threshold"}`` with ``0 < threshold < 1``; the answer is
732
+ ``true`` iff the returned probability exceeds it. ``score``: ``{"type",
733
+ "levels", "reduce"}`` with 2-10 unique string levels and ``reduce:
734
+ nearest_level``; the answer is the level at ``floor(score + 0.5)``.
735
+ """
736
+ kind = question.get("type") if isinstance(question, dict) else None
737
+ if kind not in QUESTION_TYPES:
738
+ raise ValueError("invalid_primitive_configuration")
739
+ if kind == "noul":
740
+ threshold = question.get("threshold")
741
+ if (
742
+ set(question) != {"type", "threshold"}
743
+ or isinstance(threshold, bool)
744
+ or not isinstance(threshold, (int, float))
745
+ or not 0 < threshold < 1
746
+ ):
747
+ raise ValueError("invalid_primitive_configuration")
748
+ if kind == "score":
749
+ levels = question.get("levels")
750
+ if (
751
+ set(question) != {"type", "levels", "reduce"}
752
+ or question.get("reduce") != "nearest_level"
753
+ or not isinstance(levels, list)
754
+ or not SCORE_LEVELS[0] <= len(levels) <= SCORE_LEVELS[1]
755
+ or any(not isinstance(level, str) or not level for level in levels)
756
+ or len(set(levels)) != len(levels)
757
+ ):
758
+ raise ValueError("invalid_primitive_configuration")
759
+
760
+
761
+ SEMANTIC_PLAN_VERSIONS = frozenset({"function-plan-v3", "function-plan-v4", "function-plan-v5"})
762
+
763
+
764
+ def semantic_plan(version: str) -> bool:
765
+ return version in SEMANTIC_PLAN_VERSIONS
766
+
767
+
768
+ class Plan(Contract):
769
+ version: Literal[
770
+ "function-plan-v1",
771
+ "function-plan-v2",
772
+ "function-plan-v3",
773
+ "function-plan-v4",
774
+ "function-plan-v5",
775
+ ] = "function-plan-v1"
776
+ steps: list[Step] = Field(min_length=1, max_length=16)
777
+ fallback: bool = False
778
+ max_items: int = Field(default=1000, ge=1, le=10000)
779
+
780
+ @model_validator(mode="after")
781
+ def check(self):
782
+ from .conditional import CONTROL_OPS, validate_graph
783
+
784
+ conditional = self.version == "function-plan-v5"
785
+ seen = {"input"}
786
+ learned = 0
787
+ for step in self.steps:
788
+ from .semantic import OPERATORS, validate_config
789
+
790
+ if not conditional and (
791
+ step.op in CONTROL_OPS
792
+ or any(
793
+ getattr(step, key) is not None
794
+ for key in (
795
+ "next",
796
+ "predicate",
797
+ "true_next",
798
+ "false_next",
799
+ "incoming",
800
+ "bind_call",
801
+ )
802
+ )
803
+ ):
804
+ raise ValueError("control_flow_requires_v5")
805
+ if step.op == "generated_kernel":
806
+ from .research_kernels import validate_config
807
+
808
+ validate_config(step)
809
+ if step.op in OPERATORS:
810
+ if not semantic_plan(self.version):
811
+ raise ValueError("operator_requires_v3")
812
+ if step.op in {"merge_spans", "merge_records", "merge_labels"} and (
813
+ self.version not in {"function-plan-v4", "function-plan-v5"}
814
+ ):
815
+ raise ValueError("operator_requires_v4")
816
+ validate_config(step.op, step.inputs, step.config)
817
+ if step.output_binding == "stage" and not semantic_plan(self.version):
818
+ raise ValueError("stage_binding_requires_v3")
819
+ if (
820
+ step.op in {"choice", "extract"}
821
+ and step.config.get("mode") in {"pairs", "spans", "records"}
822
+ and not semantic_plan(self.version)
823
+ ):
824
+ raise ValueError("operator_requires_v3")
825
+ if step.over or step.max_chunks is not None:
826
+ if self.version != "function-plan-v4":
827
+ raise ValueError("fanout_requires_v4")
828
+ if not step.over or reference(step.over)[0] not in seen:
829
+ raise ValueError("forward_reference")
830
+ if step.config.get("view") not in {None, "full", "bindings"}:
831
+ raise ValueError("invalid_primitive_configuration")
832
+ if step.op == "choice" and isinstance(step.config.get("questions"), dict):
833
+ for question in step.config["questions"].values():
834
+ check_question(question)
835
+ if step.config.get("view") == "bindings" and not semantic_plan(self.version):
836
+ raise ValueError("view_requires_v3")
837
+ if step.id in seen:
838
+ raise ValueError("duplicate_step")
839
+ for ref in step.inputs:
840
+ if reference(ref)[0] not in seen:
841
+ raise ValueError("forward_reference")
842
+ if step.output_schema:
843
+ bounded_schema(step.output_schema)
844
+ if step.op in {"llm", "choice", "extract"}:
845
+ learned += 1
846
+ if not step.model or not step.call:
847
+ raise ValueError("model_binding_required")
848
+ if step.instruction_mode == "append_instruction" and not step.prompt:
849
+ raise ValueError("prompt_required")
850
+ if step.instruction_mode == "replacement_messages" and not step.messages:
851
+ raise ValueError("messages_required")
852
+ elif step.model or step.prompt or step.messages:
853
+ raise ValueError("deterministic_step_has_prompt")
854
+ seen.add(step.id)
855
+ if conditional:
856
+ validate_graph(self)
857
+ elif learned > 3:
858
+ raise ValueError("model_call_limit")
859
+ return self