Datasets:
File size: 5,479 Bytes
7825400 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | """Inference response schema — the contract between model adapters and metrics.
Models return a list of DetectionResult dicts per image (COCO-style).
An empty list means no violations were detected.
An empty list is ambiguous on its own, though: it looks identical whether the
model said "no violations" or produced something we failed to parse. Every
response therefore carries a ``parse_status`` recording which of those happened,
so a silent parse failure cannot be mistaken for a clean negative.
"""
from typing import Literal
from pydantic import BaseModel, Field, field_validator
ParseStatus = Literal["ok", "empty", "parse_error", "format_mismatch", "unrecorded"]
"""How the adapter's raw output was interpreted.
* ``ok`` — parsed cleanly, at least one detection
* ``empty`` — parsed cleanly, the model reported no violations (a real answer)
* ``parse_error`` — the output could not be parsed at all
* ``format_mismatch`` — parsed as structured data, but not in the expected shape
* ``unrecorded`` — the adapter did not say. The default, so that results written
before parse tracking existed are not silently upgraded to ``ok``; every
current adapter sets a real status.
"""
FormatSeen = Literal["json", "json_repaired", "yaml", "plain_text", "empty", "other"]
"""The output format actually observed, regardless of what was asked for.
``json_repaired`` means the response was JSON in every respect except that it
would not parse as written — in practice, zero-padded integers like
``"category_id": 03``. Kept distinct from ``json`` because it measures a real
compliance failure, and distinct from ``yaml`` because YAML happens to accept
those literals, which previously made well-formed JSON look like a model
answering in the wrong format entirely.
"""
class DetectionResult(BaseModel):
"""A single detection predicted by a model for one image.
Follows format:
{category_id, bbox, score}
An image with no detections simply has zero ``DetectionResult`` entries.
"""
category_id: int
bbox: list[float] = Field(..., min_length=4, max_length=4)
score: float = Field(ge=0.0, le=1.0)
@field_validator("bbox")
@classmethod
def validate_bbox(cls, v: list[float]) -> list[float]:
"""Ensure bbox has exactly 4 elements [x, y, width, height]."""
if len(v) != 4:
raise ValueError("bbox must have exactly 4 elements [x, y, width, height]")
return v
class InferenceResponse(BaseModel):
"""Wrapper for the full model response for a single image.
This is the single source of truth for the inference→metrics boundary.
The ``detections`` list may be empty if no violations were detected.
"""
image_id: str
detections: list[DetectionResult] = []
raw_text: str | None = None
model_name: str
latency_ms: float
# Parse tracking. The defaults describe an adapter that said nothing, so
# older results stay readable without being credited with a clean parse.
parse_status: ParseStatus = "unrecorded"
format_seen: FormatSeen | None = None
parse_error: str | None = None
# Geometry tracking. ``bbox`` above is always canonical unit [x, y, w, h];
# this records the convention it was converted *from*, and what the
# conversion had to repair. None means the file predates geometry tracking —
# its boxes were stored exactly as the model emitted them and may not be
# canonical at all.
box_convention: str | None = None
box_repairs: dict[str, int] = {}
# What this one image cost, as reported by the provider. ``None`` means no
# cost was reported — a local model, or a provider that does not say — and
# is deliberately distinct from ``0.0``, which claims the call was free.
# Never estimated from token counts: a benchmark that publishes cost per
# image must publish what was actually billed.
cost_usd: float | None = None
# Why generation stopped, as the provider reported it. ``"length"`` means
# the answer was cut off at ``max_tokens`` — a fact about our request, not
# about the model, and the difference between "this model cannot do the
# task" and "we did not let it finish". Reasoning models make that
# distinction load-bearing: they spend the token budget thinking before
# they emit a single character of answer, so a budget that is merely
# generous for a normal model leaves them with an empty ``content`` and a
# results file that reads as total failure. ``None`` means the provider did
# not say, or the adapter is local.
finish_reason: str | None = None
# Optional accounting used by local and hosted multi-pass runs. Older
# result files remain valid because every field is additive.
input_tokens: int | None = None
output_tokens: int | None = None
context_limit: int | None = None
context_headroom: int | None = None
provider_diagnostics: dict = {}
pass_summaries: list[dict] = []
@property
def parsed_cleanly(self) -> bool:
"""Whether the model's output was understood, detections or not."""
return self.parse_status in ("ok", "empty")
class InferenceAttempt(BaseModel):
"""Auditable record of every model call made for one image."""
image_id: str
attempt: int = Field(ge=1)
status: Literal["ok", "failed"]
response: InferenceResponse | None = None
error_type: str | None = None
error: str | None = None
|