Datasets:
File size: 3,790 Bytes
e1ced61 | 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 | """JSON Schema loading, validation, and one-shot JSON repair parsing.
The pipeline persists every model output and intermediate artifact as JSON
validated against a schema in ``schemas/``. Model JSON is parsed strictly: a
malformed response is repaired at most once, and a second failure routes the item
to the human queue (never a silent regex fallback).
"""
from __future__ import annotations
import json
from collections.abc import Callable
from pathlib import Path
from typing import Any
from jsonschema import Draft202012Validator
from .hashing import sha256_text
ParseStatus = str # "valid_first_response" | "valid_after_one_repair" | "invalid"
class SchemaError(ValueError):
"""Raised when a schema document itself is invalid."""
def load_schema(path: str | Path) -> dict[str, Any]:
"""Load and compile-check a JSON Schema (draft 2020-12) from ``path``."""
schema: dict[str, Any] = json.loads(Path(path).read_text(encoding="utf-8"))
try:
Draft202012Validator.check_schema(schema)
except Exception as exc: # jsonschema raises various error types
raise SchemaError(f"invalid schema {path}: {exc}") from exc
return schema
def validate(instance: Any, schema: dict[str, Any]) -> list[str]:
"""Return a list of human-readable validation errors (empty if valid)."""
validator = Draft202012Validator(schema)
return [
_format_error(error)
for error in sorted(validator.iter_errors(instance), key=lambda e: list(e.path))
]
def is_valid(instance: Any, schema: dict[str, Any]) -> bool:
"""True when ``instance`` satisfies ``schema``."""
return not validate(instance, schema)
def _format_error(error: Any) -> str:
path = ".".join(str(part) for part in error.path) or "$"
return f"{path}: {error.message}"
def parse_json(raw: str) -> Any:
"""Parse a JSON document, tolerating a leading/trailing code fence.
Raises ``json.JSONDecodeError`` on failure (no silent fallback).
"""
text = raw.strip()
if text.startswith("```"):
# Strip a single surrounding fenced block (```json ... ``` or ``` ... ```).
lines = text.splitlines()
if lines and lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip().startswith("```"):
lines = lines[:-1]
text = "\n".join(lines).strip()
return json.loads(text)
def parse_with_repair(
raw: str,
schema: dict[str, Any],
repair: Callable[[str, list[str]], str | None],
) -> tuple[Any | None, ParseStatus, list[str]]:
"""Parse ``raw`` against ``schema``, allowing at most one repair call.
``repair(raw, errors)`` must return either a repaired raw string (re-parsed
and re-validated) or ``None``/empty to give up. Returns
``(parsed_or_None, parse_status, final_errors)``.
"""
try:
candidate = parse_json(raw)
except json.JSONDecodeError as exc:
candidate = None
first_errors = [f"json: {exc}"]
else:
first_errors = validate(candidate, schema)
if not first_errors:
return candidate, "valid_first_response", []
repaired = repair(raw, first_errors)
if not repaired:
return None, "invalid", first_errors
try:
candidate = parse_json(repaired)
except json.JSONDecodeError as exc:
return None, "invalid", [*first_errors, f"repair-json: {exc}"]
second_errors = validate(candidate, schema)
if second_errors:
return None, "invalid", [*first_errors, *second_errors]
return candidate, "valid_after_one_repair", []
def request_hash(payload: Any) -> str:
"""Stable SHA-256 of a request payload for idempotent response caching."""
return sha256_text(json.dumps(payload, sort_keys=True, ensure_ascii=False))
|